utils.go 6.0 KB

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