utils.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. /*
  2. * Copyright (c) 2016, 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 common
  20. import (
  21. "bytes"
  22. "compress/zlib"
  23. "crypto/rand"
  24. "encoding/base64"
  25. "encoding/hex"
  26. "errors"
  27. "fmt"
  28. "io/ioutil"
  29. "math"
  30. "math/big"
  31. "runtime"
  32. "strings"
  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, error) {
  86. var padding []byte
  87. paddingSize, err := MakeSecureRandomInt(maxLength - minLength)
  88. if err != nil {
  89. return nil, ContextError(err)
  90. }
  91. paddingSize += minLength
  92. padding, err = MakeSecureRandomBytes(paddingSize)
  93. if err != nil {
  94. return nil, ContextError(err)
  95. }
  96. return padding, nil
  97. }
  98. // MakeRandomPeriod returns a random duration, within a given range.
  99. // In the unlikely case where an underlying MakeRandom functions fails,
  100. // the period is the minimum.
  101. func MakeRandomPeriod(min, max time.Duration) (time.Duration, error) {
  102. period, err := MakeSecureRandomInt64(max.Nanoseconds() - min.Nanoseconds())
  103. if err != nil {
  104. return 0, ContextError(err)
  105. }
  106. return min + time.Duration(period), nil
  107. }
  108. // MakeRandomStringHex returns a hex encoded random string.
  109. // byteLength specifies the pre-encoded data length.
  110. func MakeRandomStringHex(byteLength int) (string, error) {
  111. bytes, err := MakeSecureRandomBytes(byteLength)
  112. if err != nil {
  113. return "", ContextError(err)
  114. }
  115. return hex.EncodeToString(bytes), nil
  116. }
  117. // MakeRandomStringBase64 returns a base64 encoded random string.
  118. // byteLength specifies the pre-encoded data length.
  119. func MakeRandomStringBase64(byteLength int) (string, error) {
  120. bytes, err := MakeSecureRandomBytes(byteLength)
  121. if err != nil {
  122. return "", ContextError(err)
  123. }
  124. return base64.RawURLEncoding.EncodeToString(bytes), nil
  125. }
  126. // Jitter returns n +/- the given factor.
  127. // For example, for n = 100 and factor = 0.1, the
  128. // return value will be in the range [90, 110].
  129. func Jitter(n int64, factor float64) int64 {
  130. a := int64(math.Ceil(float64(n) * factor))
  131. r, _ := MakeSecureRandomInt64(2*a + 1)
  132. return n + r - a
  133. }
  134. // JitterDuration is a helper function that wraps Jitter.
  135. func JitterDuration(
  136. d time.Duration, factor float64) time.Duration {
  137. return time.Duration(Jitter(int64(d), factor))
  138. }
  139. // GetCurrentTimestamp returns the current time in UTC as
  140. // an RFC 3339 formatted string.
  141. func GetCurrentTimestamp() string {
  142. return time.Now().UTC().Format(time.RFC3339)
  143. }
  144. // TruncateTimestampToHour truncates an RFC 3339 formatted string
  145. // to hour granularity. If the input is not a valid format, the
  146. // result is "".
  147. func TruncateTimestampToHour(timestamp string) string {
  148. t, err := time.Parse(time.RFC3339, timestamp)
  149. if err != nil {
  150. return ""
  151. }
  152. return t.Truncate(1 * time.Hour).Format(time.RFC3339)
  153. }
  154. // getFunctionName is a helper that extracts a simple function name from
  155. // full name returned byruntime.Func.Name(). This is used to declutter
  156. // log messages containing function names.
  157. func getFunctionName(pc uintptr) string {
  158. funcName := runtime.FuncForPC(pc).Name()
  159. index := strings.LastIndex(funcName, "/")
  160. if index != -1 {
  161. funcName = funcName[index+1:]
  162. }
  163. return funcName
  164. }
  165. // GetParentContext returns the parent function name and source file
  166. // line number.
  167. func GetParentContext() string {
  168. pc, _, line, _ := runtime.Caller(2)
  169. return fmt.Sprintf("%s#%d", getFunctionName(pc), line)
  170. }
  171. // ContextError prefixes an error message with the current function
  172. // name and source file line number.
  173. func ContextError(err error) error {
  174. if err == nil {
  175. return nil
  176. }
  177. pc, _, line, _ := runtime.Caller(1)
  178. return fmt.Errorf("%s#%d: %s", getFunctionName(pc), line, err)
  179. }
  180. // Compress returns zlib compressed data
  181. func Compress(data []byte) []byte {
  182. var compressedData bytes.Buffer
  183. writer := zlib.NewWriter(&compressedData)
  184. writer.Write(data)
  185. writer.Close()
  186. return compressedData.Bytes()
  187. }
  188. // Decompress returns zlib decompressed data
  189. func Decompress(data []byte) ([]byte, error) {
  190. reader, err := zlib.NewReader(bytes.NewReader(data))
  191. if err != nil {
  192. return nil, ContextError(err)
  193. }
  194. uncompressedData, err := ioutil.ReadAll(reader)
  195. reader.Close()
  196. if err != nil {
  197. return nil, ContextError(err)
  198. }
  199. return uncompressedData, nil
  200. }