TimeZoneContentManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. using LibHac;
  2. using LibHac.Common;
  3. using LibHac.Fs;
  4. using LibHac.Fs.Fsa;
  5. using LibHac.FsSystem;
  6. using LibHac.FsSystem.NcaUtils;
  7. using Ryujinx.Common.Logging;
  8. using Ryujinx.Configuration;
  9. using Ryujinx.HLE.Exceptions;
  10. using Ryujinx.HLE.FileSystem;
  11. using Ryujinx.HLE.FileSystem.Content;
  12. using Ryujinx.HLE.HOS.Services.Time.Clock;
  13. using Ryujinx.HLE.Utilities;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using static Ryujinx.HLE.HOS.Services.Time.TimeZone.TimeZoneRule;
  18. namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
  19. {
  20. public class TimeZoneContentManager
  21. {
  22. private const long TimeZoneBinaryTitleId = 0x010000000000080E;
  23. private readonly string TimeZoneSystemTitleMissingErrorMessage = "TimeZoneBinary system title not found! TimeZone conversions will not work, provide the system archive to fix this error. (See https://github.com/Ryujinx/Ryujinx/wiki/Ryujinx-Setup-&-Configuration-Guide#initial-setup-continued---installation-of-firmware for more information)";
  24. private VirtualFileSystem _virtualFileSystem;
  25. private IntegrityCheckLevel _fsIntegrityCheckLevel;
  26. private ContentManager _contentManager;
  27. public string[] LocationNameCache { get; private set; }
  28. internal TimeZoneManager Manager { get; private set; }
  29. public TimeZoneContentManager()
  30. {
  31. Manager = new TimeZoneManager();
  32. }
  33. public void InitializeInstance(VirtualFileSystem virtualFileSystem, ContentManager contentManager, IntegrityCheckLevel fsIntegrityCheckLevel)
  34. {
  35. _virtualFileSystem = virtualFileSystem;
  36. _contentManager = contentManager;
  37. _fsIntegrityCheckLevel = fsIntegrityCheckLevel;
  38. InitializeLocationNameCache();
  39. }
  40. public string SanityCheckDeviceLocationName()
  41. {
  42. string locationName = ConfigurationState.Instance.System.TimeZone;
  43. if (IsLocationNameValid(locationName))
  44. {
  45. return locationName;
  46. }
  47. Logger.Warning?.Print(LogClass.ServiceTime, $"Invalid device TimeZone {locationName}, switching back to UTC");
  48. ConfigurationState.Instance.System.TimeZone.Value = "UTC";
  49. return "UTC";
  50. }
  51. internal void Initialize(TimeManager timeManager, Switch device)
  52. {
  53. InitializeInstance(device.FileSystem, device.System.ContentManager, device.System.FsIntegrityCheckLevel);
  54. SteadyClockTimePoint timeZoneUpdatedTimePoint = timeManager.StandardSteadyClock.GetCurrentTimePoint(null);
  55. string deviceLocationName = SanityCheckDeviceLocationName();
  56. ResultCode result = GetTimeZoneBinary(deviceLocationName, out Stream timeZoneBinaryStream, out LocalStorage ncaFile);
  57. if (result == ResultCode.Success)
  58. {
  59. // TODO: Read TimeZoneVersion from sysarchive.
  60. timeManager.SetupTimeZoneManager(deviceLocationName, timeZoneUpdatedTimePoint, (uint)LocationNameCache.Length, new UInt128(), timeZoneBinaryStream);
  61. ncaFile.Dispose();
  62. }
  63. else
  64. {
  65. // In the case the user don't have the timezone system archive, we just mark the manager as initialized.
  66. Manager.MarkInitialized();
  67. }
  68. }
  69. private void InitializeLocationNameCache()
  70. {
  71. if (HasTimeZoneBinaryTitle())
  72. {
  73. using (IStorage ncaFileStream = new LocalStorage(_virtualFileSystem.SwitchPathToSystemPath(GetTimeZoneBinaryTitleContentPath()), FileAccess.Read, FileMode.Open))
  74. {
  75. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFileStream);
  76. IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel);
  77. romfs.OpenFile(out IFile binaryListFile, "/binaryList.txt".ToU8Span(), OpenMode.Read).ThrowIfFailure();
  78. StreamReader reader = new StreamReader(binaryListFile.AsStream());
  79. List<string> locationNameList = new List<string>();
  80. string locationName;
  81. while ((locationName = reader.ReadLine()) != null)
  82. {
  83. locationNameList.Add(locationName);
  84. }
  85. LocationNameCache = locationNameList.ToArray();
  86. }
  87. }
  88. else
  89. {
  90. LocationNameCache = new string[] { "UTC" };
  91. Logger.Error?.Print(LogClass.ServiceTime, TimeZoneSystemTitleMissingErrorMessage);
  92. }
  93. }
  94. public IEnumerable<(int Offset, string Location, string Abbr)> ParseTzOffsets()
  95. {
  96. var tzBinaryContentPath = GetTimeZoneBinaryTitleContentPath();
  97. if (string.IsNullOrEmpty(tzBinaryContentPath))
  98. {
  99. return new[] { (0, "UTC", "UTC") };
  100. }
  101. List<(int Offset, string Location, string Abbr)> outList = new List<(int Offset, string Location, string Abbr)>();
  102. var now = System.DateTimeOffset.Now.ToUnixTimeSeconds();
  103. using (IStorage ncaStorage = new LocalStorage(_virtualFileSystem.SwitchPathToSystemPath(tzBinaryContentPath), FileAccess.Read, FileMode.Open))
  104. using (IFileSystem romfs = new Nca(_virtualFileSystem.KeySet, ncaStorage).OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel))
  105. {
  106. foreach (string locName in LocationNameCache)
  107. {
  108. if (locName.StartsWith("Etc"))
  109. {
  110. continue;
  111. }
  112. if (romfs.OpenFile(out IFile tzif, $"/zoneinfo/{locName}".ToU8Span(), OpenMode.Read).IsFailure())
  113. {
  114. Logger.Error?.Print(LogClass.ServiceTime, $"Error opening /zoneinfo/{locName}");
  115. continue;
  116. }
  117. using (tzif)
  118. {
  119. TimeZone.ParseTimeZoneBinary(out TimeZoneRule tzRule, tzif.AsStream());
  120. TimeTypeInfo ttInfo;
  121. if (tzRule.TimeCount > 0) // Find the current transition period
  122. {
  123. int fin = 0;
  124. for (int i = 0; i < tzRule.TimeCount; ++i)
  125. {
  126. if (tzRule.Ats[i] <= now)
  127. {
  128. fin = i;
  129. }
  130. }
  131. ttInfo = tzRule.Ttis[tzRule.Types[fin]];
  132. }
  133. else if (tzRule.TypeCount >= 1) // Otherwise, use the first offset in TTInfo
  134. {
  135. ttInfo = tzRule.Ttis[0];
  136. }
  137. else
  138. {
  139. Logger.Error?.Print(LogClass.ServiceTime, $"Couldn't find UTC offset for zone {locName}");
  140. continue;
  141. }
  142. var abbrStart = tzRule.Chars.AsSpan(ttInfo.AbbreviationListIndex);
  143. int abbrEnd = abbrStart.IndexOf('\0');
  144. outList.Add((ttInfo.GmtOffset, locName, abbrStart.Slice(0, abbrEnd).ToString()));
  145. }
  146. }
  147. }
  148. outList.Sort();
  149. return outList;
  150. }
  151. private bool IsLocationNameValid(string locationName)
  152. {
  153. foreach (string cachedLocationName in LocationNameCache)
  154. {
  155. if (cachedLocationName.Equals(locationName))
  156. {
  157. return true;
  158. }
  159. }
  160. return false;
  161. }
  162. public ResultCode SetDeviceLocationName(string locationName)
  163. {
  164. ResultCode result = GetTimeZoneBinary(locationName, out Stream timeZoneBinaryStream, out LocalStorage ncaFile);
  165. if (result == ResultCode.Success)
  166. {
  167. result = Manager.SetDeviceLocationNameWithTimeZoneRule(locationName, timeZoneBinaryStream);
  168. ncaFile.Dispose();
  169. }
  170. return result;
  171. }
  172. public ResultCode LoadLocationNameList(uint index, out string[] outLocationNameArray, uint maxLength)
  173. {
  174. List<string> locationNameList = new List<string>();
  175. for (int i = 0; i < LocationNameCache.Length && i < maxLength; i++)
  176. {
  177. if (i < index)
  178. {
  179. continue;
  180. }
  181. string locationName = LocationNameCache[i];
  182. // If the location name is too long, error out.
  183. if (locationName.Length > 0x24)
  184. {
  185. outLocationNameArray = new string[0];
  186. return ResultCode.LocationNameTooLong;
  187. }
  188. locationNameList.Add(locationName);
  189. }
  190. outLocationNameArray = locationNameList.ToArray();
  191. return ResultCode.Success;
  192. }
  193. public string GetTimeZoneBinaryTitleContentPath()
  194. {
  195. return _contentManager.GetInstalledContentPath(TimeZoneBinaryTitleId, StorageId.NandSystem, NcaContentType.Data);
  196. }
  197. public bool HasTimeZoneBinaryTitle()
  198. {
  199. return !string.IsNullOrEmpty(GetTimeZoneBinaryTitleContentPath());
  200. }
  201. internal ResultCode GetTimeZoneBinary(string locationName, out Stream timeZoneBinaryStream, out LocalStorage ncaFile)
  202. {
  203. timeZoneBinaryStream = null;
  204. ncaFile = null;
  205. if (!HasTimeZoneBinaryTitle() || !IsLocationNameValid(locationName))
  206. {
  207. return ResultCode.TimeZoneNotFound;
  208. }
  209. ncaFile = new LocalStorage(_virtualFileSystem.SwitchPathToSystemPath(GetTimeZoneBinaryTitleContentPath()), FileAccess.Read, FileMode.Open);
  210. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile);
  211. IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _fsIntegrityCheckLevel);
  212. Result result = romfs.OpenFile(out IFile timeZoneBinaryFile, $"/zoneinfo/{locationName}".ToU8Span(), OpenMode.Read);
  213. timeZoneBinaryStream = timeZoneBinaryFile.AsStream();
  214. return (ResultCode)result.Value;
  215. }
  216. internal ResultCode LoadTimeZoneRule(out TimeZoneRule outRules, string locationName)
  217. {
  218. outRules = new TimeZoneRule
  219. {
  220. Ats = new long[TzMaxTimes],
  221. Types = new byte[TzMaxTimes],
  222. Ttis = new TimeTypeInfo[TzMaxTypes],
  223. Chars = new char[TzCharsArraySize]
  224. };
  225. if (!HasTimeZoneBinaryTitle())
  226. {
  227. throw new InvalidSystemResourceException(TimeZoneSystemTitleMissingErrorMessage);
  228. }
  229. ResultCode result = GetTimeZoneBinary(locationName, out Stream timeZoneBinaryStream, out LocalStorage ncaFile);
  230. if (result == ResultCode.Success)
  231. {
  232. result = Manager.ParseTimeZoneRuleBinary(out outRules, timeZoneBinaryStream);
  233. ncaFile.Dispose();
  234. }
  235. return result;
  236. }
  237. }
  238. }