utils.go 8.7 KB

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