util.go 10 KB

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