Merge pull request #1321 from esdrubal/currentsystemtimezone
[mono.git] / mcs / class / System.Core / System / TimeZoneInfo.Android.cs
1 /*
2  * System.TimeZoneInfo Android Support
3  *
4  * Author(s)
5  *      Jonathan Pryor  <jpryor@novell.com>
6  *      The Android Open Source Project
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  */
20
21 #if (INSIDE_CORLIB && MONODROID)
22
23 using System;
24 using System.Collections.Generic;
25 using System.IO;
26 using System.Runtime.CompilerServices;
27 using System.Runtime.InteropServices;
28 using System.Text;
29
30 namespace System {
31
32         interface IAndroidTimeZoneDB {
33                 IEnumerable<string>   GetAvailableIds ();
34                 byte[]                GetTimeZoneData (string id);
35         }
36
37         [StructLayout (LayoutKind.Sequential, Pack=1)]
38         unsafe struct AndroidTzDataHeader {
39                 public fixed byte signature [12];
40                 public int        indexOffset;
41                 public int        dataOffset;
42                 public int        zoneTabOffset;
43         }
44
45         [StructLayout (LayoutKind.Sequential, Pack=1)]
46         unsafe struct AndroidTzDataEntry {
47                 public fixed byte id [40];
48                 public int        byteOffset;
49                 public int        length;
50                 public int        rawUtcOffset;
51         }
52
53         /*
54          * Android v4.3 Timezone support infrastructure.
55          *
56          * This is a C# port of libcore.util.ZoneInfoDB:
57          *
58          *    https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/util/ZoneInfoDB.java
59          *
60          * This is needed in order to read Android v4.3 tzdata files.
61          */
62         sealed class AndroidTzData : IAndroidTimeZoneDB {
63
64                 internal static readonly string[] Paths = new string[]{
65                         Environment.GetEnvironmentVariable ("ANDROID_DATA") + "/misc/zoneinfo/tzdata",
66                         Environment.GetEnvironmentVariable ("ANDROID_ROOT") + "/usr/share/zoneinfo/tzdata",
67                 };
68
69                 string    tzdataPath;
70                 Stream    data;
71                 string    version;
72                 string    zoneTab;
73
74                 string[]  ids;
75                 int[]     byteOffsets;
76                 int[]     lengths;
77
78                 public AndroidTzData (params string[] paths)
79                 {
80                         foreach (var path in paths)
81                                 if (LoadData (path)) {
82                                         tzdataPath = path;
83                                         return;
84                                 }
85
86                         Console.Error.WriteLine ("Couldn't find any tzdata!");
87                         tzdataPath  = "/";
88                         version     = "missing";
89                         zoneTab     = "# Emergency fallback data.\n";
90                         ids         = new[]{ "GMT" };
91                 }
92
93                 public string Version {
94                         get {return version;}
95                 }
96
97                 public string ZoneTab {
98                         get {return zoneTab;}
99                 }
100
101                 bool LoadData (string path)
102                 {
103                         if (!File.Exists (path))
104                                 return false;
105                         try {
106                                 data = File.OpenRead (path);
107                         } catch (IOException) {
108                                 return false;
109                         } catch (UnauthorizedAccessException) {
110                                 return false;
111                         }
112
113                         try {
114                                 ReadHeader ();
115                                 return true;
116                         } catch (Exception e) {
117                                 Console.Error.WriteLine ("tzdata file \"{0}\" was present but invalid: {1}", path, e);
118                         }
119                         return false;
120                 }
121
122                 unsafe void ReadHeader ()
123                 {
124                         int size   = System.Math.Max (Marshal.SizeOf (typeof (AndroidTzDataHeader)), Marshal.SizeOf (typeof (AndroidTzDataEntry)));
125                         var buffer = new byte [size];
126                         var header = ReadAt<AndroidTzDataHeader>(0, buffer);
127
128                         header.indexOffset    = NetworkToHostOrder (header.indexOffset);
129                         header.dataOffset     = NetworkToHostOrder (header.dataOffset);
130                         header.zoneTabOffset  = NetworkToHostOrder (header.zoneTabOffset);
131
132                         sbyte* s = (sbyte*) header.signature;
133                         string magic = new string (s, 0, 6, Encoding.ASCII);
134                         if (magic != "tzdata" || header.signature [11] != 0) {
135                                 var b = new StringBuilder ();
136                                 b.Append ("bad tzdata magic:");
137                                 for (int i = 0; i < 12; ++i) {
138                                         b.Append (" ").Append (((byte) s [i]).ToString ("x2"));
139                                 }
140                                 throw new InvalidOperationException ("bad tzdata magic: " + b.ToString ());
141                         }
142
143                         version = new string (s, 6, 5, Encoding.ASCII);
144
145                         ReadIndex (header.indexOffset, header.dataOffset, buffer);
146                         ReadZoneTab (header.zoneTabOffset, checked ((int) data.Length) - header.zoneTabOffset);
147                 }
148
149                 unsafe T ReadAt<T> (long position, byte[] buffer)
150                         where T : struct
151                 {
152                         int size = Marshal.SizeOf (typeof (T));
153                         if (buffer.Length < size)
154                                 throw new InvalidOperationException ("Internal error: buffer too small");
155
156                         data.Position = position;
157                         int r;
158                         if ((r = data.Read (buffer, 0, size)) < size)
159                                 throw new InvalidOperationException (
160                                                 string.Format ("Error reading '{0}': read {1} bytes, expected {2}", tzdataPath, r, size));
161
162                         fixed (byte* b = buffer)
163                                 return (T) Marshal.PtrToStructure ((IntPtr) b, typeof (T));
164                 }
165
166                 static int NetworkToHostOrder (int value)
167                 {
168                         if (!BitConverter.IsLittleEndian)
169                                 return value;
170
171                         return
172                                 (((value >> 24) & 0xFF) |
173                                  ((value >> 08) & 0xFF00) |
174                                  ((value << 08) & 0xFF0000) |
175                                  ((value << 24)));
176                 }
177
178                 unsafe void ReadIndex (int indexOffset, int dataOffset, byte[] buffer)
179                 {
180                         int indexSize   = dataOffset - indexOffset;
181                         int entryCount  = indexSize / Marshal.SizeOf (typeof (AndroidTzDataEntry));
182                         int entrySize   = Marshal.SizeOf (typeof (AndroidTzDataEntry));
183
184                         byteOffsets   = new int [entryCount];
185                         ids           = new string [entryCount];
186                         lengths       = new int [entryCount];
187
188                         for (int i = 0; i < entryCount; ++i) {
189                                 var entry = ReadAt<AndroidTzDataEntry>(indexOffset + (entrySize*i), buffer);
190                                 var p     = (sbyte*) entry.id;
191
192                                 byteOffsets [i]   = NetworkToHostOrder (entry.byteOffset) + dataOffset;
193                                 ids [i]           = new string (p, 0, GetStringLength (p, 40), Encoding.ASCII);
194                                 lengths [i]       = NetworkToHostOrder (entry.length);
195
196                                 if (lengths [i] < Marshal.SizeOf (typeof (AndroidTzDataHeader)))
197                                         throw new InvalidOperationException ("Length in index file < sizeof(tzhead)");
198                         }
199                 }
200
201                 static unsafe int GetStringLength (sbyte* s, int maxLength)
202                 {
203                         int len;
204                         for (len = 0; len < maxLength; len++, s++) {
205                                 if (*s == 0)
206                                         break;
207                         }
208                         return len;
209                 }
210
211                 unsafe void ReadZoneTab (int zoneTabOffset, int zoneTabSize)
212                 {
213                         byte[] zoneTab = new byte [zoneTabSize];
214
215                         data.Position = zoneTabOffset;
216
217                         int r;
218                         if ((r = data.Read (zoneTab, 0, zoneTab.Length)) < zoneTab.Length)
219                                 throw new InvalidOperationException (
220                                                 string.Format ("Error reading zonetab: read {0} bytes, expected {1}", r, zoneTabSize));
221
222                         this.zoneTab = Encoding.ASCII.GetString (zoneTab, 0, zoneTab.Length);
223                 }
224
225                 public IEnumerable<string> GetAvailableIds ()
226                 {
227                         return ids;
228                 }
229
230                 public byte[] GetTimeZoneData (string id)
231                 {
232                         int i = Array.BinarySearch (ids, id, StringComparer.Ordinal);
233                         if (i < 0)
234                                 return null;
235
236                         int offset = byteOffsets [i];
237                         int length = lengths [i];
238                         var buffer = new byte [length];
239
240                         lock (data) {
241                                 data.Position = offset;
242                                 int r;
243                                 if ((r = data.Read (buffer, 0, buffer.Length)) < buffer.Length)
244                                         throw new InvalidOperationException (
245                                                         string.Format ("Unable to fully read from file '{0}' at offset {1} length {2}; read {3} bytes expected {4}.",
246                                                                 tzdataPath, offset, length, r, buffer.Length));
247                         }
248
249                         return buffer;
250                 }
251         }
252
253         partial class TimeZoneInfo {
254
255                 /*
256                  * Android < v4.3 Timezone support infrastructure.
257                  *
258                  * This is a C# port of org.apache.harmony.luni.internal.util.ZoneInfoDB:
259                  *
260                  *    http://android.git.kernel.org/?p=platform/libcore.git;a=blob;f=luni/src/main/java/org/apache/harmony/luni/internal/util/ZoneInfoDB.java;h=3e7bdc3a952b24da535806d434a3a27690feae26;hb=HEAD
261                  *
262                  * From the ZoneInfoDB source:
263                  *
264                  *    However, to conserve disk space the data for all time zones are 
265                  *    concatenated into a single file, and a second file is used to indicate 
266                  *    the starting position of each time zone record.  A third file indicates
267                  *    the version of the zoneinfo databse used to generate the data.
268                  *
269                  * which succinctly describes why we can't just use the LIBC implementation in
270                  * TimeZoneInfo.cs -- the "standard Unixy" directory structure is NOT used.
271                  */
272                 sealed class ZoneInfoDB : IAndroidTimeZoneDB {
273                         const int TimeZoneNameLength  = 40;
274                         const int TimeZoneIntSize     = 4;
275
276                         internal static readonly string ZoneDirectoryName  = Environment.GetEnvironmentVariable ("ANDROID_ROOT") + "/usr/share/zoneinfo/";
277
278                         const    string ZoneFileName       = "zoneinfo.dat";
279                         const    string IndexFileName      = "zoneinfo.idx";
280                         const    string DefaultVersion     = "2007h";
281                         const    string VersionFileName    = "zoneinfo.version";
282
283                         readonly string    zoneRoot;
284                         readonly string    version;
285                         readonly string[]  names;
286                         readonly int[]     starts;
287                         readonly int[]     lengths;
288                         readonly int[]     offsets;
289
290                         public ZoneInfoDB (string zoneInfoDB = null)
291                         {
292                                 zoneRoot = zoneInfoDB ?? ZoneDirectoryName;
293                                 try {
294                                         version = ReadVersion (Path.Combine (zoneRoot, VersionFileName));
295                                 } catch {
296                                         version = DefaultVersion;
297                                 }
298
299                                 try {
300                                         ReadDatabase (Path.Combine (zoneRoot, IndexFileName), out names, out starts, out lengths, out offsets);
301                                 } catch {
302                                         names   = new string [0];
303                                         starts  = new int [0];
304                                         lengths = new int [0];
305                                         offsets = new int [0];
306                                 }
307                         }
308
309                         static string ReadVersion (string path)
310                         {
311                                 using (var file = new StreamReader (path, Encoding.GetEncoding ("iso-8859-1"))) {
312                                         return file.ReadToEnd ().Trim ();
313                                 }
314                         }
315
316                         void ReadDatabase (string path, out string[] names, out int[] starts, out int[] lengths, out int[] offsets)
317                         {
318                                 using (var file = File.OpenRead (path)) {
319                                         var nbuf = new byte [TimeZoneNameLength];
320
321                                         int numEntries = (int) (file.Length / (TimeZoneNameLength + 3*TimeZoneIntSize));
322
323                                         char[]  namebuf = new char [TimeZoneNameLength];
324
325                                         names   = new string [numEntries];
326                                         starts  = new int [numEntries];
327                                         lengths = new int [numEntries];
328                                         offsets = new int [numEntries];
329
330                                         for (int i = 0; i < numEntries; ++i) {
331                                                 Fill (file, nbuf, nbuf.Length);
332                                                 int namelen;
333                                                 for (namelen = 0; namelen < nbuf.Length; ++namelen) {
334                                                         if (nbuf [namelen] == '\0')
335                                                                 break;
336                                                         namebuf [namelen] = (char) (nbuf [namelen] & 0xFF);
337                                                 }
338
339                                                 names   [i] = new string (namebuf, 0, namelen);
340                                                 starts  [i] = ReadInt32 (file, nbuf);
341                                                 lengths [i] = ReadInt32 (file, nbuf);
342                                                 offsets [i] = ReadInt32 (file, nbuf);
343                                         }
344                                 }
345                         }
346
347                         static void Fill (Stream stream, byte[] nbuf, int required)
348                         {
349                                 int read = 0, offset = 0;
350                                 while (offset < required && (read = stream.Read (nbuf, offset, required - offset)) > 0)
351                                         offset += read;
352                                 if (read != required)
353                                         throw new EndOfStreamException ("Needed to read " + required + " bytes; read " + read + " bytes");
354                         }
355
356                         // From java.io.RandomAccessFioe.readInt(), as we need to use the same
357                         // byte ordering as Java uses.
358                         static int ReadInt32 (Stream stream, byte[] nbuf)
359                         {
360                                 Fill (stream, nbuf, 4);
361                                 return ((nbuf [0] & 0xff) << 24) + ((nbuf [1] & 0xff) << 16) +
362                                         ((nbuf [2] & 0xff) << 8) + (nbuf [3] & 0xff);
363                         }
364
365                         internal string Version {
366                                 get {return version;}
367                         }
368
369                         public IEnumerable<string> GetAvailableIds ()
370                         {
371                                 return GetAvailableIds (0, false);
372                         }
373
374                         IEnumerable<string> GetAvailableIds (int rawOffset)
375                         {
376                                 return GetAvailableIds (rawOffset, true);
377                         }
378
379                         IEnumerable<string> GetAvailableIds (int rawOffset, bool checkOffset)
380                         {
381                                 for (int i = 0; i < offsets.Length; ++i) {
382                                         if (!checkOffset || offsets [i] == rawOffset)
383                                                 yield return names [i];
384                                 }
385                         }
386
387                         public byte[] GetTimeZoneData (string id)
388                         {
389                                 int start, length;
390                                 using (var stream = GetTimeZoneData (id, out start, out length)) {
391                                         if (stream == null)
392                                                 return null;
393                                         byte[] buf = new byte [length];
394                                         Fill (stream, buf, buf.Length);
395                                         return buf;
396                                 }
397                         }
398
399                         FileStream GetTimeZoneData (string name, out int start, out int length)
400                         {
401                                 if (name == null) { // Just in case, to avoid NREX as in xambug #4902
402                                         start = 0;
403                                         length = 0;
404                                         return null;
405                                 }
406                                 
407                                 var f = new FileInfo (Path.Combine (zoneRoot, name));
408                                 if (f.Exists) {
409                                         start   = 0;
410                                         length  = (int) f.Length;
411                                         return f.OpenRead ();
412                                 }
413
414                                 start = length = 0;
415
416                                 int i = Array.BinarySearch (names, name, StringComparer.Ordinal);
417                                 if (i < 0)
418                                         return null;
419
420                                 start   = starts [i];
421                                 length  = lengths [i];
422
423                                 var stream = File.OpenRead (Path.Combine (zoneRoot, ZoneFileName));
424                                 stream.Seek (start, SeekOrigin.Begin);
425
426                                 return stream;
427                         }
428                 }
429
430                 static class AndroidTimeZones {
431
432                         static IAndroidTimeZoneDB db;
433
434                         static AndroidTimeZones ()
435                         {
436                                 db = GetDefaultTimeZoneDB ();
437                         }
438
439                         static IAndroidTimeZoneDB GetDefaultTimeZoneDB ()
440                         {
441                                 foreach (var p in AndroidTzData.Paths)
442                                         if (File.Exists (p))
443                                                 return new AndroidTzData (AndroidTzData.Paths);
444                                 if (Directory.Exists (ZoneInfoDB.ZoneDirectoryName))
445                                         return new ZoneInfoDB ();
446                                 return null;
447                         }
448
449                         internal static IEnumerable<string> GetAvailableIds ()
450                         {
451                                 return db == null
452                                         ? new string [0]
453                                         : db.GetAvailableIds ();
454                         }
455
456                         static TimeZoneInfo _GetTimeZone (string id, string name)
457                         {
458                                 if (db == null)
459                                         return null;
460                                 byte[] buffer = db.GetTimeZoneData (name);
461                                 if (buffer == null)
462                                         return null;
463                                 return TimeZoneInfo.ParseTZBuffer (id, buffer, buffer.Length);
464                         }
465
466                         internal static TimeZoneInfo GetTimeZone (string id, string name)
467                         {
468                                 if (name != null) {
469                                         if (name == "GMT" || name == "UTC")
470                                                 return new TimeZoneInfo (id, TimeSpan.FromSeconds (0), id, name, name, null, disableDaylightSavingTime:true);
471                                         if (name.StartsWith ("GMT"))
472                                                 return new TimeZoneInfo (id,
473                                                                 TimeSpan.FromSeconds (ParseNumericZone (name)),
474                                                                 id, name, name, null, disableDaylightSavingTime:true);
475                                 }
476
477                                 try {
478                                         return _GetTimeZone (id, name);
479                                 } catch (Exception) {
480                                         return null;
481                                 }
482                         }
483
484                         static int ParseNumericZone (string name)
485                         {
486                                 if (name == null || !name.StartsWith ("GMT") || name.Length <= 3)
487                                         return 0;
488
489                                 int sign;
490                                 if (name [3] == '+')
491                                         sign = 1;
492                                 else if (name [3] == '-')
493                                         sign = -1;
494                                 else
495                                         return 0;
496
497                                 int where;
498                                 int hour = 0;
499                                 bool colon = false;
500                                 for (where = 4; where < name.Length; where++) {
501                                         char c = name [where];
502
503                                         if (c == ':') {
504                                                 where++;
505                                                 colon = true;
506                                                 break;
507                                         }
508
509                                         if (c >= '0' && c <= '9')
510                                                 hour = hour * 10 + c - '0';
511                                         else
512                                                 return 0;
513                                 }
514
515                                 int min = 0;
516                                 for (; where < name.Length; where++) {
517                                         char c = name [where];
518
519                                         if (c >= '0' && c <= '9')
520                                                 min = min * 10 + c - '0';
521                                         else
522                                                 return 0;
523                                 }
524
525                                 if (colon)
526                                         return sign * (hour * 60 + min) * 60;
527                                 else if (hour >= 100)
528                                         return sign * ((hour / 100) * 60 + (hour % 100)) * 60;
529                                 else
530                                         return sign * (hour * 60) * 60;
531                         }
532
533                         static readonly object _lock = new object ();
534
535                         static TimeZoneInfo defaultZone;
536                         internal static TimeZoneInfo Local {
537                                 get {
538                                         lock (_lock) {
539                                                 if (defaultZone != null)
540                                                         return defaultZone;
541                                                 return defaultZone = GetTimeZone ("Local", GetDefaultTimeZoneName ());
542                                         }
543                                 }
544                         }
545                         
546                         [DllImport ("__Internal")]
547                         static extern int monodroid_get_system_property (string name, ref IntPtr value);
548
549                         [DllImport ("__Internal")]
550                         static extern void monodroid_free (IntPtr ptr);
551                         
552                         static string GetDefaultTimeZoneName ()
553                         {
554                                 IntPtr value = IntPtr.Zero;
555                                 int n = 0;
556                                 string defaultTimeZone  = Environment.GetEnvironmentVariable ("__XA_OVERRIDE_TIMEZONE_ID__");
557
558                                 if (!string.IsNullOrEmpty (defaultTimeZone))
559                                         return defaultTimeZone;
560
561                                 // Used by the tests
562                                 if (Environment.GetEnvironmentVariable ("__XA_USE_JAVA_DEFAULT_TIMEZONE_ID__") == null)
563                                         n = monodroid_get_system_property ("persist.sys.timezone", ref value);
564                                 
565                                 if (n > 0 && value != IntPtr.Zero) {
566                                         defaultTimeZone = (Marshal.PtrToStringAnsi (value) ?? String.Empty).Trim ();
567                                         monodroid_free (value);
568                                         if (!String.IsNullOrEmpty (defaultTimeZone))
569                                                 return defaultTimeZone;
570                                 }
571                                 
572                                 defaultTimeZone = (AndroidPlatform.GetDefaultTimeZone () ?? String.Empty).Trim ();
573                                 if (!String.IsNullOrEmpty (defaultTimeZone))
574                                         return defaultTimeZone;
575
576                                 return null;
577                         }
578
579 #if SELF_TEST
580                         /*
581                          * Compile:
582                          *    mcs /debug+ /out:tzi.exe /unsafe "/d:INSIDE_CORLIB;MONODROID;NET_4_0;LIBC;SELF_TEST" ../corlib/System/AndroidPlatform.cs System/TimeZone*.cs ../../build/common/Consts.cs ../Mono.Options/Mono.Options/Options.cs
583                          * Prep:
584                          *    mkdir -p usr/share/zoneinfo
585                          *    mkdir -p misc/zoneinfo/zoneinfo
586                          *    android_root=`adb shell echo '$ANDROID_ROOT' | tr -d "\r"`
587                          *    android_data=`adb shell echo '$ANDROID_DATA' | tr -d "\r"`
588                          *    adb pull $android_root/usr/share/zoneinfo usr/share/zoneinfo
589                          *    adb pull $android_data/misc/zoneinfo/tzdata misc/zoneinfo
590                          * Run:
591                          *    __XA_OVERRIDE_TIMEZONE_ID__=America/New_York ANDROID_ROOT=`pwd` ANDROID_DATA=`pwd` mono --debug tzi.exe --offset=1969-01-01
592                          */
593                         static void Main (string[] args)
594                         {
595                                 DateTime? offset           = null;
596                                 Func<IAndroidTimeZoneDB> c = () => GetDefaultTimeZoneDB ();
597                                 Mono.Options.OptionSet p = null;
598                                 p = new Mono.Options.OptionSet () {
599                                         { "T=", "Create AndroidTzData from {PATH}.", v => {
600                                                         c = () => new AndroidTzData (v);
601                                         } },
602                                         { "Z=", "Create ZoneInfoDB from {DIR}.", v => {
603                                                         c = () => new ZoneInfoDB (v);
604                                         } },
605                                         { "offset=", "Show timezone info offset for DateTime {OFFSET}.", v => {
606                                                 offset = DateTime.Parse (v);
607                                                 Console.WriteLine ("Using DateTime Offset: {0}", offset);
608                                         } },
609                                         { "help", "Show this message and exit", v => {
610                                                         p.WriteOptionDescriptions (Console.Out);
611                                                         Environment.Exit (0);
612                                         } },
613                                 };
614                                 p.Parse (args);
615                                 AndroidTimeZones.db = c ();
616                                 Console.WriteLine ("DB type: {0}", AndroidTimeZones.db.GetType ().FullName);
617                                 foreach (var id in GetAvailableIds ()) {
618                                         Console.Write ("name={0,-40}", id);
619                                         try {
620                                                 TimeZoneInfo zone = _GetTimeZone (id, id);
621                                                 if (zone != null) {
622                                                         Console.Write (" {0,-40}", zone);
623                                                         if (offset.HasValue) {
624                                                                 Console.Write ("From Offset: {0}", zone.GetUtcOffset (offset.Value));
625                                                         }
626                                                 }
627                                                 else {
628                                                         Console.Write (" ERROR:null");
629                                                 }
630                                         } catch (Exception e) {
631                                                 Console.WriteLine ();
632                                                 Console.Write ("ERROR: {0}", e);
633                                         }
634                                         Console.WriteLine ();
635                                 }
636                         }
637 #endif
638                 }
639         }
640 }
641
642 #endif // MONODROID
643