11package tzdata
22
33import (
4+ "bytes"
45 "encoding/xml"
56 "fmt"
67 "io"
78 "net/http"
9+ "time"
810)
911
1012const winZonesURL = `https://raw.githubusercontent.com/unicode-org/cldr/master/common/supplemental/windowsZones.xml`
1113
14+ const maxDownloadSize = 10 << 20
15+
1216type SupplementalData struct {
1317 WindowsZones WindowsZones `xml:"windowsZones"`
1418}
@@ -30,24 +34,60 @@ type MapZone struct {
3034
3135// DownloadWindowsZones fetches Windows mapping info from unicode.org
3236func DownloadWindowsZones () (SupplementalData , error ) {
37+ return downloadWindowsZones (winZonesURL )
38+ }
39+
40+ func downloadWindowsZones (target string ) (SupplementalData , error ) {
41+ buf , err := downloadHTTP (target )
42+ if err != nil {
43+ return SupplementalData {}, err
44+ }
45+ return parseWindowsZones (buf .Bytes (), target )
46+ }
47+
48+ func parseWindowsZones (contents []byte , source string ) (SupplementalData , error ) {
3349 var data SupplementalData
3450
35- resp , err := http .Get (winZonesURL )
51+ if err := xml .Unmarshal (contents , & data ); err != nil {
52+ return data , fmt .Errorf ("failed to parse %q: %w" , source , err )
53+ }
54+ foundMappings := false
55+ for _ , mappings := range data .WindowsZones .MapTimezones {
56+ if len (mappings .MapZone ) > 0 {
57+ foundMappings = true
58+ break
59+ }
60+ }
61+ if ! foundMappings {
62+ return data , fmt .Errorf ("failed to parse %q: no time zone mappings found" , source )
63+ }
64+
65+ return data , nil
66+ }
67+
68+ func downloadHTTP (target string ) (bytes.Buffer , error ) {
69+ client := http.Client {Timeout : 30 * time .Second }
70+ return downloadHTTPWithClient (& client , target )
71+ }
72+
73+ func downloadHTTPWithClient (client * http.Client , target string ) (bytes.Buffer , error ) {
74+ var buf bytes.Buffer
75+ resp , err := client .Get (target )
3676 if err != nil {
37- return data , err
77+ return buf , err
3878 }
3979 defer resp .Body .Close ()
4080
4181 if resp .StatusCode != http .StatusOK {
42- return data , fmt .Errorf ("failed to download \" %v \" , http error : %v " , winZonesURL , resp .StatusCode )
82+ return buf , fmt .Errorf ("failed to download %q, HTTP status : %s " , target , resp .Status )
4383 }
4484
45- bytes , err := io .ReadAll (resp .Body )
46- if err != nil {
47- return data , err
85+ if _ , err := io .Copy (& buf , io .LimitReader (resp .Body , maxDownloadSize + 1 )); err != nil {
86+ return buf , err
87+ }
88+ if buf .Len () > maxDownloadSize {
89+ return bytes.Buffer {}, fmt .Errorf ("failed to download %q: response exceeds %d bytes" , target , maxDownloadSize )
4890 }
4991
50- xml .Unmarshal (bytes , & data )
51-
52- return data , nil
92+ return buf , nil
5393}
0 commit comments