utils.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. "net"
  26. "net/url"
  27. "os"
  28. "runtime"
  29. "runtime/debug"
  30. "syscall"
  31. "time"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  34. )
  35. // MakePsiphonUserAgent constructs a User-Agent value to use for web service
  36. // requests made by the tunnel-core client. The User-Agent includes useful stats
  37. // information; it is to be used only for HTTPS requests, where the header
  38. // cannot be seen by an adversary.
  39. func MakePsiphonUserAgent(config *Config) string {
  40. userAgent := "psiphon-tunnel-core"
  41. if config.ClientVersion != "" {
  42. userAgent += fmt.Sprintf("/%s", config.ClientVersion)
  43. }
  44. if config.ClientPlatform != "" {
  45. userAgent += fmt.Sprintf(" (%s)", config.ClientPlatform)
  46. }
  47. return userAgent
  48. }
  49. func DecodeCertificate(encodedCertificate string) (certificate *x509.Certificate, err error) {
  50. derEncodedCertificate, err := base64.StdEncoding.DecodeString(encodedCertificate)
  51. if err != nil {
  52. return nil, common.ContextError(err)
  53. }
  54. certificate, err = x509.ParseCertificate(derEncodedCertificate)
  55. if err != nil {
  56. return nil, common.ContextError(err)
  57. }
  58. return certificate, nil
  59. }
  60. // FilterUrlError transforms an error, when it is a url.Error, removing
  61. // the URL value. This is to avoid logging private user data in cases
  62. // where the URL may be a user input value.
  63. // This function is used with errors returned by net/http and net/url,
  64. // which are (currently) of type url.Error. In particular, the round trip
  65. // function used by our HttpProxy, http.Client.Do, returns errors of type
  66. // url.Error, with the URL being the url sent from the user's tunneled
  67. // applications:
  68. // https://github.com/golang/go/blob/release-branch.go1.4/src/net/http/client.go#L394
  69. func FilterUrlError(err error) error {
  70. if urlErr, ok := err.(*url.Error); ok {
  71. err = &url.Error{
  72. Op: urlErr.Op,
  73. URL: "",
  74. Err: urlErr.Err,
  75. }
  76. }
  77. return err
  78. }
  79. // TrimError removes the middle of over-long error message strings
  80. func TrimError(err error) error {
  81. const MAX_LEN = 100
  82. message := fmt.Sprintf("%s", err)
  83. if len(message) > MAX_LEN {
  84. return errors.New(message[:MAX_LEN/2] + "..." + message[len(message)-MAX_LEN/2:])
  85. }
  86. return err
  87. }
  88. // IsAddressInUseError returns true when the err is due to EADDRINUSE/WSAEADDRINUSE.
  89. func IsAddressInUseError(err error) bool {
  90. if err, ok := err.(*net.OpError); ok {
  91. if err, ok := err.Err.(*os.SyscallError); ok {
  92. if err.Err == syscall.EADDRINUSE {
  93. return true
  94. }
  95. // Special case for Windows (WSAEADDRINUSE = 10048)
  96. if errno, ok := err.Err.(syscall.Errno); ok {
  97. if 10048 == int(errno) {
  98. return true
  99. }
  100. }
  101. }
  102. }
  103. return false
  104. }
  105. // SyncFileWriter wraps a file and exposes an io.Writer. At predefined
  106. // steps, the file is synced (flushed to disk) while writing.
  107. type SyncFileWriter struct {
  108. file *os.File
  109. step int
  110. count int
  111. }
  112. // NewSyncFileWriter creates a SyncFileWriter.
  113. func NewSyncFileWriter(file *os.File) *SyncFileWriter {
  114. return &SyncFileWriter{
  115. file: file,
  116. step: 2 << 16,
  117. count: 0}
  118. }
  119. // Write implements io.Writer with periodic file syncing.
  120. func (writer *SyncFileWriter) Write(p []byte) (n int, err error) {
  121. n, err = writer.file.Write(p)
  122. if err != nil {
  123. return
  124. }
  125. writer.count += n
  126. if writer.count >= writer.step {
  127. err = writer.file.Sync()
  128. writer.count = 0
  129. }
  130. return
  131. }
  132. // emptyAddr implements the net.Addr interface. emptyAddr is intended to be
  133. // used as a stub, when a net.Addr is required but not used.
  134. type emptyAddr struct {
  135. }
  136. func (e *emptyAddr) String() string {
  137. return ""
  138. }
  139. func (e *emptyAddr) Network() string {
  140. return ""
  141. }
  142. // channelConn implements the net.Conn interface. channelConn allows use of
  143. // SSH.Channels in contexts where a net.Conn is expected. Only Read/Write/Close
  144. // are implemented and the remaining functions are stubs and expected to not
  145. // be used.
  146. type channelConn struct {
  147. ssh.Channel
  148. }
  149. func newChannelConn(channel ssh.Channel) *channelConn {
  150. return &channelConn{
  151. Channel: channel,
  152. }
  153. }
  154. func (conn *channelConn) LocalAddr() net.Addr {
  155. return new(emptyAddr)
  156. }
  157. func (conn *channelConn) RemoteAddr() net.Addr {
  158. return new(emptyAddr)
  159. }
  160. func (conn *channelConn) SetDeadline(_ time.Time) error {
  161. return common.ContextError(errors.New("unsupported"))
  162. }
  163. func (conn *channelConn) SetReadDeadline(_ time.Time) error {
  164. return common.ContextError(errors.New("unsupported"))
  165. }
  166. func (conn *channelConn) SetWriteDeadline(_ time.Time) error {
  167. return common.ContextError(errors.New("unsupported"))
  168. }
  169. func emitMemoryMetrics() {
  170. var memStats runtime.MemStats
  171. runtime.ReadMemStats(&memStats)
  172. NoticeInfo("Memory metrics at %s: goroutines %d | objects %d | alloc %s | inuse %s | sys %s | cumulative %d %s",
  173. common.GetParentContext(),
  174. runtime.NumGoroutine(),
  175. memStats.HeapObjects,
  176. common.FormatByteCount(memStats.HeapAlloc),
  177. common.FormatByteCount(memStats.HeapInuse+memStats.StackInuse+memStats.MSpanInuse+memStats.MCacheInuse),
  178. common.FormatByteCount(memStats.Sys),
  179. memStats.Mallocs,
  180. common.FormatByteCount(memStats.TotalAlloc))
  181. }
  182. func DoGarbageCollection() {
  183. debug.SetGCPercent(5)
  184. debug.FreeOSMemory()
  185. }