utils.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "math"
  28. "time"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/wildcard"
  31. )
  32. const RFC3339Milli = "2006-01-02T15:04:05.000Z07:00"
  33. // Contains is a helper function that returns true
  34. // if the target string is in the list.
  35. func Contains(list []string, target string) bool {
  36. for _, listItem := range list {
  37. if listItem == target {
  38. return true
  39. }
  40. }
  41. return false
  42. }
  43. // ContainsWildcard returns true if target matches
  44. // any of the patterns. Patterns may contain the
  45. // '*' wildcard.
  46. func ContainsWildcard(patterns []string, target string) bool {
  47. for _, pattern := range patterns {
  48. if wildcard.Match(pattern, target) {
  49. return true
  50. }
  51. }
  52. return false
  53. }
  54. // ContainsAny returns true if any string in targets
  55. // is present in the list.
  56. func ContainsAny(list, targets []string) bool {
  57. for _, target := range targets {
  58. if Contains(list, target) {
  59. return true
  60. }
  61. }
  62. return false
  63. }
  64. // ContainsInt returns true if the target int is
  65. // in the list.
  66. func ContainsInt(list []int, target int) bool {
  67. for _, listItem := range list {
  68. if listItem == target {
  69. return true
  70. }
  71. }
  72. return false
  73. }
  74. // GetStringSlice converts an interface{} which is
  75. // of type []interace{}, and with the type of each
  76. // element a string, to []string.
  77. func GetStringSlice(value interface{}) ([]string, bool) {
  78. slice, ok := value.([]interface{})
  79. if !ok {
  80. return nil, false
  81. }
  82. strSlice := make([]string, len(slice))
  83. for index, element := range slice {
  84. str, ok := element.(string)
  85. if !ok {
  86. return nil, false
  87. }
  88. strSlice[index] = str
  89. }
  90. return strSlice, true
  91. }
  92. // MakeSecureRandomBytes is a helper function that wraps
  93. // crypto/rand.Read.
  94. func MakeSecureRandomBytes(length int) ([]byte, error) {
  95. randomBytes := make([]byte, length)
  96. n, err := rand.Read(randomBytes)
  97. if err != nil {
  98. return nil, errors.Trace(err)
  99. }
  100. if n != length {
  101. return nil, errors.TraceNew("insufficient random bytes")
  102. }
  103. return randomBytes, nil
  104. }
  105. // GetCurrentTimestamp returns the current time in UTC as
  106. // an RFC 3339 formatted string.
  107. func GetCurrentTimestamp() string {
  108. return time.Now().UTC().Format(time.RFC3339)
  109. }
  110. // TruncateTimestampToHour truncates an RFC 3339 formatted string
  111. // to hour granularity. If the input is not a valid format, the
  112. // result is "".
  113. func TruncateTimestampToHour(timestamp string) string {
  114. t, err := time.Parse(time.RFC3339, timestamp)
  115. if err != nil {
  116. return ""
  117. }
  118. return t.Truncate(1 * time.Hour).Format(time.RFC3339)
  119. }
  120. // Compress returns zlib compressed data
  121. func Compress(data []byte) []byte {
  122. var compressedData bytes.Buffer
  123. writer := zlib.NewWriter(&compressedData)
  124. writer.Write(data)
  125. writer.Close()
  126. return compressedData.Bytes()
  127. }
  128. // Decompress returns zlib decompressed data
  129. func Decompress(data []byte) ([]byte, error) {
  130. reader, err := zlib.NewReader(bytes.NewReader(data))
  131. if err != nil {
  132. return nil, errors.Trace(err)
  133. }
  134. uncompressedData, err := ioutil.ReadAll(reader)
  135. reader.Close()
  136. if err != nil {
  137. return nil, errors.Trace(err)
  138. }
  139. return uncompressedData, nil
  140. }
  141. // FormatByteCount returns a string representation of the specified
  142. // byte count in conventional, human-readable format.
  143. func FormatByteCount(bytes uint64) string {
  144. // 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
  145. base := uint64(1024)
  146. if bytes < base {
  147. return fmt.Sprintf("%dB", bytes)
  148. }
  149. exp := int(math.Log(float64(bytes)) / math.Log(float64(base)))
  150. return fmt.Sprintf(
  151. "%.1f%c", float64(bytes)/math.Pow(float64(base), float64(exp)), "KMGTPEZ"[exp-1])
  152. }
  153. func CopyNBuffer(dst io.Writer, src io.Reader, n int64, buf []byte) (written int64, err error) {
  154. // Based on io.CopyN:
  155. // https://github.com/golang/go/blob/release-branch.go1.11/src/io/io.go#L339
  156. written, err = io.CopyBuffer(dst, io.LimitReader(src, n), buf)
  157. if written == n {
  158. return n, nil
  159. }
  160. if written < n && err == nil {
  161. err = io.EOF
  162. }
  163. return
  164. }