IsolatedStorageFile.cs 18 KB

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