utils.go 6.9 KB

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