utils.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. "syscall"
  34. "time"
  35. )
  36. // Contains is a helper function that returns true
  37. // if the target string is in the list.
  38. func Contains(list []string, target string) bool {
  39. for _, listItem := range list {
  40. if listItem == target {
  41. return true
  42. }
  43. }
  44. return false
  45. }
  46. // FlipCoin is a helper function that randomly
  47. // returns true or false. If the underlying random
  48. // number generator fails, FlipCoin still returns
  49. // a result.
  50. func FlipCoin() bool {
  51. randomInt, _ := MakeSecureRandomInt(2)
  52. return randomInt == 1
  53. }
  54. // MakeSecureRandomInt is a helper function that wraps
  55. // MakeSecureRandomInt64.
  56. func MakeSecureRandomInt(max int) (int, error) {
  57. randomInt, err := MakeSecureRandomInt64(int64(max))
  58. return int(randomInt), err
  59. }
  60. // MakeSecureRandomInt64 is a helper function that wraps
  61. // crypto/rand.Int, which returns a uniform random value in [0, max).
  62. func MakeSecureRandomInt64(max int64) (int64, error) {
  63. randomInt, err := rand.Int(rand.Reader, big.NewInt(max))
  64. if err != nil {
  65. return 0, ContextError(err)
  66. }
  67. return randomInt.Int64(), nil
  68. }
  69. // MakeSecureRandomBytes is a helper function that wraps
  70. // crypto/rand.Read.
  71. func MakeSecureRandomBytes(length int) ([]byte, error) {
  72. randomBytes := make([]byte, length)
  73. n, err := rand.Read(randomBytes)
  74. if err != nil {
  75. return nil, ContextError(err)
  76. }
  77. if n != length {
  78. return nil, ContextError(errors.New("insufficient random bytes"))
  79. }
  80. return randomBytes, nil
  81. }
  82. // MakeSecureRandomPadding selects a random padding length in the indicated
  83. // range and returns a random byte array of the selected length.
  84. // In the unlikely case where an underlying MakeRandom functions fails,
  85. // the padding is length 0.
  86. func MakeSecureRandomPadding(minLength, maxLength int) []byte {
  87. var padding []byte
  88. paddingSize, err := MakeSecureRandomInt(maxLength - minLength)
  89. if err != nil {
  90. NoticeAlert("MakeSecureRandomPadding: MakeSecureRandomInt failed")
  91. return make([]byte, 0)
  92. }
  93. paddingSize += minLength
  94. padding, err = MakeSecureRandomBytes(paddingSize)
  95. if err != nil {
  96. NoticeAlert("MakeSecureRandomPadding: MakeSecureRandomBytes failed")
  97. return make([]byte, 0)
  98. }
  99. return padding
  100. }
  101. // MakeRandomPeriod returns a random duration, within a given range.
  102. // In the unlikely case where an underlying MakeRandom functions fails,
  103. // the period is the minimum.
  104. func MakeRandomPeriod(min, max time.Duration) (duration time.Duration) {
  105. period, err := MakeSecureRandomInt64(max.Nanoseconds() - min.Nanoseconds())
  106. if err != nil {
  107. NoticeAlert("NextRandomRangePeriod: MakeSecureRandomInt64 failed")
  108. }
  109. duration = min + time.Duration(period)
  110. return
  111. }
  112. // MakeRandomStringHex returns a hex encoded random string.
  113. // byteLength specifies the pre-encoded data length.
  114. func MakeRandomStringHex(byteLength int) (string, error) {
  115. bytes, err := MakeSecureRandomBytes(byteLength)
  116. if err != nil {
  117. return "", ContextError(err)
  118. }
  119. return hex.EncodeToString(bytes), nil
  120. }
  121. // MakeRandomStringBase64 returns a base64 encoded random string.
  122. // byteLength specifies the pre-encoded data length.
  123. func MakeRandomStringBase64(byteLength int) (string, error) {
  124. bytes, err := MakeSecureRandomBytes(byteLength)
  125. if err != nil {
  126. return "", ContextError(err)
  127. }
  128. return base64.RawURLEncoding.EncodeToString(bytes), nil
  129. }
  130. func DecodeCertificate(encodedCertificate string) (certificate *x509.Certificate, err error) {
  131. derEncodedCertificate, err := base64.StdEncoding.DecodeString(encodedCertificate)
  132. if err != nil {
  133. return nil, ContextError(err)
  134. }
  135. certificate, err = x509.ParseCertificate(derEncodedCertificate)
  136. if err != nil {
  137. return nil, ContextError(err)
  138. }
  139. return certificate, nil
  140. }
  141. // FilterUrlError transforms an error, when it is a url.Error, removing
  142. // the URL value. This is to avoid logging private user data in cases
  143. // where the URL may be a user input value.
  144. // This function is used with errors returned by net/http and net/url,
  145. // which are (currently) of type url.Error. In particular, the round trip
  146. // function used by our HttpProxy, http.Client.Do, returns errors of type
  147. // url.Error, with the URL being the url sent from the user's tunneled
  148. // applications:
  149. // https://github.com/golang/go/blob/release-branch.go1.4/src/net/http/client.go#L394
  150. func FilterUrlError(err error) error {
  151. if urlErr, ok := err.(*url.Error); ok {
  152. err = &url.Error{
  153. Op: urlErr.Op,
  154. URL: "",
  155. Err: urlErr.Err,
  156. }
  157. }
  158. return err
  159. }
  160. // TrimError removes the middle of over-long error message strings
  161. func TrimError(err error) error {
  162. const MAX_LEN = 100
  163. message := fmt.Sprintf("%s", err)
  164. if len(message) > MAX_LEN {
  165. return errors.New(message[:MAX_LEN/2] + "..." + message[len(message)-MAX_LEN/2:])
  166. }
  167. return err
  168. }
  169. // getFunctionName is a helper that extracts a simple function name from
  170. // full name returned byruntime.Func.Name(). This is used to declutter
  171. // log messages containing function names.
  172. func getFunctionName(pc uintptr) string {
  173. funcName := runtime.FuncForPC(pc).Name()
  174. index := strings.LastIndex(funcName, "/")
  175. if index != -1 {
  176. funcName = funcName[index+1:]
  177. }
  178. return funcName
  179. }
  180. // GetParentContext returns the parent function name and source file
  181. // line number.
  182. func GetParentContext() string {
  183. pc, _, line, _ := runtime.Caller(2)
  184. return fmt.Sprintf("%s#%d", getFunctionName(pc), line)
  185. }
  186. // ContextError prefixes an error message with the current function
  187. // name and source file line number.
  188. func ContextError(err error) error {
  189. if err == nil {
  190. return nil
  191. }
  192. pc, _, line, _ := runtime.Caller(1)
  193. return fmt.Errorf("%s#%d: %s", getFunctionName(pc), line, err)
  194. }
  195. // IsAddressInUseError returns true when the err is due to EADDRINUSE/WSAEADDRINUSE.
  196. func IsAddressInUseError(err error) bool {
  197. if err, ok := err.(*net.OpError); ok {
  198. if err, ok := err.Err.(*os.SyscallError); ok {
  199. if err.Err == syscall.EADDRINUSE {
  200. return true
  201. }
  202. // Special case for Windows (WSAEADDRINUSE = 10048)
  203. if errno, ok := err.Err.(syscall.Errno); ok {
  204. if 10048 == int(errno) {
  205. return true
  206. }
  207. }
  208. }
  209. }
  210. return false
  211. }
  212. // SyncFileWriter wraps a file and exposes an io.Writer. At predefined
  213. // steps, the file is synced (flushed to disk) while writing.
  214. type SyncFileWriter struct {
  215. file *os.File
  216. step int
  217. count int
  218. }
  219. // NewSyncFileWriter creates a SyncFileWriter.
  220. func NewSyncFileWriter(file *os.File) *SyncFileWriter {
  221. return &SyncFileWriter{
  222. file: file,
  223. step: 2 << 16,
  224. count: 0}
  225. }
  226. // Write implements io.Writer with periodic file syncing.
  227. func (writer *SyncFileWriter) Write(p []byte) (n int, err error) {
  228. n, err = writer.file.Write(p)
  229. if err != nil {
  230. return
  231. }
  232. writer.count += n
  233. if writer.count >= writer.step {
  234. err = writer.file.Sync()
  235. writer.count = 0
  236. }
  237. return
  238. }
  239. // GetCurrentTimestamp returns the current time in UTC as
  240. // an RFC 3339 formatted string.
  241. func GetCurrentTimestamp() string {
  242. return time.Now().UTC().Format(time.RFC3339)
  243. }
  244. // TruncateTimestampToHour truncates an RFC 3339 formatted string
  245. // to hour granularity. If the input is not a valid format, the
  246. // result is "".
  247. func TruncateTimestampToHour(timestamp string) string {
  248. t, err := time.Parse(time.RFC3339, timestamp)
  249. if err != nil {
  250. NoticeAlert("failed to truncate timestamp: %s", err)
  251. return ""
  252. }
  253. return t.Truncate(1 * time.Hour).Format(time.RFC3339)
  254. }