utils.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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. "crypto/rand"
  22. "encoding/base64"
  23. "encoding/hex"
  24. "errors"
  25. "fmt"
  26. "math/big"
  27. "runtime"
  28. "strings"
  29. "time"
  30. )
  31. // Contains is a helper function that returns true
  32. // if the target string is in the list.
  33. func Contains(list []string, target string) bool {
  34. for _, listItem := range list {
  35. if listItem == target {
  36. return true
  37. }
  38. }
  39. return false
  40. }
  41. // FlipCoin is a helper function that randomly
  42. // returns true or false. If the underlying random
  43. // number generator fails, FlipCoin still returns
  44. // a result.
  45. func FlipCoin() bool {
  46. randomInt, _ := MakeSecureRandomInt(2)
  47. return randomInt == 1
  48. }
  49. // MakeSecureRandomInt is a helper function that wraps
  50. // MakeSecureRandomInt64.
  51. func MakeSecureRandomInt(max int) (int, error) {
  52. randomInt, err := MakeSecureRandomInt64(int64(max))
  53. return int(randomInt), err
  54. }
  55. // MakeSecureRandomInt64 is a helper function that wraps
  56. // crypto/rand.Int, which returns a uniform random value in [0, max).
  57. func MakeSecureRandomInt64(max int64) (int64, error) {
  58. randomInt, err := rand.Int(rand.Reader, big.NewInt(max))
  59. if err != nil {
  60. return 0, ContextError(err)
  61. }
  62. return randomInt.Int64(), nil
  63. }
  64. // MakeSecureRandomBytes is a helper function that wraps
  65. // crypto/rand.Read.
  66. func MakeSecureRandomBytes(length int) ([]byte, error) {
  67. randomBytes := make([]byte, length)
  68. n, err := rand.Read(randomBytes)
  69. if err != nil {
  70. return nil, ContextError(err)
  71. }
  72. if n != length {
  73. return nil, ContextError(errors.New("insufficient random bytes"))
  74. }
  75. return randomBytes, nil
  76. }
  77. // MakeSecureRandomPadding selects a random padding length in the indicated
  78. // range and returns a random byte array of the selected length.
  79. // In the unlikely case where an underlying MakeRandom functions fails,
  80. // the padding is length 0.
  81. func MakeSecureRandomPadding(minLength, maxLength int) ([]byte, error) {
  82. var padding []byte
  83. paddingSize, err := MakeSecureRandomInt(maxLength - minLength)
  84. if err != nil {
  85. return nil, ContextError(err)
  86. }
  87. paddingSize += minLength
  88. padding, err = MakeSecureRandomBytes(paddingSize)
  89. if err != nil {
  90. return nil, ContextError(err)
  91. }
  92. return padding, nil
  93. }
  94. // MakeRandomPeriod returns a random duration, within a given range.
  95. // In the unlikely case where an underlying MakeRandom functions fails,
  96. // the period is the minimum.
  97. func MakeRandomPeriod(min, max time.Duration) (time.Duration, error) {
  98. period, err := MakeSecureRandomInt64(max.Nanoseconds() - min.Nanoseconds())
  99. if err != nil {
  100. return 0, ContextError(err)
  101. }
  102. return min + time.Duration(period), nil
  103. }
  104. // MakeRandomStringHex returns a hex encoded random string.
  105. // byteLength specifies the pre-encoded data length.
  106. func MakeRandomStringHex(byteLength int) (string, error) {
  107. bytes, err := MakeSecureRandomBytes(byteLength)
  108. if err != nil {
  109. return "", ContextError(err)
  110. }
  111. return hex.EncodeToString(bytes), nil
  112. }
  113. // MakeRandomStringBase64 returns a base64 encoded random string.
  114. // byteLength specifies the pre-encoded data length.
  115. func MakeRandomStringBase64(byteLength int) (string, error) {
  116. bytes, err := MakeSecureRandomBytes(byteLength)
  117. if err != nil {
  118. return "", ContextError(err)
  119. }
  120. return base64.RawURLEncoding.EncodeToString(bytes), nil
  121. }
  122. // GetCurrentTimestamp returns the current time in UTC as
  123. // an RFC 3339 formatted string.
  124. func GetCurrentTimestamp() string {
  125. return time.Now().UTC().Format(time.RFC3339)
  126. }
  127. // TruncateTimestampToHour truncates an RFC 3339 formatted string
  128. // to hour granularity. If the input is not a valid format, the
  129. // result is "".
  130. func TruncateTimestampToHour(timestamp string) string {
  131. t, err := time.Parse(time.RFC3339, timestamp)
  132. if err != nil {
  133. return ""
  134. }
  135. return t.Truncate(1 * time.Hour).Format(time.RFC3339)
  136. }
  137. // getFunctionName is a helper that extracts a simple function name from
  138. // full name returned byruntime.Func.Name(). This is used to declutter
  139. // log messages containing function names.
  140. func getFunctionName(pc uintptr) string {
  141. funcName := runtime.FuncForPC(pc).Name()
  142. index := strings.LastIndex(funcName, "/")
  143. if index != -1 {
  144. funcName = funcName[index+1:]
  145. }
  146. return funcName
  147. }
  148. // GetParentContext returns the parent function name and source file
  149. // line number.
  150. func GetParentContext() string {
  151. pc, _, line, _ := runtime.Caller(2)
  152. return fmt.Sprintf("%s#%d", getFunctionName(pc), line)
  153. }
  154. // ContextError prefixes an error message with the current function
  155. // name and source file line number.
  156. func ContextError(err error) error {
  157. if err == nil {
  158. return nil
  159. }
  160. pc, _, line, _ := runtime.Caller(1)
  161. return fmt.Errorf("%s#%d: %s", getFunctionName(pc), line, err)
  162. }