IsolatedStorageFile.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. //
  2. // System.IO.IsolatedStorage.IsolatedStorageFile
  3. //
  4. // Authors
  5. // Jonathan Pryor ([email protected])
  6. // Sebastien Pouliot <[email protected]>
  7. //
  8. // (C) 2003 Jonathan Pryor
  9. // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System.Collections;
  31. using System.Reflection;
  32. using System.Runtime.Serialization.Formatters.Binary;
  33. using System.Security;
  34. using System.Security.Cryptography;
  35. using System.Security.Permissions;
  36. using System.Security.Policy;
  37. using System.Text;
  38. using Mono.Security.Cryptography;
  39. namespace System.IO.IsolatedStorage {
  40. // This is a terribly named class. It doesn't actually represent a file as
  41. // much as a directory
  42. // FIXME: Further limit the assertion when imperative Assert is implemented
  43. [FileIOPermission (SecurityAction.Assert, Unrestricted = true)]
  44. public sealed class IsolatedStorageFile : IsolatedStorage, IDisposable {
  45. public static IEnumerator GetEnumerator (IsolatedStorageScope scope)
  46. {
  47. Demand (scope);
  48. switch (scope) {
  49. case IsolatedStorageScope.User:
  50. case IsolatedStorageScope.User | IsolatedStorageScope.Roaming:
  51. #if NET_2_0
  52. case IsolatedStorageScope.Machine:
  53. #endif
  54. break;
  55. default:
  56. string msg = Locale.GetText ("Invalid scope, only User, User|Roaming and Machine are valid");
  57. throw new ArgumentException (msg);
  58. }
  59. return new IsolatedStorageFileEnumerator (scope, GetIsolatedStorageRoot (scope));
  60. }
  61. public static IsolatedStorageFile GetStore (IsolatedStorageScope scope,
  62. Evidence domainEvidence, Type domainEvidenceType,
  63. Evidence assemblyEvidence, Type assemblyEvidenceType)
  64. {
  65. Demand (scope);
  66. bool domain = ((scope & IsolatedStorageScope.Domain) != 0);
  67. if (domain && (domainEvidence == null))
  68. throw new ArgumentNullException ("domainEvidence");
  69. bool assembly = ((scope & IsolatedStorageScope.Assembly) != 0);
  70. if (assembly && (assemblyEvidence == null))
  71. throw new ArgumentNullException ("assemblyEvidence");
  72. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  73. if (domain) {
  74. if (domainEvidenceType == null) {
  75. storageFile._domainIdentity = GetDomainIdentityFromEvidence (domainEvidence);
  76. } else {
  77. storageFile._domainIdentity = GetTypeFromEvidence (domainEvidence, domainEvidenceType);
  78. }
  79. if (storageFile._domainIdentity == null)
  80. throw new IsolatedStorageException (Locale.GetText ("Couldn't find domain identity."));
  81. }
  82. if (assembly) {
  83. if (assemblyEvidenceType == null) {
  84. storageFile._assemblyIdentity = GetAssemblyIdentityFromEvidence (assemblyEvidence);
  85. } else {
  86. storageFile._assemblyIdentity = GetTypeFromEvidence (assemblyEvidence, assemblyEvidenceType);
  87. }
  88. if (storageFile._assemblyIdentity == null)
  89. throw new IsolatedStorageException (Locale.GetText ("Couldn't find assembly identity."));
  90. }
  91. storageFile.PostInit ();
  92. return storageFile;
  93. }
  94. public static IsolatedStorageFile GetStore (IsolatedStorageScope scope, object domainIdentity, object assemblyIdentity)
  95. {
  96. Demand (scope);
  97. if (((scope & IsolatedStorageScope.Domain) != 0) && (domainIdentity == null))
  98. throw new ArgumentNullException ("domainIdentity");
  99. if (((scope & IsolatedStorageScope.Assembly) != 0) && (assemblyIdentity == null))
  100. throw new ArgumentNullException ("assemblyIdentity");
  101. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  102. storageFile._domainIdentity = domainIdentity;
  103. storageFile._assemblyIdentity = assemblyIdentity;
  104. storageFile.PostInit ();
  105. return storageFile;
  106. }
  107. public static IsolatedStorageFile GetStore (IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType)
  108. {
  109. Demand (scope);
  110. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  111. if ((scope & IsolatedStorageScope.Domain) != 0) {
  112. storageFile._domainIdentity = GetTypeFromEvidence (AppDomain.CurrentDomain.Evidence, domainEvidenceType);
  113. }
  114. if ((scope & IsolatedStorageScope.Assembly) != 0) {
  115. storageFile._assemblyIdentity = GetTypeFromEvidence (Assembly.GetCallingAssembly ().Evidence, assemblyEvidenceType);
  116. }
  117. storageFile.PostInit ();
  118. return storageFile;
  119. }
  120. #if NET_2_0
  121. public static IsolatedStorageFile GetStore (IsolatedStorageScope scope, object applicationIdentity)
  122. {
  123. Demand (scope);
  124. if (applicationIdentity == null)
  125. throw new ArgumentNullException ("applicationIdentity");
  126. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  127. storageFile._applicationIdentity = applicationIdentity;
  128. storageFile.PostInit ();
  129. return storageFile;
  130. }
  131. public static IsolatedStorageFile GetStore (IsolatedStorageScope scope, Type applicationEvidenceType)
  132. {
  133. Demand (scope);
  134. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  135. storageFile.InitStore (scope, applicationEvidenceType);
  136. storageFile.PostInit ();
  137. return storageFile;
  138. }
  139. [IsolatedStorageFilePermission (SecurityAction.Demand, UsageAllowed = IsolatedStorageContainment.ApplicationIsolationByMachine)]
  140. public static IsolatedStorageFile GetMachineStoreForApplication ()
  141. {
  142. IsolatedStorageScope scope = IsolatedStorageScope.Machine | IsolatedStorageScope.Application;
  143. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  144. storageFile.InitStore (scope, null);
  145. storageFile.PostInit ();
  146. return storageFile;
  147. }
  148. [IsolatedStorageFilePermission (SecurityAction.Demand, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByMachine)]
  149. public static IsolatedStorageFile GetMachineStoreForAssembly ()
  150. {
  151. IsolatedStorageScope scope = IsolatedStorageScope.Machine | IsolatedStorageScope.Assembly;
  152. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  153. storageFile._assemblyIdentity = GetAssemblyIdentityFromEvidence (Assembly.GetCallingAssembly ().Evidence);
  154. storageFile.PostInit ();
  155. return storageFile;
  156. }
  157. [IsolatedStorageFilePermission (SecurityAction.Demand, UsageAllowed = IsolatedStorageContainment.DomainIsolationByMachine)]
  158. public static IsolatedStorageFile GetMachineStoreForDomain ()
  159. {
  160. IsolatedStorageScope scope = IsolatedStorageScope.Machine | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly;
  161. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  162. storageFile._domainIdentity = GetDomainIdentityFromEvidence (AppDomain.CurrentDomain.Evidence);
  163. storageFile._assemblyIdentity = GetAssemblyIdentityFromEvidence (Assembly.GetCallingAssembly ().Evidence);
  164. storageFile.PostInit ();
  165. return storageFile;
  166. }
  167. [IsolatedStorageFilePermission (SecurityAction.Demand, UsageAllowed = IsolatedStorageContainment.ApplicationIsolationByUser)]
  168. public static IsolatedStorageFile GetUserStoreForApplication ()
  169. {
  170. IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Application;
  171. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  172. storageFile.InitStore (scope, null);
  173. storageFile.PostInit ();
  174. return storageFile;
  175. }
  176. #endif
  177. [IsolatedStorageFilePermission (SecurityAction.Demand, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser)]
  178. public static IsolatedStorageFile GetUserStoreForAssembly ()
  179. {
  180. IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Assembly;
  181. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  182. storageFile._assemblyIdentity = GetAssemblyIdentityFromEvidence (Assembly.GetCallingAssembly ().Evidence);
  183. storageFile.PostInit ();
  184. return storageFile;
  185. }
  186. [IsolatedStorageFilePermission (SecurityAction.Demand, UsageAllowed = IsolatedStorageContainment.DomainIsolationByUser)]
  187. public static IsolatedStorageFile GetUserStoreForDomain ()
  188. {
  189. IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly;
  190. IsolatedStorageFile storageFile = new IsolatedStorageFile (scope);
  191. storageFile._domainIdentity = GetDomainIdentityFromEvidence (AppDomain.CurrentDomain.Evidence);
  192. storageFile._assemblyIdentity = GetAssemblyIdentityFromEvidence (Assembly.GetCallingAssembly ().Evidence);
  193. storageFile.PostInit ();
  194. return storageFile;
  195. }
  196. public static void Remove (IsolatedStorageScope scope)
  197. {
  198. string dir = GetIsolatedStorageRoot (scope);
  199. Directory.Delete (dir, true);
  200. }
  201. // internal static stuff
  202. // Security Note: We're using InternalGetFolderPath because
  203. // IsolatedStorage must be able to work even if we do not have
  204. // FileIOPermission's PathDiscovery permissions
  205. internal static string GetIsolatedStorageRoot (IsolatedStorageScope scope)
  206. {
  207. // IsolatedStorageScope mixes several flags into one.
  208. // This first level deals with the root directory - it
  209. // is decided based on User, User+Roaming or Machine
  210. string root = null;
  211. if ((scope & IsolatedStorageScope.User) != 0) {
  212. if ((scope & IsolatedStorageScope.Roaming) != 0) {
  213. root = Environment.InternalGetFolderPath (Environment.SpecialFolder.LocalApplicationData);
  214. } else {
  215. root = Environment.InternalGetFolderPath (Environment.SpecialFolder.ApplicationData);
  216. }
  217. #if NET_2_0
  218. } else if ((scope & IsolatedStorageScope.Machine) != 0) {
  219. root = Environment.InternalGetFolderPath (Environment.SpecialFolder.CommonApplicationData);
  220. #endif
  221. }
  222. if (root == null) {
  223. string msg = Locale.GetText ("Couldn't access storage location for '{0}'.");
  224. throw new IsolatedStorageException (String.Format (msg, scope));
  225. }
  226. return Path.Combine (root, ".isolated-storage");
  227. }
  228. private static void Demand (IsolatedStorageScope scope)
  229. {
  230. if (SecurityManager.SecurityEnabled) {
  231. IsolatedStorageFilePermission isfp = new IsolatedStorageFilePermission (PermissionState.None);
  232. isfp.UsageAllowed = ScopeToContainment (scope);
  233. // TODO: quota
  234. isfp.Demand ();
  235. }
  236. }
  237. private static IsolatedStorageContainment ScopeToContainment (IsolatedStorageScope scope)
  238. {
  239. switch (scope) {
  240. case IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly | IsolatedStorageScope.User:
  241. return IsolatedStorageContainment.DomainIsolationByUser;
  242. case IsolatedStorageScope.Assembly | IsolatedStorageScope.User:
  243. return IsolatedStorageContainment.AssemblyIsolationByUser;
  244. case IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly | IsolatedStorageScope.User | IsolatedStorageScope.Roaming:
  245. return IsolatedStorageContainment.DomainIsolationByRoamingUser;
  246. case IsolatedStorageScope.Assembly | IsolatedStorageScope.User | IsolatedStorageScope.Roaming:
  247. return IsolatedStorageContainment.AssemblyIsolationByRoamingUser;
  248. #if NET_2_0
  249. case IsolatedStorageScope.Application | IsolatedStorageScope.User:
  250. return IsolatedStorageContainment.ApplicationIsolationByUser;
  251. case IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly | IsolatedStorageScope.Machine:
  252. return IsolatedStorageContainment.DomainIsolationByMachine;
  253. case IsolatedStorageScope.Assembly | IsolatedStorageScope.Machine:
  254. return IsolatedStorageContainment.AssemblyIsolationByMachine;
  255. case IsolatedStorageScope.Application | IsolatedStorageScope.Machine:
  256. return IsolatedStorageContainment.ApplicationIsolationByMachine;
  257. case IsolatedStorageScope.Application | IsolatedStorageScope.User | IsolatedStorageScope.Roaming:
  258. return IsolatedStorageContainment.ApplicationIsolationByRoamingUser;
  259. #endif
  260. default:
  261. // unknown ?!?! then ask for maximum (unrestricted)
  262. return IsolatedStorageContainment.UnrestrictedIsolatedStorage;
  263. }
  264. }
  265. internal static ulong GetDirectorySize (DirectoryInfo di)
  266. {
  267. ulong size = 0;
  268. foreach (FileInfo fi in di.GetFiles ())
  269. size += (ulong) fi.Length;
  270. foreach (DirectoryInfo d in di.GetDirectories ())
  271. size += GetDirectorySize (d);
  272. return size;
  273. }
  274. // non-static stuff
  275. private DirectoryInfo directory;
  276. private IsolatedStorageFile (IsolatedStorageScope scope)
  277. {
  278. storage_scope = scope;
  279. }
  280. internal IsolatedStorageFile (IsolatedStorageScope scope, string location)
  281. {
  282. storage_scope = scope;
  283. directory = new DirectoryInfo (location);
  284. if (!directory.Exists) {
  285. string msg = Locale.GetText ("Invalid storage.");
  286. throw new IsolatedStorageException (msg);
  287. }
  288. // load the identities
  289. }
  290. ~IsolatedStorageFile ()
  291. {
  292. }
  293. private void PostInit ()
  294. {
  295. string root = GetIsolatedStorageRoot (Scope);
  296. string dir = null;
  297. #if NET_2_0
  298. if (_applicationIdentity != null) {
  299. dir = String.Format ("a{0}{1}", SeparatorInternal, GetNameFromIdentity (_applicationIdentity));
  300. } else
  301. #endif
  302. if (_domainIdentity != null) {
  303. dir = String.Format ("d{0}{1}{0}{2}", SeparatorInternal,
  304. GetNameFromIdentity (_domainIdentity), GetNameFromIdentity (_assemblyIdentity));
  305. } else if (_assemblyIdentity != null) {
  306. dir = String.Format ("d{0}none{0}{1}", SeparatorInternal, GetNameFromIdentity (_assemblyIdentity));
  307. } else {
  308. throw new IsolatedStorageException (Locale.GetText ("No code identity available."));
  309. }
  310. root = Path.Combine (root, dir);
  311. // identities have been selected
  312. directory = new DirectoryInfo (root);
  313. if (!directory.Exists) {
  314. directory.Create ();
  315. SaveIdentities (root);
  316. }
  317. }
  318. [CLSCompliant(false)]
  319. public override ulong CurrentSize {
  320. get { return GetDirectorySize (directory); }
  321. }
  322. [CLSCompliant(false)]
  323. [MonoTODO ("Maximum size must be restricted by the security policy")]
  324. public override ulong MaximumSize {
  325. // return an ulong but default is signed long
  326. get { return Int64.MaxValue; }
  327. }
  328. internal string Root {
  329. get { return directory.FullName; }
  330. }
  331. // methods
  332. public void Close ()
  333. {
  334. }
  335. public void CreateDirectory (string dir)
  336. {
  337. directory.CreateSubdirectory (dir);
  338. }
  339. public void DeleteDirectory (string dir)
  340. {
  341. DirectoryInfo subdir = directory.CreateSubdirectory (dir);
  342. subdir.Delete ();
  343. }
  344. public void DeleteFile (string file)
  345. {
  346. File.Delete (Path.Combine (directory.FullName, file));
  347. }
  348. public void Dispose ()
  349. {
  350. }
  351. public string[] GetDirectoryNames (string searchPattern)
  352. {
  353. DirectoryInfo[] adi = directory.GetDirectories (searchPattern);
  354. return GetNames (adi);
  355. }
  356. private string[] GetNames (FileSystemInfo[] afsi)
  357. {
  358. string[] r = new string[afsi.Length];
  359. for (int i = 0; i != afsi.Length; ++i)
  360. r[i] = afsi[i].Name;
  361. return r;
  362. }
  363. public string[] GetFileNames (string searchPattern)
  364. {
  365. FileInfo[] afi = directory.GetFiles (searchPattern);
  366. return GetNames (afi);
  367. }
  368. public override void Remove ()
  369. {
  370. directory.Delete (true);
  371. }
  372. [MonoTODO ("Permissions are CAS related")]
  373. protected override IsolatedStoragePermission GetPermission (PermissionSet ps)
  374. {
  375. throw new NotImplementedException ();
  376. }
  377. // internal stuff
  378. private string GetNameFromIdentity (object identity)
  379. {
  380. // Note: Default evidences return an XML string with ToString
  381. byte[] id = Encoding.UTF8.GetBytes (identity.ToString ());
  382. SHA1 hash = SHA1.Create ();
  383. // this create an unique name for an identity - bad identities like Url
  384. // results in bad (i.e. changing) names.
  385. byte[] full = hash.ComputeHash (id, 0, id.Length);
  386. byte[] half = new byte [10];
  387. Buffer.BlockCopy (full, 0, half, 0, half.Length);
  388. return CryptoConvert.ToHex (half);
  389. }
  390. private static object GetTypeFromEvidence (Evidence e, Type t)
  391. {
  392. foreach (object o in e) {
  393. if (o.GetType () == t)
  394. return o;
  395. }
  396. return null;
  397. }
  398. internal static object GetAssemblyIdentityFromEvidence (Evidence e)
  399. {
  400. // we prefer...
  401. // a. a Publisher evidence
  402. object identity = GetTypeFromEvidence (e, typeof (Publisher));
  403. if (identity != null)
  404. return identity;
  405. // b. a StrongName evidence
  406. identity = GetTypeFromEvidence (e, typeof (StrongName));
  407. if (identity != null)
  408. return identity;
  409. // c. a Url evidence
  410. return GetTypeFromEvidence (e, typeof (Url));
  411. }
  412. internal static object GetDomainIdentityFromEvidence (Evidence e)
  413. {
  414. // we prefer...
  415. // a. a ApplicationDirectory evidence
  416. object identity = GetTypeFromEvidence (e, typeof (ApplicationDirectory));
  417. if (identity != null)
  418. return identity;
  419. // b. a Url evidence
  420. return GetTypeFromEvidence (e, typeof (Url));
  421. }
  422. [Serializable]
  423. private struct Identities {
  424. public object Application;
  425. public object Assembly;
  426. public object Domain;
  427. public Identities (object application, object assembly, object domain)
  428. {
  429. Application = application;
  430. Assembly = assembly;
  431. Domain = domain;
  432. }
  433. }
  434. private void LoadIdentities (string root)
  435. {
  436. if (!File.Exists (root + ".storage"))
  437. throw new IsolatedStorageException (Locale.GetText ("Missing identities."));
  438. using (FileStream fs = File.OpenRead (root + ".storage")) {
  439. BinaryFormatter deformatter = new BinaryFormatter ();
  440. Identities identities = (Identities) deformatter.Deserialize (fs);
  441. fs.Close ();
  442. _applicationIdentity = identities.Application;
  443. _assemblyIdentity = identities.Assembly;
  444. _domainIdentity = identities.Domain;
  445. }
  446. }
  447. private void SaveIdentities (string root)
  448. {
  449. Identities identities = new Identities (_applicationIdentity, _assemblyIdentity, _domainIdentity);
  450. using (FileStream fs = File.OpenWrite (root + ".storage")) {
  451. BinaryFormatter formatter = new BinaryFormatter ();
  452. formatter.Serialize (fs, identities);
  453. fs.Close ();
  454. }
  455. }
  456. }
  457. }