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