File: directive.go

package info (click to toggle)
golang-github-pquerna-cachecontrol 0.0~git20171018.0dec1b3-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, experimental, forky, sid, trixie
  • size: 200 kB
  • sloc: makefile: 4
file content (510 lines) | stat: -rw-r--r-- 15,641 bytes parent folder | download | duplicates (6)
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
/**
 *  Copyright 2015 Paul Querna
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package cacheobject

import (
	"errors"
	"math"
	"net/http"
	"net/textproto"
	"strconv"
	"strings"
)

// TODO(pquerna): add extensions from here: http://www.iana.org/assignments/http-cache-directives/http-cache-directives.xhtml

var (
	ErrQuoteMismatch         = errors.New("Missing closing quote")
	ErrMaxAgeDeltaSeconds    = errors.New("Failed to parse delta-seconds in `max-age`")
	ErrSMaxAgeDeltaSeconds   = errors.New("Failed to parse delta-seconds in `s-maxage`")
	ErrMaxStaleDeltaSeconds  = errors.New("Failed to parse delta-seconds in `min-fresh`")
	ErrMinFreshDeltaSeconds  = errors.New("Failed to parse delta-seconds in `min-fresh`")
	ErrNoCacheNoArgs         = errors.New("Unexpected argument to `no-cache`")
	ErrNoStoreNoArgs         = errors.New("Unexpected argument to `no-store`")
	ErrNoTransformNoArgs     = errors.New("Unexpected argument to `no-transform`")
	ErrOnlyIfCachedNoArgs    = errors.New("Unexpected argument to `only-if-cached`")
	ErrMustRevalidateNoArgs  = errors.New("Unexpected argument to `must-revalidate`")
	ErrPublicNoArgs          = errors.New("Unexpected argument to `public`")
	ErrProxyRevalidateNoArgs = errors.New("Unexpected argument to `proxy-revalidate`")
)

func whitespace(b byte) bool {
	if b == '\t' || b == ' ' {
		return true
	}
	return false
}

func parse(value string, cd cacheDirective) error {
	var err error = nil
	i := 0

	for i < len(value) && err == nil {
		// eat leading whitespace or commas
		if whitespace(value[i]) || value[i] == ',' {
			i++
			continue
		}

		j := i + 1

		for j < len(value) {
			if !isToken(value[j]) {
				break
			}
			j++
		}

		token := strings.ToLower(value[i:j])
		tokenHasFields := hasFieldNames(token)
		/*
			println("GOT TOKEN:")
			println("	i -> ", i)
			println("	j -> ", j)
			println("	token -> ", token)
		*/

		if j+1 < len(value) && value[j] == '=' {
			k := j + 1
			// minimum size two bytes of "", but we let httpUnquote handle it.
			if k < len(value) && value[k] == '"' {
				eaten, result := httpUnquote(value[k:])
				if eaten == -1 {
					return ErrQuoteMismatch
				}
				i = k + eaten

				err = cd.addPair(token, result)
			} else {
				z := k
				for z < len(value) {
					if tokenHasFields {
						if whitespace(value[z]) {
							break
						}
					} else {
						if whitespace(value[z]) || value[z] == ',' {
							break
						}
					}
					z++
				}
				i = z

				result := value[k:z]
				if result != "" && result[len(result)-1] == ',' {
					result = result[:len(result)-1]
				}

				err = cd.addPair(token, result)
			}
		} else {
			if token != "," {
				err = cd.addToken(token)
			}
			i = j
		}
	}

	return err
}

// DeltaSeconds specifies a non-negative integer, representing
// time in seconds: http://tools.ietf.org/html/rfc7234#section-1.2.1
//
// When set to -1, this means unset.
//
type DeltaSeconds int32

// Parser for delta-seconds, a uint31, more or less:
// http://tools.ietf.org/html/rfc7234#section-1.2.1
func parseDeltaSeconds(v string) (DeltaSeconds, error) {
	n, err := strconv.ParseUint(v, 10, 32)
	if err != nil {
		if numError, ok := err.(*strconv.NumError); ok {
			if numError.Err == strconv.ErrRange {
				return DeltaSeconds(math.MaxInt32), nil
			}
		}
		return DeltaSeconds(-1), err
	} else {
		if n > math.MaxInt32 {
			return DeltaSeconds(math.MaxInt32), nil
		} else {
			return DeltaSeconds(n), nil
		}
	}
}

