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