TimeZoneInfo.Unix.cs 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Buffers;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Diagnostics.CodeAnalysis;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Security;
  13. using System.Runtime.CompilerServices;
  14. using System.Runtime.InteropServices;
  15. using Internal.IO;
  16. namespace System
  17. {
  18. public sealed partial class TimeZoneInfo
  19. {
  20. private const string DefaultTimeZoneDirectory = "/usr/share/zoneinfo/";
  21. private const string ZoneTabFileName = "zone.tab";
  22. private const string TimeZoneEnvironmentVariable = "TZ";
  23. private const string TimeZoneDirectoryEnvironmentVariable = "TZDIR";
  24. private TimeZoneInfo(byte[] data, string id, bool dstDisabled)
  25. {
  26. TZifHead t;
  27. DateTime[] dts;
  28. byte[] typeOfLocalTime;
  29. TZifType[] transitionType;
  30. string zoneAbbreviations;
  31. bool[] StandardTime;
  32. bool[] GmtTime;
  33. string? futureTransitionsPosixFormat;
  34. // parse the raw TZif bytes; this method can throw ArgumentException when the data is malformed.
  35. TZif_ParseRaw(data, out t, out dts, out typeOfLocalTime, out transitionType, out zoneAbbreviations, out StandardTime, out GmtTime, out futureTransitionsPosixFormat);
  36. _id = id;
  37. _displayName = LocalId;
  38. _baseUtcOffset = TimeSpan.Zero;
  39. // find the best matching baseUtcOffset and display strings based on the current utcNow value.
  40. // NOTE: read the display strings from the tzfile now in case they can't be loaded later
  41. // from the globalization data.
  42. DateTime utcNow = DateTime.UtcNow;
  43. for (int i = 0; i < dts.Length && dts[i] <= utcNow; i++)
  44. {
  45. int type = typeOfLocalTime[i];
  46. if (!transitionType[type].IsDst)
  47. {
  48. _baseUtcOffset = transitionType[type].UtcOffset;
  49. _standardDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[type].AbbreviationIndex);
  50. }
  51. else
  52. {
  53. _daylightDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[type].AbbreviationIndex);
  54. }
  55. }
  56. if (dts.Length == 0)
  57. {
  58. // time zones like Africa/Bujumbura and Etc/GMT* have no transition times but still contain
  59. // TZifType entries that may contain a baseUtcOffset and display strings
  60. for (int i = 0; i < transitionType.Length; i++)
  61. {
  62. if (!transitionType[i].IsDst)
  63. {
  64. _baseUtcOffset = transitionType[i].UtcOffset;
  65. _standardDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[i].AbbreviationIndex);
  66. }
  67. else
  68. {
  69. _daylightDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[i].AbbreviationIndex);
  70. }
  71. }
  72. }
  73. _displayName = _standardDisplayName;
  74. GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType.Generic, ref _displayName);
  75. GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType.Standard, ref _standardDisplayName);
  76. GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType.DaylightSavings, ref _daylightDisplayName);
  77. if (_standardDisplayName == _displayName)
  78. {
  79. if (_baseUtcOffset >= TimeSpan.Zero)
  80. _displayName = $"(UTC+{_baseUtcOffset:hh\\:mm}) {_standardDisplayName}";
  81. else
  82. _displayName = $"(UTC-{_baseUtcOffset:hh\\:mm}) {_standardDisplayName}";
  83. }
  84. // TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns
  85. // with DateTimeOffset, SQL Server, and the W3C XML Specification
  86. if (_baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
  87. {
  88. _baseUtcOffset = new TimeSpan(_baseUtcOffset.Hours, _baseUtcOffset.Minutes, 0);
  89. }
  90. if (!dstDisabled)
  91. {
  92. // only create the adjustment rule if DST is enabled
  93. TZif_GenerateAdjustmentRules(out _adjustmentRules, _baseUtcOffset, dts, typeOfLocalTime, transitionType, StandardTime, GmtTime, futureTransitionsPosixFormat);
  94. }
  95. ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
  96. }
  97. private unsafe void GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType nameType, ref string? displayName)
  98. {
  99. if (GlobalizationMode.Invariant)
  100. {
  101. displayName = _standardDisplayName;
  102. return;
  103. }
  104. string? timeZoneDisplayName;
  105. bool result = Interop.CallStringMethod(
  106. (buffer, locale, id, type) =>
  107. {
  108. fixed (char* bufferPtr = buffer)
  109. {
  110. return Interop.Globalization.GetTimeZoneDisplayName(locale, id, type, bufferPtr, buffer.Length);
  111. }
  112. },
  113. CultureInfo.CurrentUICulture.Name,
  114. _id,
  115. nameType,
  116. out timeZoneDisplayName);
  117. // If there is an unknown error, don't set the displayName field.
  118. // It will be set to the abbreviation that was read out of the tzfile.
  119. if (result)
  120. {
  121. displayName = timeZoneDisplayName;
  122. }
  123. }
  124. /// <summary>
  125. /// Returns a cloned array of AdjustmentRule objects
  126. /// </summary>
  127. public AdjustmentRule[] GetAdjustmentRules()
  128. {
  129. if (_adjustmentRules == null)
  130. {
  131. return Array.Empty<AdjustmentRule>();
  132. }
  133. // The rules we use in Unix care mostly about the start and end dates but don't fill the transition start and end info.
  134. // as the rules now is public, we should fill it properly so the caller doesn't have to know how we use it internally
  135. // and can use it as it is used in Windows
  136. AdjustmentRule[] rules = new AdjustmentRule[_adjustmentRules.Length];
  137. for (int i = 0; i < _adjustmentRules.Length; i++)
  138. {
  139. var rule = _adjustmentRules[i];
  140. var start = rule.DateStart.Kind == DateTimeKind.Utc ?
  141. // At the daylight start we didn't start the daylight saving yet then we convert to Local time
  142. // by adding the _baseUtcOffset to the UTC time
  143. new DateTime(rule.DateStart.Ticks + _baseUtcOffset.Ticks, DateTimeKind.Unspecified) :
  144. rule.DateStart;
  145. var end = rule.DateEnd.Kind == DateTimeKind.Utc ?
  146. // At the daylight saving end, the UTC time is mapped to local time which is already shifted by the daylight delta
  147. // we calculate the local time by adding _baseUtcOffset + DaylightDelta to the UTC time
  148. new DateTime(rule.DateEnd.Ticks + _baseUtcOffset.Ticks + rule.DaylightDelta.Ticks, DateTimeKind.Unspecified) :
  149. rule.DateEnd;
  150. var startTransition = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, start.Hour, start.Minute, start.Second), start.Month, start.Day);
  151. var endTransition = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, end.Hour, end.Minute, end.Second), end.Month, end.Day);
  152. rules[i] = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(start.Date, end.Date, rule.DaylightDelta, startTransition, endTransition);
  153. }
  154. return rules;
  155. }
  156. private static void PopulateAllSystemTimeZones(CachedData cachedData)
  157. {
  158. Debug.Assert(Monitor.IsEntered(cachedData));
  159. string timeZoneDirectory = GetTimeZoneDirectory();
  160. foreach (string timeZoneId in GetTimeZoneIds(timeZoneDirectory))
  161. {
  162. TryGetTimeZone(timeZoneId, false, out _, out _, cachedData, alwaysFallbackToLocalMachine: true); // populate the cache
  163. }
  164. }
  165. /// <summary>
  166. /// Helper function for retrieving the local system time zone.
  167. /// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.
  168. /// Assumes cachedData lock is taken.
  169. /// </summary>
  170. /// <returns>A new TimeZoneInfo instance.</returns>
  171. private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
  172. {
  173. Debug.Assert(Monitor.IsEntered(cachedData));
  174. // Without Registry support, create the TimeZoneInfo from a TZ file
  175. return GetLocalTimeZoneFromTzFile();
  176. }
  177. private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo? value, out Exception? e)
  178. {
  179. value = null;
  180. e = null;
  181. string timeZoneDirectory = GetTimeZoneDirectory();
  182. string timeZoneFilePath = Path.Combine(timeZoneDirectory, id);
  183. byte[] rawData;
  184. try
  185. {
  186. rawData = File.ReadAllBytes(timeZoneFilePath);
  187. }
  188. catch (UnauthorizedAccessException ex)
  189. {
  190. e = ex;
  191. return TimeZoneInfoResult.SecurityException;
  192. }
  193. catch (FileNotFoundException ex)
  194. {
  195. e = ex;
  196. return TimeZoneInfoResult.TimeZoneNotFoundException;
  197. }
  198. catch (DirectoryNotFoundException ex)
  199. {
  200. e = ex;
  201. return TimeZoneInfoResult.TimeZoneNotFoundException;
  202. }
  203. catch (IOException ex)
  204. {
  205. e = new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidFileData, id, timeZoneFilePath), ex);
  206. return TimeZoneInfoResult.InvalidTimeZoneException;
  207. }
  208. value = GetTimeZoneFromTzData(rawData, id);
  209. if (value == null)
  210. {
  211. e = new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidFileData, id, timeZoneFilePath));
  212. return TimeZoneInfoResult.InvalidTimeZoneException;
  213. }
  214. return TimeZoneInfoResult.Success;
  215. }
  216. /// <summary>
  217. /// Returns a collection of TimeZone Id values from the zone.tab file in the timeZoneDirectory.
  218. /// </summary>
  219. /// <remarks>
  220. /// Lines that start with # are comments and are skipped.
  221. /// </remarks>
  222. private static List<string> GetTimeZoneIds(string timeZoneDirectory)
  223. {
  224. List<string> timeZoneIds = new List<string>();
  225. try
  226. {
  227. using (StreamReader sr = new StreamReader(Path.Combine(timeZoneDirectory, ZoneTabFileName), Encoding.UTF8))
  228. {
  229. string? zoneTabFileLine;
  230. while ((zoneTabFileLine = sr.ReadLine()) != null)
  231. {
  232. if (!string.IsNullOrEmpty(zoneTabFileLine) && zoneTabFileLine[0] != '#')
  233. {
  234. // the format of the line is "country-code \t coordinates \t TimeZone Id \t comments"
  235. int firstTabIndex = zoneTabFileLine.IndexOf('\t');
  236. if (firstTabIndex != -1)
  237. {
  238. int secondTabIndex = zoneTabFileLine.IndexOf('\t', firstTabIndex + 1);
  239. if (secondTabIndex != -1)
  240. {
  241. string timeZoneId;
  242. int startIndex = secondTabIndex + 1;
  243. int thirdTabIndex = zoneTabFileLine.IndexOf('\t', startIndex);
  244. if (thirdTabIndex != -1)
  245. {
  246. int length = thirdTabIndex - startIndex;
  247. timeZoneId = zoneTabFileLine.Substring(startIndex, length);
  248. }
  249. else
  250. {
  251. timeZoneId = zoneTabFileLine.Substring(startIndex);
  252. }
  253. if (!string.IsNullOrEmpty(timeZoneId))
  254. {
  255. timeZoneIds.Add(timeZoneId);
  256. }
  257. }
  258. }
  259. }
  260. }
  261. }
  262. }
  263. catch (IOException) { }
  264. catch (UnauthorizedAccessException) { }
  265. return timeZoneIds;
  266. }
  267. /// <summary>
  268. /// Gets the tzfile raw data for the current 'local' time zone using the following rules.
  269. /// 1. Read the TZ environment variable. If it is set, use it.
  270. /// 2. Look for the data in /etc/localtime.
  271. /// 3. Look for the data in GetTimeZoneDirectory()/localtime.
  272. /// 4. Use UTC if all else fails.
  273. /// </summary>
  274. private static bool TryGetLocalTzFile([NotNullWhen(true)] out byte[]? rawData, [NotNullWhen(true)] out string? id)
  275. {
  276. rawData = null;
  277. id = null;
  278. string? tzVariable = GetTzEnvironmentVariable();
  279. // If the env var is null, use the localtime file
  280. if (tzVariable == null)
  281. {
  282. return
  283. TryLoadTzFile("/etc/localtime", ref rawData, ref id) ||
  284. TryLoadTzFile(Path.Combine(GetTimeZoneDirectory(), "localtime"), ref rawData, ref id);
  285. }
  286. // If it's empty, use UTC (TryGetLocalTzFile() should return false).
  287. if (tzVariable.Length == 0)
  288. {
  289. return false;
  290. }
  291. // Otherwise, use the path from the env var. If it's not absolute, make it relative
  292. // to the system timezone directory
  293. string tzFilePath;
  294. if (tzVariable[0] != '/')
  295. {
  296. id = tzVariable;
  297. tzFilePath = Path.Combine(GetTimeZoneDirectory(), tzVariable);
  298. }
  299. else
  300. {
  301. tzFilePath = tzVariable;
  302. }
  303. return TryLoadTzFile(tzFilePath, ref rawData, ref id);
  304. }
  305. private static string? GetTzEnvironmentVariable()
  306. {
  307. string? result = Environment.GetEnvironmentVariable(TimeZoneEnvironmentVariable);
  308. if (!string.IsNullOrEmpty(result))
  309. {
  310. if (result[0] == ':')
  311. {
  312. // strip off the ':' prefix
  313. result = result.Substring(1);
  314. }
  315. }
  316. return result;
  317. }
  318. private static bool TryLoadTzFile(string tzFilePath, [NotNullWhen(true)] ref byte[]? rawData, [NotNullWhen(true)] ref string? id)
  319. {
  320. if (File.Exists(tzFilePath))
  321. {
  322. try
  323. {
  324. rawData = File.ReadAllBytes(tzFilePath);
  325. if (string.IsNullOrEmpty(id))
  326. {
  327. id = FindTimeZoneIdUsingReadLink(tzFilePath);
  328. if (string.IsNullOrEmpty(id))
  329. {
  330. id = FindTimeZoneId(rawData);
  331. }
  332. }
  333. return true;
  334. }
  335. catch (IOException) { }
  336. catch (SecurityException) { }
  337. catch (UnauthorizedAccessException) { }
  338. }
  339. return false;
  340. }
  341. /// <summary>
  342. /// Finds the time zone id by using 'readlink' on the path to see if tzFilePath is
  343. /// a symlink to a file.
  344. /// </summary>
  345. private static string? FindTimeZoneIdUsingReadLink(string tzFilePath)
  346. {
  347. string? id = null;
  348. string? symlinkPath = Interop.Sys.ReadLink(tzFilePath);
  349. if (symlinkPath != null)
  350. {
  351. // symlinkPath can be relative path, use Path to get the full absolute path.
  352. symlinkPath = Path.GetFullPath(symlinkPath, Path.GetDirectoryName(tzFilePath)!);
  353. string timeZoneDirectory = GetTimeZoneDirectory();
  354. if (symlinkPath.StartsWith(timeZoneDirectory, StringComparison.Ordinal))
  355. {
  356. id = symlinkPath.Substring(timeZoneDirectory.Length);
  357. }
  358. }
  359. return id;
  360. }
  361. private static string? GetDirectoryEntryFullPath(ref Interop.Sys.DirectoryEntry dirent, string currentPath)
  362. {
  363. ReadOnlySpan<char> direntName = dirent.GetName(stackalloc char[Interop.Sys.DirectoryEntry.NameBufferSize]);
  364. if ((direntName.Length == 1 && direntName[0] == '.') ||
  365. (direntName.Length == 2 && direntName[0] == '.' && direntName[1] == '.'))
  366. return null;
  367. return Path.Join(currentPath.AsSpan(), direntName);
  368. }
  369. /// <summary>
  370. /// Enumerate files
  371. /// </summary>
  372. private static unsafe void EnumerateFilesRecursively(string path, Predicate<string> condition)
  373. {
  374. List<string>? toExplore = null; // List used as a stack
  375. int bufferSize = Interop.Sys.GetReadDirRBufferSize();
  376. byte[]? dirBuffer = null;
  377. try
  378. {
  379. dirBuffer = ArrayPool<byte>.Shared.Rent(bufferSize);
  380. string currentPath = path;
  381. fixed (byte* dirBufferPtr = dirBuffer)
  382. {
  383. while (true)
  384. {
  385. IntPtr dirHandle = Interop.Sys.OpenDir(currentPath);
  386. if (dirHandle == IntPtr.Zero)
  387. {
  388. throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), currentPath, isDirectory: true);
  389. }
  390. try
  391. {
  392. // Read each entry from the enumerator
  393. Interop.Sys.DirectoryEntry dirent;
  394. while (Interop.Sys.ReadDirR(dirHandle, dirBufferPtr, bufferSize, out dirent) == 0)
  395. {
  396. string? fullPath = GetDirectoryEntryFullPath(ref dirent, currentPath);
  397. if (fullPath == null)
  398. continue;
  399. // Get from the dir entry whether the entry is a file or directory.
  400. // We classify everything as a file unless we know it to be a directory.
  401. bool isDir;
  402. if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR)
  403. {
  404. // We know it's a directory.
  405. isDir = true;
  406. }
  407. else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN)
  408. {
  409. // It's a symlink or unknown: stat to it to see if we can resolve it to a directory.
  410. // If we can't (e.g. symlink to a file, broken symlink, etc.), we'll just treat it as a file.
  411. Interop.Sys.FileStatus fileinfo;
  412. if (Interop.Sys.Stat(fullPath, out fileinfo) >= 0)
  413. {
  414. isDir = (fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR;
  415. }
  416. else
  417. {
  418. isDir = false;
  419. }
  420. }
  421. else
  422. {
  423. // Otherwise, treat it as a file. This includes regular files, FIFOs, etc.
  424. isDir = false;
  425. }
  426. // Yield the result if the user has asked for it. In the case of directories,
  427. // always explore it by pushing it onto the stack, regardless of whether
  428. // we're returning directories.
  429. if (isDir)
  430. {
  431. toExplore ??= new List<string>();
  432. toExplore.Add(fullPath);
  433. }
  434. else if (condition(fullPath))
  435. {
  436. return;
  437. }
  438. }
  439. }
  440. finally
  441. {
  442. if (dirHandle != IntPtr.Zero)
  443. Interop.Sys.CloseDir(dirHandle);
  444. }
  445. if (toExplore == null || toExplore.Count == 0)
  446. break;
  447. currentPath = toExplore[toExplore.Count - 1];
  448. toExplore.RemoveAt(toExplore.Count - 1);
  449. }
  450. }
  451. }
  452. finally
  453. {
  454. if (dirBuffer != null)
  455. ArrayPool<byte>.Shared.Return(dirBuffer);
  456. }
  457. }
  458. /// <summary>
  459. /// Find the time zone id by searching all the tzfiles for the one that matches rawData
  460. /// and return its file name.
  461. /// </summary>
  462. private static string FindTimeZoneId(byte[] rawData)
  463. {
  464. // default to "Local" if we can't find the right tzfile
  465. string id = LocalId;
  466. string timeZoneDirectory = GetTimeZoneDirectory();
  467. string localtimeFilePath = Path.Combine(timeZoneDirectory, "localtime");
  468. string posixrulesFilePath = Path.Combine(timeZoneDirectory, "posixrules");
  469. byte[] buffer = new byte[rawData.Length];
  470. try
  471. {
  472. EnumerateFilesRecursively(timeZoneDirectory, (string filePath) =>
  473. {
  474. // skip the localtime and posixrules file, since they won't give us the correct id
  475. if (!string.Equals(filePath, localtimeFilePath, StringComparison.OrdinalIgnoreCase)
  476. && !string.Equals(filePath, posixrulesFilePath, StringComparison.OrdinalIgnoreCase))
  477. {
  478. if (CompareTimeZoneFile(filePath, buffer, rawData))
  479. {
  480. // if all bytes are the same, this must be the right tz file
  481. id = filePath;
  482. // strip off the root time zone directory
  483. if (id.StartsWith(timeZoneDirectory, StringComparison.Ordinal))
  484. {
  485. id = id.Substring(timeZoneDirectory.Length);
  486. }
  487. return true;
  488. }
  489. }
  490. return false;
  491. });
  492. }
  493. catch (IOException) { }
  494. catch (SecurityException) { }
  495. catch (UnauthorizedAccessException) { }
  496. return id;
  497. }
  498. private static bool CompareTimeZoneFile(string filePath, byte[] buffer, byte[] rawData)
  499. {
  500. try
  501. {
  502. // bufferSize == 1 used to avoid unnecessary buffer in FileStream
  503. using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1))
  504. {
  505. if (stream.Length == rawData.Length)
  506. {
  507. int index = 0;
  508. int count = rawData.Length;
  509. while (count > 0)
  510. {
  511. int n = stream.Read(buffer, index, count);
  512. if (n == 0)
  513. throw Error.GetEndOfFile();
  514. int end = index + n;
  515. for (; index < end; index++)
  516. {
  517. if (buffer[index] != rawData[index])
  518. {
  519. return false;
  520. }
  521. }
  522. count -= n;
  523. }
  524. return true;
  525. }
  526. }
  527. }
  528. catch (IOException) { }
  529. catch (SecurityException) { }
  530. catch (UnauthorizedAccessException) { }
  531. return false;
  532. }
  533. /// <summary>
  534. /// Helper function used by 'GetLocalTimeZone()' - this function wraps the call
  535. /// for loading time zone data from computers without Registry support.
  536. ///
  537. /// The TryGetLocalTzFile() call returns a Byte[] containing the compiled tzfile.
  538. /// </summary>
  539. private static TimeZoneInfo GetLocalTimeZoneFromTzFile()
  540. {
  541. byte[]? rawData;
  542. string? id;
  543. if (TryGetLocalTzFile(out rawData, out id))
  544. {
  545. TimeZoneInfo? result = GetTimeZoneFromTzData(rawData, id);
  546. if (result != null)
  547. {
  548. return result;
  549. }
  550. }
  551. // if we can't find a local time zone, return UTC
  552. return Utc;
  553. }
  554. private static TimeZoneInfo? GetTimeZoneFromTzData(byte[]? rawData, string id)
  555. {
  556. if (rawData != null)
  557. {
  558. try
  559. {
  560. return new TimeZoneInfo(rawData, id, dstDisabled: false); // create a TimeZoneInfo instance from the TZif data w/ DST support
  561. }
  562. catch (ArgumentException) { }
  563. catch (InvalidTimeZoneException) { }
  564. try
  565. {
  566. return new TimeZoneInfo(rawData, id, dstDisabled: true); // create a TimeZoneInfo instance from the TZif data w/o DST support
  567. }
  568. catch (ArgumentException) { }
  569. catch (InvalidTimeZoneException) { }
  570. }
  571. return null;
  572. }
  573. private static string GetTimeZoneDirectory()
  574. {
  575. string? tzDirectory = Environment.GetEnvironmentVariable(TimeZoneDirectoryEnvironmentVariable);
  576. if (tzDirectory == null)
  577. {
  578. tzDirectory = DefaultTimeZoneDirectory;
  579. }
  580. else if (!tzDirectory.EndsWith(Path.DirectorySeparatorChar))
  581. {
  582. tzDirectory += PathInternal.DirectorySeparatorCharAsString;
  583. }
  584. return tzDirectory;
  585. }
  586. /// <summary>
  587. /// Helper function for retrieving a TimeZoneInfo object by time_zone_name.
  588. /// This function wraps the logic necessary to keep the private
  589. /// SystemTimeZones cache in working order
  590. ///
  591. /// This function will either return a valid TimeZoneInfo instance or
  592. /// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.
  593. /// </summary>
  594. public static TimeZoneInfo FindSystemTimeZoneById(string id)
  595. {
  596. // Special case for Utc as it will not exist in the dictionary with the rest
  597. // of the system time zones. There is no need to do this check for Local.Id
  598. // since Local is a real time zone that exists in the dictionary cache
  599. if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase))
  600. {
  601. return Utc;
  602. }
  603. if (id == null)
  604. {
  605. throw new ArgumentNullException(nameof(id));
  606. }
  607. else if (id.Length == 0 || id.Contains('\0'))
  608. {
  609. throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));
  610. }
  611. TimeZoneInfo? value;
  612. Exception? e;
  613. TimeZoneInfoResult result;
  614. CachedData cachedData = s_cachedData;
  615. lock (cachedData)
  616. {
  617. result = TryGetTimeZone(id, false, out value, out e, cachedData, alwaysFallbackToLocalMachine: true);
  618. }
  619. if (result == TimeZoneInfoResult.Success)
  620. {
  621. return value!;
  622. }
  623. else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
  624. {
  625. Debug.Assert(e is InvalidTimeZoneException,
  626. "TryGetTimeZone must create an InvalidTimeZoneException when it returns TimeZoneInfoResult.InvalidTimeZoneException");
  627. throw e;
  628. }
  629. else if (result == TimeZoneInfoResult.SecurityException)
  630. {
  631. throw new SecurityException(SR.Format(SR.Security_CannotReadFileData, id), e);
  632. }
  633. else
  634. {
  635. throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);
  636. }
  637. }
  638. // DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
  639. internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst)
  640. {
  641. bool isDaylightSavings;
  642. // Use the standard code path for Unix since there isn't a faster way of handling current-year-only time zones
  643. return GetUtcOffsetFromUtc(time, Local, out isDaylightSavings, out isAmbiguousLocalDst);
  644. }
  645. // TZFILE(5) BSD File Formats Manual TZFILE(5)
  646. //
  647. // NAME
  648. // tzfile -- timezone information
  649. //
  650. // SYNOPSIS
  651. // #include "/usr/src/lib/libc/stdtime/tzfile.h"
  652. //
  653. // DESCRIPTION
  654. // The time zone information files used by tzset(3) begin with the magic
  655. // characters ``TZif'' to identify them as time zone information files, fol-
  656. // lowed by sixteen bytes reserved for future use, followed by four four-
  657. // byte values written in a ``standard'' byte order (the high-order byte of
  658. // the value is written first). These values are, in order:
  659. //
  660. // tzh_ttisgmtcnt The number of UTC/local indicators stored in the file.
  661. // tzh_ttisstdcnt The number of standard/wall indicators stored in the
  662. // file.
  663. // tzh_leapcnt The number of leap seconds for which data is stored in
  664. // the file.
  665. // tzh_timecnt The number of ``transition times'' for which data is
  666. // stored in the file.
  667. // tzh_typecnt The number of ``local time types'' for which data is
  668. // stored in the file (must not be zero).
  669. // tzh_charcnt The number of characters of ``time zone abbreviation
  670. // strings'' stored in the file.
  671. //
  672. // The above header is followed by tzh_timecnt four-byte values of type
  673. // long, sorted in ascending order. These values are written in ``stan-
  674. // dard'' byte order. Each is used as a transition time (as returned by
  675. // time(3)) at which the rules for computing local time change. Next come
  676. // tzh_timecnt one-byte values of type unsigned char; each one tells which
  677. // of the different types of ``local time'' types described in the file is
  678. // associated with the same-indexed transition time. These values serve as
  679. // indices into an array of ttinfo structures that appears next in the file;
  680. // these structures are defined as follows:
  681. //
  682. // struct ttinfo {
  683. // long tt_gmtoff;
  684. // int tt_isdst;
  685. // unsigned int tt_abbrind;
  686. // };
  687. //
  688. // Each structure is written as a four-byte value for tt_gmtoff of type
  689. // long, in a standard byte order, followed by a one-byte value for tt_isdst
  690. // and a one-byte value for tt_abbrind. In each structure, tt_gmtoff gives
  691. // the number of seconds to be added to UTC, tt_isdst tells whether tm_isdst
  692. // should be set by localtime(3) and tt_abbrind serves as an index into the
  693. // array of time zone abbreviation characters that follow the ttinfo struc-
  694. // ture(s) in the file.
  695. //
  696. // Then there are tzh_leapcnt pairs of four-byte values, written in standard
  697. // byte order; the first value of each pair gives the time (as returned by
  698. // time(3)) at which a leap second occurs; the second gives the total number
  699. // of leap seconds to be applied after the given time. The pairs of values
  700. // are sorted in ascending order by time.b
  701. //
  702. // Then there are tzh_ttisstdcnt standard/wall indicators, each stored as a
  703. // one-byte value; they tell whether the transition times associated with
  704. // local time types were specified as standard time or wall clock time, and
  705. // are used when a time zone file is used in handling POSIX-style time zone
  706. // environment variables.
  707. //
  708. // Finally there are tzh_ttisgmtcnt UTC/local indicators, each stored as a
  709. // one-byte value; they tell whether the transition times associated with
  710. // local time types were specified as UTC or local time, and are used when a
  711. // time zone file is used in handling POSIX-style time zone environment
  712. // variables.
  713. //
  714. // localtime uses the first standard-time ttinfo structure in the file (or
  715. // simply the first ttinfo structure in the absence of a standard-time
  716. // structure) if either tzh_timecnt is zero or the time argument is less
  717. // than the first transition time recorded in the file.
  718. //
  719. // SEE ALSO
  720. // ctime(3), time2posix(3), zic(8)
  721. //
  722. // BSD September 13, 1994 BSD
  723. //
  724. //
  725. //
  726. // TIME(3) BSD Library Functions Manual TIME(3)
  727. //
  728. // NAME
  729. // time -- get time of day
  730. //
  731. // LIBRARY
  732. // Standard C Library (libc, -lc)
  733. //
  734. // SYNOPSIS
  735. // #include <time.h>
  736. //
  737. // time_t
  738. // time(time_t *tloc);
  739. //
  740. // DESCRIPTION
  741. // The time() function returns the value of time in seconds since 0 hours, 0
  742. // minutes, 0 seconds, January 1, 1970, Coordinated Universal Time, without
  743. // including leap seconds. If an error occurs, time() returns the value
  744. // (time_t)-1.
  745. //
  746. // The return value is also stored in *tloc, provided that tloc is non-null.
  747. //
  748. // ERRORS
  749. // The time() function may fail for any of the reasons described in
  750. // gettimeofday(2).
  751. //
  752. // SEE ALSO
  753. // gettimeofday(2), ctime(3)
  754. //
  755. // STANDARDS
  756. // The time function conforms to IEEE Std 1003.1-2001 (``POSIX.1'').
  757. //
  758. // BUGS
  759. // Neither ISO/IEC 9899:1999 (``ISO C99'') nor IEEE Std 1003.1-2001
  760. // (``POSIX.1'') requires time() to set errno on failure; thus, it is impos-
  761. // sible for an application to distinguish the valid time value -1 (repre-
  762. // senting the last UTC second of 1969) from the error return value.
  763. //
  764. // Systems conforming to earlier versions of the C and POSIX standards
  765. // (including older versions of FreeBSD) did not set *tloc in the error
  766. // case.
  767. //
  768. // HISTORY
  769. // A time() function appeared in Version 6 AT&T UNIX.
  770. //
  771. // BSD July 18, 2003 BSD
  772. //
  773. //
  774. private static void TZif_GenerateAdjustmentRules(out AdjustmentRule[]? rules, TimeSpan baseUtcOffset, DateTime[] dts, byte[] typeOfLocalTime,
  775. TZifType[] transitionType, bool[] StandardTime, bool[] GmtTime, string? futureTransitionsPosixFormat)
  776. {
  777. rules = null;
  778. if (dts.Length > 0)
  779. {
  780. int index = 0;
  781. List<AdjustmentRule> rulesList = new List<AdjustmentRule>();
  782. while (index <= dts.Length)
  783. {
  784. TZif_GenerateAdjustmentRule(ref index, baseUtcOffset, rulesList, dts, typeOfLocalTime, transitionType, StandardTime, GmtTime, futureTransitionsPosixFormat);
  785. }
  786. rules = rulesList.ToArray();
  787. if (rules != null && rules.Length == 0)
  788. {
  789. rules = null;
  790. }
  791. }
  792. }
  793. private static void TZif_GenerateAdjustmentRule(ref int index, TimeSpan timeZoneBaseUtcOffset, List<AdjustmentRule> rulesList, DateTime[] dts,
  794. byte[] typeOfLocalTime, TZifType[] transitionTypes, bool[] StandardTime, bool[] GmtTime, string? futureTransitionsPosixFormat)
  795. {
  796. // To generate AdjustmentRules, use the following approach:
  797. // The first AdjustmentRule will go from DateTime.MinValue to the first transition time greater than DateTime.MinValue.
  798. // Each middle AdjustmentRule wil go from dts[index-1] to dts[index].
  799. // The last AdjustmentRule will go from dts[dts.Length-1] to Datetime.MaxValue.
  800. // 0. Skip any DateTime.MinValue transition times. In newer versions of the tzfile, there
  801. // is a "big bang" transition time, which is before the year 0001. Since any times before year 0001
  802. // cannot be represented by DateTime, there is no reason to make AdjustmentRules for these unrepresentable time periods.
  803. // 1. If there are no DateTime.MinValue times, the first AdjustmentRule goes from DateTime.MinValue
  804. // to the first transition and uses the first standard transitionType (or the first transitionType if none of them are standard)
  805. // 2. Create an AdjustmentRule for each transition, i.e. from dts[index - 1] to dts[index].
  806. // This rule uses the transitionType[index - 1] and the whole AdjustmentRule only describes a single offset - either
  807. // all daylight savings, or all stanard time.
  808. // 3. After all the transitions are filled out, the last AdjustmentRule is created from either:
  809. // a. a POSIX-style timezone description ("futureTransitionsPosixFormat"), if there is one or
  810. // b. continue the last transition offset until DateTime.Max
  811. while (index < dts.Length && dts[index] == DateTime.MinValue)
  812. {
  813. index++;
  814. }
  815. if (rulesList.Count == 0 && index < dts.Length)
  816. {
  817. TZifType transitionType = TZif_GetEarlyDateTransitionType(transitionTypes);
  818. DateTime endTransitionDate = dts[index];
  819. TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(transitionType.UtcOffset, timeZoneBaseUtcOffset);
  820. TimeSpan daylightDelta = transitionType.IsDst ? transitionOffset : TimeSpan.Zero;
  821. TimeSpan baseUtcDelta = transitionType.IsDst ? TimeSpan.Zero : transitionOffset;
  822. AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(
  823. DateTime.MinValue,
  824. endTransitionDate.AddTicks(-1),
  825. daylightDelta,
  826. default(TransitionTime),
  827. default(TransitionTime),
  828. baseUtcDelta,
  829. noDaylightTransitions: true);
  830. if (!IsValidAdjustmentRuleOffest(timeZoneBaseUtcOffset, r))
  831. {
  832. NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r);
  833. }
  834. rulesList.Add(r);
  835. }
  836. else if (index < dts.Length)
  837. {
  838. DateTime startTransitionDate = dts[index - 1];
  839. TZifType startTransitionType = transitionTypes[typeOfLocalTime[index - 1]];
  840. DateTime endTransitionDate = dts[index];
  841. TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(startTransitionType.UtcOffset, timeZoneBaseUtcOffset);
  842. TimeSpan daylightDelta = startTransitionType.IsDst ? transitionOffset : TimeSpan.Zero;
  843. TimeSpan baseUtcDelta = startTransitionType.IsDst ? TimeSpan.Zero : transitionOffset;
  844. TransitionTime dstStart;
  845. if (startTransitionType.IsDst)
  846. {
  847. // the TransitionTime fields are not used when AdjustmentRule.NoDaylightTransitions == true.
  848. // However, there are some cases in the past where DST = true, and the daylight savings offset
  849. // now equals what the current BaseUtcOffset is. In that case, the AdjustmentRule.DaylightOffset
  850. // is going to be TimeSpan.Zero. But we still need to return 'true' from AdjustmentRule.HasDaylightSaving.
  851. // To ensure we always return true from HasDaylightSaving, make a "special" dstStart that will make the logic
  852. // in HasDaylightSaving return true.
  853. dstStart = TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(2), 1, 1);
  854. }
  855. else
  856. {
  857. dstStart = default(TransitionTime);
  858. }
  859. AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(
  860. startTransitionDate,
  861. endTransitionDate.AddTicks(-1),
  862. daylightDelta,
  863. dstStart,
  864. default(TransitionTime),
  865. baseUtcDelta,
  866. noDaylightTransitions: true);
  867. if (!IsValidAdjustmentRuleOffest(timeZoneBaseUtcOffset, r))
  868. {
  869. NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r);
  870. }
  871. rulesList.Add(r);
  872. }
  873. else
  874. {
  875. // create the AdjustmentRule that will be used for all DateTimes after the last transition
  876. // NOTE: index == dts.Length
  877. DateTime startTransitionDate = dts[index - 1];
  878. if (!string.IsNullOrEmpty(futureTransitionsPosixFormat))
  879. {
  880. AdjustmentRule? r = TZif_CreateAdjustmentRuleForPosixFormat(futureTransitionsPosixFormat, startTransitionDate, timeZoneBaseUtcOffset);
  881. if (r != null)
  882. {
  883. if (!IsValidAdjustmentRuleOffest(timeZoneBaseUtcOffset, r))
  884. {
  885. NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r);
  886. }
  887. rulesList.Add(r);
  888. }
  889. }
  890. else
  891. {
  892. // just use the last transition as the rule which will be used until the end of time
  893. TZifType transitionType = transitionTypes[typeOfLocalTime[index - 1]];
  894. TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(transitionType.UtcOffset, timeZoneBaseUtcOffset);
  895. TimeSpan daylightDelta = transitionType.IsDst ? transitionOffset : TimeSpan.Zero;
  896. TimeSpan baseUtcDelta = transitionType.IsDst ? TimeSpan.Zero : transitionOffset;
  897. AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule(
  898. startTransitionDate,
  899. DateTime.MaxValue,
  900. daylightDelta,
  901. default(TransitionTime),
  902. default(TransitionTime),
  903. baseUtcDelta,
  904. noDaylightTransitions: true);
  905. if (!IsValidAdjustmentRuleOffest(timeZoneBaseUtcOffset, r))
  906. {
  907. NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r);
  908. }
  909. rulesList.Add(r);
  910. }
  911. }
  912. index++;
  913. }
  914. private static TimeSpan TZif_CalculateTransitionOffsetFromBase(TimeSpan transitionOffset, TimeSpan timeZoneBaseUtcOffset)
  915. {
  916. TimeSpan result = transitionOffset - timeZoneBaseUtcOffset;
  917. // TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns
  918. // with DateTimeOffset, SQL Server, and the W3C XML Specification
  919. if (result.Ticks % TimeSpan.TicksPerMinute != 0)
  920. {
  921. result = new TimeSpan(result.Hours, result.Minutes, 0);
  922. }
  923. return result;
  924. }
  925. /// <summary>
  926. /// Gets the first standard-time transition type, or simply the first transition type
  927. /// if there are no standard transition types.
  928. /// </summary>>
  929. /// <remarks>
  930. /// from 'man tzfile':
  931. /// localtime(3) uses the first standard-time ttinfo structure in the file
  932. /// (or simply the first ttinfo structure in the absence of a standard-time
  933. /// structure) if either tzh_timecnt is zero or the time argument is less
  934. /// than the first transition time recorded in the file.
  935. /// </remarks>
  936. private static TZifType TZif_GetEarlyDateTransitionType(TZifType[] transitionTypes)
  937. {
  938. foreach (TZifType transitionType in transitionTypes)
  939. {
  940. if (!transitionType.IsDst)
  941. {
  942. return transitionType;
  943. }
  944. }
  945. if (transitionTypes.Length > 0)
  946. {
  947. return transitionTypes[0];
  948. }
  949. throw new InvalidTimeZoneException(SR.InvalidTimeZone_NoTTInfoStructures);
  950. }
  951. /// <summary>
  952. /// Creates an AdjustmentRule given the POSIX TZ environment variable string.
  953. /// </summary>
  954. /// <remarks>
  955. /// See http://man7.org/linux/man-pages/man3/tzset.3.html for the format and semantics of this POSX string.
  956. /// </remarks>
  957. private static AdjustmentRule? TZif_CreateAdjustmentRuleForPosixFormat(string posixFormat, DateTime startTransitionDate, TimeSpan timeZoneBaseUtcOffset)
  958. {
  959. if (TZif_ParsePosixFormat(posixFormat,
  960. out ReadOnlySpan<char> standardName,
  961. out ReadOnlySpan<char> standardOffset,
  962. out ReadOnlySpan<char> daylightSavingsName,
  963. out ReadOnlySpan<char> daylightSavingsOffset,
  964. out ReadOnlySpan<char> start,
  965. out ReadOnlySpan<char> startTime,
  966. out ReadOnlySpan<char> end,
  967. out ReadOnlySpan<char> endTime))
  968. {
  969. // a valid posixFormat has at least standardName and standardOffset
  970. TimeSpan? parsedBaseOffset = TZif_ParseOffsetString(standardOffset);
  971. if (parsedBaseOffset.HasValue)
  972. {
  973. TimeSpan baseOffset = parsedBaseOffset.GetValueOrDefault().Negate(); // offsets are backwards in POSIX notation
  974. baseOffset = TZif_CalculateTransitionOffsetFromBase(baseOffset, timeZoneBaseUtcOffset);
  975. // having a daylightSavingsName means there is a DST rule
  976. if (!daylightSavingsName.IsEmpty)
  977. {
  978. TimeSpan? parsedDaylightSavings = TZif_ParseOffsetString(daylightSavingsOffset);
  979. TimeSpan daylightSavingsTimeSpan;
  980. if (!parsedDaylightSavings.HasValue)
  981. {
  982. // default DST to 1 hour if it isn't specified
  983. daylightSavingsTimeSpan = new TimeSpan(1, 0, 0);
  984. }
  985. else
  986. {
  987. daylightSavingsTimeSpan = parsedDaylightSavings.GetValueOrDefault().Negate(); // offsets are backwards in POSIX notation
  988. daylightSavingsTimeSpan = TZif_CalculateTransitionOffsetFromBase(daylightSavingsTimeSpan, timeZoneBaseUtcOffset);
  989. daylightSavingsTimeSpan = TZif_CalculateTransitionOffsetFromBase(daylightSavingsTimeSpan, baseOffset);
  990. }
  991. TransitionTime dstStart = TZif_CreateTransitionTimeFromPosixRule(start, startTime);
  992. TransitionTime dstEnd = TZif_CreateTransitionTimeFromPosixRule(end, endTime);
  993. return AdjustmentRule.CreateAdjustmentRule(
  994. startTransitionDate,
  995. DateTime.MaxValue,
  996. daylightSavingsTimeSpan,
  997. dstStart,
  998. dstEnd,
  999. baseOffset,
  1000. noDaylightTransitions: false);
  1001. }
  1002. else
  1003. {
  1004. // if there is no daylightSavingsName, the whole AdjustmentRule should be with no transitions - just the baseOffset
  1005. return AdjustmentRule.CreateAdjustmentRule(
  1006. startTransitionDate,
  1007. DateTime.MaxValue,
  1008. TimeSpan.Zero,
  1009. default(TransitionTime),
  1010. default(TransitionTime),
  1011. baseOffset,
  1012. noDaylightTransitions: true);
  1013. }
  1014. }
  1015. }
  1016. return null;
  1017. }
  1018. private static TimeSpan? TZif_ParseOffsetString(ReadOnlySpan<char> offset)
  1019. {
  1020. TimeSpan? result = null;
  1021. if (offset.Length > 0)
  1022. {
  1023. bool negative = offset[0] == '-';
  1024. if (negative || offset[0] == '+')
  1025. {
  1026. offset = offset.Slice(1);
  1027. }
  1028. // Try parsing just hours first.
  1029. // Note, TimeSpan.TryParseExact "%h" can't be used here because some time zones using values
  1030. // like "26" or "144" and TimeSpan parsing would turn that into 26 or 144 *days* instead of hours.
  1031. int hours;
  1032. if (int.TryParse(offset, out hours))
  1033. {
  1034. result = new TimeSpan(hours, 0, 0);
  1035. }
  1036. else
  1037. {
  1038. TimeSpan parsedTimeSpan;
  1039. if (TimeSpan.TryParseExact(offset, "g", CultureInfo.InvariantCulture, out parsedTimeSpan))
  1040. {
  1041. result = parsedTimeSpan;
  1042. }
  1043. }
  1044. if (result.HasValue && negative)
  1045. {
  1046. result = result.GetValueOrDefault().Negate();
  1047. }
  1048. }
  1049. return result;
  1050. }
  1051. private static DateTime ParseTimeOfDay(ReadOnlySpan<char> time)
  1052. {
  1053. DateTime timeOfDay;
  1054. TimeSpan? timeOffset = TZif_ParseOffsetString(time);
  1055. if (timeOffset.HasValue)
  1056. {
  1057. // This logic isn't correct and can't be corrected until https://github.com/dotnet/corefx/issues/2618 is fixed.
  1058. // Some time zones use time values like, "26", "144", or "-2".
  1059. // This allows the week to sometimes be week 4 and sometimes week 5 in the month.
  1060. // For now, strip off any 'days' in the offset, and just get the time of day correct
  1061. timeOffset = new TimeSpan(timeOffset.GetValueOrDefault().Hours, timeOffset.GetValueOrDefault().Minutes, timeOffset.GetValueOrDefault().Seconds);
  1062. if (timeOffset.GetValueOrDefault() < TimeSpan.Zero)
  1063. {
  1064. timeOfDay = new DateTime(1, 1, 2, 0, 0, 0);
  1065. }
  1066. else
  1067. {
  1068. timeOfDay = new DateTime(1, 1, 1, 0, 0, 0);
  1069. }
  1070. timeOfDay += timeOffset.GetValueOrDefault();
  1071. }
  1072. else
  1073. {
  1074. // default to 2AM.
  1075. timeOfDay = new DateTime(1, 1, 1, 2, 0, 0);
  1076. }
  1077. return timeOfDay;
  1078. }
  1079. private static TransitionTime TZif_CreateTransitionTimeFromPosixRule(ReadOnlySpan<char> date, ReadOnlySpan<char> time)
  1080. {
  1081. if (date.IsEmpty)
  1082. {
  1083. return default;
  1084. }
  1085. if (date[0] == 'M')
  1086. {
  1087. // Mm.w.d
  1088. // This specifies day d of week w of month m. The day d must be between 0(Sunday) and 6.The week w must be between 1 and 5;
  1089. // week 1 is the first week in which day d occurs, and week 5 specifies the last d day in the month. The month m should be between 1 and 12.
  1090. int month;
  1091. int week;
  1092. DayOfWeek day;
  1093. if (!TZif_ParseMDateRule(date, out month, out week, out day))
  1094. {
  1095. throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_UnparseablePosixMDateString, date.ToString()));
  1096. }
  1097. return TransitionTime.CreateFloatingDateRule(ParseTimeOfDay(time), month, week, day);
  1098. }
  1099. else
  1100. {
  1101. if (date[0] != 'J')
  1102. {
  1103. // should be n Julian day format which we don't support.
  1104. //
  1105. // This specifies the Julian day, with n between 0 and 365. February 29 is counted in leap years.
  1106. //
  1107. // n would be a relative number from the begining of the year. which should handle if the
  1108. // the year is a leap year or not.
  1109. //
  1110. // In leap year, n would be counted as:
  1111. //
  1112. // 0 30 31 59 60 90 335 365
  1113. // |-------Jan--------|-------Feb--------|-------Mar--------|....|-------Dec--------|
  1114. //
  1115. // while in non leap year we'll have
  1116. //
  1117. // 0 30 31 58 59 89 334 364
  1118. // |-------Jan--------|-------Feb--------|-------Mar--------|....|-------Dec--------|
  1119. //
  1120. //
  1121. // For example if n is specified as 60, this means in leap year the rule will start at Mar 1,
  1122. // while in non leap year the rule will start at Mar 2.
  1123. //
  1124. // If we need to support n format, we'll have to have a floating adjustment rule support this case.
  1125. throw new InvalidTimeZoneException(SR.InvalidTimeZone_NJulianDayNotSupported);
  1126. }
  1127. // Julian day
  1128. TZif_ParseJulianDay(date, out int month, out int day);
  1129. return TransitionTime.CreateFixedDateRule(ParseTimeOfDay(time), month, day);
  1130. }
  1131. }
  1132. /// <summary>
  1133. /// Parses a string like Jn or n into month and day values.
  1134. /// </summary>
  1135. private static void TZif_ParseJulianDay(ReadOnlySpan<char> date, out int month, out int day)
  1136. {
  1137. // Jn
  1138. // This specifies the Julian day, with n between 1 and 365.February 29 is never counted, even in leap years.
  1139. Debug.Assert(!date.IsEmpty);
  1140. Debug.Assert(date[0] == 'J');
  1141. month = day = 0;
  1142. int index = 1;
  1143. if (index >= date.Length || ((uint)(date[index] - '0') > '9'-'0'))
  1144. {
  1145. throw new InvalidTimeZoneException(SR.InvalidTimeZone_InvalidJulianDay);
  1146. }
  1147. int julianDay = 0;
  1148. do
  1149. {
  1150. julianDay = julianDay * 10 + (int) (date[index] - '0');
  1151. index++;
  1152. } while (index < date.Length && ((uint)(date[index] - '0') <= '9'-'0'));
  1153. int[] days = GregorianCalendarHelper.DaysToMonth365;
  1154. if (julianDay == 0 || julianDay > days[days.Length - 1])
  1155. {
  1156. throw new InvalidTimeZoneException(SR.InvalidTimeZone_InvalidJulianDay);
  1157. }
  1158. int i = 1;
  1159. while (i < days.Length && julianDay > days[i])
  1160. {
  1161. i++;
  1162. }
  1163. Debug.Assert(i > 0 && i < days.Length);
  1164. month = i;
  1165. day = julianDay - days[i - 1];
  1166. }
  1167. /// <summary>
  1168. /// Parses a string like Mm.w.d into month, week and DayOfWeek values.
  1169. /// </summary>
  1170. /// <returns>
  1171. /// true if the parsing succeeded; otherwise, false.
  1172. /// </returns>
  1173. private static bool TZif_ParseMDateRule(ReadOnlySpan<char> dateRule, out int month, out int week, out DayOfWeek dayOfWeek)
  1174. {
  1175. if (dateRule[0] == 'M')
  1176. {
  1177. int monthWeekDotIndex = dateRule.IndexOf('.');
  1178. if (monthWeekDotIndex > 0)
  1179. {
  1180. ReadOnlySpan<char> weekDaySpan = dateRule.Slice(monthWeekDotIndex + 1);
  1181. int weekDayDotIndex = weekDaySpan.IndexOf('.');
  1182. if (weekDayDotIndex > 0)
  1183. {
  1184. if (int.TryParse(dateRule.Slice(1, monthWeekDotIndex - 1), out month) &&
  1185. int.TryParse(weekDaySpan.Slice(0, weekDayDotIndex), out week) &&
  1186. int.TryParse(weekDaySpan.Slice(weekDayDotIndex + 1), out int day))
  1187. {
  1188. dayOfWeek = (DayOfWeek)day;
  1189. return true;
  1190. }
  1191. }
  1192. }
  1193. }
  1194. month = 0;
  1195. week = 0;
  1196. dayOfWeek = default(DayOfWeek);
  1197. return false;
  1198. }
  1199. private static bool TZif_ParsePosixFormat(
  1200. ReadOnlySpan<char> posixFormat,
  1201. out ReadOnlySpan<char> standardName,
  1202. out ReadOnlySpan<char> standardOffset,
  1203. out ReadOnlySpan<char> daylightSavingsName,
  1204. out ReadOnlySpan<char> daylightSavingsOffset,
  1205. out ReadOnlySpan<char> start,
  1206. out ReadOnlySpan<char> startTime,
  1207. out ReadOnlySpan<char> end,
  1208. out ReadOnlySpan<char> endTime)
  1209. {
  1210. standardName = null;
  1211. standardOffset = null;
  1212. daylightSavingsName = null;
  1213. daylightSavingsOffset = null;
  1214. start = null;
  1215. startTime = null;
  1216. end = null;
  1217. endTime = null;
  1218. int index = 0;
  1219. standardName = TZif_ParsePosixName(posixFormat, ref index);
  1220. standardOffset = TZif_ParsePosixOffset(posixFormat, ref index);
  1221. daylightSavingsName = TZif_ParsePosixName(posixFormat, ref index);
  1222. if (!daylightSavingsName.IsEmpty)
  1223. {
  1224. daylightSavingsOffset = TZif_ParsePosixOffset(posixFormat, ref index);
  1225. if (index < posixFormat.Length && posixFormat[index] == ',')
  1226. {
  1227. index++;
  1228. TZif_ParsePosixDateTime(posixFormat, ref index, out start, out startTime);
  1229. if (index < posixFormat.Length && posixFormat[index] == ',')
  1230. {
  1231. index++;
  1232. TZif_ParsePosixDateTime(posixFormat, ref index, out end, out endTime);
  1233. }
  1234. }
  1235. }
  1236. return !standardName.IsEmpty && !standardOffset.IsEmpty;
  1237. }
  1238. private static ReadOnlySpan<char> TZif_ParsePosixName(ReadOnlySpan<char> posixFormat, ref int index)
  1239. {
  1240. bool isBracketEnclosed = index < posixFormat.Length && posixFormat[index] == '<';
  1241. if (isBracketEnclosed)
  1242. {
  1243. // move past the opening bracket
  1244. index++;
  1245. ReadOnlySpan<char> result = TZif_ParsePosixString(posixFormat, ref index, c => c == '>');
  1246. // move past the closing bracket
  1247. if (index < posixFormat.Length && posixFormat[index] == '>')
  1248. {
  1249. index++;
  1250. }
  1251. return result;
  1252. }
  1253. else
  1254. {
  1255. return TZif_ParsePosixString(
  1256. posixFormat,
  1257. ref index,
  1258. c => char.IsDigit(c) || c == '+' || c == '-' || c == ',');
  1259. }
  1260. }
  1261. private static ReadOnlySpan<char> TZif_ParsePosixOffset(ReadOnlySpan<char> posixFormat, ref int index) =>
  1262. TZif_ParsePosixString(posixFormat, ref index, c => !char.IsDigit(c) && c != '+' && c != '-' && c != ':');
  1263. private static void TZif_ParsePosixDateTime(ReadOnlySpan<char> posixFormat, ref int index, out ReadOnlySpan<char> date, out ReadOnlySpan<char> time)
  1264. {
  1265. time = null;
  1266. date = TZif_ParsePosixDate(posixFormat, ref index);
  1267. if (index < posixFormat.Length && posixFormat[index] == '/')
  1268. {
  1269. index++;
  1270. time = TZif_ParsePosixTime(posixFormat, ref index);
  1271. }
  1272. }
  1273. private static ReadOnlySpan<char> TZif_ParsePosixDate(ReadOnlySpan<char> posixFormat, ref int index) =>
  1274. TZif_ParsePosixString(posixFormat, ref index, c => c == '/' || c == ',');
  1275. private static ReadOnlySpan<char> TZif_ParsePosixTime(ReadOnlySpan<char> posixFormat, ref int index) =>
  1276. TZif_ParsePosixString(posixFormat, ref index, c => c == ',');
  1277. private static ReadOnlySpan<char> TZif_ParsePosixString(ReadOnlySpan<char> posixFormat, ref int index, Func<char, bool> breakCondition)
  1278. {
  1279. int startIndex = index;
  1280. for (; index < posixFormat.Length; index++)
  1281. {
  1282. char current = posixFormat[index];
  1283. if (breakCondition(current))
  1284. {
  1285. break;
  1286. }
  1287. }
  1288. return posixFormat.Slice(startIndex, index - startIndex);
  1289. }
  1290. // Returns the Substring from zoneAbbreviations starting at index and ending at '\0'
  1291. // zoneAbbreviations is expected to be in the form: "PST\0PDT\0PWT\0\PPT"
  1292. private static string TZif_GetZoneAbbreviation(string zoneAbbreviations, int index)
  1293. {
  1294. int lastIndex = zoneAbbreviations.IndexOf('\0', index);
  1295. return lastIndex > 0 ?
  1296. zoneAbbreviations.Substring(index, lastIndex - index) :
  1297. zoneAbbreviations.Substring(index);
  1298. }
  1299. // Converts an array of bytes into an int - always using standard byte order (Big Endian)
  1300. // per TZif file standard
  1301. private static unsafe int TZif_ToInt32(byte[] value, int startIndex)
  1302. {
  1303. fixed (byte* pbyte = &value[startIndex])
  1304. {
  1305. return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
  1306. }
  1307. }
  1308. // Converts an array of bytes into a long - always using standard byte order (Big Endian)
  1309. // per TZif file standard
  1310. private static unsafe long TZif_ToInt64(byte[] value, int startIndex)
  1311. {
  1312. fixed (byte* pbyte = &value[startIndex])
  1313. {
  1314. int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
  1315. int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7));
  1316. return (uint)i2 | ((long)i1 << 32);
  1317. }
  1318. }
  1319. private static long TZif_ToUnixTime(byte[] value, int startIndex, TZVersion version) =>
  1320. version != TZVersion.V1 ?
  1321. TZif_ToInt64(value, startIndex) :
  1322. TZif_ToInt32(value, startIndex);
  1323. private static DateTime TZif_UnixTimeToDateTime(long unixTime) =>
  1324. unixTime < DateTimeOffset.UnixMinSeconds ? DateTime.MinValue :
  1325. unixTime > DateTimeOffset.UnixMaxSeconds ? DateTime.MaxValue :
  1326. DateTimeOffset.FromUnixTimeSeconds(unixTime).UtcDateTime;
  1327. private static void TZif_ParseRaw(byte[] data, out TZifHead t, out DateTime[] dts, out byte[] typeOfLocalTime, out TZifType[] transitionType,
  1328. out string zoneAbbreviations, out bool[] StandardTime, out bool[] GmtTime, out string? futureTransitionsPosixFormat)
  1329. {
  1330. // initialize the out parameters in case the TZifHead ctor throws
  1331. dts = null!;
  1332. typeOfLocalTime = null!;
  1333. transitionType = null!;
  1334. zoneAbbreviations = string.Empty;
  1335. StandardTime = null!;
  1336. GmtTime = null!;
  1337. futureTransitionsPosixFormat = null;
  1338. // read in the 44-byte TZ header containing the count/length fields
  1339. //
  1340. int index = 0;
  1341. t = new TZifHead(data, index);
  1342. index += TZifHead.Length;
  1343. int timeValuesLength = 4; // the first version uses 4-bytes to specify times
  1344. if (t.Version != TZVersion.V1)
  1345. {
  1346. // move index past the V1 information to read the V2 information
  1347. index += (int)((timeValuesLength * t.TimeCount) + t.TimeCount + (6 * t.TypeCount) + ((timeValuesLength + 4) * t.LeapCount) + t.IsStdCount + t.IsGmtCount + t.CharCount);
  1348. // read the V2 header
  1349. t = new TZifHead(data, index);
  1350. index += TZifHead.Length;
  1351. timeValuesLength = 8; // the second version uses 8-bytes
  1352. }
  1353. // initialize the containers for the rest of the TZ data
  1354. dts = new DateTime[t.TimeCount];
  1355. typeOfLocalTime = new byte[t.TimeCount];
  1356. transitionType = new TZifType[t.TypeCount];
  1357. zoneAbbreviations = string.Empty;
  1358. StandardTime = new bool[t.TypeCount];
  1359. GmtTime = new bool[t.TypeCount];
  1360. // read in the UTC transition points and convert them to Windows
  1361. //
  1362. for (int i = 0; i < t.TimeCount; i++)
  1363. {
  1364. long unixTime = TZif_ToUnixTime(data, index, t.Version);
  1365. dts[i] = TZif_UnixTimeToDateTime(unixTime);
  1366. index += timeValuesLength;
  1367. }
  1368. // read in the Type Indices; there is a 1:1 mapping of UTC transition points to Type Indices
  1369. // these indices directly map to the array index in the transitionType array below
  1370. //
  1371. for (int i = 0; i < t.TimeCount; i++)
  1372. {
  1373. typeOfLocalTime[i] = data[index];
  1374. index++;
  1375. }
  1376. // read in the Type table. Each 6-byte entry represents
  1377. // {UtcOffset, IsDst, AbbreviationIndex}
  1378. //
  1379. // each AbbreviationIndex is a character index into the zoneAbbreviations string below
  1380. //
  1381. for (int i = 0; i < t.TypeCount; i++)
  1382. {
  1383. transitionType[i] = new TZifType(data, index);
  1384. index += 6;
  1385. }
  1386. // read in the Abbreviation ASCII string. This string will be in the form:
  1387. // "PST\0PDT\0PWT\0\PPT"
  1388. //
  1389. Encoding enc = Encoding.UTF8;
  1390. zoneAbbreviations = enc.GetString(data, index, (int)t.CharCount);
  1391. index += (int)t.CharCount;
  1392. // skip ahead of the Leap-Seconds Adjustment data. In a future release, consider adding
  1393. // support for Leap-Seconds
  1394. //
  1395. index += (int)(t.LeapCount * (timeValuesLength + 4)); // skip the leap second transition times
  1396. // read in the Standard Time table. There should be a 1:1 mapping between Type-Index and Standard
  1397. // Time table entries.
  1398. //
  1399. // TRUE = transition time is standard time
  1400. // FALSE = transition time is wall clock time
  1401. // ABSENT = transition time is wall clock time
  1402. //
  1403. for (int i = 0; i < t.IsStdCount && i < t.TypeCount && index < data.Length; i++)
  1404. {
  1405. StandardTime[i] = (data[index++] != 0);
  1406. }
  1407. // read in the GMT Time table. There should be a 1:1 mapping between Type-Index and GMT Time table
  1408. // entries.
  1409. //
  1410. // TRUE = transition time is UTC
  1411. // FALSE = transition time is local time
  1412. // ABSENT = transition time is local time
  1413. //
  1414. for (int i = 0; i < t.IsGmtCount && i < t.TypeCount && index < data.Length; i++)
  1415. {
  1416. GmtTime[i] = (data[index++] != 0);
  1417. }
  1418. if (t.Version != TZVersion.V1)
  1419. {
  1420. // read the POSIX-style format, which should be wrapped in newlines with the last newline at the end of the file
  1421. if (data[index++] == '\n' && data[data.Length - 1] == '\n')
  1422. {
  1423. futureTransitionsPosixFormat = enc.GetString(data, index, data.Length - index - 1);
  1424. }
  1425. }
  1426. }
  1427. /// <summary>
  1428. /// Normalize adjustment rule offset so that it is within valid range
  1429. /// This method should not be called at all but is here in case something changes in the future
  1430. /// or if really old time zones are present on the OS (no combination is known at the moment)
  1431. /// </summary>
  1432. private static void NormalizeAdjustmentRuleOffset(TimeSpan baseUtcOffset, [NotNull] ref AdjustmentRule adjustmentRule)
  1433. {
  1434. // Certain time zones such as:
  1435. // Time Zone start date end date offset
  1436. // -----------------------------------------------------
  1437. // America/Yakutat 0001-01-01 1867-10-18 14:41:00
  1438. // America/Yakutat 1867-10-18 1900-08-20 14:41:00
  1439. // America/Sitka 0001-01-01 1867-10-18 14:58:00
  1440. // America/Sitka 1867-10-18 1900-08-20 14:58:00
  1441. // Asia/Manila 0001-01-01 1844-12-31 -15:56:00
  1442. // Pacific/Guam 0001-01-01 1845-01-01 -14:21:00
  1443. // Pacific/Saipan 0001-01-01 1845-01-01 -14:21:00
  1444. //
  1445. // have larger offset than currently supported by framework.
  1446. // If for whatever reason we find that time zone exceeding max
  1447. // offset of 14h this function will truncate it to the max valid offset.
  1448. // Updating max offset may cause problems with interacting with SQL server
  1449. // which uses SQL DATETIMEOFFSET field type which was originally designed to be
  1450. // bit-for-bit compatible with DateTimeOffset.
  1451. TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule);
  1452. // utc base offset delta increment
  1453. TimeSpan adjustment = TimeSpan.Zero;
  1454. if (utcOffset > MaxOffset)
  1455. {
  1456. adjustment = MaxOffset - utcOffset;
  1457. }
  1458. else if (utcOffset < MinOffset)
  1459. {
  1460. adjustment = MinOffset - utcOffset;
  1461. }
  1462. if (adjustment != TimeSpan.Zero)
  1463. {
  1464. adjustmentRule = AdjustmentRule.CreateAdjustmentRule(
  1465. adjustmentRule.DateStart,
  1466. adjustmentRule.DateEnd,
  1467. adjustmentRule.DaylightDelta,
  1468. adjustmentRule.DaylightTransitionStart,
  1469. adjustmentRule.DaylightTransitionEnd,
  1470. adjustmentRule.BaseUtcOffsetDelta + adjustment,
  1471. adjustmentRule.NoDaylightTransitions);
  1472. }
  1473. }
  1474. private struct TZifType
  1475. {
  1476. public const int Length = 6;
  1477. public readonly TimeSpan UtcOffset;
  1478. public readonly bool IsDst;
  1479. public readonly byte AbbreviationIndex;
  1480. public TZifType(byte[] data, int index)
  1481. {
  1482. if (data == null || data.Length < index + Length)
  1483. {
  1484. throw new ArgumentException(SR.Argument_TimeZoneInfoInvalidTZif, nameof(data));
  1485. }
  1486. UtcOffset = new TimeSpan(0, 0, TZif_ToInt32(data, index + 00));
  1487. IsDst = (data[index + 4] != 0);
  1488. AbbreviationIndex = data[index + 5];
  1489. }
  1490. }
  1491. private struct TZifHead
  1492. {
  1493. public const int Length = 44;
  1494. public readonly uint Magic; // TZ_MAGIC "TZif"
  1495. public readonly TZVersion Version; // 1 byte for a \0 or 2 or 3
  1496. // public byte[15] Reserved; // reserved for future use
  1497. public readonly uint IsGmtCount; // number of transition time flags
  1498. public readonly uint IsStdCount; // number of transition time flags
  1499. public readonly uint LeapCount; // number of leap seconds
  1500. public readonly uint TimeCount; // number of transition times
  1501. public readonly uint TypeCount; // number of local time types
  1502. public readonly uint CharCount; // number of abbreviated characters
  1503. public TZifHead(byte[] data, int index)
  1504. {
  1505. if (data == null || data.Length < Length)
  1506. {
  1507. throw new ArgumentException("bad data", nameof(data));
  1508. }
  1509. Magic = (uint)TZif_ToInt32(data, index + 00);
  1510. if (Magic != 0x545A6966)
  1511. {
  1512. // 0x545A6966 = {0x54, 0x5A, 0x69, 0x66} = "TZif"
  1513. throw new ArgumentException(SR.Argument_TimeZoneInfoBadTZif, nameof(data));
  1514. }
  1515. byte version = data[index + 04];
  1516. Version =
  1517. version == '2' ? TZVersion.V2 :
  1518. version == '3' ? TZVersion.V3 :
  1519. TZVersion.V1; // default/fallback to V1 to guard against future, unsupported version numbers
  1520. // skip the 15 byte reserved field
  1521. // don't use the BitConverter class which parses data
  1522. // based on the Endianess of the machine architecture.
  1523. // this data is expected to always be in "standard byte order",
  1524. // regardless of the machine it is being processed on.
  1525. IsGmtCount = (uint)TZif_ToInt32(data, index + 20);
  1526. IsStdCount = (uint)TZif_ToInt32(data, index + 24);
  1527. LeapCount = (uint)TZif_ToInt32(data, index + 28);
  1528. TimeCount = (uint)TZif_ToInt32(data, index + 32);
  1529. TypeCount = (uint)TZif_ToInt32(data, index + 36);
  1530. CharCount = (uint)TZif_ToInt32(data, index + 40);
  1531. }
  1532. }
  1533. private enum TZVersion : byte
  1534. {
  1535. V1 = 0,
  1536. V2,
  1537. V3,
  1538. // when adding more versions, ensure all the logic using TZVersion is still correct
  1539. }
  1540. }
  1541. }