TimeZoneContentManager.cs 11 KB

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