utils.go 6.8 KB

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