TimeZoneContentManager.cs 11 KB

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