utils.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "crypto/x509"
  22. "encoding/base64"
  23. "errors"
  24. "fmt"
  25. "math"
  26. "net"
  27. "net/url"
  28. "os"
  29. "runtime"
  30. "runtime/debug"
  31. "syscall"
  32. "time"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  35. )
  36. // MakePsiphonUserAgent constructs a User-Agent value to use for web service
  37. // requests made by the tunnel-core client. The User-Agent includes useful stats
  38. // information; it is to be used only for HTTPS requests, where the header
  39. // cannot be seen by an adversary.
  40. func MakePsiphonUserAgent(config *Config) string {
  41. userAgent := "psiphon-tunnel-core"
  42. if config.ClientVersion != "" {
  43. userAgent += fmt.Sprintf("/%s", config.ClientVersion)
  44. }
  45. if config.ClientPlatform != "" {
  46. userAgent += fmt.Sprintf(" (%s)", config.ClientPlatform)
  47. }
  48. return userAgent
  49. }
  50. func DecodeCertificate(encodedCertificate string) (certificate *x509.Certificate, err error) {
  51. derEncodedCertificate, err := base64.StdEncoding.DecodeString(encodedCertificate)
  52. if err != nil {
  53. return nil, common.ContextError(err)
  54. }
  55. certificate, err = x509.ParseCertificate(derEncodedCertificate)
  56. if err != nil {
  57. return nil, common.ContextError(err)
  58. }
  59. return certificate, nil
  60. }
  61. // FilterUrlError transforms an error, when it is a url.Error, removing
  62. // the URL value. This is to avoid logging private user data in cases
  63. // where the URL may be a user input value.
  64. // This function is used with errors returned by net/http and net/url,
  65. // which are (currently) of type url.Error. In particular, the round trip
  66. // function used by our HttpProxy, http.Client.Do, returns errors of type
  67. // url.Error, with the URL being the url sent from the user's tunneled
  68. // applications:
  69. // https://github.com/golang/go/blob/release-branch.go1.4/src/net/http/client.go#L394
  70. func FilterUrlError(err error) error {
  71. if urlErr, ok := err.(*url.Error); ok {
  72. err = &url.Error{
  73. Op: urlErr.Op,
  74. URL: "",
  75. Err: urlErr.Err,
  76. }
  77. }
  78. return err
  79. }
  80. // TrimError removes the middle of over-long error message strings
  81. func TrimError(err error) error {
  82. const MAX_LEN = 100
  83. message := fmt.Sprintf("%s", err)
  84. if len(message) > MAX_LEN {
  85. return errors.New(message[:MAX_LEN/2] + "..." + message[len(message)-MAX_LEN/2:])
  86. }
  87. return err
  88. }
  89. // IsAddressInUseError returns true when the err is due to EADDRINUSE/WSAEADDRINUSE.
  90. func IsAddressInUseError(err error) bool {
  91. if err, ok := err.(*net.OpError); ok {
  92. if err, ok := err.Err.(*os.SyscallError); ok {
  93. if err.Err == syscall.EADDRINUSE {
  94. return true
  95. }
  96. // Special case for Windows (WSAEADDRINUSE = 10048)
  97. if errno, ok := err.Err.(syscall.Errno); ok {
  98. if 10048 == int(errno) {
  99. return true
  100. }
  101. }
  102. }
  103. }
  104. return false
  105. }
  106. // SyncFileWriter wraps a file and exposes an io.Writer. At predefined
  107. // steps, the file is synced (flushed to disk) while writing.
  108. type SyncFileWriter struct {
  109. file *os.File
  110. step int
  111. count int
  112. }
  113. // NewSyncFileWriter creates a SyncFileWriter.
  114. func NewSyncFileWriter(file *os.File) *SyncFileWriter {
  115. return &SyncFileWriter{
  116. file: file,
  117. step: 2 << 16,
  118. count: 0}
  119. }
  120. // Write implements io.Writer with periodic file syncing.
  121. func (writer *SyncFileWriter) Write(p []byte) (n int, err error) {
  122. n, err = writer.file.Write(p)
  123. if err != nil {
  124. return
  125. }
  126. writer.count += n
  127. if writer.count >= writer.step {
  128. err = writer.file.Sync()
  129. writer.count = 0
  130. }
  131. return
  132. }
  133. // emptyAddr implements the net.Addr interface. emptyAddr is intended to be
  134. // used as a stub, when a net.Addr is required but not used.
  135. type emptyAddr struct {
  136. }
  137. func (e *emptyAddr) String() string {
  138. return ""
  139. }
  140. func (e *emptyAddr) Network() string {
  141. return ""
  142. }
  143. // channelConn implements the net.Conn interface. channelConn allows use of
  144. // SSH.Channels in contexts where a net.Conn is expected. Only Read/Write/Close
  145. // are implemented and the remaining functions are stubs and expected to not
  146. // be used.
  147. type channelConn struct {
  148. ssh.Channel
  149. }
  150. func newChannelConn(channel ssh.Channel) *channelConn {
  151. return &channelConn{
  152. Channel: channel,
  153. }
  154. }
  155. func (conn *channelConn) LocalAddr() net.Addr {
  156. return new(emptyAddr)
  157. }
  158. func (conn *channelConn) RemoteAddr() net.Addr {
  159. return new(emptyAddr)
  160. }
  161. func (conn *channelConn) SetDeadline(_ time.Time) error {
  162. return common.ContextError(errors.New("unsupported"))
  163. }
  164. func (conn *channelConn) SetReadDeadline(_ time.Time) error {
  165. return common.ContextError(errors.New("unsupported"))
  166. }
  167. func (conn *channelConn) SetWriteDeadline(_ time.Time) error {
  168. return common.ContextError(errors.New("unsupported"))
  169. }
  170. // Based on: https://bitbucket.org/psiphon/psiphon-circumvention-system/src/b2884b0d0a491e55420ed1888aea20d00fefdb45/Android/app/src/main/java/com/psiphon3/psiphonlibrary/Utils.java?at=default#Utils.java-646
  171. func byteCountFormatter(bytes uint64) string {
  172. base := uint64(1024)
  173. if bytes < base {
  174. return fmt.Sprintf("%dB", bytes)
  175. }
  176. exp := int(math.Log(float64(bytes)) / math.Log(float64(base)))
  177. return fmt.Sprintf(
  178. "%.1f%c", float64(bytes)/math.Pow(float64(base), float64(exp)), "KMGTPEZ"[exp-1])
  179. }
  180. func emitMemoryMetrics() uint64 {
  181. var memStats runtime.MemStats
  182. runtime.ReadMemStats(&memStats)
  183. NoticeInfo("Memory metrics at %s: goroutines %d | total alloc %s | sys %s | heap alloc/sys/idle/inuse/released/objects %s/%s/%s/%s/%s/%d | stack inuse/sys %s/%s | mspan inuse/sys %s/%s | mcached inuse/sys %s/%s | buckhash/gc/other sys %s/%s/%s | nextgc %s",
  184. common.GetParentContext(),
  185. runtime.NumGoroutine(),
  186. byteCountFormatter(memStats.TotalAlloc),
  187. byteCountFormatter(memStats.Sys),
  188. byteCountFormatter(memStats.HeapAlloc),
  189. byteCountFormatter(memStats.HeapSys),
  190. byteCountFormatter(memStats.HeapIdle),
  191. byteCountFormatter(memStats.HeapInuse),
  192. byteCountFormatter(memStats.HeapReleased),
  193. memStats.HeapObjects,
  194. byteCountFormatter(memStats.StackInuse),
  195. byteCountFormatter(memStats.StackSys),
  196. byteCountFormatter(memStats.MSpanInuse),
  197. byteCountFormatter(memStats.MSpanSys),
  198. byteCountFormatter(memStats.MCacheInuse),
  199. byteCountFormatter(memStats.MCacheSys),
  200. byteCountFormatter(memStats.BuckHashSys),
  201. byteCountFormatter(memStats.GCSys),
  202. byteCountFormatter(memStats.OtherSys),
  203. byteCountFormatter(memStats.NextGC))
  204. return memStats.Sys
  205. }
  206. func setAggressiveGarbageCollection() {
  207. debug.SetGCPercent(5)
  208. debug.FreeOSMemory()
  209. }
  210. func setStandardGarbageCollection() {
  211. debug.SetGCPercent(100)
  212. debug.FreeOSMemory()
  213. }