utils.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. std_errors "errors"
  24. "fmt"
  25. "net"
  26. "os"
  27. "runtime"
  28. "runtime/debug"
  29. "strings"
  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. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/refraction"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/resolver"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/stacktrace"
  39. )
  40. // MakePsiphonUserAgent constructs a User-Agent value to use for web service
  41. // requests made by the tunnel-core client. The User-Agent includes useful stats
  42. // information; it is to be used only for HTTPS requests, where the header
  43. // cannot be seen by an adversary.
  44. func MakePsiphonUserAgent(config *Config) string {
  45. userAgent := "psiphon-tunnel-core"
  46. if config.ClientVersion != "" {
  47. userAgent += fmt.Sprintf("/%s", config.ClientVersion)
  48. }
  49. if config.ClientPlatform != "" {
  50. userAgent += fmt.Sprintf(" (%s)", config.ClientPlatform)
  51. }
  52. return userAgent
  53. }
  54. func DecodeCertificate(encodedCertificate string) (certificate *x509.Certificate, err error) {
  55. derEncodedCertificate, err := base64.StdEncoding.DecodeString(encodedCertificate)
  56. if err != nil {
  57. return nil, errors.Trace(err)
  58. }
  59. certificate, err = x509.ParseCertificate(derEncodedCertificate)
  60. if err != nil {
  61. return nil, errors.Trace(err)
  62. }
  63. return certificate, nil
  64. }
  65. // TrimError removes the middle of over-long error message strings
  66. func TrimError(err error) error {
  67. const MAX_LEN = 100
  68. message := fmt.Sprintf("%s", err)
  69. if len(message) > MAX_LEN {
  70. return std_errors.New(message[:MAX_LEN/2] + "..." + message[len(message)-MAX_LEN/2:])
  71. }
  72. return err
  73. }
  74. // IsAddressInUseError returns true when the err is due to EADDRINUSE/WSAEADDRINUSE.
  75. func IsAddressInUseError(err error) bool {
  76. if err, ok := err.(*net.OpError); ok {
  77. if err, ok := err.Err.(*os.SyscallError); ok {
  78. if err.Err == syscall.EADDRINUSE {
  79. return true
  80. }
  81. // Special case for Windows, WSAEADDRINUSE (10048). In the case
  82. // where the socket already bound to the port has set
  83. // SO_EXCLUSIVEADDRUSE, the error will instead be WSAEACCES (10013).
  84. if errno, ok := err.Err.(syscall.Errno); ok {
  85. if int(errno) == 10048 || int(errno) == 10013 {
  86. return true
  87. }
  88. }
  89. }
  90. }
  91. return false
  92. }
  93. // SyncFileWriter wraps a file and exposes an io.Writer. At predefined
  94. // steps, the file is synced (flushed to disk) while writing.
  95. type SyncFileWriter struct {
  96. file *os.File
  97. step int
  98. count int
  99. }
  100. // NewSyncFileWriter creates a SyncFileWriter.
  101. func NewSyncFileWriter(file *os.File) *SyncFileWriter {
  102. return &SyncFileWriter{
  103. file: file,
  104. step: 2 << 16,
  105. count: 0}
  106. }
  107. // Write implements io.Writer with periodic file syncing.
  108. func (writer *SyncFileWriter) Write(p []byte) (n int, err error) {
  109. n, err = writer.file.Write(p)
  110. if err != nil {
  111. return
  112. }
  113. writer.count += n
  114. if writer.count >= writer.step {
  115. err = writer.file.Sync()
  116. writer.count = 0
  117. }
  118. return
  119. }
  120. // emptyAddr implements the net.Addr interface. emptyAddr is intended to be
  121. // used as a stub, when a net.Addr is required but not used.
  122. type emptyAddr struct {
  123. }
  124. func (e *emptyAddr) String() string {
  125. return ""
  126. }
  127. func (e *emptyAddr) Network() string {
  128. return ""
  129. }
  130. // channelConn implements the net.Conn interface. channelConn allows use of
  131. // SSH.Channels in contexts where a net.Conn is expected. Only Read/Write/Close
  132. // are implemented and the remaining functions are stubs and expected to not
  133. // be used.
  134. type channelConn struct {
  135. ssh.Channel
  136. }
  137. func newChannelConn(channel ssh.Channel) *channelConn {
  138. return &channelConn{
  139. Channel: channel,
  140. }
  141. }
  142. func (conn *channelConn) LocalAddr() net.Addr {
  143. return new(emptyAddr)
  144. }
  145. func (conn *channelConn) RemoteAddr() net.Addr {
  146. return new(emptyAddr)
  147. }
  148. func (conn *channelConn) SetDeadline(_ time.Time) error {
  149. return errors.TraceNew("unsupported")
  150. }
  151. func (conn *channelConn) SetReadDeadline(_ time.Time) error {
  152. return errors.TraceNew("unsupported")
  153. }
  154. func (conn *channelConn) SetWriteDeadline(_ time.Time) error {
  155. return errors.TraceNew("unsupported")
  156. }
  157. func emitMemoryMetrics() {
  158. var memStats runtime.MemStats
  159. runtime.ReadMemStats(&memStats)
  160. NoticeInfo("Memory metrics at %s: goroutines %d | objects %d | alloc %s | inuse %s | sys %s | cumulative %d %s",
  161. stacktrace.GetParentFunctionName(),
  162. runtime.NumGoroutine(),
  163. memStats.HeapObjects,
  164. common.FormatByteCount(memStats.HeapAlloc),
  165. common.FormatByteCount(memStats.HeapInuse+memStats.StackInuse+memStats.MSpanInuse+memStats.MCacheInuse),
  166. common.FormatByteCount(memStats.Sys),
  167. memStats.Mallocs,
  168. common.FormatByteCount(memStats.TotalAlloc))
  169. }
  170. func emitDatastoreMetrics() {
  171. NoticeInfo("Datastore metrics at %s: %s", stacktrace.GetParentFunctionName(), GetDataStoreMetrics())
  172. }
  173. func emitDNSMetrics(resolver *resolver.Resolver) {
  174. NoticeInfo("DNS metrics at %s: %s", stacktrace.GetParentFunctionName(), resolver.GetMetrics())
  175. }
  176. func DoGarbageCollection() {
  177. debug.SetGCPercent(5)
  178. debug.FreeOSMemory()
  179. }
  180. // conditionallyEnabledComponents implements the
  181. // protocol.ConditionallyEnabledComponents interface.
  182. type conditionallyEnabledComponents struct {
  183. }
  184. func (c conditionallyEnabledComponents) QUICEnabled() bool {
  185. return quic.Enabled()
  186. }
  187. func (c conditionallyEnabledComponents) RefractionNetworkingEnabled() bool {
  188. return refraction.Enabled()
  189. }
  190. // FileMigration represents the action of moving a file, or directory, to a new
  191. // location.
  192. type FileMigration struct {
  193. // Name is the name of the migration for logging because file paths are not
  194. // logged as they may contain sensitive information.
  195. Name string
  196. // OldPath is the current location of the file.
  197. OldPath string
  198. // NewPath is the location that the file should be moved to.
  199. NewPath string
  200. // IsDir should be set to true if the file is a directory.
  201. IsDir bool
  202. }
  203. // DoFileMigration performs the specified file move operation. An error will be
  204. // returned and the operation will not performed if: a file is expected, but a
  205. // directory is found; a directory is expected, but a file is found; or a file,
  206. // or directory, already exists at the target path of the move operation.
  207. // Note: an attempt is made to redact any file paths from the returned error.
  208. func DoFileMigration(migration FileMigration) error {
  209. // Prefix string added to any errors for debug purposes.
  210. errPrefix := ""
  211. if len(migration.Name) > 0 {
  212. errPrefix = fmt.Sprintf("(%s) ", migration.Name)
  213. }
  214. if !common.FileExists(migration.OldPath) {
  215. return errors.TraceNew(errPrefix + "old path does not exist")
  216. }
  217. info, err := os.Stat(migration.OldPath)
  218. if err != nil {
  219. return errors.Tracef(errPrefix+"error getting file info: %s", common.RedactFilePathsError(err, migration.OldPath))
  220. }
  221. if info.IsDir() != migration.IsDir {
  222. if migration.IsDir {
  223. return errors.TraceNew(errPrefix + "expected directory but found file")
  224. }
  225. return errors.TraceNew(errPrefix + "expected but found directory")
  226. }
  227. if common.FileExists(migration.NewPath) {
  228. return errors.TraceNew(errPrefix + "file already exists, will not overwrite")
  229. }
  230. err = os.Rename(migration.OldPath, migration.NewPath)
  231. if err != nil {
  232. return errors.Tracef(errPrefix+"renaming file failed with error %s", common.RedactFilePathsError(err, migration.OldPath, migration.NewPath))
  233. }
  234. return nil
  235. }
  236. // GetNetworkType returns a network type name, suitable for metrics, which is
  237. // derived from the network ID.
  238. func GetNetworkType(networkID string) string {
  239. // Unlike the logic in loggingNetworkIDGetter.GetNetworkID, we don't take the
  240. // arbitrary text before the first "-" since some platforms without network
  241. // detection support stub in random values to enable tactics. Instead we
  242. // check for and use the common network type prefixes currently used in
  243. // NetworkIDGetter implementations.
  244. if strings.HasPrefix(networkID, "VPN") {
  245. return "VPN"
  246. }
  247. if strings.HasPrefix(networkID, "WIFI") {
  248. return "WIFI"
  249. }
  250. if strings.HasPrefix(networkID, "MOBILE") {
  251. return "MOBILE"
  252. }
  253. return "UNKNOWN"
  254. }
  255. // IsInproxyCompatibleNetworkType indicates if the network type for the given
  256. // network ID is compatible with in-proxy operation.
  257. func IsInproxyCompatibleNetworkType(networkID string) bool {
  258. // When the network type is "VPN", the outer client (or MobileLibrary) has
  259. // detected that some other, non-Psiphon VPN is active. In this case,
  260. // most in-proxy operations are expected to fail.
  261. return GetNetworkType(networkID) != "VPN"
  262. }