1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
15 // This implementation is done according to RFC 6265:
17 // http://tools.ietf.org/html/rfc6265
19 // A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an
20 // HTTP response or the Cookie header of an HTTP request.
29 // MaxAge=0 means no 'Max-Age' attribute specified.
30 // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
31 // MaxAge>0 means Max-Age attribute present and given in seconds
36 Unparsed []string // Raw text of unparsed attribute-value pairs
39 // readSetCookies parses all "Set-Cookie" values from
40 // the header h and returns the successfully parsed Cookies.
41 func readSetCookies(h Header) []*Cookie {
42 cookies := []*Cookie{}
43 for _, line := range h["Set-Cookie"] {
44 parts := strings.Split(strings.TrimSpace(line), ";")
45 if len(parts) == 1 && parts[0] == "" {
48 parts[0] = strings.TrimSpace(parts[0])
49 j := strings.Index(parts[0], "=")
53 name, value := parts[0][:j], parts[0][j+1:]
54 if !isCookieNameValid(name) {
57 value, success := parseCookieValue(value)
66 for i := 1; i < len(parts); i++ {
67 parts[i] = strings.TrimSpace(parts[i])
68 if len(parts[i]) == 0 {
72 attr, val := parts[i], ""
73 if j := strings.Index(attr, "="); j >= 0 {
74 attr, val = attr[:j], attr[j+1:]
76 lowerAttr := strings.ToLower(attr)
77 parseCookieValueFn := parseCookieValue
78 if lowerAttr == "expires" {
79 parseCookieValueFn = parseCookieExpiresValue
81 val, success = parseCookieValueFn(val)
83 c.Unparsed = append(c.Unparsed, parts[i])
95 // TODO: Add domain parsing
98 secs, err := strconv.Atoi(val)
99 if err != nil || secs < 0 || secs != 0 && val[0] == '0' {
110 exptime, err := time.Parse(time.RFC1123, val)
112 exptime, err = time.Parse("Mon, 02-Jan-2006 15:04:05 MST", val)
114 c.Expires = time.Time{}
122 // TODO: Add path parsing
125 c.Unparsed = append(c.Unparsed, parts[i])
127 cookies = append(cookies, c)
132 // SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers.
133 func SetCookie(w ResponseWriter, cookie *Cookie) {
134 w.Header().Add("Set-Cookie", cookie.String())
137 // String returns the serialization of the cookie for use in a Cookie
138 // header (if only Name and Value are set) or a Set-Cookie response
139 // header (if other fields are set).
140 func (c *Cookie) String() string {
142 fmt.Fprintf(&b, "%s=%s", sanitizeName(c.Name), sanitizeValue(c.Value))
144 fmt.Fprintf(&b, "; Path=%s", sanitizeValue(c.Path))
146 if len(c.Domain) > 0 {
147 fmt.Fprintf(&b, "; Domain=%s", sanitizeValue(c.Domain))
149 if len(c.Expires.Zone) > 0 {
150 fmt.Fprintf(&b, "; Expires=%s", c.Expires.Format(time.RFC1123))
153 fmt.Fprintf(&b, "; Max-Age=%d", c.MaxAge)
154 } else if c.MaxAge < 0 {
155 fmt.Fprintf(&b, "; Max-Age=0")
158 fmt.Fprintf(&b, "; HttpOnly")
161 fmt.Fprintf(&b, "; Secure")
166 // readCookies parses all "Cookie" values from the header h and
167 // returns the successfully parsed Cookies.
169 // if filter isn't empty, only cookies of that name are returned
170 func readCookies(h Header, filter string) []*Cookie {
171 cookies := []*Cookie{}
172 lines, ok := h["Cookie"]
177 for _, line := range lines {
178 parts := strings.Split(strings.TrimSpace(line), ";")
179 if len(parts) == 1 && parts[0] == "" {
182 // Per-line attributes
184 for i := 0; i < len(parts); i++ {
185 parts[i] = strings.TrimSpace(parts[i])
186 if len(parts[i]) == 0 {
189 name, val := parts[i], ""
190 if j := strings.Index(name, "="); j >= 0 {
191 name, val = name[:j], name[j+1:]
193 if !isCookieNameValid(name) {
196 if filter != "" && filter != name {
199 val, success := parseCookieValue(val)
203 cookies = append(cookies, &Cookie{Name: name, Value: val})
210 var cookieNameSanitizer = strings.NewReplacer("\n", "-", "\r", "-")
212 func sanitizeName(n string) string {
213 return cookieNameSanitizer.Replace(n)
216 var cookieValueSanitizer = strings.NewReplacer("\n", " ", "\r", " ", ";", " ")
218 func sanitizeValue(v string) string {
219 return cookieValueSanitizer.Replace(v)
222 func unquoteCookieValue(v string) string {
223 if len(v) > 1 && v[0] == '"' && v[len(v)-1] == '"' {
224 return v[1 : len(v)-1]
229 func isCookieByte(c byte) bool {
231 case c == 0x21, 0x23 <= c && c <= 0x2b, 0x2d <= c && c <= 0x3a,
232 0x3c <= c && c <= 0x5b, 0x5d <= c && c <= 0x7e:
238 func isCookieExpiresByte(c byte) (ok bool) {
239 return isCookieByte(c) || c == ',' || c == ' '
242 func parseCookieValue(raw string) (string, bool) {
243 return parseCookieValueUsing(raw, isCookieByte)
246 func parseCookieExpiresValue(raw string) (string, bool) {
247 return parseCookieValueUsing(raw, isCookieExpiresByte)
250 func parseCookieValueUsing(raw string, validByte func(byte) bool) (string, bool) {
251 raw = unquoteCookieValue(raw)
252 for i := 0; i < len(raw); i++ {
253 if !validByte(raw[i]) {
260 func isCookieNameValid(raw string) bool {
261 for _, c := range raw {
262 if !isToken(byte(c)) {