utils.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. const (
  124. CompressionNone = int32(0)
  125. CompressionZlib = int32(1)
  126. )
  127. // Compress compresses data with the specified algorithm.
  128. func Compress(compression int32, data []byte) ([]byte, error) {
  129. if compression == CompressionNone {
  130. return data, nil
  131. }
  132. if compression != CompressionZlib {
  133. return nil, errors.TraceNew("unknown compression algorithm")
  134. }
  135. var compressedData bytes.Buffer
  136. writer := zlib.NewWriter(&compressedData)
  137. _, err := writer.Write(data)
  138. if err != nil {
  139. return nil, errors.Trace(err)
  140. }
  141. _ = writer.Close()
  142. return compressedData.Bytes(), nil
  143. }
  144. // Decompress decompresses data with the specified algorithm.
  145. func Decompress(compression int32, data []byte) ([]byte, error) {
  146. if compression == CompressionNone {
  147. return data, nil
  148. }
  149. if compression != CompressionZlib {
  150. return nil, errors.TraceNew("unknown compression algorithm")
  151. }
  152. reader, err := zlib.NewReader(bytes.NewReader(data))
  153. if err != nil {
  154. return nil, errors.Trace(err)
  155. }
  156. uncompressedData, err := ioutil.ReadAll(reader)
  157. _ = reader.Close()
  158. if err != nil {
  159. return nil, errors.Trace(err)
  160. }
  161. return uncompressedData, nil
  162. }
  163. // FormatByteCount returns a string representation of the specified
  164. // byte count in conventional, human-readable format.
  165. func FormatByteCount(bytes uint64) string {
  166. // 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
  167. base := uint64(1024)
  168. if bytes < base {
  169. return fmt.Sprintf("%dB", bytes)
  170. }
  171. exp := int(math.Log(float64(bytes)) / math.Log(float64(base)))
  172. return fmt.Sprintf(
  173. "%.1f%c", float64(bytes)/math.Pow(float64(base), float64(exp)), "KMGTPEZ"[exp-1])
  174. }
  175. // CopyBuffer calls io.CopyBuffer, masking out any src.WriteTo or dst.ReadFrom
  176. // to force use of the specified buf.
  177. func CopyBuffer(dst io.Writer, src io.Reader, buf []byte) (written int64, err error) {
  178. return io.CopyBuffer(struct{ io.Writer }{dst}, struct{ io.Reader }{src}, buf)
  179. }
  180. func CopyNBuffer(dst io.Writer, src io.Reader, n int64, buf []byte) (written int64, err error) {
  181. // Based on io.CopyN:
  182. // https://github.com/golang/go/blob/release-branch.go1.11/src/io/io.go#L339
  183. written, err = CopyBuffer(dst, io.LimitReader(src, n), buf)
  184. if written == n {
  185. return n, nil
  186. }
  187. if written < n && err == nil {
  188. err = io.EOF
  189. }
  190. return
  191. }
  192. // FileExists returns true if a file, or directory, exists at the given path.
  193. func FileExists(filePath string) bool {
  194. if _, err := os.Stat(filePath); err != nil && os.IsNotExist(err) {
  195. return false
  196. }
  197. return true
  198. }
  199. // SafeParseURL wraps url.Parse, stripping the input URL from any error
  200. // message. This allows logging url.Parse errors without unintentially logging
  201. // PII that may appear in the input URL.
  202. func SafeParseURL(rawurl string) (*url.URL, error) {
  203. parsedURL, err := url.Parse(rawurl)
  204. if err != nil {
  205. // Unwrap yields just the url.Error error field without the url.Error URL
  206. // and operation fields.
  207. err = std_errors.Unwrap(err)
  208. if err == nil {
  209. err = std_errors.New("SafeParseURL: Unwrap failed")
  210. } else {
  211. err = fmt.Errorf("url.Parse: %v", err)
  212. }
  213. }
  214. return parsedURL, err
  215. }
  216. // SafeParseRequestURI wraps url.ParseRequestURI, stripping the input URL from
  217. // any error message. This allows logging url.ParseRequestURI errors without
  218. // unintentially logging PII that may appear in the input URL.
  219. func SafeParseRequestURI(rawurl string) (*url.URL, error) {
  220. parsedURL, err := url.ParseRequestURI(rawurl)
  221. if err != nil {
  222. err = std_errors.Unwrap(err)
  223. if err == nil {
  224. err = std_errors.New("SafeParseRequestURI: Unwrap failed")
  225. } else {
  226. err = fmt.Errorf("url.ParseRequestURI: %v", err)
  227. }
  228. }
  229. return parsedURL, err
  230. }
  231. // SleepWithContext returns after the specified duration or once the input ctx
  232. // is done, whichever is first.
  233. func SleepWithContext(ctx context.Context, duration time.Duration) {
  234. timer := time.NewTimer(duration)
  235. defer timer.Stop()
  236. select {
  237. case <-timer.C:
  238. case <-ctx.Done():
  239. }
  240. }
  241. // SleepWithJitter returns after the specified duration, with random jitter
  242. // applied, or once the input ctx is done, whichever is first.
  243. func SleepWithJitter(ctx context.Context, duration time.Duration, jitter float64) {
  244. timer := time.NewTimer(prng.JitterDuration(duration, jitter))
  245. defer timer.Stop()
  246. select {
  247. case <-ctx.Done():
  248. case <-timer.C:
  249. }
  250. }
  251. // ValueOrDefault returns the input value, or, when value is the zero value of
  252. // its type, defaultValue.
  253. func ValueOrDefault[T comparable](value, defaultValue T) T {
  254. var zero T
  255. if value == zero {
  256. return defaultValue
  257. }
  258. return value
  259. }
  260. // MergeContextCancel returns a context which has the properties of the 1st
  261. // input content and merges in the cancellation signal of the 2nd context, so
  262. // the returned context is cancelled when either input context is cancelled.
  263. //
  264. // See (and adapted from): https://pkg.go.dev/context#example-AfterFunc-Merge
  265. func MergeContextCancel(ctx, cancelCtx context.Context) (context.Context, context.CancelFunc) {
  266. ctx, cancel := context.WithCancelCause(ctx)
  267. stop := context.AfterFunc(cancelCtx, func() {
  268. cancel(context.Cause(cancelCtx))
  269. })
  270. return ctx, func() {
  271. stop()
  272. cancel(context.Canceled)
  273. }
  274. }
  275. // MaxDuration returns the maximum duration in durations or 0 if durations is
  276. // empty.
  277. func MaxDuration(durations ...time.Duration) time.Duration {
  278. if len(durations) == 0 {
  279. return 0
  280. }
  281. max := durations[0]
  282. for _, d := range durations[1:] {
  283. if d > max {
  284. max = d
  285. }
  286. }
  287. return max
  288. }
  289. // ToRandomASCIICasing returns s with each ASCII letter randomly mapped to
  290. // either its upper or lower case.
  291. func ToRandomASCIICasing(s string, seed *prng.Seed) string {
  292. PRNG := prng.NewPRNGWithSeed(seed)
  293. var b strings.Builder
  294. b.Grow(len(s))
  295. for _, r := range s {
  296. isLower := ('a' <= r && r <= 'z')
  297. isUpper := ('A' <= r && r <= 'Z')
  298. if (isLower || isUpper) && PRNG.FlipCoin() {
  299. b.WriteRune(r ^ 0x20)
  300. } else {
  301. b.WriteRune(r)
  302. }
  303. }
  304. return b.String()
  305. }