-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathcookiejar.go
More file actions
511 lines (451 loc) · 14 KB
/
Copy pathcookiejar.go
File metadata and controls
511 lines (451 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
// The code was originally taken from https://github.com/valyala/fasthttp/pull/526.
package client
import (
"bytes"
"net"
"strings"
"sync"
"time"
"github.com/gofiber/utils/v2"
utilsbytes "github.com/gofiber/utils/v2/bytes"
utilsstrings "github.com/gofiber/utils/v2/strings"
"github.com/valyala/fasthttp"
"golang.org/x/net/publicsuffix"
)
const maxCookieJarHosts = 1024
var cookieJarPool = sync.Pool{
New: func() any {
return &CookieJar{}
},
}
// AcquireCookieJar returns an empty CookieJar object from the pool.
func AcquireCookieJar() *CookieJar {
jar, ok := cookieJarPool.Get().(*CookieJar)
if !ok {
panic(errCookieJarTypeAssertion)
}
return jar
}
// ReleaseCookieJar returns a CookieJar object to the pool.
func ReleaseCookieJar(c *CookieJar) {
c.Release()
cookieJarPool.Put(c)
}
// CookieJar manages cookie storage for the client.
// CookieJar is safe for concurrent use, except Release. Release must not run
// concurrently with other methods, and the jar must not be used after Release.
type CookieJar struct {
// hostCookies stores wrapped cookies keyed by storage scope:
// host-only cookies use the request host, while domain cookies use the
// accepted Domain attribute.
// If release logic is re-enabled for these entries, iterate as storedCookie
// values and call fasthttp.ReleaseCookie(stored.cookie) on the wrapped cookie.
hostCookies map[string][]storedCookie
mu sync.Mutex
}
type storedCookie struct {
cookie *fasthttp.Cookie
isHostOnly bool
}
type cookieDomainAcceptance struct {
domain string
isHostOnly bool
isOk bool
}
// Get returns all cookies stored for a given URI. If there are no cookies for the
// provided host, the returned slice will be nil.
//
// The CookieJar keeps its own copies of cookies, so it is safe to release the returned
// cookies after use.
func (cj *CookieJar) Get(uri *fasthttp.URI) []*fasthttp.Cookie {
if uri == nil {
return nil
}
secure := bytes.Equal(uri.Scheme(), httpsScheme)
return cj.getByHostAndPath(uri.Host(), uri.Path(), secure)
}
// getByHostAndPath returns cookies stored for a specific host and path.
func (cj *CookieJar) getByHostAndPath(host, path []byte, secure bool) []*fasthttp.Cookie {
if cj.hostCookies == nil {
return nil
}
var (
err error
hostStr = utils.UnsafeString(host)
)
// port must not be included.
hostStr, _, err = net.SplitHostPort(hostStr)
if err != nil {
hostStr = utils.UnsafeString(host)
}
return cj.cookiesForRequest(hostStr, path, secure)
}
// getCookiesByHost returns cookies stored for a specific host, removing any that have expired.
func (cj *CookieJar) getCookiesByHost(host string) []*fasthttp.Cookie {
cj.mu.Lock()
defer cj.mu.Unlock()
now := time.Now()
stored := cj.hostCookies[host]
kept := stored[:0]
for _, sc := range stored {
c := sc.cookie
// Remove expired cookies.
if !c.Expire().Equal(fasthttp.CookieExpireUnlimited) && c.Expire().Before(now) {
fasthttp.ReleaseCookie(c)
continue
}
kept = append(kept, sc)
}
if len(kept) == 0 {
delete(cj.hostCookies, host)
} else {
cj.hostCookies[host] = kept
}
out := make([]*fasthttp.Cookie, 0, len(kept))
for _, sc := range kept {
out = append(out, sc.cookie)
}
return out
}
// cookiesForRequest returns cookies that match the given host, path and security settings.
func (cj *CookieJar) cookiesForRequest(host string, path []byte, secure bool) []*fasthttp.Cookie { //nolint:revive // secure is a deliberate scheme filter, not a control-flow flag
cj.mu.Lock()
defer cj.mu.Unlock()
host = utilsstrings.ToLower(host)
now := time.Now()
var matched []*fasthttp.Cookie
for domain, cookies := range cj.hostCookies {
if len(cookies) == 0 {
continue
}
if !domainMatch(host, domain) {
continue
}
kept := cookies[:0]
for _, sc := range cookies {
c := sc.cookie
if !c.Expire().Equal(fasthttp.CookieExpireUnlimited) && c.Expire().Before(now) {
fasthttp.ReleaseCookie(c)
continue
}
kept = append(kept, sc)
if sc.isHostOnly && host != domain {
continue
}
if !pathMatch(path, c.Path()) {
continue
}
if c.Secure() && !secure {
continue
}
nc := fasthttp.AcquireCookie()
nc.CopyTo(c)
matched = append(matched, nc)
}
if len(kept) == 0 {
delete(cj.hostCookies, domain)
} else {
cj.hostCookies[domain] = kept
}
}
return matched
}
// Set stores the given cookies for the specified URI host. If a cookie key already exists,
// it will be replaced by the new cookie value.
//
// CookieJar stores copies of the provided cookies, so they may be safely released after use.
func (cj *CookieJar) Set(uri *fasthttp.URI, cookies ...*fasthttp.Cookie) {
if uri == nil {
return
}
cj.SetByHost(uri.Host(), cookies...)
}
// SetByHost stores the given cookies for the specified host. If a cookie key already exists,
// it will be replaced by the new cookie value.
//
// CookieJar stores copies of the provided cookies, so they may be safely released after use.
func (cj *CookieJar) SetByHost(host []byte, cookies ...*fasthttp.Cookie) {
hostStr := utils.UnsafeString(host)
if h, _, err := net.SplitHostPort(hostStr); err == nil {
hostStr = h
}
hostStr = utilsstrings.ToLower(hostStr)
hostKey := utils.CopyString(hostStr)
cj.mu.Lock()
defer cj.mu.Unlock()
if cj.hostCookies == nil {
cj.hostCookies = make(map[string][]storedCookie)
}
for _, cookie := range cookies {
domain := utils.TrimLeft(cookie.Domain(), '.')
utilsbytes.UnsafeToLower(domain)
key := hostKey
storedDomain := hostStr
isHostOnly := len(domain) == 0
if !isHostOnly {
acceptance := acceptCookieDomain(hostStr, utils.UnsafeString(domain))
if !acceptance.isOk {
continue
}
isHostOnly = acceptance.isHostOnly
if !isHostOnly {
key = utils.CopyString(acceptance.domain)
storedDomain = acceptance.domain
}
}
cj.ensureHostCapacityLocked(key, time.Now())
hostCookies := cj.hostCookies[key]
existing := searchCookieByKeyAndPath(cookie.Key(), cookie.Path(), hostCookies)
if existing == nil {
existing = fasthttp.AcquireCookie()
hostCookies = append(hostCookies, storedCookie{cookie: existing, isHostOnly: isHostOnly})
} else {
for i := range hostCookies {
if hostCookies[i].cookie == existing {
hostCookies[i].isHostOnly = isHostOnly
break
}
}
}
existing.CopyTo(cookie)
existing.SetDomain(storedDomain)
cj.hostCookies[key] = hostCookies
}
}
// SetKeyValue sets a cookie for the specified host with the given key and value.
//
// This function helps prevent extra allocations by avoiding duplication of repeated cookies.
func (cj *CookieJar) SetKeyValue(host, key, value string) {
c := fasthttp.AcquireCookie()
defer fasthttp.ReleaseCookie(c)
c.SetKey(key)
c.SetValue(value)
cj.SetByHost(utils.UnsafeBytes(host), c)
}
// SetKeyValueBytes sets a cookie for the specified host using byte slices for the key and value.
//
// This function helps prevent extra allocations by avoiding duplication of repeated cookies.
func (cj *CookieJar) SetKeyValueBytes(host string, key, value []byte) {
c := fasthttp.AcquireCookie()
defer fasthttp.ReleaseCookie(c)
c.SetKeyBytes(key)
c.SetValueBytes(value)
cj.SetByHost(utils.UnsafeBytes(host), c)
}
// dumpCookiesToReq writes the stored cookies to the given request.
func (cj *CookieJar) dumpCookiesToReq(req *fasthttp.Request) {
uri := req.URI()
secure := bytes.Equal(uri.Scheme(), httpsScheme)
cookies := cj.getByHostAndPath(uri.Host(), uri.Path(), secure)
for _, cookie := range cookies {
req.Header.SetCookieBytesKV(cookie.Key(), cookie.Value())
fasthttp.ReleaseCookie(cookie)
}
}
// parseCookiesFromResp parses the cookies from the response and stores them for the specified host and path.
func (cj *CookieJar) parseCookiesFromResp(host, _ []byte, resp *fasthttp.Response) {
hostStr := utils.UnsafeString(host)
if h, _, err := net.SplitHostPort(hostStr); err == nil {
hostStr = h
}
hostStr = utilsstrings.ToLower(hostStr)
hostKey := utils.CopyString(hostStr)
cj.mu.Lock()
defer cj.mu.Unlock()
if cj.hostCookies == nil {
cj.hostCookies = make(map[string][]storedCookie)
}
now := time.Now()
for _, value := range resp.Header.Cookies() {
tmp := fasthttp.AcquireCookie()
_ = tmp.ParseBytes(value) //nolint:errcheck // ignore error
domainBytes := utils.TrimLeft(tmp.Domain(), '.')
utilsbytes.UnsafeToLower(domainBytes)
key := hostKey
isHostOnly := len(domainBytes) == 0
if isHostOnly {
tmp.SetDomain(hostStr)
} else {
domain := utils.UnsafeString(domainBytes)
acceptance := acceptCookieDomain(hostStr, domain)
if !acceptance.isOk {
fasthttp.ReleaseCookie(tmp)
continue
}
isHostOnly = acceptance.isHostOnly
if isHostOnly {
tmp.SetDomain(hostStr)
} else {
key = utils.CopyString(acceptance.domain)
tmp.SetDomain(acceptance.domain)
}
}
cj.ensureHostCapacityLocked(key, now)
cookies := cj.hostCookies[key]
c := searchCookieByKeyAndPath(tmp.Key(), tmp.Path(), cookies)
if c == nil {
c = fasthttp.AcquireCookie()
cookies = append(cookies, storedCookie{cookie: c, isHostOnly: isHostOnly})
} else {
for i := range cookies {
if cookies[i].cookie == c {
cookies[i].isHostOnly = isHostOnly
break
}
}
}
c.CopyTo(tmp)
if c.Expire().Equal(fasthttp.CookieExpireUnlimited) || c.Expire().After(now) {
cj.hostCookies[key] = cookies
} else {
kept := cookies[:0]
for _, v := range cookies {
if v.cookie != c {
kept = append(kept, v)
}
}
cj.hostCookies[key] = kept
fasthttp.ReleaseCookie(c)
}
fasthttp.ReleaseCookie(tmp)
}
}
// ensureHostCapacityLocked bounds the number of stored hosts by evicting
// expired entries first and then one remaining host if the jar is still full.
func (cj *CookieJar) ensureHostCapacityLocked(key string, now time.Time) {
if _, ok := cj.hostCookies[key]; ok || len(cj.hostCookies) < maxCookieJarHosts {
return
}
for host, cookies := range cj.hostCookies {
kept := cookies[:0]
for _, sc := range cookies {
if !sc.cookie.Expire().Equal(fasthttp.CookieExpireUnlimited) && sc.cookie.Expire().Before(now) {
fasthttp.ReleaseCookie(sc.cookie)
continue
}
kept = append(kept, sc)
}
if len(kept) == 0 {
delete(cj.hostCookies, host)
if len(cj.hostCookies) < maxCookieJarHosts {
return
}
continue
}
cj.hostCookies[host] = kept
}
var evictHost string
for host := range cj.hostCookies {
if evictHost == "" || host < evictHost {
evictHost = host
}
}
if evictHost != "" {
releaseStoredCookies(cj.hostCookies[evictHost])
delete(cj.hostCookies, evictHost)
}
}
// releaseStoredCookies releases pooled cookies for an evicted host entry.
func releaseStoredCookies(cookies []storedCookie) {
for _, sc := range cookies {
fasthttp.ReleaseCookie(sc.cookie)
}
}
// Release releases all stored cookies. After this, the CookieJar is empty and
// must not be used again.
func (cj *CookieJar) Release() {
// FOLLOW-UP performance optimization:
// Currently, a race condition is found because the reset method modifies a value
// that is not a copy but a reference. A solution would be to make a copy.
// for _, v := range cj.hostCookies {
// for _, c := range v {
// fasthttp.ReleaseCookie(c)
// }
// }
cj.hostCookies = nil
}
// searchCookieByKeyAndPath looks up a cookie by its key and path from the provided slice of cookies.
func searchCookieByKeyAndPath(key, path []byte, cookies []storedCookie) *fasthttp.Cookie {
for _, sc := range cookies {
c := sc.cookie
if bytes.Equal(key, c.Key()) {
if pathMatch(path, c.Path()) {
return c
}
}
}
return nil
}
// pathMatch determines whether the request path matches the cookie path
// according to RFC 6265 section 5.1.4.
func pathMatch(reqPath, cookiePath []byte) bool {
if len(reqPath) == 0 {
reqPath = []byte("/")
}
if len(cookiePath) == 0 {
cookiePath = []byte("/")
}
if bytes.Equal(reqPath, cookiePath) {
return true
}
if !bytes.HasPrefix(reqPath, cookiePath) {
return false
}
if cookiePath[len(cookiePath)-1] == '/' {
return true
}
return len(reqPath) > len(cookiePath) && reqPath[len(cookiePath)] == '/'
}
// domainMatch reports whether host domain-matches the given cookie domain
// (RFC 6265 Section 5.1.3). The comparison itself is ASCII case-insensitive
// and allocation-free, but callers still normalize hosts and domains to
// lowercase: the jar's map keys and its exact-match checks (e.g. the
// host-only comparison in cookiesForRequest) rely on it.
func domainMatch(host, domain string) bool {
if utils.EqualFold(host, domain) {
return true
}
return len(host) > len(domain) &&
host[len(host)-len(domain)-1] == '.' &&
utils.HasSuffixFold(host, domain)
}
// acceptCookieDomain enforces RFC 6265 response-domain acceptance. Trailing-dot,
// exact-match public-suffix, and exact-match IP-literal Domain attributes are
// downgraded to host-only so same-host behavior is preserved without storing
// cookies under shared suffixes or allowing IP suffix matching across
// unrelated hosts.
func acceptCookieDomain(host, domain string) cookieDomainAcceptance {
if strings.HasSuffix(domain, ".") {
return cookieDomainAcceptance{domain: host, isHostOnly: true, isOk: true}
}
if host == domain {
if isIPLiteral(domain) || isPublicSuffixDomain(domain) {
return cookieDomainAcceptance{domain: host, isHostOnly: true, isOk: true}
}
return cookieDomainAcceptance{domain: domain, isOk: true}
}
if isIPLiteral(host) || isIPLiteral(domain) || isPublicSuffixDomain(domain) || !domainMatch(host, domain) {
return cookieDomainAcceptance{}
}
return cookieDomainAcceptance{domain: domain, isOk: true}
}
func isIPLiteral(host string) bool {
if len(host) >= 2 && host[0] == '[' && host[len(host)-1] == ']' {
host = host[1 : len(host)-1]
}
// Equivalent to net.ParseIP(host) != nil: utils.ParseIPv4/ParseIPv6
// accept the same strings once zoned addresses (which net.ParseIP
// rejects) are screened out, without allocating on either outcome.
if strings.IndexByte(host, '%') >= 0 {
return false
}
if _, ok := utils.ParseIPv4(host); ok {
return true
}
_, ok := utils.ParseIPv6(host)
return ok
}
func isPublicSuffixDomain(domain string) bool {
suffix, _ := publicsuffix.PublicSuffix(domain)
return suffix == domain
}