TimeZoneInfo.Unix.cs 73 KB

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