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. "context"
  24. "crypto/rand"
  25. std_errors "errors"
  26. "fmt"
  27. "io"
  28. "io/ioutil"
  29. "math"
  30. "net/url"
  31. "os"
  32. "time"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/wildcard"
  36. )
  37. const RFC3339Milli = "2006-01-02T15:04:05.000Z07:00"
  38. // Contains is a helper function that returns true
  39. // if the target string is in the list.
  40. func Contains(list []string, target string) bool {
  41. for _, listItem := range list {
  42. if listItem == target {
  43. return true
  44. }
  45. }
  46. return false
  47. }
  48. // ContainsWildcard returns true if target matches
  49. // any of the patterns. Patterns may contain the
  50. // '*' wildcard.
  51. func ContainsWildcard(patterns []string, target string) bool {
  52. for _, pattern := range patterns {
  53. if wildcard.Match(pattern, target) {
  54. return true
  55. }
  56. }
  57. return false
  58. }
  59. // ContainsAny returns true if any string in targets
  60. // is present in the list.
  61. func ContainsAny(list, targets []string) bool {
  62. for _, target := range targets {
  63. if Contains(list, target) {
  64. return true
  65. }
  66. }
  67. return false
  68. }
  69. // ContainsInt returns true if the target int is
  70. // in the list.
  71. func ContainsInt(list []int, target int) bool {
  72. for _, listItem := range list {
  73. if listItem == target {
  74. return true
  75. }
  76. }
  77. return false
  78. }
  79. // GetStringSlice converts an interface{} which is
  80. // of type []interace{}, and with the type of each
  81. // element a string, to []string.
  82. func GetStringSlice(value interface{}) ([]string, bool) {
  83. slice, ok := value.([]interface{})
  84. if !ok {
  85. return nil, false
  86. }
  87. strSlice := make([]string, len(slice))
  88. for index, element := range slice {
  89. str, ok := element.(string)
  90. if !ok {
  91. return nil, false
  92. }
  93. strSlice[index] = str
  94. }
  95. return strSlice, true
  96. }
  97. // MakeSecureRandomBytes is a helper function that wraps
  98. // crypto/rand.Read.
  99. func MakeSecureRandomBytes(length int) ([]byte, error) {
  100. randomBytes := make([]byte, length)
  101. _, err := rand.Read(randomBytes)
  102. if err != nil {
  103. return nil, errors.Trace(err)
  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. // Compress returns zlib compressed data
  123. func Compress(data []byte) []byte {
  124. var compressedData bytes.Buffer
  125. writer := zlib.NewWriter(&compressedData)
  126. writer.Write(data)
  127. writer.Close()
  128. return compressedData.Bytes()
  129. }
  130. // Decompress returns zlib decompressed data
  131. func Decompress(data []byte) ([]byte, error) {
  132. reader, err := zlib.NewReader(bytes.NewReader(data))
  133. if err != nil {
  134. return nil, errors.Trace(err)
  135. }
  136. uncompressedData, err := ioutil.ReadAll(reader)
  137. reader.Close()
  138. if err != nil {
  139. return nil, errors.Trace(err)
  140. }
  141. return uncompressedData, nil
  142. }
  143. // FormatByteCount returns a string representation of the specified
  144. // byte count in conventional, human-readable format.
  145. func FormatByteCount(bytes uint64) string {
  146. // 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
  147. base := uint64(1024)
  148. if bytes < base {
  149. return fmt.Sprintf("%dB", bytes)
  150. }
  151. exp := int(math.Log(float64(bytes)) / math.Log(float64(base)))
  152. return fmt.Sprintf(
  153. "%.1f%c", float64(bytes)/math.Pow(float64(base), float64(exp)), "KMGTPEZ"[exp-1])
  154. }
  155. // CopyBuffer calls io.CopyBuffer, masking out any src.WriteTo or dst.ReadFrom
  156. // to force use of the specified buf.
  157. func CopyBuffer(dst io.Writer, src io.Reader, buf []byte) (written int64, err error) {
  158. return io.CopyBuffer(struct{ io.Writer }{dst}, struct{ io.Reader }{src}, buf)
  159. }
  160. func CopyNBuffer(dst io.Writer, src io.Reader, n int64, buf []byte) (written int64, err error) {
  161. // Based on io.CopyN:
  162. // https://github.com/golang/go/blob/release-branch.go1.11/src/io/io.go#L339
  163. written, err = CopyBuffer(dst, io.LimitReader(src, n), buf)
  164. if written == n {
  165. return n, nil
  166. }
  167. if written < n && err == nil {
  168. err = io.EOF
  169. }
  170. return
  171. }
  172. // FileExists returns true if a file, or directory, exists at the given path.
  173. func FileExists(filePath string) bool {
  174. if _, err := os.Stat(filePath); err != nil && os.IsNotExist(err) {
  175. return false
  176. }
  177. return true
  178. }
  179. // SafeParseURL wraps url.Parse, stripping the input URL from any error
  180. // message. This allows logging url.Parse errors without unintentially logging
  181. // PII that may appear in the input URL.
  182. func SafeParseURL(rawurl string) (*url.URL, error) {
  183. parsedURL, err := url.Parse(rawurl)
  184. if err != nil {
  185. // Unwrap yields just the url.Error error field without the url.Error URL
  186. // and operation fields.
  187. err = std_errors.Unwrap(err)
  188. if err == nil {
  189. err = std_errors.New("SafeParseURL: Unwrap failed")
  190. } else {
  191. err = fmt.Errorf("url.Parse: %v", err)
  192. }
  193. }
  194. return parsedURL, err
  195. }
  196. // SafeParseRequestURI wraps url.ParseRequestURI, stripping the input URL from
  197. // any error message. This allows logging url.ParseRequestURI errors without
  198. // unintentially logging PII that may appear in the input URL.
  199. func SafeParseRequestURI(rawurl string) (*url.URL, error) {
  200. parsedURL, err := url.ParseRequestURI(rawurl)
  201. if err != nil {
  202. err = std_errors.Unwrap(err)
  203. if err == nil {
  204. err = std_errors.New("SafeParseRequestURI: Unwrap failed")
  205. } else {
  206. err = fmt.Errorf("url.ParseRequestURI: %v", err)
  207. }
  208. }
  209. return parsedURL, err
  210. }
  211. // SleepWithContext returns after the specified duration or once the input ctx
  212. // is done, whichever is first.
  213. func SleepWithContext(ctx context.Context, duration time.Duration) {
  214. timer := time.NewTimer(duration)
  215. defer timer.Stop()
  216. select {
  217. case <-timer.C:
  218. case <-ctx.Done():
  219. }
  220. }
  221. // SleepWithJitter returns after the specified duration, with random jitter
  222. // applied, or once the input ctx is done, whichever is first.
  223. func SleepWithJitter(ctx context.Context, duration time.Duration, jitter float64) {
  224. timer := time.NewTimer(prng.JitterDuration(duration, jitter))
  225. defer timer.Stop()
  226. select {
  227. case <-ctx.Done():
  228. case <-timer.C:
  229. }
  230. }
  231. // ValueOrDefault returns the input value, or, when value is the zero value of
  232. // its type, defaultValue.
  233. func ValueOrDefault[T comparable](value, defaultValue T) T {
  234. var zero T
  235. if value == zero {
  236. return defaultValue
  237. }
  238. return value
  239. }
  240. // MergeContextCancel returns a context which has the properties of the 1st
  241. // input content and merges in the cancellation signal of the 2nd context, so
  242. // the returned context is cancelled when either input context is cancelled.
  243. //
  244. // See (and adapted from): https://pkg.go.dev/context#example-AfterFunc-Merge
  245. func MergeContextCancel(ctx, cancelCtx context.Context) (context.Context, context.CancelFunc) {
  246. ctx, cancel := context.WithCancelCause(ctx)
  247. stop := context.AfterFunc(cancelCtx, func() {
  248. cancel(context.Cause(cancelCtx))
  249. })
  250. return ctx, func() {
  251. stop()
  252. cancel(context.Canceled)
  253. }
  254. }