// Fields present in a header.
type FieldNames map[string]bool

// internal interface for shared methods of RequestCacheDirectives and ResponseCacheDirectives
type cacheDirective interface {
	addToken(s string) error
	addPair(s string, v string) error
}

// LOW LEVEL API: Repersentation of possible request directives in a `Cache-Control` header: http://tools.ietf.org/html/rfc7234#section-5.2.1
//
// Note: Many fields will be `nil` in practice.
//
type RequestCacheDirectives struct {

	// max-age(delta seconds): http://tools.ietf.org/html/rfc7234#section-5.2.1.1
	//
	// The "max-age" request directive indicates that the client is
	// unwilling to accept a response whose age is greater than the
	// specified number of seconds.  Unless the max-stale request directive
	// is also present, the client is not willing to accept a stale
	// response.
	MaxAge DeltaSeconds

	// max-stale(delta seconds): http://tools.ietf.org/html/rfc7234#section-5.2.1.2
	//
	// The "max-stale" request directive indicates that the client is
	// willing to accept a response that has exceeded its freshness
	// lifetime.  If max-stale is assigned a value, then the client is
	// willing to accept a response that has exceeded its freshness lifetime
	// by no more than the specified number of seconds.  If no value is
	// assigned to max-stale, then the client is willing to accept a stale
	// response of any age.
	MaxStale DeltaSeconds

	// min-fresh(delta seconds): http://tools.ietf.org/html/rfc7234#section-5.2.1.3
	//
	// The "min-fresh" request directive indicates that the client is
	// willing to accept a response whose freshness lifetime is no less than
	// its current age plus the specified time in seconds.  That is, the
	// client wants a response that will still be fresh for at least the
	// specified number of seconds.
	MinFresh DeltaSeconds

	// no-cache(bool): http://tools.ietf.org/html/rfc7234#section-5.2.1.4
	//
	// The "no-cache" request directive indicates that a cache MUST NOT use
	// a stored response to satisfy the request without successful
	// validation on the origin server.
	NoCache bool

	// no-store(bool): http://tools.ietf.org/html/rfc7234#section-5.2.1.5
	//
	// The "no-store" request directive indicates that a cache MUST NOT
	// store any part of either this request or any response to it.  This
	// directive applies to both private and shared caches.
	NoStore bool

	// no-transform(bool): http://tools.ietf.org/html/rfc7234#section-5.2.1.6
	//
	// The "no-transform" request directive indicates that an intermediary
	// (whether or not it implements a cache) MUST NOT transform the
	// payload, as defined in Section 5.7.2 of RFC7230.
	NoTransform bool

	// only-if-cached(bool): http://tools.ietf.org/html/rfc7234#section-5.2.1.7
	//
	// The "only-if-cached" request directive indicates that the client only
	// wishes to obtain a stored response.
	OnlyIfCached bool

	// Extensions: http://tools.ietf.org/html/rfc7234#section-5.2.3
	//
	// The Cache-Control header field can be extended through the use of one
	// or more cache-extension tokens, each with an optional value.  A cache
	// MUST ignore unrecognized cache directives.
	Extensions []string
}

func (cd *RequestCacheDirectives) addToken(token string) error {
	var err error = nil

	switch token {
	case "max-age":
		err = ErrMaxAgeDeltaSeconds
	case "max-stale":
		err = ErrMaxStaleDeltaSeconds
	case "min-fresh":
		err = ErrMinFreshDeltaSeconds
	case "no-cache":
		cd.NoCache = true
	case "no-store":
		cd.NoStore = true
	case "no-transform":
		cd.NoTransform = true
	case "only-if-cached":
		cd.OnlyIfCached = true
	default:
		cd.Extensions = append(cd.Extensions, token)
	}
	return err
}

