utils.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. const RFC3339Milli = "2006-01-02T15:04:05.000Z07:00"
  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. // ContainsAny returns true if any string in targets
  47. // is present in the list.
  48. func ContainsAny(list, targets []string) bool {
  49. for _, target := range targets {
  50. if Contains(list, target) {
  51. return true
  52. }
  53. }
  54. return false
  55. }
  56. // ContainsInt returns true if the target int is
  57. // in the list.
  58. func ContainsInt(list []int, target int) bool {
  59. for _, listItem := range list {
  60. if listItem == target {
  61. return true
  62. }
  63. }
  64. return false
  65. }
  66. // FlipCoin is a helper function that randomly
  67. // returns true or false.
  68. //
  69. // If the underlying random number generator fails,
  70. // FlipCoin still returns a result.
  71. func FlipCoin() bool {
  72. randomInt, _ := MakeSecureRandomInt(2)
  73. return randomInt == 1
  74. }
  75. // FlipWeightedCoin returns the result of a weighted
  76. // random coin flip. If the weight is 0.5, the outcome
  77. // is equally likely to be true or false. If the weight
  78. // is 1.0, the outcome is always true, and if the
  79. // weight is 0.0, the outcome is always false.
  80. //
  81. // Input weights > 1.0 are treated as 1.0.
  82. //
  83. // If the underlying random number generator fails,
  84. // FlipWeightedCoin still returns a result.
  85. func FlipWeightedCoin(weight float64) bool {
  86. if weight > 1.0 {
  87. weight = 1.0
  88. }
  89. n, _ := MakeSecureRandomInt64(math.MaxInt64)
  90. f := float64(n) / float64(math.MaxInt64)
  91. return f > 1.0-weight
  92. }
  93. // MakeSecureRandomInt is a helper function that wraps
  94. // MakeSecureRandomInt64.
  95. func MakeSecureRandomInt(max int) (int, error) {
  96. randomInt, err := MakeSecureRandomInt64(int64(max))
  97. return int(randomInt), err
  98. }
  99. // MakeSecureRandomInt64 is a helper function that wraps
  100. // crypto/rand.Int, which returns a uniform random value in [0, max).
  101. func MakeSecureRandomInt64(max int64) (int64, error) {
  102. if max <= 0 {
  103. return 0, nil
  104. }
  105. randomInt, err := rand.Int(rand.Reader, big.NewInt(max))
  106. if err != nil {
  107. return 0, ContextError(err)
  108. }
  109. return randomInt.Int64(), nil
  110. }
  111. // MakeSecureRandomBytes is a helper function that wraps
  112. // crypto/rand.Read.
  113. func MakeSecureRandomBytes(length int) ([]byte, error) {
  114. randomBytes := make([]byte, length)
  115. n, err := rand.Read(randomBytes)
  116. if err != nil {
  117. return nil, ContextError(err)
  118. }
  119. if n != length {
  120. return nil, ContextError(errors.New("insufficient random bytes"))
  121. }
  122. return randomBytes, nil
  123. }
  124. // MakeSecureRandomPadding selects a random padding length in the indicated
  125. // range and returns a random byte array of the selected length.
  126. // If maxLength <= minLength, the padding is minLength.
  127. func MakeSecureRandomPadding(minLength, maxLength int) ([]byte, error) {
  128. var padding []byte
  129. paddingSize, err := MakeSecureRandomInt(maxLength - minLength)
  130. if err != nil {
  131. return nil, ContextError(err)
  132. }
  133. paddingSize += minLength
  134. padding, err = MakeSecureRandomBytes(paddingSize)
  135. if err != nil {
  136. return nil, ContextError(err)
  137. }
  138. return padding, nil
  139. }
  140. // MakeRandomPeriod returns a random duration, within a given range.
  141. // If max <= min, the duration is min.
  142. func MakeRandomPeriod(min, max time.Duration) (time.Duration, error) {
  143. period, err := MakeSecureRandomInt64(max.Nanoseconds() - min.Nanoseconds())
  144. if err != nil {
  145. return 0, ContextError(err)
  146. }
  147. return min + time.Duration(period), nil
  148. }
  149. // MakeRandomStringHex returns a hex encoded random string.
  150. // byteLength specifies the pre-encoded data length.
  151. func MakeRandomStringHex(byteLength int) (string, error) {
  152. bytes, err := MakeSecureRandomBytes(byteLength)
  153. if err != nil {
  154. return "", ContextError(err)
  155. }
  156. return hex.EncodeToString(bytes), nil
  157. }
  158. // MakeRandomStringBase64 returns a base64 encoded random string.
  159. // byteLength specifies the pre-encoded data length.
  160. func MakeRandomStringBase64(byteLength int) (string, error) {
  161. bytes, err := MakeSecureRandomBytes(byteLength)
  162. if err != nil {
  163. return "", ContextError(err)
  164. }
  165. return base64.RawURLEncoding.EncodeToString(bytes), nil
  166. }
  167. // Jitter returns n +/- the given factor.
  168. // For example, for n = 100 and factor = 0.1, the
  169. // return value will be in the range [90, 110].
  170. func Jitter(n int64, factor float64) int64 {
  171. a := int64(math.Ceil(float64(n) * factor))
  172. r, _ := MakeSecureRandomInt64(2*a + 1)
  173. return n + r - a
  174. }
  175. // JitterDuration is a helper function that wraps Jitter.
  176. func JitterDuration(
  177. d time.Duration, factor float64) time.Duration {
  178. return time.Duration(Jitter(int64(d), factor))
  179. }
  180. // GetCurrentTimestamp returns the current time in UTC as
  181. // an RFC 3339 formatted string.
  182. func GetCurrentTimestamp() string {
  183. return time.Now().UTC().Format(time.RFC3339)
  184. }
  185. // TruncateTimestampToHour truncates an RFC 3339 formatted string
  186. // to hour granularity. If the input is not a valid format, the
  187. // result is "".
  188. func TruncateTimestampToHour(timestamp string) string {
  189. t, err := time.Parse(time.RFC3339, timestamp)
  190. if err != nil {
  191. return ""
  192. }
  193. return t.Truncate(1 * time.Hour).Format(time.RFC3339)
  194. }
  195. // getFunctionName is a helper that extracts a simple function name from
  196. // full name returned byruntime.Func.Name(). This is used to declutter
  197. // log messages containing function names.
  198. func getFunctionName(pc uintptr) string {
  199. funcName := runtime.FuncForPC(pc).Name()
  200. index := strings.LastIndex(funcName, "/")
  201. if index != -1 {
  202. funcName = funcName[index+1:]
  203. }
  204. return funcName
  205. }
  206. // GetParentContext returns the parent function name and source file
  207. // line number.
  208. func GetParentContext() string {
  209. pc, _, line, _ := runtime.Caller(2)
  210. return fmt.Sprintf("%s#%d", getFunctionName(pc), line)
  211. }
  212. // ContextError prefixes an error message with the current function
  213. // name and source file line number.
  214. func ContextError(err error) error {
  215. if err == nil {
  216. return nil
  217. }
  218. pc, _, line, _ := runtime.Caller(1)
  219. return fmt.Errorf("%s#%d: %s", getFunctionName(pc), line, err)
  220. }
  221. // Compress returns zlib compressed data
  222. func Compress(data []byte) []byte {
  223. var compressedData bytes.Buffer
  224. writer := zlib.NewWriter(&compressedData)
  225. writer.Write(data)
  226. writer.Close()
  227. return compressedData.Bytes()
  228. }
  229. // Decompress returns zlib decompressed data
  230. func Decompress(data []byte) ([]byte, error) {
  231. reader, err := zlib.NewReader(bytes.NewReader(data))
  232. if err != nil {
  233. return nil, ContextError(err)
  234. }
  235. uncompressedData, err := ioutil.ReadAll(reader)
  236. reader.Close()
  237. if err != nil {
  238. return nil, ContextError(err)
  239. }
  240. return uncompressedData, nil
  241. }
  242. // FormatByteCount returns a string representation of the specified
  243. // byte count in conventional, human-readable format.
  244. func FormatByteCount(bytes uint64) string {
  245. // Based on: https://bitbucket.org/psiphon/psiphon-circumvention-system/src/b2884b0d0a491e55420ed1888aea20d00fefdb45/Android/app/src/main/java/com/psiphon3/psiphonlibrary/Utils.java?at=default#Utils.java-646
  246. base := uint64(1024)
  247. if bytes < base {
  248. return fmt.Sprintf("%dB", bytes)
  249. }
  250. exp := int(math.Log(float64(bytes)) / math.Log(float64(base)))
  251. return fmt.Sprintf(
  252. "%.1f%c", float64(bytes)/math.Pow(float64(base), float64(exp)), "KMGTPEZ"[exp-1])
  253. }