]> Cypherpunks.ru repositories - gostls13.git/blob - src/time/zoneinfo_read.go
lib/time, time, time/tzdata: use slim tz data format
[gostls13.git] / src / time / zoneinfo_read.go
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.
4
5 // Parse "zoneinfo" time zone file.
6 // This is a fairly standard file format used on OS X, Linux, BSD, Sun, and others.
7 // See tzfile(5), https://en.wikipedia.org/wiki/Zoneinfo,
8 // and ftp://munnari.oz.au/pub/oldtz/
9
10 package time
11
12 import (
13         "errors"
14         "runtime"
15         "syscall"
16 )
17
18 // registerLoadFromEmbeddedTZData is called by the time/tzdata package,
19 // if it is imported.
20 func registerLoadFromEmbeddedTZData(f func(string) (string, error)) {
21         loadFromEmbeddedTZData = f
22 }
23
24 // loadFromEmbeddedTZData is used to load a specific tzdata file
25 // from tzdata information embedded in the binary itself.
26 // This is set when the time/tzdata package is imported,
27 // via registerLoadFromEmbeddedTzdata.
28 var loadFromEmbeddedTZData func(zipname string) (string, error)
29
30 // maxFileSize is the max permitted size of files read by readFile.
31 // As reference, the zoneinfo.zip distributed by Go is ~350 KB,
32 // so 10MB is overkill.
33 const maxFileSize = 10 << 20
34
35 type fileSizeError string
36
37 func (f fileSizeError) Error() string {
38         return "time: file " + string(f) + " is too large"
39 }
40
41 // Copies of io.Seek* constants to avoid importing "io":
42 const (
43         seekStart   = 0
44         seekCurrent = 1
45         seekEnd     = 2
46 )
47
48 // Simple I/O interface to binary blob of data.
49 type dataIO struct {
50         p     []byte
51         error bool
52 }
53
54 func (d *dataIO) read(n int) []byte {
55         if len(d.p) < n {
56                 d.p = nil
57                 d.error = true
58                 return nil
59         }
60         p := d.p[0:n]
61         d.p = d.p[n:]
62         return p
63 }
64
65 func (d *dataIO) big4() (n uint32, ok bool) {
66         p := d.read(4)
67         if len(p) < 4 {
68                 d.error = true
69                 return 0, false
70         }
71         return uint32(p[3]) | uint32(p[2])<<8 | uint32(p[1])<<16 | uint32(p[0])<<24, true
72 }
73
74 func (d *dataIO) big8() (n uint64, ok bool) {
75         n1, ok1 := d.big4()
76         n2, ok2 := d.big4()
77         if !ok1 || !ok2 {
78                 d.error = true
79                 return 0, false
80         }
81         return (uint64(n1) << 32) | uint64(n2), true
82 }
83
84 func (d *dataIO) byte() (n byte, ok bool) {
85         p := d.read(1)
86         if len(p) < 1 {
87                 d.error = true
88                 return 0, false
89         }
90         return p[0], true
91 }
92
93 // read returns the read of the data in the buffer.
94 func (d *dataIO) rest() []byte {
95         r := d.p
96         d.p = nil
97         return r
98 }
99
100 // Make a string by stopping at the first NUL
101 func byteString(p []byte) string {
102         for i := 0; i < len(p); i++ {
103                 if p[i] == 0 {
104                         return string(p[0:i])
105                 }
106         }
107         return string(p)
108 }
109
110 var badData = errors.New("malformed time zone information")
111
112 // LoadLocationFromTZData returns a Location with the given name
113 // initialized from the IANA Time Zone database-formatted data.
114 // The data should be in the format of a standard IANA time zone file
115 // (for example, the content of /etc/localtime on Unix systems).
116 func LoadLocationFromTZData(name string, data []byte) (*Location, error) {
117         d := dataIO{data, false}
118
119         // 4-byte magic "TZif"
120         if magic := d.read(4); string(magic) != "TZif" {
121                 return nil, badData
122         }
123
124         // 1-byte version, then 15 bytes of padding
125         var version int
126         var p []byte
127         if p = d.read(16); len(p) != 16 {
128                 return nil, badData
129         } else {
130                 switch p[0] {
131                 case 0:
132                         version = 1
133                 case '2':
134                         version = 2
135                 case '3':
136                         version = 3
137                 default:
138                         return nil, badData
139                 }
140         }
141
142         // six big-endian 32-bit integers:
143         //      number of UTC/local indicators
144         //      number of standard/wall indicators
145         //      number of leap seconds
146         //      number of transition times
147         //      number of local time zones
148         //      number of characters of time zone abbrev strings
149         const (
150                 NUTCLocal = iota
151                 NStdWall
152                 NLeap
153                 NTime
154                 NZone
155                 NChar
156         )
157         var n [6]int
158         for i := 0; i < 6; i++ {
159                 nn, ok := d.big4()
160                 if !ok {
161                         return nil, badData
162                 }
163                 if uint32(int(nn)) != nn {
164                         return nil, badData
165                 }
166                 n[i] = int(nn)
167         }
168
169         // If we have version 2 or 3, then the data is first written out
170         // in a 32-bit format, then written out again in a 64-bit format.
171         // Skip the 32-bit format and read the 64-bit one, as it can
172         // describe a broader range of dates.
173
174         is64 := false
175         if version > 1 {
176                 // Skip the 32-bit data.
177                 skip := n[NTime]*4 +
178                         n[NTime] +
179                         n[NZone]*6 +
180                         n[NChar] +
181                         n[NLeap]*8 +
182                         n[NStdWall] +
183                         n[NUTCLocal]
184                 // Skip the version 2 header that we just read.
185                 skip += 4 + 16
186                 d.read(skip)
187
188                 is64 = true
189
190                 // Read the counts again, they can differ.
191                 for i := 0; i < 6; i++ {
192                         nn, ok := d.big4()
193                         if !ok {
194                                 return nil, badData
195                         }
196                         if uint32(int(nn)) != nn {
197                                 return nil, badData
198                         }
199                         n[i] = int(nn)
200                 }
201         }
202
203         size := 4
204         if is64 {
205                 size = 8
206         }
207
208         // Transition times.
209         txtimes := dataIO{d.read(n[NTime] * size), false}
210
211         // Time zone indices for transition times.
212         txzones := d.read(n[NTime])
213
214         // Zone info structures
215         zonedata := dataIO{d.read(n[NZone] * 6), false}
216
217         // Time zone abbreviations.
218         abbrev := d.read(n[NChar])
219
220         // Leap-second time pairs
221         d.read(n[NLeap] * (size + 4))
222
223         // Whether tx times associated with local time types
224         // are specified as standard time or wall time.
225         isstd := d.read(n[NStdWall])
226
227         // Whether tx times associated with local time types
228         // are specified as UTC or local time.
229         isutc := d.read(n[NUTCLocal])
230
231         if d.error { // ran out of data
232                 return nil, badData
233         }
234
235         var extend string
236         rest := d.rest()
237         if len(rest) > 2 && rest[0] == '\n' && rest[len(rest)-1] == '\n' {
238                 extend = string(rest[1 : len(rest)-1])
239         }
240
241         // Now we can build up a useful data structure.
242         // First the zone information.
243         //      utcoff[4] isdst[1] nameindex[1]
244         nzone := n[NZone]
245         if nzone == 0 {
246                 // Reject tzdata files with no zones. There's nothing useful in them.
247                 // This also avoids a panic later when we add and then use a fake transition (golang.org/issue/29437).
248                 return nil, badData
249         }
250         zone := make([]zone, nzone)
251         for i := range zone {
252                 var ok bool
253                 var n uint32
254                 if n, ok = zonedata.big4(); !ok {
255                         return nil, badData
256                 }
257                 if uint32(int(n)) != n {
258                         return nil, badData
259                 }
260                 zone[i].offset = int(int32(n))
261                 var b byte
262                 if b, ok = zonedata.byte(); !ok {
263                         return nil, badData
264                 }
265                 zone[i].isDST = b != 0
266                 if b, ok = zonedata.byte(); !ok || int(b) >= len(abbrev) {
267                         return nil, badData
268                 }
269                 zone[i].name = byteString(abbrev[b:])
270                 if runtime.GOOS == "aix" && len(name) > 8 && (name[:8] == "Etc/GMT+" || name[:8] == "Etc/GMT-") {
271                         // There is a bug with AIX 7.2 TL 0 with files in Etc,
272                         // GMT+1 will return GMT-1 instead of GMT+1 or -01.
273                         if name != "Etc/GMT+0" {
274                                 // GMT+0 is OK
275                                 zone[i].name = name[4:]
276                         }
277                 }
278         }
279
280         // Now the transition time info.
281         tx := make([]zoneTrans, n[NTime])
282         for i := range tx {
283                 var n int64
284                 if !is64 {
285                         if n4, ok := txtimes.big4(); !ok {
286                                 return nil, badData
287                         } else {
288                                 n = int64(int32(n4))
289                         }
290                 } else {
291                         if n8, ok := txtimes.big8(); !ok {
292                                 return nil, badData
293                         } else {
294                                 n = int64(n8)
295                         }
296                 }
297                 tx[i].when = n
298                 if int(txzones[i]) >= len(zone) {
299                         return nil, badData
300                 }
301                 tx[i].index = txzones[i]
302                 if i < len(isstd) {
303                         tx[i].isstd = isstd[i] != 0
304                 }
305                 if i < len(isutc) {
306                         tx[i].isutc = isutc[i] != 0
307                 }
308         }
309
310         if len(tx) == 0 {
311                 // Build fake transition to cover all time.
312                 // This happens in fixed locations like "Etc/GMT0".
313                 tx = append(tx, zoneTrans{when: alpha, index: 0})
314         }
315
316         // Committed to succeed.
317         l := &Location{zone: zone, tx: tx, name: name, extend: extend}
318
319         // Fill in the cache with information about right now,
320         // since that will be the most common lookup.
321         sec, _, _ := now()
322         for i := range tx {
323                 if tx[i].when <= sec && (i+1 == len(tx) || sec < tx[i+1].when) {
324                         l.cacheStart = tx[i].when
325                         l.cacheEnd = omega
326                         if i+1 < len(tx) {
327                                 l.cacheEnd = tx[i+1].when
328                         } else if l.extend != "" {
329                                 // If we're at the end of the known zone transitions,
330                                 // try the extend string.
331                                 if _, _, estart, eend, ok := tzset(l.extend, l.cacheEnd, sec); ok {
332                                         l.cacheStart = estart
333                                         l.cacheEnd = eend
334                                 }
335                         }
336                         l.cacheZone = &l.zone[tx[i].index]
337                         break
338                 }
339         }
340
341         return l, nil
342 }
343
344 // loadTzinfoFromDirOrZip returns the contents of the file with the given name
345 // in dir. dir can either be an uncompressed zip file, or a directory.
346 func loadTzinfoFromDirOrZip(dir, name string) ([]byte, error) {
347         if len(dir) > 4 && dir[len(dir)-4:] == ".zip" {
348                 return loadTzinfoFromZip(dir, name)
349         }
350         if dir != "" {
351                 name = dir + "/" + name
352         }
353         return readFile(name)
354 }
355
356 // There are 500+ zoneinfo files. Rather than distribute them all
357 // individually, we ship them in an uncompressed zip file.
358 // Used this way, the zip file format serves as a commonly readable
359 // container for the individual small files. We choose zip over tar
360 // because zip files have a contiguous table of contents, making
361 // individual file lookups faster, and because the per-file overhead
362 // in a zip file is considerably less than tar's 512 bytes.
363
364 // get4 returns the little-endian 32-bit value in b.
365 func get4(b []byte) int {
366         if len(b) < 4 {
367                 return 0
368         }
369         return int(b[0]) | int(b[1])<<8 | int(b[2])<<16 | int(b[3])<<24
370 }
371
372 // get2 returns the little-endian 16-bit value in b.
373 func get2(b []byte) int {
374         if len(b) < 2 {
375                 return 0
376         }
377         return int(b[0]) | int(b[1])<<8
378 }
379
380 // loadTzinfoFromZip returns the contents of the file with the given name
381 // in the given uncompressed zip file.
382 func loadTzinfoFromZip(zipfile, name string) ([]byte, error) {
383         fd, err := open(zipfile)
384         if err != nil {
385                 return nil, err
386         }
387         defer closefd(fd)
388
389         const (
390                 zecheader = 0x06054b50
391                 zcheader  = 0x02014b50
392                 ztailsize = 22
393
394                 zheadersize = 30
395                 zheader     = 0x04034b50
396         )
397
398         buf := make([]byte, ztailsize)
399         if err := preadn(fd, buf, -ztailsize); err != nil || get4(buf) != zecheader {
400                 return nil, errors.New("corrupt zip file " + zipfile)
401         }
402         n := get2(buf[10:])
403         size := get4(buf[12:])
404         off := get4(buf[16:])
405
406         buf = make([]byte, size)
407         if err := preadn(fd, buf, off); err != nil {
408                 return nil, errors.New("corrupt zip file " + zipfile)
409         }
410
411         for i := 0; i < n; i++ {
412                 // zip entry layout:
413                 //      0       magic[4]
414                 //      4       madevers[1]
415                 //      5       madeos[1]
416                 //      6       extvers[1]
417                 //      7       extos[1]
418                 //      8       flags[2]
419                 //      10      meth[2]
420                 //      12      modtime[2]
421                 //      14      moddate[2]
422                 //      16      crc[4]
423                 //      20      csize[4]
424                 //      24      uncsize[4]
425                 //      28      namelen[2]
426                 //      30      xlen[2]
427                 //      32      fclen[2]
428                 //      34      disknum[2]
429                 //      36      iattr[2]
430                 //      38      eattr[4]
431                 //      42      off[4]
432                 //      46      name[namelen]
433                 //      46+namelen+xlen+fclen - next header
434                 //
435                 if get4(buf) != zcheader {
436                         break
437                 }
438                 meth := get2(buf[10:])
439                 size := get4(buf[24:])
440                 namelen := get2(buf[28:])
441                 xlen := get2(buf[30:])
442                 fclen := get2(buf[32:])
443                 off := get4(buf[42:])
444                 zname := buf[46 : 46+namelen]
445                 buf = buf[46+namelen+xlen+fclen:]
446                 if string(zname) != name {
447                         continue
448                 }
449                 if meth != 0 {
450                         return nil, errors.New("unsupported compression for " + name + " in " + zipfile)
451                 }
452
453                 // zip per-file header layout:
454                 //      0       magic[4]
455                 //      4       extvers[1]
456                 //      5       extos[1]
457                 //      6       flags[2]
458                 //      8       meth[2]
459                 //      10      modtime[2]
460                 //      12      moddate[2]
461                 //      14      crc[4]
462                 //      18      csize[4]
463                 //      22      uncsize[4]
464                 //      26      namelen[2]
465                 //      28      xlen[2]
466                 //      30      name[namelen]
467                 //      30+namelen+xlen - file data
468                 //
469                 buf = make([]byte, zheadersize+namelen)
470                 if err := preadn(fd, buf, off); err != nil ||
471                         get4(buf) != zheader ||
472                         get2(buf[8:]) != meth ||
473                         get2(buf[26:]) != namelen ||
474                         string(buf[30:30+namelen]) != name {
475                         return nil, errors.New("corrupt zip file " + zipfile)
476                 }
477                 xlen = get2(buf[28:])
478
479                 buf = make([]byte, size)
480                 if err := preadn(fd, buf, off+30+namelen+xlen); err != nil {
481                         return nil, errors.New("corrupt zip file " + zipfile)
482                 }
483
484                 return buf, nil
485         }
486
487         return nil, syscall.ENOENT
488 }
489
490 // loadTzinfoFromTzdata returns the time zone information of the time zone
491 // with the given name, from a tzdata database file as they are typically
492 // found on android.
493 var loadTzinfoFromTzdata func(file, name string) ([]byte, error)
494
495 // loadTzinfo returns the time zone information of the time zone
496 // with the given name, from a given source. A source may be a
497 // timezone database directory, tzdata database file or an uncompressed
498 // zip file, containing the contents of such a directory.
499 func loadTzinfo(name string, source string) ([]byte, error) {
500         if len(source) >= 6 && source[len(source)-6:] == "tzdata" {
501                 return loadTzinfoFromTzdata(source, name)
502         }
503         return loadTzinfoFromDirOrZip(source, name)
504 }
505
506 // loadLocation returns the Location with the given name from one of
507 // the specified sources. See loadTzinfo for a list of supported sources.
508 // The first timezone data matching the given name that is successfully loaded
509 // and parsed is returned as a Location.
510 func loadLocation(name string, sources []string) (z *Location, firstErr error) {
511         for _, source := range sources {
512                 var zoneData, err = loadTzinfo(name, source)
513                 if err == nil {
514                         if z, err = LoadLocationFromTZData(name, zoneData); err == nil {
515                                 return z, nil
516                         }
517                 }
518                 if firstErr == nil && err != syscall.ENOENT {
519                         firstErr = err
520                 }
521         }
522         if loadFromEmbeddedTZData != nil {
523                 zonedata, err := loadFromEmbeddedTZData(name)
524                 if err == nil {
525                         if z, err = LoadLocationFromTZData(name, []byte(zonedata)); err == nil {
526                                 return z, nil
527                         }
528                 }
529                 if firstErr == nil && err != syscall.ENOENT {
530                         firstErr = err
531                 }
532         }
533         if firstErr != nil {
534                 return nil, firstErr
535         }
536         return nil, errors.New("unknown time zone " + name)
537 }
538
539 // readFile reads and returns the content of the named file.
540 // It is a trivial implementation of ioutil.ReadFile, reimplemented
541 // here to avoid depending on io/ioutil or os.
542 // It returns an error if name exceeds maxFileSize bytes.
543 func readFile(name string) ([]byte, error) {
544         f, err := open(name)
545         if err != nil {
546                 return nil, err
547         }
548         defer closefd(f)
549         var (
550                 buf [4096]byte
551                 ret []byte
552                 n   int
553         )
554         for {
555                 n, err = read(f, buf[:])
556                 if n > 0 {
557                         ret = append(ret, buf[:n]...)
558                 }
559                 if n == 0 || err != nil {
560                         break
561                 }
562                 if len(ret) > maxFileSize {
563                         return nil, fileSizeError(name)
564                 }
565         }
566         return ret, err
567 }