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 // Make a string by stopping at the first NUL
94 func byteString(p []byte) string {
95 for i := 0; i < len(p); i++ {
103 var badData = errors.New("malformed time zone information")
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}
112 // 4-byte magic "TZif"
113 if magic := d.read(4); string(magic) != "TZif" {
117 // 1-byte version, then 15 bytes of padding
120 if p = d.read(16); len(p) != 16 {
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
151 for i := 0; i < 6; i++ {
156 if uint32(int(nn)) != nn {
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.
169 // Skip the 32-bit data.
177 // Skip the version 2 header that we just read.
183 // Read the counts again, they can differ.
184 for i := 0; i < 6; i++ {
189 if uint32(int(nn)) != nn {
202 txtimes := dataIO{d.read(n[NTime] * size), false}
204 // Time zone indices for transition times.
205 txzones := d.read(n[NTime])
207 // Zone info structures
208 zonedata := dataIO{d.read(n[NZone] * 6), false}
210 // Time zone abbreviations.
211 abbrev := d.read(n[NChar])
213 // Leap-second time pairs
214 d.read(n[NLeap] * (size + 4))
216 // Whether tx times associated with local time types
217 // are specified as standard time or wall time.
218 isstd := d.read(n[NStdWall])
220 // Whether tx times associated with local time types
221 // are specified as UTC or local time.
222 isutc := d.read(n[NUTCLocal])
224 if d.error { // ran out of data
228 // Now we can build up a useful data structure.
229 // First the zone information.
230 // utcoff[4] isdst[1] nameindex[1]
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).
237 zone := make([]zone, nzone)
238 for i := range zone {
241 if n, ok = zonedata.big4(); !ok {
244 if uint32(int(n)) != n {
247 zone[i].offset = int(int32(n))
249 if b, ok = zonedata.byte(); !ok {
252 zone[i].isDST = b != 0
253 if b, ok = zonedata.byte(); !ok || int(b) >= len(abbrev) {
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" {
262 zone[i].name = name[4:]
267 // Now the transition time info.
268 tx := make([]zoneTrans, n[NTime])
272 if n4, ok := txtimes.big4(); !ok {
278 if n8, ok := txtimes.big8(); !ok {
285 if int(txzones[i]) >= len(zone) {
288 tx[i].index = txzones[i]
290 tx[i].isstd = isstd[i] != 0
293 tx[i].isutc = isutc[i] != 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})
303 // Committed to succeed.
304 l := &Location{zone: zone, tx: tx, name: name}
306 // Fill in the cache with information about right now,
307 // since that will be the most common lookup.
310 if tx[i].when <= sec && (i+1 == len(tx) || sec < tx[i+1].when) {
311 l.cacheStart = tx[i].when
314 l.cacheEnd = tx[i+1].when
316 l.cacheZone = &l.zone[tx[i].index]
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)
330 name = dir + "/" + name
332 return readFile(name)
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.
343 // get4 returns the little-endian 32-bit value in b.
344 func get4(b []byte) int {
348 return int(b[0]) | int(b[1])<<8 | int(b[2])<<16 | int(b[3])<<24
351 // get2 returns the little-endian 16-bit value in b.
352 func get2(b []byte) int {
356 return int(b[0]) | int(b[1])<<8
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)
369 zecheader = 0x06054b50
370 zcheader = 0x02014b50
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)
382 size := get4(buf[12:])
383 off := get4(buf[16:])
385 buf = make([]byte, size)
386 if err := preadn(fd, buf, off); err != nil {
387 return nil, errors.New("corrupt zip file " + zipfile)
390 for i := 0; i < n; i++ {
412 // 46+namelen+xlen+fclen - next header
414 if get4(buf) != zcheader {
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 {
429 return nil, errors.New("unsupported compression for " + name + " in " + zipfile)
432 // zip per-file header layout:
446 // 30+namelen+xlen - file data
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)
456 xlen = get2(buf[28:])
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)
466 return nil, syscall.ENOENT
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
472 var loadTzinfoFromTzdata func(file, name string) ([]byte, error)
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)
482 return loadTzinfoFromDirOrZip(source, name)
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)
493 if z, err = LoadLocationFromTZData(name, zoneData); err == nil {
497 if firstErr == nil && err != syscall.ENOENT {
501 if loadFromEmbeddedTZData != nil {
502 zonedata, err := loadFromEmbeddedTZData(name)
504 if z, err = LoadLocationFromTZData(name, []byte(zonedata)); err == nil {
508 if firstErr == nil && err != syscall.ENOENT {
515 return nil, errors.New("unknown time zone " + name)
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) {
534 n, err = read(f, buf[:])
536 ret = append(ret, buf[:n]...)
538 if n == 0 || err != nil {
541 if len(ret) > maxFileSize {
542 return nil, fileSizeError(name)