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
|
package httpcc
import (
"bufio"
"fmt"
"strconv"
"strings"
"unicode/utf8"
)
const (
// Request Cache-Control directives
MaxAge = "max-age" // used in response as well
MaxStale = "max-stale"
MinFresh = "min-fresh"
NoCache = "no-cache" // used in response as well
NoStore = "no-store" // used in response as well
NoTransform = "no-transform" // used in response as well
OnlyIfCached = "only-if-cached"
// Response Cache-Control directive
MustRevalidate = "must-revalidate"
Public = "public"
Private = "private"
ProxyRevalidate = "proxy-revalidate"
SMaxAge = "s-maxage"
)
type TokenPair struct {
Name string
Value string
}
type TokenValuePolicy int
const (
NoArgument TokenValuePolicy = iota
TokenOnly
QuotedStringOnly
AnyTokenValue
)
type directiveValidator interface {
Validate(string) TokenValuePolicy
}
type directiveValidatorFn func(string) TokenValuePolicy
func (fn directiveValidatorFn) Validate(ccd string) TokenValuePolicy {
return fn(ccd)
}
func responseDirectiveValidator(s string) TokenValuePolicy {
switch s {
case MustRevalidate, NoStore, NoTransform, Public, ProxyRevalidate:
return NoArgument
case NoCache, Private:
return QuotedStringOnly
case MaxAge, SMaxAge:
return TokenOnly
default:
return AnyTokenValue
}
}
func requestDirectiveValidator(s string) TokenValuePolicy {
switch s {
case MaxAge, MaxStale, MinFresh:
return TokenOnly
case NoCache, NoStore, NoTransform, OnlyIfCached:
return NoArgument
default:
return AnyTokenValue
}
}
// ParseRequestDirective parses a single token.
func ParseRequestDirective(s string) (*TokenPair, error) {
return parseDirective(s, directiveValidatorFn(requestDirectiveValidator))
}
func ParseResponseDirective(s string) (*TokenPair, error) {
return parseDirective(s, directiveValidatorFn(responseDirectiveValidator))
}
func parseDirective(s string, ccd directiveValidator) (*TokenPair, error) {
s = strings.TrimSpace(s)
i := strings.IndexByte(s, '=')
if i == -1 {
return &TokenPair{Name: s}, nil
}
pair := &TokenPair{Name: strings.TrimSpace(s[:i])}
if len(s) <= i {
// `key=` feels like it's a parse error, but it's HTTP...
// for now, return as if nothing happened.
return pair, nil
}
v := strings.TrimSpace(s[i+1:])
switch ccd.Validate(pair.Name) {
case TokenOnly:
if v[0] == '"' {
return nil, fmt.Errorf(`invalid value for %s (quoted string not allowed)`, pair.Name)
}
case QuotedStringOnly: // quoted-string only
if v[0] != '"' {
return nil, fmt.Errorf(`invalid value for %s (bare token not allowed)`, pair.Name)
}
tmp, err := strconv.Unquote(v)
if err != nil {
return nil, fmt.Errorf(`malformed quoted string in token`)
}
v = tmp
case AnyTokenValue:
if v[0] == '"' {
tmp, err := strconv.Unquote(v)
if err != nil {
return nil, fmt.Errorf(`malformed quoted string in token`)
}
v = tmp
}
case NoArgument:
if len(v) > 0 {
return nil, fmt.Errorf(`received argument to directive %s`, pair.Name)
}
}
pair.Value = v
return pair, nil
}
func ParseResponseDirectives(s string) ([]*TokenPair, error) {
return parseDirectives(s, ParseResponseDirective)
}
func ParseRequestDirectives(s string) ([]*TokenPair, error) {
return parseDirectives(s, ParseRequestDirective)
}
func parseDirectives(s string, p func(string) (*TokenPair, error)) ([]*TokenPair, error) {
scanner := bufio.NewScanner(strings.NewReader(s))
scanner.Split(scanCommaSeparatedWords)
var tokens []*TokenPair
for scanner.Scan() {
tok, err := p(scanner.Text())
if err != nil {
return nil, fmt.Errorf(`failed to parse token #%d: %w`, len(tokens)+1, err)
}
tokens = append(tokens, tok)
}
return tokens, nil
}
// isSpace reports whether the character is a Unicode white space character.
// We avoid dependency on the unicode package, but check validity of the implementation
// in the tests.
func isSpace(r rune) bool {
if r <= '\u00FF' {
// Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs.
switch r {
case ' ', '\t', '\n', '\v', '\f', '\r':
return true
case '\u0085', '\u00A0':
return true
}
return false
}
// High-valued ones.
if '\u2000' <= r && r <= '\u200a' {
return true
}
switch r {
case '\u1680', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000':
return true
}
return false
}
func scanCommaSeparatedWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
// Skip leading spaces.
start := 0
for width := 0; start < len(data); start += width {
var r rune
r, width = utf8.DecodeRune(data[start:])
if !isSpace(r) {
break
}
}
// Scan until we find a comma. Keep track of consecutive whitespaces
// so we remove them from the end result
var ws int
for width, i := 0, start; i < len(data); i += width {
var r rune
r, width = utf8.DecodeRune(data[i:])
switch {
case isSpace(r):
ws++
case r == ',':
return i + width, data[start : i-ws], nil
default:
ws = 0
}
}
// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
if atEOF && len(data) > start {
return len(data), data[start : len(data)-ws], nil
}
// Request more data.
return start, nil, nil
}
// ParseRequest parses the content of `Cache-Control` header of an HTTP Request.
func ParseRequest(v string) (*RequestDirective, error) {
var dir RequestDirective
tokens, err := ParseRequestDirectives(v)
if err != nil {
return nil, fmt.Errorf(`failed to parse tokens: %w`, err)
}
for _, token := range tokens {
name := strings.ToLower(token.Name)
switch name {
case MaxAge:
iv, err := strconv.ParseUint(token.Value, 10, 64)
if err != nil {
return nil, fmt.Errorf(`failed to parse max-age: %w`, err)
}
dir.maxAge = &iv
case MaxStale:
iv, err := strconv.ParseUint(token.Value, 10, 64)
if err != nil {
return nil, fmt.Errorf(`failed to parse max-stale: %w`, err)
}
dir.maxStale = &iv
case MinFresh:
iv, err := strconv.ParseUint(token.Value, 10, 64)
if err != nil {
return nil, fmt.Errorf(`failed to parse min-fresh: %w`, err)
}
dir.minFresh = &iv
case NoCache:
dir.noCache = true
case NoStore:
dir.noStore = true
case NoTransform:
dir.noTransform = true
case OnlyIfCached:
dir.onlyIfCached = true
default:
dir.extensions[token.Name] = token.Value
}
}
return &dir, nil
}
// ParseResponse parses the content of `Cache-Control` header of an HTTP Response.
func ParseResponse(v string) (*ResponseDirective, error) {
tokens, err := ParseResponseDirectives(v)
if err != nil {
return nil, fmt.Errorf(`failed to parse tokens: %w`, err)
}
var dir ResponseDirective
dir.extensions = make(map[string]string)
for _, token := range tokens {
name := strings.ToLower(token.Name)
switch name {
case MaxAge:
iv, err := strconv.ParseUint(token.Value, 10, 64)
if err != nil {
return nil, fmt.Errorf(`failed to parse max-age: %w`, err)
}
dir.maxAge = &iv
case NoCache:
scanner := bufio.NewScanner(strings.NewReader(token.Value))
scanner.Split(scanCommaSeparatedWords)
for scanner.Scan() {
dir.noCache = append(dir.noCache, scanner.Text())
}
case NoStore:
dir.noStore = true
case NoTransform:
dir.noTransform = true
case Public:
dir.public = true
case Private:
scanner := bufio.NewScanner(strings.NewReader(token.Value))
scanner.Split(scanCommaSeparatedWords)
for scanner.Scan() {
dir.private = append(dir.private, scanner.Text())
}
case ProxyRevalidate:
dir.proxyRevalidate = true
case SMaxAge:
iv, err := strconv.ParseUint(token.Value, 10, 64)
if err != nil {
return nil, fmt.Errorf(`failed to parse s-maxage: %w`, err)
}
dir.sMaxAge = &iv
default:
dir.extensions[token.Name] = token.Value
}
}
return &dir, nil
}
|