Debian Codegraph @

common.go

raw
1 // ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
2 // 🤖 Github Repository: https://github.com/gofiber/fiber
3 // 📌 API Documentation: https://docs.gofiber.io
4
5 package utils
6
7 import (
8 "crypto/rand"
9 "encoding/base64"
10 "fmt"
11 "math"
12 "net"
13 "os"
14 "reflect"
15 "runtime"
16 "slices"
17 "strings"
18
19 "github.com/google/uuid"
20 )
21
22 const (
23 defaultSecureTokenLength = 32
24 maxFastTokenEncodedLength = 43 // base64.RawURLEncoding.EncodedLen(32)
25 )
26
27 func readRandomOrPanic(dst []byte) {
28 if _, err := rand.Read(dst); err != nil {
29 // On supported Go versions (1.24+), crypto/rand.Read panics internally and
30 // does not return errors. This check preserves explicit panic semantics if
31 // the behavior changes or an alternate implementation is used in the future.
32 // See: https://cs.opensource.google/go/go/+/refs/tags/go1.24.0:src/crypto/rand/rand.go
33 panic(fmt.Errorf("utils: failed to read random bytes for token: %w", err))
34 }
35 }
36
37 // Lookup table for ASCII whitespace characters (true = whitespace, false = not whitespace)
38 var whitespaceTable = [256]bool{
39 '\t': true, // 9 - horizontal tab
40 '\n': true, // 10 - line feed
41 '\v': true, // 11 - vertical tab
42 '\f': true, // 12 - form feed
43 '\r': true, // 13 - carriage return
44 ' ': true, // 32 - space
45 }
46
47 // UUIDv4 returns a Random (Version 4) UUID.
48 // The strength of the UUIDs is based on the strength of the crypto/rand package.
49 func UUIDv4() string {
50 token, err := uuid.NewRandom()
51 if err != nil {
52 panic(fmt.Errorf("utils: failed to generate secure UUID: %w", err))
53 }
54 return token.String()
55 }
56
57 // UUID generates an universally unique identifier (UUID).
58 // This is an alias for UUIDv4 for backward compatibility.
59 func UUID() string {
60 return UUIDv4()
61 }
62
63 // GenerateSecureToken generates a cryptographically secure random token encoded in base64.
64 // It uses crypto/rand for randomness and base64.RawURLEncoding for URL-safe output.
65 // If length is less than or equal to 0, it defaults to 32 bytes (256 bits of entropy).
66 // Panics if the random source fails.
67 func GenerateSecureToken(length int) string {
68 if length <= 0 {
69 length = defaultSecureTokenLength
70 }
71
72 if length == defaultSecureTokenLength {
73 var randomBuf [defaultSecureTokenLength]byte
74 src := randomBuf[:]
75 readRandomOrPanic(src)
76
77 var encoded [maxFastTokenEncodedLength]byte
78 encodedLen := base64.RawURLEncoding.EncodedLen(length)
79 base64.RawURLEncoding.Encode(encoded[:encodedLen], src)
80 return string(encoded[:encodedLen])
81 }
82
83 bytes := make([]byte, length)
84 readRandomOrPanic(bytes)
85 return base64.RawURLEncoding.EncodeToString(bytes)
86 }
87
88 // SecureToken generates a secure token with 32 bytes of entropy.
89 // Panics if the random source fails. See GenerateSecureToken for details.
90 func SecureToken() string {
91 return GenerateSecureToken(defaultSecureTokenLength)
92 }
93
94 // FunctionName returns function name
95 func FunctionName(fn any) string {
96 if fn == nil {
97 return ""
98 }
99 v := reflect.ValueOf(fn)
100 if v.Kind() == reflect.Func {
101 if v.IsNil() {
102 return ""
103 }
104 pc := v.Pointer()
105 f := runtime.FuncForPC(pc)
106 if f == nil {
107 return ""
108 }
109 return f.Name()
110 }
111 return v.Type().String()
112 }
113
114 // GetArgument check if key is in arguments
115 func GetArgument(arg string) bool {
116 return slices.Contains(os.Args[1:], arg)
117 }
118
119 // IncrementIPRange Find available next IP address
120 func IncrementIPRange(ip net.IP) {
121 for j := len(ip) - 1; j >= 0; j-- { //nolint:modernize // slicesbackward: false positive
122 ip[j]++
123 if ip[j] > 0 {
124 break
125 }
126 }
127 }
128
129 // ConvertToBytes returns integer size of bytes from human-readable string, ex. 42kb, 42M
130 // Decimal units are powers of 1000 (42k = 42000); binary units with an 'i' infix
131 // are powers of 1024 (42Ki = 43008). Note that ByteSize formats with powers of 1024,
132 // so use binary suffixes for a lossless round-trip.
133 // Returns 0 if the string is unrecognized or negative.
134 func ConvertToBytes(humanReadableString string) int {
135 strLen := len(humanReadableString)
136 if strLen == 0 {
137 return 0
138 }
139
140 // Fast path for plain byte values (e.g. "42", "42B", "42b").
141 var sizeFast uint64
142 maxInt := uint64(math.MaxInt)
143 i := 0
144 for ; i < strLen; i++ {
145 c := humanReadableString[i]
146 if c < '0' || c > '9' {
147 break
148 }
149 d := uint64(c - '0')
150 if sizeFast > maxInt/10 || (sizeFast == maxInt/10 && d > maxInt%10) {
151 sizeFast = maxInt
152 } else if sizeFast < maxInt {
153 sizeFast = sizeFast*10 + d
154 }
155 }
156 if i > 0 {
157 if i == strLen {
158 return int(sizeFast)
159 }
160 if i+1 == strLen {
161 last := humanReadableString[i]
162 if last == 'b' || last == 'B' {
163 return int(sizeFast)
164 }
165 }
166 }
167
168 // Find the last digit position by scanning backwards
169 // Also identify the unit prefix position in the same pass
170 lastNumberPos := -1
171 unitPrefixPos := 0
172 for i := strLen - 1; i >= 0; i-- {
173 c := humanReadableString[i]
174 if c >= '0' && c <= '9' {
175 lastNumberPos = i
176 break
177 }
178 // Track the first letter position (unit prefix) from the end
179 if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') {
180 unitPrefixPos = i
181 }
182 }
183
184 // No digits found
185 if lastNumberPos < 0 {
186 return 0
187 }
188
189 numPart := humanReadableString[:lastNumberPos+1]
190 var size float64
191
192 if strings.IndexByte(numPart, '.') >= 0 {
193 var err error
194 size, err = ParseFloat64(numPart)
195 if err != nil || size < 0 {
196 return 0
197 }
198 } else {
199 i64, err := ParseUint(numPart)
200 if err != nil {
201 return 0
202 }
203 size = float64(i64)
204 }
205
206 if unitPrefixPos > 0 {
207 // An 'i' after the unit prefix selects binary units (KiB = 1024).
208 binary := unitPrefixPos+1 < strLen &&
209 (humanReadableString[unitPrefixPos+1] == 'i' || humanReadableString[unitPrefixPos+1] == 'I')
210 var decMul, binMul float64
211 switch humanReadableString[unitPrefixPos] {
212 case 'k', 'K':
213 decMul, binMul = 1e3, 1<<10
214 case 'm', 'M':
215 decMul, binMul = 1e6, 1<<20
216 case 'g', 'G':
217 decMul, binMul = 1e9, 1<<30
218 case 't', 'T':
219 decMul, binMul = 1e12, 1<<40
220 case 'p', 'P':
221 decMul, binMul = 1e15, 1<<50
222 default:
223 decMul, binMul = 1, 1
224 }
225 if binary {
226 size *= binMul
227 } else {
228 size *= decMul
229 }
230 }
231
232 if size > float64(math.MaxInt) {
233 return math.MaxInt
234 }
235
236 return int(size)
237 }