func (cd *RequestCacheDirectives) addPair(token string, v string) error {
	var err error = nil

	switch token {
	case "max-age":
		cd.MaxAge, err = parseDeltaSeconds(v)
		if err != nil {
			err = ErrMaxAgeDeltaSeconds
		}
	case "max-stale":
		cd.MaxStale, err = parseDeltaSeconds(v)
		if err != nil {
			err = ErrMaxStaleDeltaSeconds
		}
	case "min-fresh":
		cd.MinFresh, err = parseDeltaSeconds(v)
		if err != nil {
			err = ErrMinFreshDeltaSeconds
		}
	case "no-cache":
		err = ErrNoCacheNoArgs
	case "no-store":
		err = ErrNoStoreNoArgs
	case "no-transform":
		err = ErrNoTransformNoArgs
	case "only-if-cached":
		err = ErrOnlyIfCachedNoArgs
	default:
		// TODO(pquerna): this sucks, making user re-parse
		cd.Extensions = append(cd.Extensions, token+"="+v)
	}

	return err
}

// LOW LEVEL API: Parses a Cache Control Header from a Request into a set of directives.
func ParseRequestCacheControl(value string) (*RequestCacheDirectives, error) {
	cd := &RequestCacheDirectives{
		MaxAge:   -1,
		MaxStale: -1,
		MinFresh: -1,
	}

	err := parse(value, cd)
	if err != nil {
		return nil, err
	}
	return cd, nil
}

// LOW LEVEL API: Repersentation of possible response directives in a `Cache-Control` header: http://tools.ietf.org/html/rfc7234#section-5.2.2
//
// Note: Many fields will be `nil` in practice.
//
type ResponseCacheDirectives struct {

	// must-revalidate(bool): http://tools.ietf.org/html/rfc7234#section-5.2.2.1
	//
	// The "must-revalidate" response directive indicates that once it has
	// become stale, a cache MUST NOT use the response to satisfy subsequent
	// requests without successful validation on the origin server.
	MustRevalidate bool

	// no-cache(FieldName): http://tools.ietf.org/html/rfc7234#section-5.2.2.2
	//
	// The "no-cache" response directive indicates that the response MUST
	// NOT be used to satisfy a subsequent request without successful
	// validation on the origin server.
	//
	// If the no-cache response directive specifies one or more field-names,
	// then a cache MAY use the response to satisfy a subsequent request,
	// subject to any other restrictions on caching.  However, any header
	// fields in the response that have the field-name(s) listed MUST NOT be
	// sent in the response to a subsequent request without successful
	// revalidation with the origin server.
	NoCache FieldNames

	// no-cache(cast-to-bool): http://tools.ietf.org/html/rfc7234#section-5.2.2.2
	//
	// While the RFC defines optional field-names on a no-cache directive,
	// many applications only want to know if any no-cache directives were
	// present at all.
	NoCachePresent bool

	// no-store(bool): http://tools.ietf.org/html/rfc7234#section-5.2.2.3
	//
	// The "no-store" request directive indicates that a cache MUST NOT
	// store any part of either this request or any response to it.  This
	// directive applies to both private and shared caches.
	NoStore bool

	// no-transform(bool): http://tools.ietf.org/html/rfc7234#section-5.2.2.4
	//
	// The "no-transform" response directive indicates that an intermediary
	// (regardless of whether it implements a cache) MUST NOT transform the
	// payload, as defined in Section 5.7.2 of RFC7230.
	NoTransform bool

	// public(bool): http://tools.ietf.org/html/rfc7234#section-5.2.2.5
	//
	// The "public" response directive indicates that any cache MAY store
	// the response, even if the response would normally be non-cacheable or
	// cacheable only within a private cache.
	Public bool

	// private(FieldName): http://tools.ietf.org/html/rfc7234#section-5.2.2.6
	//
	// The "private" response directive indicates that the response message
	// is intended for a single user and MUST NOT be stored by a shared
	// cache.  A private cache MAY store the response and reuse it for later
	// requests, even if the response would normally be non-cacheable.
	//
	// If the private response directive specifies one or more field-names,
	// this requirement is limited to the field-values associated with the
	// listed response header fields.  That is, a shared cache MUST NOT
	// store the specified field-names(s), whereas it MAY store the
	// remainder of the response message.
	Private FieldNames

	// private(cast-to-bool): http://tools.ietf.org/html/rfc7234#section-5.2.2.6
	//
	// While the RFC defines optional field-names on a private directive,
	// many applications only want to know if any private directives were
	// present at all.
	PrivatePresent bool

	// proxy-revalidate(bool): http://tools.ietf.org/html/rfc7234#section-5.2.2.7
	//
	// The "proxy-revalidate" response directive has the same meaning as the
	// must-revalidate response directive, except that it does not apply to
	// private caches.
	ProxyRevalidate bool

	// max-age(delta seconds): http://tools.ietf.org/html/rfc7234#section-5.2.2.8
	//
	// The "max-age" response directive indicates that the response is to be
	// considered stale after its age is greater than the specified number
	// of seconds.
	MaxAge DeltaSeconds

	// s-maxage(delta seconds): http://tools.ietf.org/html/rfc7234#section-5.2.2.9
	//
	// The "s-maxage" response directive indicates that, in shared caches,
	// the maximum age specified by this directive overrides the maximum age
	// specified by either the max-age directive or the Expires header
	// field.  The s-maxage directive also implies the semantics of the
	// proxy-revalidate response directive.
	SMaxAge DeltaSeconds

	// Extensions: http://tools.ietf.org/html/rfc7234#section-5.2.3
	//
	// The Cache-Control header field can be extended through the use of one
	// or more cache-extension tokens, each with an optional value.  A cache
	// MUST ignore unrecognized cache directives.
	Extensions []string
}

