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