Debian Codegraph @

util/util.go

raw
1 package util
2
3 import (
4 "bytes"
5 crand "crypto/rand"
6 "encoding/base64"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io"
11 "math"
12 "net/netip"
13 "os"
14 "regexp"
15 "slices"
16 "strconv"
17 "strings"
18 "time"
19 "unicode/utf8"
20
21 "github.com/gabriel-vasile/mimetype"
22 "golang.org/x/term"
23 "golang.org/x/time/rate"
24 )
25
26 const (
27 randomStringCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
28 randomStringLowerCaseCharset = "abcdefghijklmnopqrstuvwxyz0123456789"
29 )
30
31 var (
32 sizeStrRegex = regexp.MustCompile(`(?i)^(\d+)([gmkb])?$`)
33 errInvalidPriority = errors.New("invalid priority")
34 noQuotesRegex = regexp.MustCompile(`^[-_./:@a-zA-Z0-9]+$`)
35 )
36
37 // Errors for UnmarshalJSON and UnmarshalJSONWithLimit functions
38 var (
39 ErrUnmarshalJSON = errors.New("unmarshalling JSON failed")
40 ErrTooLargeJSON = errors.New("too large JSON")
41 )
42
43 // FileExists checks if a file exists, and returns true if it does
44 func FileExists(filename string) bool {
45 stat, _ := os.Stat(filename)
46 return stat != nil
47 }
48
49 // Contains returns true if needle is contained in haystack
50 func Contains[T comparable](haystack []T, needle T) bool {
51 return slices.Contains(haystack, needle)
52 }
53
54 // ContainsIP returns true if any one of the of prefixes contains the ip.
55 func ContainsIP(haystack []netip.Prefix, needle netip.Addr) bool {
56 for _, s := range haystack {
57 if s.Contains(needle) {
58 return true
59 }
60 }
61 return false
62 }
63
64 // ContainsAll returns true if all needles are contained in haystack
65 func ContainsAll[T comparable](haystack []T, needles []T) bool {
66 for _, needle := range needles {
67 if !Contains(haystack, needle) {
68 return false
69 }
70 }
71 return true
72 }
73
74 // SplitNoEmpty splits a string using strings.Split, but filters out empty strings
75 func SplitNoEmpty(s string, sep string) []string {
76 res := make([]string, 0)
77 for _, r := range strings.Split(s, sep) {
78 if r != "" {
79 res = append(res, r)
80 }
81 }
82 return res
83 }
84
85 // SplitKV splits a string into a key/value pair using a separator, and trimming space. If the separator
86 // is not found, key is empty.
87 func SplitKV(s string, sep string) (key string, value string) {
88 kv := strings.SplitN(strings.TrimSpace(s), sep, 2)
89 if len(kv) == 2 {
90 return strings.TrimSpace(kv[0]), strings.TrimSpace(kv[1])
91 }
92 return "", strings.TrimSpace(kv[0])
93 }
94
95 // Map applies a function to each element of a slice and returns a new slice with the results
96 // Example: Map([]int{1, 2, 3}, func(i int) int { return i * 2 }) -> []int{2, 4, 6}
97 func Map[T any, U any](slice []T, f func(T) U) []U {
98 result := make([]U, len(slice))
99 for i, v := range slice {
100 result[i] = f(v)
101 }
102 return result
103 }
104
105 // Filter returns a new slice containing only the elements of the original slice for which the
106 // given function returns true.
107 func Filter[T any](slice []T, f func(T) bool) []T {
108 result := make([]T, 0)
109 for _, v := range slice {
110 if f(v) {
111 result = append(result, v)
112 }
113 }
114 return result
115 }
116
117 // Find returns the first element in the slice that satisfies the given function, and a boolean indicating
118 // whether such an element was found. If no element is found, it returns the zero value of T and false.
119 func Find[T any](slice []T, f func(T) bool) (T, bool) {
120 for _, v := range slice {
121 if f(v) {
122 return v, true
123 }
124 }
125 var zero T
126 return zero, false
127 }
128
129 // RandomString returns a random string with a given length
130 func RandomString(length int) string {
131 return RandomStringPrefix("", length)
132 }
133
134 // RandomStringPrefix returns a random string with a given length, with a prefix
135 func RandomStringPrefix(prefix string, length int) string {
136 return randomStringPrefixWithCharset(prefix, length, randomStringCharset)
137 }
138
139 // RandomLowerStringPrefix returns a random lowercase-only string with a given length, with a prefix
140 func RandomLowerStringPrefix(prefix string, length int) string {
141 return randomStringPrefixWithCharset(prefix, length, randomStringLowerCaseCharset)
142 }
143
144 // randomStringPrefixWithCharset builds a random string from charset using crypto/rand.
145 // We use rejection sampling (dropping the few highest byte values that would skew the
146 // distribution) so every character is uniformly distributed -- important because these
147 // strings back security tokens (access tokens, magic-link tokens, IDs), not just labels.
148 func randomStringPrefixWithCharset(prefix string, length int, charset string) string {
149 n := length - len(prefix)
150 if n <= 0 {
151 return prefix[:length]
152 }
153 result := make([]byte, n)
154 limit := 256 - (256 % len(charset)) // reject byte values >= limit to avoid modulo bias
155 buf := make([]byte, n)
156 for i := 0; i < n; {
157 if _, err := crand.Read(buf); err != nil {
158 panic("crypto/rand failed: " + err.Error()) // Should never happen on a sane system
159 }
160 for _, c := range buf {
161 if i >= n {
162 break
163 }
164 if int(c) < limit {
165 result[i] = charset[int(c)%len(charset)]
166 i++
167 }
168 }
169 }
170 return prefix + string(result)
171 }
172
173 // ValidRandomString returns true if the given string matches the format created by RandomString
174 func ValidRandomString(s string, length int) bool {
175 if len(s) != length {
176 return false
177 }
178 for _, c := range strings.Split(s, "") {
179 if !strings.Contains(randomStringCharset, c) {
180 return false
181 }
182 }
183 return true
184 }
185
186 // ParsePriority parses a priority string into its equivalent integer value
187 func ParsePriority(priority string) (int, error) {
188 p := strings.TrimSpace(strings.ToLower(priority))
189 switch p {
190 case "":
191 return 0, nil
192 case "1", "min":
193 return 1, nil
194 case "2", "low":
195 return 2, nil
196 case "3", "default":
197 return 3, nil
198 case "4", "high":
199 return 4, nil
200 case "5", "max", "urgent":
201 return 5, nil
202 default:
203 return 0, errInvalidPriority
204 }
205 }
206
207 // PriorityString converts a priority number to a string
208 func PriorityString(priority int) (string, error) {
209 switch priority {
210 case 0:
211 return "default", nil
212 case 1:
213 return "min", nil
214 case 2:
215 return "low", nil
216 case 3:
217 return "default", nil
218 case 4:
219 return "high", nil
220 case 5:
221 return "max", nil
222 default:
223 return "", errInvalidPriority
224 }
225 }
226
227 // ShortTopicURL shortens the topic URL to be human-friendly, removing the http:// or https://
228 func ShortTopicURL(s string) string {
229 return strings.TrimPrefix(strings.TrimPrefix(s, "https://"), "http://")
230 }
231
232 // DetectContentType probes the byte array b and returns mime type and file extension.
233 // The filename is only used to override certain special cases.
234 func DetectContentType(b []byte, filename string) (mimeType string, ext string) {
235 if strings.HasSuffix(strings.ToLower(filename), ".apk") {
236 return "application/vnd.android.package-archive", ".apk"
237 }
238 m := mimetype.Detect(b)
239 mimeType, ext = m.String(), m.Extension()
240 if ext == "" {
241 ext = ".bin"
242 }
243 return
244 }
245
246 // ParseSize parses a size string like 2K or 2M into bytes. If no unit is found, e.g. 123, bytes is assumed.
247 func ParseSize(s string) (int64, error) {
248 matches := sizeStrRegex.FindStringSubmatch(s)
249 if matches == nil {
250 return -1, fmt.Errorf("invalid size %s", s)
251 }
252 value, err := strconv.Atoi(matches[1])
253 if err != nil {
254 return -1, fmt.Errorf("cannot convert number %s", matches[1])
255 }
256 switch strings.ToUpper(matches[2]) {
257 case "T":
258 return int64(value) * 1024 * 1024 * 1024 * 1024, nil
259 case "G":
260 return int64(value) * 1024 * 1024 * 1024, nil
261 case "M":
262 return int64(value) * 1024 * 1024, nil
263 case "K":
264 return int64(value) * 1024, nil
265 default:
266 return int64(value), nil
267 }
268 }
269
270 // FormatSize formats the size in a way that it can be parsed by ParseSize.
271 // It does not include decimal places. Uneven sizes are rounded down.
272 func FormatSize(b int64) string {
273 const unit = 1024
274 if b < unit {
275 return fmt.Sprintf("%d", b)
276 }
277 div, exp := int64(unit), 0
278 for n := b / unit; n >= unit; n /= unit {
279 div *= unit
280 exp++
281 }
282 return fmt.Sprintf("%d%c", int(math.Floor(float64(b)/float64(div))), "KMGT"[exp])
283 }
284
285 // FormatSizeHuman formats bytes into a human-readable notation, e.g. 2.1 MB
286 func FormatSizeHuman(b int64) string {
287 const unit = 1024
288 if b < unit {
289 return fmt.Sprintf("%d bytes", b)
290 }
291 div, exp := int64(unit), 0
292 for n := b / unit; n >= unit; n /= unit {
293 div *= unit
294 exp++
295 }
296 return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "KMGT"[exp])
297 }
298
299 // ReadPassword will read a password from STDIN. If the terminal supports it, it will not print the
300 // input characters to the screen. If not, it'll just read using normal readline semantics (useful for testing).
301 func ReadPassword(in io.Reader) ([]byte, error) {
302 // If in is a file and a character device (a TTY), use term.ReadPassword
303 if f, ok := in.(*os.File); ok {
304 stat, err := f.Stat()
305 if err != nil {
306 return nil, err
307 }
308 if (stat.Mode() & os.ModeCharDevice) == os.ModeCharDevice {
309 password, err := term.ReadPassword(int(f.Fd())) // This is always going to be 0
310 if err != nil {
311 return nil, err
312 } else if len(password) == 0 {
313 return nil, errors.New("password cannot be empty")
314 }
315 return password, nil
316 }
317 }
318
319 // Fallback: Manually read util \n if found, see #69 for details why this is so manual
320 password := make([]byte, 0)
321 buf := make([]byte, 1)
322 for {
323 _, err := in.Read(buf)
324 if err == io.EOF || buf[0] == '\n' {
325 break
326 } else if err != nil {
327 return nil, err
328 } else if len(password) > 10240 {
329 return nil, errors.New("passwords this long are not supported")
330 }
331 password = append(password, buf[0])
332 }
333 if len(password) == 0 {
334 return nil, errors.New("password cannot be empty")
335 }
336 return password, nil
337 }
338
339 // BasicAuth encodes the Authorization header value for basic auth
340 func BasicAuth(user, pass string) string {
341 return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", user, pass))))
342 }
343
344 // BearerAuth encodes the Authorization header value for a bearer/token auth
345 func BearerAuth(token string) string {
346 return fmt.Sprintf("Bearer %s", token)
347 }
348
349 // MaybeMarshalJSON returns a JSON string of the given object, or "<cannot serialize>" if serialization failed.
350 // This is useful for logging purposes where a failure doesn't matter that much.
351 func MaybeMarshalJSON(v any) string {
352 jsonBytes, err := json.MarshalIndent(v, "", " ")
353 if err != nil {
354 return "<cannot serialize>"
355 }
356 if len(jsonBytes) > 5000 {
357 return string(jsonBytes)[:5000]
358 }
359 return string(jsonBytes)
360 }
361
362 // EncodeJSON writes the JSON encoding of v to w, without escaping HTML-significant
363 // characters (<, >, &). Unlike the standard library's default, ntfy does not embed its
364 // JSON responses in HTML, so escaping these characters only makes the raw output harder
365 // to read (see #1511).
366 func EncodeJSON(w io.Writer, v any) error {
367 encoder := json.NewEncoder(w)
368 encoder.SetEscapeHTML(false)
369 return encoder.Encode(v)
370 }
371
372 // QuoteCommand combines a command array to a string, quoting arguments that need quoting.
373 // This function is naive, and sometimes wrong. It is only meant for lo pretty-printing a command.
374 //
375 // Warning: Never use this function with the intent to run the resulting command.
376 //
377 // Example:
378 //
379 // []string{"ls", "-al", "Document Folder"} -> ls -al "Document Folder"
380 func QuoteCommand(command []string) string {
381 var quoted []string
382 for _, c := range command {
383 if noQuotesRegex.MatchString(c) {
384 quoted = append(quoted, c)
385 } else {
386 quoted = append(quoted, fmt.Sprintf(`"%s"`, c))
387 }
388 }
389 return strings.Join(quoted, " ")
390 }
391
392 // UnmarshalJSON reads the given io.ReadCloser into a struct
393 func UnmarshalJSON[T any](body io.ReadCloser) (*T, error) {
394 var obj T
395 if err := json.NewDecoder(body).Decode(&obj); err != nil {
396 return nil, ErrUnmarshalJSON
397 }
398 return &obj, nil
399 }
400
401 // UnmarshalJSONWithLimit reads the given io.ReadCloser into a struct, but only until limit is reached
402 func UnmarshalJSONWithLimit[T any](r io.ReadCloser, limit int, allowEmpty bool) (*T, error) {
403 defer r.Close()
404 p, err := Peek(r, limit)
405 if err != nil {
406 return nil, err
407 } else if p.LimitReached {
408 return nil, ErrTooLargeJSON
409 }
410 var obj T
411 if len(bytes.TrimSpace(p.PeekedBytes)) == 0 && allowEmpty {
412 return &obj, nil
413 } else if err := json.NewDecoder(p).Decode(&obj); err != nil {
414 return nil, ErrUnmarshalJSON
415 }
416 return &obj, nil
417 }
418
419 // Retry executes function f until if succeeds, and then returns t. If f fails, it sleeps
420 // and tries again. The sleep durations are passed as the after params.
421 func Retry[T any](f func() (*T, error), after ...time.Duration) (t *T, err error) {
422 for _, delay := range after {
423 if t, err = f(); err == nil {
424 return t, nil
425 }
426 time.Sleep(delay)
427 }
428 return nil, err
429 }
430
431 // MinMax returns value if it is between min and max, or either
432 // min or max if it is out of range
433 func MinMax[T int | int64](value, min, max T) T {
434 if value < min {
435 return min
436 } else if value > max {
437 return max
438 }
439 return value
440 }
441
442 // Max returns the maximum value of the two given values
443 func Max[T int | int64 | rate.Limit](a, b T) T {
444 if a > b {
445 return a
446 }
447 return b
448 }
449
450 // String turns a string into a pointer of a string
451 func String(v string) *string {
452 return &v
453 }
454
455 // Int turns an int into a pointer of an int
456 func Int(v int) *int {
457 return &v
458 }
459
460 // Time turns a time.Time into a pointer
461 func Time(v time.Time) *time.Time {
462 return &v
463 }
464
465 // SanitizeUTF8 ensures a string is safe to store in PostgreSQL by handling two cases:
466 //
467 // 1. Invalid UTF-8 sequences: Some clients send Latin-1/ISO-8859-1 encoded text (e.g. accented
468 // characters like é, ñ, ß) in HTTP headers or SMTP messages. Go treats these as raw bytes in
469 // strings, but PostgreSQL rejects them. Any invalid UTF-8 byte is replaced with the Unicode
470 // replacement character (U+FFFD, "�") so the message is still delivered rather than lost.
471 //
472 // 2. NUL bytes (0x00): These are valid in UTF-8 but PostgreSQL TEXT columns reject them.
473 // They are stripped entirely.
474 func SanitizeUTF8(s string) string {
475 if !utf8.ValidString(s) {
476 s = strings.ToValidUTF8(s, "\xef\xbf\xbd") // U+FFFD
477 }
478 if strings.ContainsRune(s, 0) {
479 s = strings.ReplaceAll(s, "\x00", "")
480 }
481 return s
482 }