cookie.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. package fasthttp
  2. import (
  3. "bytes"
  4. "errors"
  5. "io"
  6. "sync"
  7. "time"
  8. )
  9. var zeroTime time.Time
  10. var (
  11. // CookieExpireDelete may be set on Cookie.Expire for expiring the given cookie.
  12. CookieExpireDelete = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
  13. // CookieExpireUnlimited indicates that the cookie doesn't expire.
  14. CookieExpireUnlimited = zeroTime
  15. )
  16. // CookieSameSite is an enum for the mode in which the SameSite flag should be set for the given cookie.
  17. // See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.
  18. type CookieSameSite int
  19. const (
  20. // CookieSameSiteDisabled removes the SameSite flag
  21. CookieSameSiteDisabled CookieSameSite = iota
  22. // CookieSameSiteDefaultMode sets the SameSite flag
  23. CookieSameSiteDefaultMode
  24. // CookieSameSiteLaxMode sets the SameSite flag with the "Lax" parameter
  25. CookieSameSiteLaxMode
  26. // CookieSameSiteStrictMode sets the SameSite flag with the "Strict" parameter
  27. CookieSameSiteStrictMode
  28. // CookieSameSiteNoneMode sets the SameSite flag with the "None" parameter
  29. // see https://tools.ietf.org/html/draft-west-cookie-incrementalism-00
  30. CookieSameSiteNoneMode
  31. )
  32. // AcquireCookie returns an empty Cookie object from the pool.
  33. //
  34. // The returned object may be returned back to the pool with ReleaseCookie.
  35. // This allows reducing GC load.
  36. func AcquireCookie() *Cookie {
  37. return cookiePool.Get().(*Cookie)
  38. }
  39. // ReleaseCookie returns the Cookie object acquired with AcquireCookie back
  40. // to the pool.
  41. //
  42. // Do not access released Cookie object, otherwise data races may occur.
  43. func ReleaseCookie(c *Cookie) {
  44. c.Reset()
  45. cookiePool.Put(c)
  46. }
  47. var cookiePool = &sync.Pool{
  48. New: func() interface{} {
  49. return &Cookie{}
  50. },
  51. }
  52. // Cookie represents HTTP response cookie.
  53. //
  54. // Do not copy Cookie objects. Create new object and use CopyTo instead.
  55. //
  56. // Cookie instance MUST NOT be used from concurrently running goroutines.
  57. type Cookie struct {
  58. noCopy noCopy
  59. key []byte
  60. value []byte
  61. expire time.Time
  62. maxAge int
  63. domain []byte
  64. path []byte
  65. httpOnly bool
  66. secure bool
  67. sameSite CookieSameSite
  68. bufKV argsKV
  69. buf []byte
  70. }
  71. // CopyTo copies src cookie to c.
  72. func (c *Cookie) CopyTo(src *Cookie) {
  73. c.Reset()
  74. c.key = append(c.key, src.key...)
  75. c.value = append(c.value, src.value...)
  76. c.expire = src.expire
  77. c.maxAge = src.maxAge
  78. c.domain = append(c.domain, src.domain...)
  79. c.path = append(c.path, src.path...)
  80. c.httpOnly = src.httpOnly
  81. c.secure = src.secure
  82. c.sameSite = src.sameSite
  83. }
  84. // HTTPOnly returns true if the cookie is http only.
  85. func (c *Cookie) HTTPOnly() bool {
  86. return c.httpOnly
  87. }
  88. // SetHTTPOnly sets cookie's httpOnly flag to the given value.
  89. func (c *Cookie) SetHTTPOnly(httpOnly bool) {
  90. c.httpOnly = httpOnly
  91. }
  92. // Secure returns true if the cookie is secure.
  93. func (c *Cookie) Secure() bool {
  94. return c.secure
  95. }
  96. // SetSecure sets cookie's secure flag to the given value.
  97. func (c *Cookie) SetSecure(secure bool) {
  98. c.secure = secure
  99. }
  100. // SameSite returns the SameSite mode.
  101. func (c *Cookie) SameSite() CookieSameSite {
  102. return c.sameSite
  103. }
  104. // SetSameSite sets the cookie's SameSite flag to the given value.
  105. // set value CookieSameSiteNoneMode will set Secure to true also to avoid browser rejection
  106. func (c *Cookie) SetSameSite(mode CookieSameSite) {
  107. c.sameSite = mode
  108. if mode == CookieSameSiteNoneMode {
  109. c.SetSecure(true)
  110. }
  111. }
  112. // Path returns cookie path.
  113. func (c *Cookie) Path() []byte {
  114. return c.path
  115. }
  116. // SetPath sets cookie path.
  117. func (c *Cookie) SetPath(path string) {
  118. c.buf = append(c.buf[:0], path...)
  119. c.path = normalizePath(c.path, c.buf)
  120. }
  121. // SetPathBytes sets cookie path.
  122. func (c *Cookie) SetPathBytes(path []byte) {
  123. c.buf = append(c.buf[:0], path...)
  124. c.path = normalizePath(c.path, c.buf)
  125. }
  126. // Domain returns cookie domain.
  127. //
  128. // The returned value is valid until the Cookie reused or released (ReleaseCookie).
  129. // Do not store references to the returned value. Make copies instead.
  130. func (c *Cookie) Domain() []byte {
  131. return c.domain
  132. }
  133. // SetDomain sets cookie domain.
  134. func (c *Cookie) SetDomain(domain string) {
  135. c.domain = append(c.domain[:0], domain...)
  136. }
  137. // SetDomainBytes sets cookie domain.
  138. func (c *Cookie) SetDomainBytes(domain []byte) {
  139. c.domain = append(c.domain[:0], domain...)
  140. }
  141. // MaxAge returns the seconds until the cookie is meant to expire or 0
  142. // if no max age.
  143. func (c *Cookie) MaxAge() int {
  144. return c.maxAge
  145. }
  146. // SetMaxAge sets cookie expiration time based on seconds. This takes precedence
  147. // over any absolute expiry set on the cookie
  148. //
  149. // Set max age to 0 to unset
  150. func (c *Cookie) SetMaxAge(seconds int) {
  151. c.maxAge = seconds
  152. }
  153. // Expire returns cookie expiration time.
  154. //
  155. // CookieExpireUnlimited is returned if cookie doesn't expire
  156. func (c *Cookie) Expire() time.Time {
  157. expire := c.expire
  158. if expire.IsZero() {
  159. expire = CookieExpireUnlimited
  160. }
  161. return expire
  162. }
  163. // SetExpire sets cookie expiration time.
  164. //
  165. // Set expiration time to CookieExpireDelete for expiring (deleting)
  166. // the cookie on the client.
  167. //
  168. // By default cookie lifetime is limited by browser session.
  169. func (c *Cookie) SetExpire(expire time.Time) {
  170. c.expire = expire
  171. }
  172. // Value returns cookie value.
  173. //
  174. // The returned value is valid until the Cookie reused or released (ReleaseCookie).
  175. // Do not store references to the returned value. Make copies instead.
  176. func (c *Cookie) Value() []byte {
  177. return c.value
  178. }
  179. // SetValue sets cookie value.
  180. func (c *Cookie) SetValue(value string) {
  181. c.value = append(c.value[:0], value...)
  182. }
  183. // SetValueBytes sets cookie value.
  184. func (c *Cookie) SetValueBytes(value []byte) {
  185. c.value = append(c.value[:0], value...)
  186. }
  187. // Key returns cookie name.
  188. //
  189. // The returned value is valid until the Cookie reused or released (ReleaseCookie).
  190. // Do not store references to the returned value. Make copies instead.
  191. func (c *Cookie) Key() []byte {
  192. return c.key
  193. }
  194. // SetKey sets cookie name.
  195. func (c *Cookie) SetKey(key string) {
  196. c.key = append(c.key[:0], key...)
  197. }
  198. // SetKeyBytes sets cookie name.
  199. func (c *Cookie) SetKeyBytes(key []byte) {
  200. c.key = append(c.key[:0], key...)
  201. }
  202. // Reset clears the cookie.
  203. func (c *Cookie) Reset() {
  204. c.key = c.key[:0]
  205. c.value = c.value[:0]
  206. c.expire = zeroTime
  207. c.maxAge = 0
  208. c.domain = c.domain[:0]
  209. c.path = c.path[:0]
  210. c.httpOnly = false
  211. c.secure = false
  212. c.sameSite = CookieSameSiteDisabled
  213. }
  214. // AppendBytes appends cookie representation to dst and returns
  215. // the extended dst.
  216. func (c *Cookie) AppendBytes(dst []byte) []byte {
  217. if len(c.key) > 0 {
  218. dst = append(dst, c.key...)
  219. dst = append(dst, '=')
  220. }
  221. dst = append(dst, c.value...)
  222. if c.maxAge > 0 {
  223. dst = append(dst, ';', ' ')
  224. dst = append(dst, strCookieMaxAge...)
  225. dst = append(dst, '=')
  226. dst = AppendUint(dst, c.maxAge)
  227. } else if !c.expire.IsZero() {
  228. c.bufKV.value = AppendHTTPDate(c.bufKV.value[:0], c.expire)
  229. dst = append(dst, ';', ' ')
  230. dst = append(dst, strCookieExpires...)
  231. dst = append(dst, '=')
  232. dst = append(dst, c.bufKV.value...)
  233. }
  234. if len(c.domain) > 0 {
  235. dst = appendCookiePart(dst, strCookieDomain, c.domain)
  236. }
  237. if len(c.path) > 0 {
  238. dst = appendCookiePart(dst, strCookiePath, c.path)
  239. }
  240. if c.httpOnly {
  241. dst = append(dst, ';', ' ')
  242. dst = append(dst, strCookieHTTPOnly...)
  243. }
  244. if c.secure {
  245. dst = append(dst, ';', ' ')
  246. dst = append(dst, strCookieSecure...)
  247. }
  248. switch c.sameSite {
  249. case CookieSameSiteDefaultMode:
  250. dst = append(dst, ';', ' ')
  251. dst = append(dst, strCookieSameSite...)
  252. case CookieSameSiteLaxMode:
  253. dst = append(dst, ';', ' ')
  254. dst = append(dst, strCookieSameSite...)
  255. dst = append(dst, '=')
  256. dst = append(dst, strCookieSameSiteLax...)
  257. case CookieSameSiteStrictMode:
  258. dst = append(dst, ';', ' ')
  259. dst = append(dst, strCookieSameSite...)
  260. dst = append(dst, '=')
  261. dst = append(dst, strCookieSameSiteStrict...)
  262. case CookieSameSiteNoneMode:
  263. dst = append(dst, ';', ' ')
  264. dst = append(dst, strCookieSameSite...)
  265. dst = append(dst, '=')
  266. dst = append(dst, strCookieSameSiteNone...)
  267. }
  268. return dst
  269. }
  270. // Cookie returns cookie representation.
  271. //
  272. // The returned value is valid until the Cookie reused or released (ReleaseCookie).
  273. // Do not store references to the returned value. Make copies instead.
  274. func (c *Cookie) Cookie() []byte {
  275. c.buf = c.AppendBytes(c.buf[:0])
  276. return c.buf
  277. }
  278. // String returns cookie representation.
  279. func (c *Cookie) String() string {
  280. return string(c.Cookie())
  281. }
  282. // WriteTo writes cookie representation to w.
  283. //
  284. // WriteTo implements io.WriterTo interface.
  285. func (c *Cookie) WriteTo(w io.Writer) (int64, error) {
  286. n, err := w.Write(c.Cookie())
  287. return int64(n), err
  288. }
  289. var errNoCookies = errors.New("no cookies found")
  290. // Parse parses Set-Cookie header.
  291. func (c *Cookie) Parse(src string) error {
  292. c.buf = append(c.buf[:0], src...)
  293. return c.ParseBytes(c.buf)
  294. }
  295. // ParseBytes parses Set-Cookie header.
  296. func (c *Cookie) ParseBytes(src []byte) error {
  297. c.Reset()
  298. var s cookieScanner
  299. s.b = src
  300. kv := &c.bufKV
  301. if !s.next(kv) {
  302. return errNoCookies
  303. }
  304. c.key = append(c.key, kv.key...)
  305. c.value = append(c.value, kv.value...)
  306. for s.next(kv) {
  307. if len(kv.key) != 0 {
  308. // Case insensitive switch on first char
  309. switch kv.key[0] | 0x20 {
  310. case 'm':
  311. if caseInsensitiveCompare(strCookieMaxAge, kv.key) {
  312. maxAge, err := ParseUint(kv.value)
  313. if err != nil {
  314. return err
  315. }
  316. c.maxAge = maxAge
  317. }
  318. case 'e': // "expires"
  319. if caseInsensitiveCompare(strCookieExpires, kv.key) {
  320. v := b2s(kv.value)
  321. // Try the same two formats as net/http
  322. // See: https://github.com/golang/go/blob/00379be17e63a5b75b3237819392d2dc3b313a27/src/net/http/cookie.go#L133-L135
  323. exptime, err := time.ParseInLocation(time.RFC1123, v, time.UTC)
  324. if err != nil {
  325. exptime, err = time.Parse("Mon, 02-Jan-2006 15:04:05 MST", v)
  326. if err != nil {
  327. return err
  328. }
  329. }
  330. c.expire = exptime
  331. }
  332. case 'd': // "domain"
  333. if caseInsensitiveCompare(strCookieDomain, kv.key) {
  334. c.domain = append(c.domain, kv.value...)
  335. }
  336. case 'p': // "path"
  337. if caseInsensitiveCompare(strCookiePath, kv.key) {
  338. c.path = append(c.path, kv.value...)
  339. }
  340. case 's': // "samesite"
  341. if caseInsensitiveCompare(strCookieSameSite, kv.key) {
  342. if len(kv.value) > 0 {
  343. // Case insensitive switch on first char
  344. switch kv.value[0] | 0x20 {
  345. case 'l': // "lax"
  346. if caseInsensitiveCompare(strCookieSameSiteLax, kv.value) {
  347. c.sameSite = CookieSameSiteLaxMode
  348. }
  349. case 's': // "strict"
  350. if caseInsensitiveCompare(strCookieSameSiteStrict, kv.value) {
  351. c.sameSite = CookieSameSiteStrictMode
  352. }
  353. case 'n': // "none"
  354. if caseInsensitiveCompare(strCookieSameSiteNone, kv.value) {
  355. c.sameSite = CookieSameSiteNoneMode
  356. }
  357. }
  358. }
  359. }
  360. }
  361. } else if len(kv.value) != 0 {
  362. // Case insensitive switch on first char
  363. switch kv.value[0] | 0x20 {
  364. case 'h': // "httponly"
  365. if caseInsensitiveCompare(strCookieHTTPOnly, kv.value) {
  366. c.httpOnly = true
  367. }
  368. case 's': // "secure"
  369. if caseInsensitiveCompare(strCookieSecure, kv.value) {
  370. c.secure = true
  371. } else if caseInsensitiveCompare(strCookieSameSite, kv.value) {
  372. c.sameSite = CookieSameSiteDefaultMode
  373. }
  374. }
  375. } // else empty or no match
  376. }
  377. return nil
  378. }
  379. func appendCookiePart(dst, key, value []byte) []byte {
  380. dst = append(dst, ';', ' ')
  381. dst = append(dst, key...)
  382. dst = append(dst, '=')
  383. return append(dst, value...)
  384. }
  385. func getCookieKey(dst, src []byte) []byte {
  386. n := bytes.IndexByte(src, '=')
  387. if n >= 0 {
  388. src = src[:n]
  389. }
  390. return decodeCookieArg(dst, src, false)
  391. }
  392. func appendRequestCookieBytes(dst []byte, cookies []argsKV) []byte {
  393. for i, n := 0, len(cookies); i < n; i++ {
  394. kv := &cookies[i]
  395. if len(kv.key) > 0 {
  396. dst = append(dst, kv.key...)
  397. dst = append(dst, '=')
  398. }
  399. dst = append(dst, kv.value...)
  400. if i+1 < n {
  401. dst = append(dst, ';', ' ')
  402. }
  403. }
  404. return dst
  405. }
  406. // For Response we can not use the above function as response cookies
  407. // already contain the key= in the value.
  408. func appendResponseCookieBytes(dst []byte, cookies []argsKV) []byte {
  409. for i, n := 0, len(cookies); i < n; i++ {
  410. kv := &cookies[i]
  411. dst = append(dst, kv.value...)
  412. if i+1 < n {
  413. dst = append(dst, ';', ' ')
  414. }
  415. }
  416. return dst
  417. }
  418. func parseRequestCookies(cookies []argsKV, src []byte) []argsKV {
  419. var s cookieScanner
  420. s.b = src
  421. var kv *argsKV
  422. cookies, kv = allocArg(cookies)
  423. for s.next(kv) {
  424. if len(kv.key) > 0 || len(kv.value) > 0 {
  425. cookies, kv = allocArg(cookies)
  426. }
  427. }
  428. return releaseArg(cookies)
  429. }
  430. type cookieScanner struct {
  431. b []byte
  432. }
  433. func (s *cookieScanner) next(kv *argsKV) bool {
  434. b := s.b
  435. if len(b) == 0 {
  436. return false
  437. }
  438. isKey := true
  439. k := 0
  440. for i, c := range b {
  441. switch c {
  442. case '=':
  443. if isKey {
  444. isKey = false
  445. kv.key = decodeCookieArg(kv.key, b[:i], false)
  446. k = i + 1
  447. }
  448. case ';':
  449. if isKey {
  450. kv.key = kv.key[:0]
  451. }
  452. kv.value = decodeCookieArg(kv.value, b[k:i], true)
  453. s.b = b[i+1:]
  454. return true
  455. }
  456. }
  457. if isKey {
  458. kv.key = kv.key[:0]
  459. }
  460. kv.value = decodeCookieArg(kv.value, b[k:], true)
  461. s.b = b[len(b):]
  462. return true
  463. }
  464. func decodeCookieArg(dst, src []byte, skipQuotes bool) []byte {
  465. for len(src) > 0 && src[0] == ' ' {
  466. src = src[1:]
  467. }
  468. for len(src) > 0 && src[len(src)-1] == ' ' {
  469. src = src[:len(src)-1]
  470. }
  471. if skipQuotes {
  472. if len(src) > 1 && src[0] == '"' && src[len(src)-1] == '"' {
  473. src = src[1 : len(src)-1]
  474. }
  475. }
  476. return append(dst[:0], src...)
  477. }
  478. // caseInsensitiveCompare does a case insensitive equality comparison of
  479. // two []byte. Assumes only letters need to be matched.
  480. func caseInsensitiveCompare(a, b []byte) bool {
  481. if len(a) != len(b) {
  482. return false
  483. }
  484. for i := 0; i < len(a); i++ {
  485. if a[i]|0x20 != b[i]|0x20 {
  486. return false
  487. }
  488. }
  489. return true
  490. }