utils.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. "errors"
  25. "fmt"
  26. "io"
  27. "io/ioutil"
  28. "math"
  29. "runtime"
  30. "strings"
  31. "time"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/wildcard"
  33. )
  34. const RFC3339Milli = "2006-01-02T15:04:05.000Z07:00"
  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. // ContainsWildcard returns true if target matches
  46. // any of the patterns. Patterns may contain the
  47. // '*' wildcard.
  48. func ContainsWildcard(patterns []string, target string) bool {
  49. for _, pattern := range patterns {
  50. if wildcard.Match(pattern, target) {
  51. return true
  52. }
  53. }
  54. return false
  55. }
  56. // ContainsAny returns true if any string in targets
  57. // is present in the list.
  58. func ContainsAny(list, targets []string) bool {
  59. for _, target := range targets {
  60. if Contains(list, target) {
  61. return true
  62. }
  63. }
  64. return false
  65. }
  66. // ContainsInt returns true if the target int is
  67. // in the list.
  68. func ContainsInt(list []int, target int) bool {
  69. for _, listItem := range list {
  70. if listItem == target {
  71. return true
  72. }
  73. }
  74. return false
  75. }
  76. // GetStringSlice converts an interface{} which is
  77. // of type []interace{}, and with the type of each
  78. // element a string, to []string.
  79. func GetStringSlice(value interface{}) ([]string, bool) {
  80. slice, ok := value.([]interface{})
  81. if !ok {
  82. return nil, false
  83. }
  84. strSlice := make([]string, len(slice))
  85. for index, element := range slice {
  86. str, ok := element.(string)
  87. if !ok {
  88. return nil, false
  89. }
  90. strSlice[index] = str
  91. }
  92. return strSlice, true
  93. }
  94. // MakeSecureRandomBytes is a helper function that wraps
  95. // crypto/rand.Read.
  96. func MakeSecureRandomBytes(length int) ([]byte, error) {
  97. randomBytes := make([]byte, length)
  98. n, err := rand.Read(randomBytes)
  99. if err != nil {
  100. return nil, ContextError(err)
  101. }
  102. if n != length {
  103. return nil, ContextError(errors.New("insufficient random bytes"))
  104. }
  105. return randomBytes, nil
  106. }
  107. // GetCurrentTimestamp returns the current time in UTC as
  108. // an RFC 3339 formatted string.
  109. func GetCurrentTimestamp() string {
  110. return time.Now().UTC().Format(time.RFC3339)
  111. }
  112. // TruncateTimestampToHour truncates an RFC 3339 formatted string
  113. // to hour granularity. If the input is not a valid format, the
  114. // result is "".
  115. func TruncateTimestampToHour(timestamp string) string {
  116. t, err := time.Parse(time.RFC3339, timestamp)
  117. if err != nil {
  118. return ""
  119. }
  120. return t.Truncate(1 * time.Hour).Format(time.RFC3339)
  121. }
  122. // getFunctionName is a helper that extracts a simple function name from
  123. // full name returned byruntime.Func.Name(). This is used to declutter
  124. // log messages containing function names.
  125. func getFunctionName(pc uintptr) string {
  126. funcName := runtime.FuncForPC(pc).Name()
  127. index := strings.LastIndex(funcName, "/")
  128. if index != -1 {
  129. funcName = funcName[index+1:]
  130. }
  131. return funcName
  132. }
  133. // GetParentContext returns the parent function name and source file
  134. // line number.
  135. func GetParentContext() string {
  136. pc, _, line, _ := runtime.Caller(2)
  137. return fmt.Sprintf("%s#%d", getFunctionName(pc), line)
  138. }
  139. // ContextError prefixes an error message with the current function
  140. // name and source file line number.
  141. func ContextError(err error) error {
  142. if err == nil {
  143. return nil
  144. }
  145. pc, _, line, _ := runtime.Caller(1)
  146. return fmt.Errorf("%s#%d: %s", getFunctionName(pc), line, err)
  147. }
  148. // ContextErrorMsg works like ContextError, but adds a message string to
  149. // the error message.
  150. func ContextErrorMsg(err error, message string) error {
  151. if err == nil {
  152. return nil
  153. }
  154. pc, _, line, _ := runtime.Caller(1)
  155. return fmt.Errorf("%s#%d: %s: %s", getFunctionName(pc), line, message, err)
  156. }
  157. // Compress returns zlib compressed data
  158. func Compress(data []byte) []byte {
  159. var compressedData bytes.Buffer
  160. writer := zlib.NewWriter(&compressedData)
  161. writer.Write(data)
  162. writer.Close()
  163. return compressedData.Bytes()
  164. }
  165. // Decompress returns zlib decompressed data
  166. func Decompress(data []byte) ([]byte, error) {
  167. reader, err := zlib.NewReader(bytes.NewReader(data))
  168. if err != nil {
  169. return nil, ContextError(err)
  170. }
  171. uncompressedData, err := ioutil.ReadAll(reader)
  172. reader.Close()
  173. if err != nil {
  174. return nil, ContextError(err)
  175. }
  176. return uncompressedData, nil
  177. }
  178. // FormatByteCount returns a string representation of the specified
  179. // byte count in conventional, human-readable format.
  180. func FormatByteCount(bytes uint64) string {
  181. // 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
  182. base := uint64(1024)
  183. if bytes < base {
  184. return fmt.Sprintf("%dB", bytes)
  185. }
  186. exp := int(math.Log(float64(bytes)) / math.Log(float64(base)))
  187. return fmt.Sprintf(
  188. "%.1f%c", float64(bytes)/math.Pow(float64(base), float64(exp)), "KMGTPEZ"[exp-1])
  189. }
  190. func CopyNBuffer(dst io.Writer, src io.Reader, n int64, buf []byte) (written int64, err error) {
  191. // Based on io.CopyN:
  192. // https://github.com/golang/go/blob/release-branch.go1.11/src/io/io.go#L339
  193. written, err = io.CopyBuffer(dst, io.LimitReader(src, n), buf)
  194. if written == n {
  195. return n, nil
  196. }
  197. if written < n && err == nil {
  198. err = io.EOF
  199. }
  200. return
  201. }