util.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. package util
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math/rand"
  9. "net/netip"
  10. "os"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/gabriel-vasile/mimetype"
  17. "golang.org/x/term"
  18. )
  19. const (
  20. randomStringCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  21. )
  22. var (
  23. random = rand.New(rand.NewSource(time.Now().UnixNano()))
  24. randomMutex = sync.Mutex{}
  25. sizeStrRegex = regexp.MustCompile(`(?i)^(\d+)([gmkb])?$`)
  26. errInvalidPriority = errors.New("invalid priority")
  27. noQuotesRegex = regexp.MustCompile(`^[-_./:@a-zA-Z0-9]+$`)
  28. )
  29. // FileExists checks if a file exists, and returns true if it does
  30. func FileExists(filename string) bool {
  31. stat, _ := os.Stat(filename)
  32. return stat != nil
  33. }
  34. // Contains returns true if needle is contained in haystack
  35. func Contains[T comparable](haystack []T, needle T) bool {
  36. for _, s := range haystack {
  37. if s == needle {
  38. return true
  39. }
  40. }
  41. return false
  42. }
  43. // ContainsIP returns true if any one of the of prefixes contains the ip.
  44. func ContainsIP(haystack []netip.Prefix, needle netip.Addr) bool {
  45. for _, s := range haystack {
  46. if s.Contains(needle) {
  47. return true
  48. }
  49. }
  50. return false
  51. }
  52. // ContainsAll returns true if all needles are contained in haystack
  53. func ContainsAll[T comparable](haystack []T, needles []T) bool {
  54. matches := 0
  55. for _, s := range haystack {
  56. for _, needle := range needles {
  57. if s == needle {
  58. matches++
  59. }
  60. }
  61. }
  62. return matches == len(needles)
  63. }
  64. // SplitNoEmpty splits a string using strings.Split, but filters out empty strings
  65. func SplitNoEmpty(s string, sep string) []string {
  66. res := make([]string, 0)
  67. for _, r := range strings.Split(s, sep) {
  68. if r != "" {
  69. res = append(res, r)
  70. }
  71. }
  72. return res
  73. }
  74. // SplitKV splits a string into a key/value pair using a separator, and trimming space. If the separator
  75. // is not found, key is empty.
  76. func SplitKV(s string, sep string) (key string, value string) {
  77. kv := strings.SplitN(strings.TrimSpace(s), sep, 2)
  78. if len(kv) == 2 {
  79. return strings.TrimSpace(kv[0]), strings.TrimSpace(kv[1])
  80. }
  81. return "", strings.TrimSpace(kv[0])
  82. }
  83. // LastString returns the last string in a slice, or def if s is empty
  84. func LastString(s []string, def string) string {
  85. if len(s) == 0 {
  86. return def
  87. }
  88. return s[len(s)-1]
  89. }
  90. // RandomString returns a random string with a given length
  91. func RandomString(length int) string {
  92. randomMutex.Lock() // Who would have thought that random.Intn() is not thread-safe?!
  93. defer randomMutex.Unlock()
  94. b := make([]byte, length)
  95. for i := range b {
  96. b[i] = randomStringCharset[random.Intn(len(randomStringCharset))]
  97. }
  98. return string(b)
  99. }
  100. // ValidRandomString returns true if the given string matches the format created by RandomString
  101. func ValidRandomString(s string, length int) bool {
  102. if len(s) != length {
  103. return false
  104. }
  105. for _, c := range strings.Split(s, "") {
  106. if !strings.Contains(randomStringCharset, c) {
  107. return false
  108. }
  109. }
  110. return true
  111. }
  112. // ParsePriority parses a priority string into its equivalent integer value
  113. func ParsePriority(priority string) (int, error) {
  114. p := strings.TrimSpace(strings.ToLower(priority))
  115. switch p {
  116. case "":
  117. return 0, nil
  118. case "1", "min":
  119. return 1, nil
  120. case "2", "low":
  121. return 2, nil
  122. case "3", "default":
  123. return 3, nil
  124. case "4", "high":
  125. return 4, nil
  126. case "5", "max", "urgent":
  127. return 5, nil
  128. default:
  129. // Ignore new HTTP Priority header (see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-priority)
  130. // Cloudflare adds this to requests when forwarding to the backend (ntfy), so we just ignore it.
  131. if strings.HasPrefix(p, "u=") {
  132. return 3, nil
  133. }
  134. return 0, errInvalidPriority
  135. }
  136. }
  137. // PriorityString converts a priority number to a string
  138. func PriorityString(priority int) (string, error) {
  139. switch priority {
  140. case 0:
  141. return "default", nil
  142. case 1:
  143. return "min", nil
  144. case 2:
  145. return "low", nil
  146. case 3:
  147. return "default", nil
  148. case 4:
  149. return "high", nil
  150. case 5:
  151. return "max", nil
  152. default:
  153. return "", errInvalidPriority
  154. }
  155. }
  156. // ShortTopicURL shortens the topic URL to be human-friendly, removing the http:// or https://
  157. func ShortTopicURL(s string) string {
  158. return strings.TrimPrefix(strings.TrimPrefix(s, "https://"), "http://")
  159. }
  160. // DetectContentType probes the byte array b and returns mime type and file extension.
  161. // The filename is only used to override certain special cases.
  162. func DetectContentType(b []byte, filename string) (mimeType string, ext string) {
  163. if strings.HasSuffix(strings.ToLower(filename), ".apk") {
  164. return "application/vnd.android.package-archive", ".apk"
  165. }
  166. m := mimetype.Detect(b)
  167. mimeType, ext = m.String(), m.Extension()
  168. if ext == "" {
  169. ext = ".bin"
  170. }
  171. return
  172. }
  173. // ParseSize parses a size string like 2K or 2M into bytes. If no unit is found, e.g. 123, bytes is assumed.
  174. func ParseSize(s string) (int64, error) {
  175. matches := sizeStrRegex.FindStringSubmatch(s)
  176. if matches == nil {
  177. return -1, fmt.Errorf("invalid size %s", s)
  178. }
  179. value, err := strconv.Atoi(matches[1])
  180. if err != nil {
  181. return -1, fmt.Errorf("cannot convert number %s", matches[1])
  182. }
  183. switch strings.ToUpper(matches[2]) {
  184. case "G":
  185. return int64(value) * 1024 * 1024 * 1024, nil
  186. case "M":
  187. return int64(value) * 1024 * 1024, nil
  188. case "K":
  189. return int64(value) * 1024, nil
  190. default:
  191. return int64(value), nil
  192. }
  193. }
  194. // ReadPassword will read a password from STDIN. If the terminal supports it, it will not print the
  195. // input characters to the screen. If not, it'll just read using normal readline semantics (useful for testing).
  196. func ReadPassword(in io.Reader) ([]byte, error) {
  197. // If in is a file and a character device (a TTY), use term.ReadPassword
  198. if f, ok := in.(*os.File); ok {
  199. stat, err := f.Stat()
  200. if err != nil {
  201. return nil, err
  202. }
  203. if (stat.Mode() & os.ModeCharDevice) == os.ModeCharDevice {
  204. password, err := term.ReadPassword(int(f.Fd())) // This is always going to be 0
  205. if err != nil {
  206. return nil, err
  207. }
  208. return password, nil
  209. }
  210. }
  211. // Fallback: Manually read util \n if found, see #69 for details why this is so manual
  212. password := make([]byte, 0)
  213. buf := make([]byte, 1)
  214. for {
  215. _, err := in.Read(buf)
  216. if err == io.EOF || buf[0] == '\n' {
  217. break
  218. } else if err != nil {
  219. return nil, err
  220. } else if len(password) > 10240 {
  221. return nil, errors.New("passwords this long are not supported")
  222. }
  223. password = append(password, buf[0])
  224. }
  225. return password, nil
  226. }
  227. // BasicAuth encodes the Authorization header value for basic auth
  228. func BasicAuth(user, pass string) string {
  229. return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", user, pass))))
  230. }
  231. // MaybeMarshalJSON returns a JSON string of the given object, or "<cannot serialize>" if serialization failed.
  232. // This is useful for logging purposes where a failure doesn't matter that much.
  233. func MaybeMarshalJSON(v any) string {
  234. jsonBytes, err := json.MarshalIndent(v, "", " ")
  235. if err != nil {
  236. return "<cannot serialize>"
  237. }
  238. if len(jsonBytes) > 5000 {
  239. return string(jsonBytes)[:5000]
  240. }
  241. return string(jsonBytes)
  242. }
  243. // QuoteCommand combines a command array to a string, quoting arguments that need quoting.
  244. // This function is naive, and sometimes wrong. It is only meant for lo pretty-printing a command.
  245. //
  246. // Warning: Never use this function with the intent to run the resulting command.
  247. //
  248. // Example:
  249. //
  250. // []string{"ls", "-al", "Document Folder"} -> ls -al "Document Folder"
  251. func QuoteCommand(command []string) string {
  252. var quoted []string
  253. for _, c := range command {
  254. if noQuotesRegex.MatchString(c) {
  255. quoted = append(quoted, c)
  256. } else {
  257. quoted = append(quoted, fmt.Sprintf(`"%s"`, c))
  258. }
  259. }
  260. return strings.Join(quoted, " ")
  261. }