utils.go 7.1 KB

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