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.
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/
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
23 type fileSizeError string
25 func (f fileSizeError) Error() string {
26 return "time: file " + string(f) + " is too large"
29 // Copies of io.Seek* constants to avoid importing "io":
36 // Simple I/O interface to binary blob of data.
42 func (d *dataIO) read(n int) []byte {
53 func (d *dataIO) big4() (n uint32, ok bool) {
59 return uint32(p[3]) | uint32(p[2])<<8 | uint32(p[1])<<16 | uint32(p[0])<<24, true
62 func (d *dataIO) big8() (n uint64, ok bool) {
69 return (uint64(n1) << 32) | uint64(n2), true
72 func (d *dataIO) byte() (n byte, ok bool) {
81 // Make a string by stopping at the first NUL
82 func byteString(p []byte) string {
83 for i := 0; i < len(p); i++ {
91 var badData = errors.New("malformed time zone information")
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}
100 // 4-byte magic "TZif"
101 if magic := d.read(4); string(magic) != "TZif" {
105 // 1-byte version, then 15 bytes of padding
108 if p = d.read(16); len(p) != 16 {
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
139 for i := 0; i < 6; i++ {
144 if uint32(int(nn)) != nn {
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.
157 // Skip the 32-bit data.
165 // Skip the version 2 header that we just read.
171 // Read the counts again, they can differ.
172 for i := 0; i < 6; i++ {
177 if uint32(int(nn)) != nn {
190 txtimes := dataIO{d.read(n[NTime] * size), false}
192 // Time zone indices for transition times.
193 txzones := d.read(n[NTime])
195 // Zone info structures
196 zonedata := dataIO{d.read(n[NZone] * 6), false}
198 // Time zone abbreviations.
199 abbrev := d.read(n[NChar])
201 // Leap-second time pairs
202 d.read(n[NLeap] * (size + 4))
204 // Whether tx times associated with local time types
205 // are specified as standard time or wall time.
206 isstd := d.read(n[NStdWall])
208 // Whether tx times associated with local time types
209 // are specified as UTC or local time.
210 isutc := d.read(n[NUTCLocal])
212 if d.error { // ran out of data
216 // Now we can build up a useful data structure.
217 // First the zone information.
218 // utcoff[4] isdst[1] nameindex[1]
221 // Reject tzdata files with no zones. There's nothing useful in them.
222 // This also avoids a panic later when we add and then use a fake transition (golang.org/issue/29437).
225 zone := make([]zone, nzone)
226 for i := range zone {
229 if n, ok = zonedata.big4(); !ok {
232 if uint32(int(n)) != n {
235 zone[i].offset = int(int32(n))
237 if b, ok = zonedata.byte(); !ok {
240 zone[i].isDST = b != 0
241 if b, ok = zonedata.byte(); !ok || int(b) >= len(abbrev) {
244 zone[i].name = byteString(abbrev[b:])
245 if runtime.GOOS == "aix" && len(name) > 8 && (name[:8] == "Etc/GMT+" || name[:8] == "Etc/GMT-") {
246 // There is a bug with AIX 7.2 TL 0 with files in Etc,
247 // GMT+1 will return GMT-1 instead of GMT+1 or -01.
248 if name != "Etc/GMT+0" {
250 zone[i].name = name[4:]
255 // Now the transition time info.
256 tx := make([]zoneTrans, n[NTime])
260 if n4, ok := txtimes.big4(); !ok {
266 if n8, ok := txtimes.big8(); !ok {
273 if int(txzones[i]) >= len(zone) {
276 tx[i].index = txzones[i]
278 tx[i].isstd = isstd[i] != 0
281 tx[i].isutc = isutc[i] != 0
286 // Build fake transition to cover all time.
287 // This happens in fixed locations like "Etc/GMT0".
288 tx = append(tx, zoneTrans{when: alpha, index: 0})
291 // Committed to succeed.
292 l := &Location{zone: zone, tx: tx, name: name}
294 // Fill in the cache with information about right now,
295 // since that will be the most common lookup.
298 if tx[i].when <= sec && (i+1 == len(tx) || sec < tx[i+1].when) {
299 l.cacheStart = tx[i].when
302 l.cacheEnd = tx[i+1].when
304 l.cacheZone = &l.zone[tx[i].index]
311 // loadTzinfoFromDirOrZip returns the contents of the file with the given name
312 // in dir. dir can either be an uncompressed zip file, or a directory.
313 func loadTzinfoFromDirOrZip(dir, name string) ([]byte, error) {
314 if len(dir) > 4 && dir[len(dir)-4:] == ".zip" {
315 return loadTzinfoFromZip(dir, name)
318 name = dir + "/" + name
320 return readFile(name)
323 // There are 500+ zoneinfo files. Rather than distribute them all
324 // individually, we ship them in an uncompressed zip file.
325 // Used this way, the zip file format serves as a commonly readable
326 // container for the individual small files. We choose zip over tar
327 // because zip files have a contiguous table of contents, making
328 // individual file lookups faster, and because the per-file overhead
329 // in a zip file is considerably less than tar's 512 bytes.
331 // get4 returns the little-endian 32-bit value in b.
332 func get4(b []byte) int {
336 return int(b[0]) | int(b[1])<<8 | int(b[2])<<16 | int(b[3])<<24
339 // get2 returns the little-endian 16-bit value in b.
340 func get2(b []byte) int {
344 return int(b[0]) | int(b[1])<<8
347 // loadTzinfoFromZip returns the contents of the file with the given name
348 // in the given uncompressed zip file.
349 func loadTzinfoFromZip(zipfile, name string) ([]byte, error) {
350 fd, err := open(zipfile)
357 zecheader = 0x06054b50
358 zcheader = 0x02014b50
365 buf := make([]byte, ztailsize)
366 if err := preadn(fd, buf, -ztailsize); err != nil || get4(buf) != zecheader {
367 return nil, errors.New("corrupt zip file " + zipfile)
370 size := get4(buf[12:])
371 off := get4(buf[16:])
373 buf = make([]byte, size)
374 if err := preadn(fd, buf, off); err != nil {
375 return nil, errors.New("corrupt zip file " + zipfile)
378 for i := 0; i < n; i++ {
400 // 46+namelen+xlen+fclen - next header
402 if get4(buf) != zcheader {
405 meth := get2(buf[10:])
406 size := get4(buf[24:])
407 namelen := get2(buf[28:])
408 xlen := get2(buf[30:])
409 fclen := get2(buf[32:])
410 off := get4(buf[42:])
411 zname := buf[46 : 46+namelen]
412 buf = buf[46+namelen+xlen+fclen:]
413 if string(zname) != name {
417 return nil, errors.New("unsupported compression for " + name + " in " + zipfile)
420 // zip per-file header layout:
434 // 30+namelen+xlen - file data
436 buf = make([]byte, zheadersize+namelen)
437 if err := preadn(fd, buf, off); err != nil ||
438 get4(buf) != zheader ||
439 get2(buf[8:]) != meth ||
440 get2(buf[26:]) != namelen ||
441 string(buf[30:30+namelen]) != name {
442 return nil, errors.New("corrupt zip file " + zipfile)
444 xlen = get2(buf[28:])
446 buf = make([]byte, size)
447 if err := preadn(fd, buf, off+30+namelen+xlen); err != nil {
448 return nil, errors.New("corrupt zip file " + zipfile)
454 return nil, syscall.ENOENT
457 // loadTzinfoFromTzdata returns the time zone information of the time zone
458 // with the given name, from a tzdata database file as they are typically
460 var loadTzinfoFromTzdata func(file, name string) ([]byte, error)
462 // loadTzinfo returns the time zone information of the time zone
463 // with the given name, from a given source. A source may be a
464 // timezone database directory, tzdata database file or an uncompressed
465 // zip file, containing the contents of such a directory.
466 func loadTzinfo(name string, source string) ([]byte, error) {
467 if len(source) >= 6 && source[len(source)-6:] == "tzdata" {
468 return loadTzinfoFromTzdata(source, name)
470 return loadTzinfoFromDirOrZip(source, name)
473 // loadLocation returns the Location with the given name from one of
474 // the specified sources. See loadTzinfo for a list of supported sources.
475 // The first timezone data matching the given name that is successfully loaded
476 // and parsed is returned as a Location.
477 func loadLocation(name string, sources []string) (z *Location, firstErr error) {
478 for _, source := range sources {
479 var zoneData, err = loadTzinfo(name, source)
481 if z, err = LoadLocationFromTZData(name, zoneData); err == nil {
485 if firstErr == nil && err != syscall.ENOENT {
492 return nil, errors.New("unknown time zone " + name)
495 // readFile reads and returns the content of the named file.
496 // It is a trivial implementation of ioutil.ReadFile, reimplemented
497 // here to avoid depending on io/ioutil or os.
498 // It returns an error if name exceeds maxFileSize bytes.
499 func readFile(name string) ([]byte, error) {
511 n, err = read(f, buf[:])
513 ret = append(ret, buf[:n]...)
515 if n == 0 || err != nil {
518 if len(ret) > maxFileSize {
519 return nil, fileSizeError(name)