Debian Codegraph @

httpdate.go

raw
1 package utils
2
3 import (
4 "time"
5 )
6
7 // httpDateLayout is the RFC 9110 preferred date format (net/http.TimeFormat),
8 // a fixed-width 29-byte layout that doubles as the formatting template: every
9 // separator byte is already in place, so AppendHTTPDate only overwrites the
10 // fields.
11 const (
12 httpDateLayout = "Mon, 02 Jan 2006 15:04:05 GMT"
13 httpDateLen = len(httpDateLayout)
14 )
15
16 var (
17 httpWeekdays = [7]string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
18 httpMonths = [12]string{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
19
20 // httpDaysInMonth is indexed by time.Month; February is adjusted for
21 // leap years in daysInHTTPMonth.
22 httpDaysInMonth = [13]int{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
23 )
24
25 // Calendar fields are converted with Hinnant's civil_from_days and
26 // days_from_civil (400-year eras of 146097 days, origin -0400-03-01 so every
27 // intermediate is non-negative); the tests sweep every day of 0..9999.
28 const (
29 httpDateMinUnix = -62167219200 // 0000-01-01T00:00:00Z
30 httpDateMaxUnix = 253402300799 // 9999-12-31T23:59:59Z
31 secondsPerDay = 86400
32 daysPerEra = 146097
33 eraDaysToMarch = daysPerEra - 60 // 0000-01-01 to -0400-03-01
34 daysFromMarchEraToUnix = 719468 + daysPerEra // -0400-03-01 to 1970-01-01
35 weekdayOfYearZero = 6 // 0000-01-01 was a Saturday
36 )
37
38 // civilFromDays converts days since 0000-01-01 (at most 3652424) into a
39 // proleptic Gregorian year, month (1..12), and day (1..31).
40 func civilFromDays(days uint64) (year, month, day uint64) { //nolint:nonamedreturns // the three calendar fields are only readable named
41 z := days + eraDaysToMarch
42 era := z / daysPerEra
43 doe := z - era*daysPerEra // day of era, [0, 146096]
44 yoe := (doe - doe/1460 + doe/36524 - doe/146096) / 365 // year of era, [0, 399]
45 doy := doe - (365*yoe + yoe/4 - yoe/100) // day of March-based year, [0, 365]
46 mp := (5*doy + 2) / 153 // March-based month, [0, 11]
47 day = doy - (153*mp+2)/5 + 1
48 month = mp + 3
49 if mp >= 10 {
50 month = mp - 9
51 }
52 year = yoe + era*400 - 400
53 if month <= 2 {
54 year++
55 }
56 return year, month, day
57 }
58
59 // unixFromCivil returns the Unix time of valid UTC calendar fields with the
60 // year in 0..9999, as parseRFC1123 guarantees.
61 func unixFromCivil(year, month, day, hour, minute, sec int) int64 {
62 y := year + 400 // one era back keeps January/February of year 0 non-negative
63 mp := month + 9
64 if month > 2 {
65 mp = month - 3
66 } else {
67 y--
68 }
69 era := y / 400
70 yoe := y - era*400
71 doy := (153*mp+2)/5 + day - 1
72 doe := yoe*365 + yoe/4 - yoe/100 + doy
73 days := era*daysPerEra + doe - daysFromMarchEraToUnix
74 return int64(days)*secondsPerDay + int64(hour*3600+minute*60+sec)
75 }
76
77 // putPair writes n < 100 as two zero-padded digits at b[i] and b[i+1].
78 func putPair(b []byte, i int, n uint64) {
79 _ = b[i+1]
80 b[i] = decimalPairs[2*n]
81 b[i+1] = decimalPairs[2*n+1]
82 }
83
84 // AppendHTTPDate appends t in the RFC 9110 preferred HTTP date format
85 // ("Mon, 02 Jan 2006 15:04:05 GMT", net/http.TimeFormat) to dst and returns
86 // the extended slice. The output is byte-identical to
87 // t.UTC().AppendFormat(dst, http.TimeFormat) and always 29 bytes for the
88 // years 0..9999 that HTTP dates can represent; times outside that range
89 // delegate to time.AppendFormat.
90 func AppendHTTPDate(dst []byte, t time.Time) []byte {
91 sec := t.Unix()
92 if sec < httpDateMinUnix || sec > httpDateMaxUnix {
93 // RFC 1123 assumes a four-digit year; keep stdlib behavior for the
94 // unrepresentable rest instead of mis-padding it.
95 return t.UTC().AppendFormat(dst, httpDateLayout)
96 }
97 u := uint64(sec - httpDateMinUnix) // seconds since 0000-01-01, so every split is unsigned
98 days := u / secondsPerDay
99 sod := u - days*secondsPerDay
100 hour := sod / 3600
101 sod -= hour * 3600
102 minute := sod / 60
103 second := sod - minute*60
104 year, month, day := civilFromDays(days)
105
106 var b [httpDateLen]byte
107 copy(b[:], httpDateLayout)
108 weekday := httpWeekdays[(days+weekdayOfYearZero)%7] // byte stores: copy would be a memmove call
109 b[0], b[1], b[2] = weekday[0], weekday[1], weekday[2]
110 putPair(b[:], 5, day)
111 monthName := httpMonths[month-1]
112 b[8], b[9], b[10] = monthName[0], monthName[1], monthName[2]
113 century := year / 100
114 putPair(b[:], 12, century)
115 putPair(b[:], 14, year-century*100)
116 putPair(b[:], 17, hour)
117 putPair(b[:], 20, minute)
118 putPair(b[:], 23, second)
119 return append(dst, b[:]...)
120 }
121
122 // FormatHTTPDate returns t in the RFC 9110 preferred HTTP date format, equal
123 // to t.UTC().Format(http.TimeFormat) with a single allocation for the result.
124 func FormatHTTPDate(t time.Time) string {
125 var buf [httpDateLen]byte
126 return string(AppendHTTPDate(buf[:0], t))
127 }
128
129 // ParseHTTPDate parses an HTTP date the way net/http.ParseTime does:
130 // the RFC 9110 preferred format ("Mon, 02 Jan 2006 15:04:05 GMT") plus the
131 // obsolete RFC 850 and ANSI C asctime forms, with surrounding ASCII
132 // whitespace tolerated. Canonical preferred-format input takes a fast scalar
133 // path that never calls time.Parse; every other input — legacy formats,
134 // unusual casing, non-GMT zone names, padding — falls back to time.Parse
135 // with byte-for-byte stdlib semantics, including its errors. The returned
136 // time is in time.UTC on the fast path and whatever time.Parse yields on the
137 // fallback; the instants agree in both cases.
138 func ParseHTTPDate[S byteSeq](s S) (time.Time, error) {
139 if t, ok := parseRFC1123(s); ok {
140 return t, nil
141 }
142 return parseHTTPDateSlow(string(s))
143 }
144
145 // parseRFC1123 is the strict fast path for canonical
146 // "Mon, 02 Jan 2006 15:04:05 GMT" input: exact length, exact separators,
147 // exact-case names. It reports ok=false for anything else — including
148 // out-of-range fields — so the slow path can produce stdlib-identical
149 // results and errors for the long tail.
150 func parseRFC1123[S byteSeq](s S) (time.Time, bool) {
151 if len(s) != httpDateLen {
152 return time.Time{}, false
153 }
154 if s[3] != ',' || s[4] != ' ' || s[7] != ' ' || s[11] != ' ' || s[16] != ' ' ||
155 s[19] != ':' || s[22] != ':' || s[25] != ' ' ||
156 s[26] != 'G' || s[27] != 'M' || s[28] != 'T' {
157 return time.Time{}, false
158 }
159 if !isHTTPWeekday(pack3(s[0], s[1], s[2])) {
160 return time.Time{}, false
161 }
162 month := httpMonthNum(pack3(s[8], s[9], s[10]))
163 if month == 0 {
164 return time.Time{}, false
165 }
166 day, okDay := twoDigits(s[5], s[6])
167 yh, okYh := twoDigits(s[12], s[13])
168 yl, okYl := twoDigits(s[14], s[15])
169 hour, okHour := twoDigits(s[17], s[18])
170 minute, okMin := twoDigits(s[20], s[21])
171 sec, okSec := twoDigits(s[23], s[24])
172 if !okDay || !okYh || !okYl || !okHour || !okMin || !okSec {
173 return time.Time{}, false
174 }
175 year := yh*100 + yl
176 if hour > 23 || minute > 59 || sec > 59 ||
177 day < 1 || day > daysInHTTPMonth(month, year) {
178 // time.Parse rejects these; let it produce the exact error.
179 return time.Time{}, false
180 }
181 return time.Unix(unixFromCivil(year, month, day, hour, minute, sec), 0).UTC(), true
182 }
183
184 // parseHTTPDateSlow mirrors net/http.ParseTime: trim the whitespace
185 // textproto would, then try the three allowed layouts in order, returning
186 // the last error when none matches.
187 func parseHTTPDateSlow(s string) (time.Time, error) {
188 start, end := 0, len(s)
189 for start < end && isHTTPDateSpace(s[start]) {
190 start++
191 }
192 for start < end && isHTTPDateSpace(s[end-1]) {
193 end--
194 }
195 s = s[start:end]
196 t, err := time.Parse(httpDateLayout, s)
197 if err == nil {
198 return t, nil
199 }
200 if t, err850 := time.Parse(time.RFC850, s); err850 == nil {
201 return t, nil
202 }
203 t, errANSIC := time.Parse(time.ANSIC, s)
204 if errANSIC == nil {
205 return t, nil
206 }
207 return time.Time{}, errANSIC
208 }
209
210 // isHTTPDateSpace matches textproto.TrimString's notion of whitespace.
211 func isHTTPDateSpace(c byte) bool {
212 return c == ' ' || c == '\t' || c == '\r' || c == '\n'
213 }
214
215 // pack3 packs three bytes for the name switches below.
216 func pack3(a, b, c byte) uint32 {
217 return uint32(a)<<16 | uint32(b)<<8 | uint32(c)
218 }
219
220 // isHTTPWeekday reports whether w is one of the seven exact-case short
221 // weekday names. Like time.Parse, callers do not check the name against the
222 // date; any valid name is accepted.
223 func isHTTPWeekday(w uint32) bool {
224 switch w {
225 case 'S'<<16 | 'u'<<8 | 'n', 'M'<<16 | 'o'<<8 | 'n', 'T'<<16 | 'u'<<8 | 'e',
226 'W'<<16 | 'e'<<8 | 'd', 'T'<<16 | 'h'<<8 | 'u', 'F'<<16 | 'r'<<8 | 'i',
227 'S'<<16 | 'a'<<8 | 't':
228 return true
229 }
230 return false
231 }
232
233 // httpMonthNum maps an exact-case short month name to 1..12, or 0 if w is
234 // not one.
235 func httpMonthNum(w uint32) int {
236 switch w {
237 case 'J'<<16 | 'a'<<8 | 'n':
238 return 1
239 case 'F'<<16 | 'e'<<8 | 'b':
240 return 2
241 case 'M'<<16 | 'a'<<8 | 'r':
242 return 3
243 case 'A'<<16 | 'p'<<8 | 'r':
244 return 4
245 case 'M'<<16 | 'a'<<8 | 'y':
246 return 5
247 case 'J'<<16 | 'u'<<8 | 'n':
248 return 6
249 case 'J'<<16 | 'u'<<8 | 'l':
250 return 7
251 case 'A'<<16 | 'u'<<8 | 'g':
252 return 8
253 case 'S'<<16 | 'e'<<8 | 'p':
254 return 9
255 case 'O'<<16 | 'c'<<8 | 't':
256 return 10
257 case 'N'<<16 | 'o'<<8 | 'v':
258 return 11
259 case 'D'<<16 | 'e'<<8 | 'c':
260 return 12
261 }
262 return 0
263 }
264
265 // twoDigits parses two ASCII digits into an int, reporting whether both
266 // bytes were digits.
267 func twoDigits(a, b byte) (int, bool) {
268 a -= '0'
269 b -= '0'
270 if a > 9 || b > 9 {
271 return 0, false
272 }
273 return int(a)*10 + int(b), true
274 }
275
276 // daysInHTTPMonth returns the number of days in month for year, using the
277 // same leap-year rule as the time package.
278 func daysInHTTPMonth(month, year int) int {
279 if month == 2 && year%4 == 0 && (year%100 != 0 || year%400 == 0) {
280 return 29
281 }
282 return httpDaysInMonth[month]
283 }