util.go 10 KB

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