utils.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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/rand"
  22. "crypto/x509"
  23. "encoding/base64"
  24. "encoding/hex"
  25. "errors"
  26. "fmt"
  27. "math/big"
  28. "net"
  29. "net/url"
  30. "os"
  31. "runtime"
  32. "strings"
  33. "sync"
  34. "syscall"
  35. "time"
  36. )
  37. // Contains is a helper function that returns true
  38. // if the target string is in the list.
  39. func Contains(list []string, target string) bool {
  40. for _, listItem := range list {
  41. if listItem == target {
  42. return true
  43. }
  44. }
  45. return false
  46. }
  47. // FlipCoin is a helper function that randomly
  48. // returns true or false. If the underlying random
  49. // number generator fails, FlipCoin still returns
  50. // a result.
  51. func FlipCoin() bool {
  52. randomInt, _ := MakeSecureRandomInt(2)
  53. return randomInt == 1
  54. }
  55. // MakeSecureRandomInt is a helper function that wraps
  56. // MakeSecureRandomInt64.
  57. func MakeSecureRandomInt(max int) (int, error) {
  58. randomInt, err := MakeSecureRandomInt64(int64(max))
  59. return int(randomInt), err
  60. }
  61. // MakeSecureRandomInt64 is a helper function that wraps
  62. // crypto/rand.Int, which returns a uniform random value in [0, max).
  63. func MakeSecureRandomInt64(max int64) (int64, error) {
  64. randomInt, err := rand.Int(rand.Reader, big.NewInt(max))
  65. if err != nil {
  66. return 0, ContextError(err)
  67. }
  68. return randomInt.Int64(), nil
  69. }
  70. // MakeSecureRandomBytes is a helper function that wraps
  71. // crypto/rand.Read.
  72. func MakeSecureRandomBytes(length int) ([]byte, error) {
  73. randomBytes := make([]byte, length)
  74. n, err := rand.Read(randomBytes)
  75. if err != nil {
  76. return nil, ContextError(err)
  77. }
  78. if n != length {
  79. return nil, ContextError(errors.New("insufficient random bytes"))
  80. }
  81. return randomBytes, nil
  82. }
  83. // MakeSecureRandomPadding selects a random padding length in the indicated
  84. // range and returns a random byte array of the selected length.
  85. // In the unlikely case where an underlying MakeRandom functions fails,
  86. // the padding is length 0.
  87. func MakeSecureRandomPadding(minLength, maxLength int) []byte {
  88. var padding []byte
  89. paddingSize, err := MakeSecureRandomInt(maxLength - minLength)
  90. if err != nil {
  91. NoticeAlert("MakeSecureRandomPadding: MakeSecureRandomInt failed")
  92. return make([]byte, 0)
  93. }
  94. paddingSize += minLength
  95. padding, err = MakeSecureRandomBytes(paddingSize)
  96. if err != nil {
  97. NoticeAlert("MakeSecureRandomPadding: MakeSecureRandomBytes failed")
  98. return make([]byte, 0)
  99. }
  100. return padding
  101. }
  102. // MakeRandomPeriod returns a random duration, within a given range.
  103. // In the unlikely case where an underlying MakeRandom functions fails,
  104. // the period is the minimum.
  105. func MakeRandomPeriod(min, max time.Duration) (duration time.Duration) {
  106. period, err := MakeSecureRandomInt64(max.Nanoseconds() - min.Nanoseconds())
  107. if err != nil {
  108. NoticeAlert("NextRandomRangePeriod: MakeSecureRandomInt64 failed")
  109. }
  110. duration = min + time.Duration(period)
  111. return
  112. }
  113. // MakeRandomStringHex returns a hex encoded random string.
  114. // byteLength specifies the pre-encoded data length.
  115. func MakeRandomStringHex(byteLength int) (string, error) {
  116. bytes, err := MakeSecureRandomBytes(byteLength)
  117. if err != nil {
  118. return "", ContextError(err)
  119. }
  120. return hex.EncodeToString(bytes), nil
  121. }
  122. // MakeRandomStringBase64 returns a base64 encoded random string.
  123. // byteLength specifies the pre-encoded data length.
  124. func MakeRandomStringBase64(byteLength int) (string, error) {
  125. bytes, err := MakeSecureRandomBytes(byteLength)
  126. if err != nil {
  127. return "", ContextError(err)
  128. }
  129. return base64.RawURLEncoding.EncodeToString(bytes), nil
  130. }
  131. func DecodeCertificate(encodedCertificate string) (certificate *x509.Certificate, err error) {
  132. derEncodedCertificate, err := base64.StdEncoding.DecodeString(encodedCertificate)
  133. if err != nil {
  134. return nil, ContextError(err)
  135. }
  136. certificate, err = x509.ParseCertificate(derEncodedCertificate)
  137. if err != nil {
  138. return nil, ContextError(err)
  139. }
  140. return certificate, nil
  141. }
  142. // FilterUrlError transforms an error, when it is a url.Error, removing
  143. // the URL value. This is to avoid logging private user data in cases
  144. // where the URL may be a user input value.
  145. // This function is used with errors returned by net/http and net/url,
  146. // which are (currently) of type url.Error. In particular, the round trip
  147. // function used by our HttpProxy, http.Client.Do, returns errors of type
  148. // url.Error, with the URL being the url sent from the user's tunneled
  149. // applications:
  150. // https://github.com/golang/go/blob/release-branch.go1.4/src/net/http/client.go#L394
  151. func FilterUrlError(err error) error {
  152. if urlErr, ok := err.(*url.Error); ok {
  153. err = &url.Error{
  154. Op: urlErr.Op,
  155. URL: "",
  156. Err: urlErr.Err,
  157. }
  158. }
  159. return err
  160. }
  161. // TrimError removes the middle of over-long error message strings
  162. func TrimError(err error) error {
  163. const MAX_LEN = 100
  164. message := fmt.Sprintf("%s", err)
  165. if len(message) > MAX_LEN {
  166. return errors.New(message[:MAX_LEN/2] + "..." + message[len(message)-MAX_LEN/2:])
  167. }
  168. return err
  169. }
  170. // getFunctionName is a helper that extracts a simple function name from
  171. // full name returned byruntime.Func.Name(). This is used to declutter
  172. // log messages containing function names.
  173. func getFunctionName(pc uintptr) string {
  174. funcName := runtime.FuncForPC(pc).Name()
  175. index := strings.LastIndex(funcName, "/")
  176. if index != -1 {
  177. funcName = funcName[index+1:]
  178. }
  179. return funcName
  180. }
  181. // GetParentContext returns the parent function name and source file
  182. // line number.
  183. func GetParentContext() string {
  184. pc, _, line, _ := runtime.Caller(2)
  185. return fmt.Sprintf("%s#%d", getFunctionName(pc), line)
  186. }
  187. // ContextError prefixes an error message with the current function
  188. // name and source file line number.
  189. func ContextError(err error) error {
  190. if err == nil {
  191. return nil
  192. }
  193. pc, _, line, _ := runtime.Caller(1)
  194. return fmt.Errorf("%s#%d: %s", getFunctionName(pc), line, err)
  195. }
  196. // IsAddressInUseError returns true when the err is due to EADDRINUSE/WSAEADDRINUSE.
  197. func IsAddressInUseError(err error) bool {
  198. if err, ok := err.(*net.OpError); ok {
  199. if err, ok := err.Err.(*os.SyscallError); ok {
  200. if err.Err == syscall.EADDRINUSE {
  201. return true
  202. }
  203. // Special case for Windows (WSAEADDRINUSE = 10048)
  204. if errno, ok := err.Err.(syscall.Errno); ok {
  205. if 10048 == int(errno) {
  206. return true
  207. }
  208. }
  209. }
  210. }
  211. return false
  212. }
  213. // SyncFileWriter wraps a file and exposes an io.Writer. At predefined
  214. // steps, the file is synced (flushed to disk) while writing.
  215. type SyncFileWriter struct {
  216. file *os.File
  217. step int
  218. count int
  219. }
  220. // NewSyncFileWriter creates a SyncFileWriter.
  221. func NewSyncFileWriter(file *os.File) *SyncFileWriter {
  222. return &SyncFileWriter{
  223. file: file,
  224. step: 2 << 16,
  225. count: 0}
  226. }
  227. // Write implements io.Writer with periodic file syncing.
  228. func (writer *SyncFileWriter) Write(p []byte) (n int, err error) {
  229. n, err = writer.file.Write(p)
  230. if err != nil {
  231. return
  232. }
  233. writer.count += n
  234. if writer.count >= writer.step {
  235. err = writer.file.Sync()
  236. writer.count = 0
  237. }
  238. return
  239. }
  240. // GetCurrentTimestamp returns the current time in UTC as
  241. // an RFC 3339 formatted string.
  242. func GetCurrentTimestamp() string {
  243. return time.Now().UTC().Format(time.RFC3339)
  244. }
  245. // TruncateTimestampToHour truncates an RFC 3339 formatted string
  246. // to hour granularity. If the input is not a valid format, the
  247. // result is "".
  248. func TruncateTimestampToHour(timestamp string) string {
  249. t, err := time.Parse(time.RFC3339, timestamp)
  250. if err != nil {
  251. NoticeAlert("failed to truncate timestamp: %s", err)
  252. return ""
  253. }
  254. return t.Truncate(1 * time.Hour).Format(time.RFC3339)
  255. }
  256. // IsFileChanged uses os.Stat to check if the name, size, or last mod time of the
  257. // file has changed (which is a heuristic, but sufficiently robust for users of this
  258. // function). Returns nil if file has not changed; otherwise, returns a changed
  259. // os.FileInfo which may be used to check for subsequent changes.
  260. func IsFileChanged(path string, previousFileInfo os.FileInfo) (os.FileInfo, error) {
  261. fileInfo, err := os.Stat(path)
  262. if err != nil {
  263. return nil, ContextError(err)
  264. }
  265. changed := previousFileInfo == nil ||
  266. fileInfo.Name() != previousFileInfo.Name() ||
  267. fileInfo.Size() != previousFileInfo.Size() ||
  268. fileInfo.ModTime() != previousFileInfo.ModTime()
  269. if !changed {
  270. return nil, nil
  271. }
  272. return fileInfo, nil
  273. }
  274. // Reloader represents a read-only, in-memory reloadable data object. For example,
  275. // a JSON data file that is loaded into memory and accessed for read-only lookups;
  276. // and from time to time may be reloaded from the same file, updating the memory
  277. // copy.
  278. type Reloader interface {
  279. // Reload reloads the data object. Reload returns a flag indicating if the
  280. // reloadable target has changed and reloaded or remains unchanged. By
  281. // convention, when reloading fails the Reloader should revert to its previous
  282. // in-memory state.
  283. Reload() (bool, error)
  284. // WillReload indicates if the data object is capable of reloading.
  285. WillReload() bool
  286. // LogDescription returns a description to be used for logging
  287. // events related to the Reloader.
  288. LogDescription() string
  289. }
  290. // ReloadableFile is a file-backed Reloader. This type is intended to be embedded
  291. // in other types that add the actual reloadable data structures.
  292. //
  293. // ReloadableFile has a multi-reader mutex for synchronization. Its Reload() function
  294. // will obtain a write lock before reloading the data structures. Actually reloading
  295. // action is to be provided via the reloadAction callback (for example, read the contents
  296. // of the file and unmarshall the contents into data structures). All read access to
  297. // the data structures should be guarded by RLocks on the ReloadableFile mutex.
  298. //
  299. // reloadAction must ensure that data structures revert to their previous state when
  300. // a reload fails.
  301. //
  302. type ReloadableFile struct {
  303. sync.RWMutex
  304. fileName string
  305. fileInfo os.FileInfo
  306. reloadAction func(string) error
  307. }
  308. // NewReloadableFile initializes a new ReloadableFile
  309. func NewReloadableFile(
  310. fileName string,
  311. reloadAction func(string) error) ReloadableFile {
  312. return ReloadableFile{
  313. fileName: fileName,
  314. reloadAction: reloadAction,
  315. }
  316. }
  317. // WillReload indicates whether the ReloadableFile is capable
  318. // of reloading.
  319. func (reloadable *ReloadableFile) WillReload() bool {
  320. return reloadable.fileName != ""
  321. }
  322. // Reload checks if the underlying file has changed (using IsFileChanged semantics, which
  323. // are heuristics) and, when changed, invokes the reloadAction callback which should
  324. // reload, from the file, the in-memory data structures.
  325. // All data structure readers should be blocked by the ReloadableFile mutex.
  326. func (reloadable *ReloadableFile) Reload() (bool, error) {
  327. if !reloadable.WillReload() {
  328. return false, nil
  329. }
  330. // Check whether the file has changed _before_ blocking readers
  331. reloadable.RLock()
  332. changedFileInfo, err := IsFileChanged(reloadable.fileName, reloadable.fileInfo)
  333. reloadable.RUnlock()
  334. if err != nil {
  335. return false, ContextError(err)
  336. }
  337. if changedFileInfo == nil {
  338. return false, nil
  339. }
  340. // ...now block readers
  341. reloadable.Lock()
  342. defer reloadable.Unlock()
  343. err = reloadable.reloadAction(reloadable.fileName)
  344. if err != nil {
  345. return false, ContextError(err)
  346. }
  347. reloadable.fileInfo = changedFileInfo
  348. return true, nil
  349. }
  350. func (reloadable *ReloadableFile) LogDescription() string {
  351. return reloadable.fileName
  352. }