utils.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. std_errors "errors"
  25. "fmt"
  26. "io"
  27. "io/ioutil"
  28. "math"
  29. "net/url"
  30. "os"
  31. "time"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/wildcard"
  34. )
  35. const RFC3339Milli = "2006-01-02T15:04:05.000Z07:00"
  36. // Contains is a helper function that returns true
  37. // if the target string is in the list.
  38. func Contains(list []string, target string) bool {
  39. for _, listItem := range list {
  40. if listItem == target {
  41. return true
  42. }
  43. }
  44. return false
  45. }
  46. // ContainsWildcard returns true if target matches
  47. // any of the patterns. Patterns may contain the
  48. // '*' wildcard.
  49. func ContainsWildcard(patterns []string, target string) bool {
  50. for _, pattern := range patterns {
  51. if wildcard.Match(pattern, target) {
  52. return true
  53. }
  54. }
  55. return false
  56. }
  57. // ContainsAny returns true if any string in targets
  58. // is present in the list.
  59. func ContainsAny(list, targets []string) bool {
  60. for _, target := range targets {
  61. if Contains(list, target) {
  62. return true
  63. }
  64. }
  65. return false
  66. }
  67. // ContainsInt returns true if the target int is
  68. // in the list.
  69. func ContainsInt(list []int, target int) bool {
  70. for _, listItem := range list {
  71. if listItem == target {
  72. return true
  73. }
  74. }
  75. return false
  76. }
  77. // GetStringSlice converts an interface{} which is
  78. // of type []interace{}, and with the type of each
  79. // element a string, to []string.
  80. func GetStringSlice(value interface{}) ([]string, bool) {
  81. slice, ok := value.([]interface{})
  82. if !ok {
  83. return nil, false
  84. }
  85. strSlice := make([]string, len(slice))
  86. for index, element := range slice {
  87. str, ok := element.(string)
  88. if !ok {
  89. return nil, false
  90. }
  91. strSlice[index] = str
  92. }
  93. return strSlice, true
  94. }
  95. // MakeSecureRandomBytes is a helper function that wraps
  96. // crypto/rand.Read.
  97. func MakeSecureRandomBytes(length int) ([]byte, error) {
  98. randomBytes := make([]byte, length)
  99. _, err := rand.Read(randomBytes)
  100. if err != nil {
  101. return nil, errors.Trace(err)
  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. // CopyBuffer calls io.CopyBuffer, masking out any src.WriteTo or dst.ReadFrom
  154. // to force use of the specified buf.
  155. func CopyBuffer(dst io.Writer, src io.Reader, buf []byte) (written int64, err error) {
  156. return io.CopyBuffer(struct{ io.Writer }{dst}, struct{ io.Reader }{src}, buf)
  157. }
  158. func CopyNBuffer(dst io.Writer, src io.Reader, n int64, buf []byte) (written int64, err error) {
  159. // Based on io.CopyN:
  160. // https://github.com/golang/go/blob/release-branch.go1.11/src/io/io.go#L339
  161. written, err = CopyBuffer(dst, io.LimitReader(src, n), buf)
  162. if written == n {
  163. return n, nil
  164. }
  165. if written < n && err == nil {
  166. err = io.EOF
  167. }
  168. return
  169. }
  170. // FileExists returns true if a file, or directory, exists at the given path.
  171. func FileExists(filePath string) bool {
  172. if _, err := os.Stat(filePath); err != nil && os.IsNotExist(err) {
  173. return false
  174. }
  175. return true
  176. }
  177. // FileMigration represents the action of moving a file, or directory, to a new
  178. // location.
  179. type FileMigration struct {
  180. // OldPath is the current location of the file.
  181. OldPath string
  182. // NewPath is the location that the file should be moved to.
  183. NewPath string
  184. // IsDir should be set to true if the file is a directory.
  185. IsDir bool
  186. }
  187. // DoFileMigration performs the specified file move operation. An error will be
  188. // returned and the operation will not performed if: a file is expected, but a
  189. // directory is found; a directory is expected, but a file is found; or a file,
  190. // or directory, already exists at the target path of the move operation.
  191. func DoFileMigration(migration FileMigration) error {
  192. if !FileExists(migration.OldPath) {
  193. return errors.Tracef("%s does not exist", migration.OldPath)
  194. }
  195. info, err := os.Stat(migration.OldPath)
  196. if err != nil {
  197. return errors.Tracef("error getting file info of %s: %s", migration.OldPath, err.Error())
  198. }
  199. if info.IsDir() != migration.IsDir {
  200. if migration.IsDir {
  201. return errors.Tracef("expected directory %s to be directory but found file", migration.OldPath)
  202. }
  203. return errors.Tracef("expected %s to be file but found directory",
  204. migration.OldPath)
  205. }
  206. if FileExists(migration.NewPath) {
  207. return errors.Tracef("%s already exists, will not overwrite", migration.NewPath)
  208. }
  209. err = os.Rename(migration.OldPath, migration.NewPath)
  210. if err != nil {
  211. return errors.Tracef("renaming %s as %s failed with error %s", migration.OldPath, migration.NewPath, err.Error())
  212. }
  213. return nil
  214. }
  215. // SafeParseURL wraps url.Parse, stripping the input URL from any error
  216. // message. This allows logging url.Parse errors without unintentially logging
  217. // PII that may appear in the input URL.
  218. func SafeParseURL(rawurl string) (*url.URL, error) {
  219. parsedURL, err := url.Parse(rawurl)
  220. if err != nil {
  221. // Unwrap yields just the url.Error error field without the url.Error URL
  222. // and operation fields.
  223. err = std_errors.Unwrap(err)
  224. if err == nil {
  225. err = std_errors.New("SafeParseURL: Unwrap failed")
  226. } else {
  227. err = fmt.Errorf("url.Parse: %v", err)
  228. }
  229. }
  230. return parsedURL, err
  231. }
  232. // SafeParseRequestURI wraps url.ParseRequestURI, stripping the input URL from
  233. // any error message. This allows logging url.ParseRequestURI errors without
  234. // unintentially logging PII that may appear in the input URL.
  235. func SafeParseRequestURI(rawurl string) (*url.URL, error) {
  236. parsedURL, err := url.ParseRequestURI(rawurl)
  237. if err != nil {
  238. err = std_errors.Unwrap(err)
  239. if err == nil {
  240. err = std_errors.New("SafeParseRequestURI: Unwrap failed")
  241. } else {
  242. err = fmt.Errorf("url.ParseRequestURI: %v", err)
  243. }
  244. }
  245. return parsedURL, err
  246. }