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 // registerLoadFromEmbeddedTZData is called by the time/tzdata package,
20 func registerLoadFromEmbeddedTZData(f func(string) (string, error)) {
21 loadFromEmbeddedTZData = f
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)
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
35 type fileSizeError string
37 func (f fileSizeError) Error() string {
38 return "time: file " + string(f) + " is too large"
41 // Copies of io.Seek* constants to avoid importing "io":
48 // Simple I/O interface to binary blob of data.
54 func (d *dataIO) read(n int) []byte {
65 func (d *dataIO) big4() (n uint32, ok bool) {
71 return uint32(p[3]) | uint32(p[2])<<8 | uint32(p[1])<<16 | uint32(p[0])<<24, true
74 func (d *dataIO) big8() (n uint64, ok bool) {
81 return (uint64(n1) << 32) | uint64(n2), true
84 func (d *dataIO) byte() (n byte, ok bool) {
93 // read returns the read of the data in the buffer.
94 func (d *dataIO) rest() []byte {
100 // Make a string by stopping at the first NUL
101 func byteString(p []byte) string {
102 for i := 0; i < len(p); i++ {
104 return string(p[0:i])
110 var badData = errors.New("malformed time zone information")
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}
119 // 4-byte magic "TZif"
120 if magic := d.read(4); string(magic) != "TZif" {
124 // 1-byte version, then 15 bytes of padding
127 if p = d.read(16); len(p) != 16 {
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
158 for i := 0; i < 6; i++ {
163 if uint32(int(nn)) != nn {
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.
176 // Skip the 32-bit data.
184 // Skip the version 2 header that we just read.
190 // Read the counts again, they can differ.
191 for i := 0; i < 6; i++ {
196 if uint32(int(nn)) != nn {
209 txtimes := dataIO{d.read(n[NTime] * size), false}
211 // Time zone indices for transition times.
212 txzones := d.read(n[NTime])
214 // Zone info structures
215 zonedata := dataIO{d.read(n[NZone] * 6), false}
217 // Time zone abbreviations.
218 abbrev := d.read(n[NChar])
220 // Leap-second time pairs
221 d.read(n[NLeap] * (size + 4))
223 // Whether tx times associated with local time types
224 // are specified as standard time or wall time.
225 isstd := d.read(n[NStdWall])
227 // Whether tx times associated with local time types
228 // are specified as UTC or local time.
229 isutc := d.read(n[NUTCLocal])
231 if d.error { // ran out of data
237 if len(rest) > 2 && rest[0] == '\n' && rest[len(rest)-1] == '\n' {
238 extend = string(rest[1 : len(rest)-1])
241 // Now we can build up a useful data structure.
242 // First the zone information.
243 // utcoff[4] isdst[1] nameindex[1]
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).
250 zone := make([]zone, nzone)
251 for i := range zone {
254 if n, ok = zonedata.big4(); !ok {
257 if uint32(int(n)) != n {
260 zone[i].offset = int(int32(n))
262 if b, ok = zonedata.byte(); !ok {
265 zone[i].isDST = b != 0
266 if b, ok = zonedata.byte(); !ok || int(b) >= len(abbrev) {
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" {
275 zone[i].name = name[4:]
280 // Now the transition time info.
281 tx := make([]zoneTrans, n[NTime])
285 if n4, ok := txtimes.big4(); !ok {
291 if n8, ok := txtimes.big8(); !ok {
298 if int(txzones[i]) >= len(zone) {
301 tx[i].index = txzones[i]
303 tx[i].isstd = isstd[i] != 0
306 tx[i].isutc = isutc[i] != 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})
316 // Committed to succeed.
317 l := &Location{zone: zone, tx: tx, name: name, extend: extend}
319 // Fill in the cache with information about right now,
320 // since that will be the most common lookup.
323 if tx[i].when <= sec && (i+1 == len(tx) || sec < tx[i+1].when) {
324 l.cacheStart = tx[i].when
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
336 l.cacheZone = &l.zone[tx[i].index]
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)
351 name = dir + "/" + name
353 return readFile(name)
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.
364 // get4 returns the little-endian 32-bit value in b.
365 func get4(b []byte) int {
369 return int(b[0]) | int(b[1])<<8 | int(b[2])<<16 | int(b[3])<<24
372 // get2 returns the little-endian 16-bit value in b.
373 func get2(b []byte) int {
377 return int(b[0]) | int(b[1])<<8
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)
390 zecheader = 0x06054b50
391 zcheader = 0x02014b50
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)
403 size := get4(buf[12:])
404 off := get4(buf[16:])
406 buf = make([]byte, size)
407 if err := preadn(fd, buf, off); err != nil {
408 return nil, errors.New("corrupt zip file " + zipfile)
411 for i := 0; i < n; i++ {
433 // 46+namelen+xlen+fclen - next header
435 if get4(buf) != zcheader {
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 {
450 return nil, errors.New("unsupported compression for " + name + " in " + zipfile)
453 // zip per-file header layout:
467 // 30+namelen+xlen - file data
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)
477 xlen = get2(buf[28:])
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)
487 return nil, syscall.ENOENT
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
493 var loadTzinfoFromTzdata func(file, name string) ([]byte, error)
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)
503 return loadTzinfoFromDirOrZip(source, name)
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)
514 if z, err = LoadLocationFromTZData(name, zoneData); err == nil {
518 if firstErr == nil && err != syscall.ENOENT {
522 if loadFromEmbeddedTZData != nil {
523 zonedata, err := loadFromEmbeddedTZData(name)
525 if z, err = LoadLocationFromTZData(name, []byte(zonedata)); err == nil {
529 if firstErr == nil && err != syscall.ENOENT {
536 return nil, errors.New("unknown time zone " + name)
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) {
555 n, err = read(f, buf[:])
557 ret = append(ret, buf[:n]...)
559 if n == 0 || err != nil {
562 if len(ret) > maxFileSize {
563 return nil, fileSizeError(name)