// LOW LEVEL API: Parses a Cache Control Header from a Response into a set of directives.
func ParseResponseCacheControl(value string) (*ResponseCacheDirectives, error) {
	cd := &ResponseCacheDirectives{
		MaxAge:  -1,
		SMaxAge: -1,
	}

	err := parse(value, cd)
	if err != nil {
		return nil, err
	}
	return cd, nil
}

func (cd *ResponseCacheDirectives) addToken(token string) error {
	var err error = nil
	switch token {
	case "must-revalidate":
		cd.MustRevalidate = true
	case "no-cache":
		cd.NoCachePresent = true
	case "no-store":
		cd.NoStore = true
	case "no-transform":
		cd.NoTransform = true
	case "public":
		cd.Public = true
	case "private":
		cd.PrivatePresent = true
	case "proxy-revalidate":
		cd.ProxyRevalidate = true
	case "max-age":
		err = ErrMaxAgeDeltaSeconds
	case "s-maxage":
		err = ErrSMaxAgeDeltaSeconds
	default:
		cd.Extensions = append(cd.Extensions, token)
	}
	return err
}

func hasFieldNames(token string) bool {
	switch token {
	case "no-cache":
		return true
	case "private":
		return true
	}
	return false
}

func (cd *ResponseCacheDirectives) addPair(token string, v string) error {
	var err error = nil

	switch token {
	case "must-revalidate":
		err = ErrMustRevalidateNoArgs
	case "no-cache":
		cd.NoCachePresent = true
		tokens := strings.Split(v, ",")
		if cd.NoCache == nil {
			cd.NoCache = make(FieldNames)
		}
		for _, t := range tokens {
			k := http.CanonicalHeaderKey(textproto.TrimString(t))
			cd.NoCache[k] = true
		}
	case "no-store":
		err = ErrNoStoreNoArgs
	case "no-transform":
		err = ErrNoTransformNoArgs
	case "public":
		err = ErrPublicNoArgs
	case "private":
		cd.PrivatePresent = true
		tokens := strings.Split(v, ",")
		if cd.Private == nil {
			cd.Private = make(FieldNames)
		}
		for _, t := range tokens {
			k := http.CanonicalHeaderKey(textproto.TrimString(t))
			cd.Private[k] = true
		}
	case "proxy-revalidate":
		err = ErrProxyRevalidateNoArgs
	case "max-age":
		cd.MaxAge, err = parseDeltaSeconds(v)
	case "s-maxage":
		cd.SMaxAge, err = parseDeltaSeconds(v)
	default:
		// TODO(pquerna): this sucks, making user re-parse, and its technically not 'quoted' like the original,
		// but this is still easier, just a SplitN on "="
		cd.Extensions = append(cd.Extensions, token+"="+v)
	}

	return err
}