public void FlatFileListenerWillFallbackIfNotPriviledgesToWrite() { string fileName = @"trace.log"; string fullPath = String.Format(@"{0}\{1}", Directory.GetCurrentDirectory(), fileName); File.Delete(fileName); FileIOPermission fileIOPerm1 = new FileIOPermission(PermissionState.None); fileIOPerm1.SetPathList(FileIOPermissionAccess.Read, fullPath); fileIOPerm1.PermitOnly(); try { FlatFileTraceListener listener = new FlatFileTraceListener(fileName, "---header---", "***footer***", new TextFormatter("DUMMY{newline}DUMMY")); // need to go through the source to get a TraceEventCache LogSource source = new LogSource("notfromconfig", new[] { listener }, SourceLevels.All); source.TraceData(TraceEventType.Error, 0, new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null)); listener.Dispose(); } catch (SecurityException) { FileIOPermission.RevertAll(); throw; } }
private void InThread(ControllerContext context, Action<ControllerContext> functor) { var timeout = int.Parse(ConfigurationManager.AppSettings["SandboxTimeout"] ?? "5"); var thread = new Thread(()=> { try { var fileIo = new FileIOPermission(FileIOPermissionAccess.Read,AppDomain.CurrentDomain.BaseDirectory); fileIo.AllLocalFiles = FileIOPermissionAccess.NoAccess; fileIo.PermitOnly(); functor(context); } catch(Exception e) { // 全部書きだす context.HttpContext.Response.Write(e.Message); } }); thread.Start(); thread.Join(timeout*1000); if(thread.IsAlive) { thread.Abort(); throw new HttpException((int)HttpStatusCode.InternalServerError, "処理が長すぎ(" + timeout + "秒で終わらせてね)"); } }
/* Method: RemoveAssembly Purpose: Attempts to delete an assembly from the servers disk cache. */ public static void RemoveAssembly(string version, string assemblyFileName) { var assemblyRoot = ServerSettings.AssemblyPath; version = new Version(version).ToString(3); var path = new DirectoryInfo(assemblyRoot + "\\" + version); if (!path.Exists) return; var permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[] { assemblyRoot + "\\" + version }); try { permission.PermitOnly(); if (File.Exists(assemblyRoot + "\\" + version + "\\" + assemblyFileName)) File.Delete(assemblyRoot + "\\" + version + "\\" + assemblyFileName); } finally { CodeAccessPermission.RevertPermitOnly(); } }
/* Method: LoadAssembly Purpose: Grabs an assembly off the disk and returns it as a byte array. */ public static byte[] LoadAssembly(string version, string assemblyFileName) { var assemblyRoot = ServerSettings.AssemblyPath; version = new Version(version).ToString(3); var permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[] { assemblyRoot + "\\" + version }); byte[] bytes; try { permission.PermitOnly(); using (var sourceStream = File.OpenRead(assemblyRoot + "\\" + version + "\\" + assemblyFileName)) { bytes = new byte[sourceStream.Length]; sourceStream.Read(bytes, 0, (int)sourceStream.Length); } } finally { CodeAccessPermission.RevertPermitOnly(); } return bytes; }
public IsolatedStorageFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); #if FEATURE_PAL if (s_BackSlash == null) s_BackSlash = new String(System.IO.Path.DirectorySeparatorChar,1); #endif // FEATURE_PAL if ((path.Length == 0) || path.Equals(s_BackSlash)) throw new ArgumentException( Environment.GetResourceString( "IsolatedStorage_Path")); ulong oldFileSize=0, newFileSize; bool fNewFile = false, fLock=false; if (isf == null) { #if FEATURE_ISOSTORE_LIGHT throw new ArgumentNullException("isf"); #else // !FEATURE_ISOSTORE_LIGHT m_OwnedStore = true; isf = IsolatedStorageFile.GetUserStoreForDomain(); #endif // !FEATURE_ISOSTORE_LIGHT } if (isf.Disposed) throw new ObjectDisposedException(null, Environment.GetResourceString("IsolatedStorage_StoreNotOpen")); m_isf = isf; FileIOPermission fiop = new FileIOPermission(FileIOPermissionAccess.AllAccess, m_isf.RootDirectory); fiop.Assert(); fiop.PermitOnly(); m_GivenPath = path; m_FullPath = m_isf.GetFullPath(m_GivenPath); RuntimeHelpers.PrepareConstrainedRegions(); try { // for finally Unlocking locked store // Cache the old file size if the file size could change // Also find if we are going to create a new file. switch (mode) { case FileMode.CreateNew: // Assume new file #if FEATURE_ISOSTORE_LIGHT // We are going to call Reserve so we need to lock the store. m_isf.Lock(ref fLock); #endif fNewFile = true; break; case FileMode.Create: // Check for New file & Unreserve case FileMode.OpenOrCreate: // Check for new file case FileMode.Truncate: // Unreserve old file size case FileMode.Append: // Check for new file m_isf.Lock(ref fLock); // oldFileSize needs to be // protected try { #if FEATURE_ISOSTORE_LIGHT oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)(new FileInfo(m_FullPath).Length)); #else oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)LongPathFile.GetLength(m_FullPath)); #endif } catch (FileNotFoundException) { fNewFile = true; } catch { } break; case FileMode.Open: // Open existing, else exception break; default: throw new ArgumentException( Environment.GetResourceString( "IsolatedStorage_FileOpenMode")); } if (fNewFile) m_isf.ReserveOneBlock(); try { #if FEATURE_ISOSTORE_LIGHT m_fs = new FileStream(m_FullPath, mode, access, share, bufferSize, FileOptions.None, m_GivenPath, true); #else m_fs = new FileStream(m_FullPath, mode, access, share, bufferSize, FileOptions.None, m_GivenPath, true, true); #endif } catch { if (fNewFile) m_isf.UnreserveOneBlock(); #if FEATURE_ISOSTORE_LIGHT // IsoStore generally does not let arbitrary exceptions flow out: a // IsolatedStorageException is thrown instead (see examples in IsolatedStorageFile.cs // Keeping this scoped to coreclr just because changing the exception type thrown is a // breaking change and that should not be introduced into the desktop without deliberation. throw new IsolatedStorageException(Environment.GetResourceString("IsolatedStorage_Operation_ISFS")); #else throw; #endif // FEATURE_ISOSTORE_LIGHT } // make adjustment to the Reserve / Unreserve state if ((fNewFile == false) && ((mode == FileMode.Truncate) || (mode == FileMode.Create))) { newFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)m_fs.Length); if (oldFileSize > newFileSize) m_isf.Unreserve(oldFileSize - newFileSize); else if (newFileSize > oldFileSize) // Can this happen ? m_isf.Reserve(newFileSize - oldFileSize); } } finally { if (fLock) m_isf.Unlock(); } CodeAccessPermission.RevertAll(); }
/* Method: SaveAssembly Purpose: Attemps to save a byte array as an assembly on the servers disk cache. */ public static void SaveAssembly(byte[] assemblyCode, string version, string assemblyFileName) { var assemblyRoot = ServerSettings.AssemblyPath; version = new Version(version).ToString(3); var path = new DirectoryInfo(assemblyRoot + "\\" + version); if (!path.Exists) path.Create(); var permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[] { assemblyRoot + "\\" + version }); try { permission.PermitOnly(); // Use CreateNew to create so we get an exception if the file already exists -- it never should using ( var targetStream = File.Open(assemblyRoot + "\\" + version + "\\" + assemblyFileName, FileMode.CreateNew)) { try { targetStream.Write(assemblyCode, 0, assemblyCode.Length); targetStream.Close(); } catch { targetStream.Close(); // If something happens, delete the file so we don't have // a corrupted file hanging around File.Delete(assemblyRoot + "\\" + version + "\\" + assemblyFileName); throw; } } } finally { CodeAccessPermission.RevertPermitOnly(); } }
/// <summary> /// Saves the array of bytes given an assembly full name to /// the private assembly cache. /// </summary> /// <param name="bytes">The bytes of the assembly.</param> /// <param name="fullName">The full name of the original assembly.</param> public void SaveOrganismBytes(byte[] bytes, string fullName) { var directory = AssemblyDirectory; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } var fileName = GetFileName(fullName); if (File.Exists(fileName)) { return; } // Ensure that the caller can't pass us a name that actually makes this file get created somewhere else var permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[] {directory}); try { permission.PermitOnly(); var targetStream = File.Create(fileName); try { targetStream.Write(bytes, 0, bytes.Length); } catch { targetStream.Close(); // If something happens, delete the file so we don't have // a corrupted file hanging around File.Delete(fileName); throw; } finally { targetStream.Close(); } } finally { CodeAccessPermission.RevertPermitOnly(); } OnPacAssembliesChanged(new EventArgs()); }
/// <summary> /// Save an assembly along with symbols given a full path to the /// assembly and symbols to the cache. /// </summary> /// <param name="assemblyPath">A local path to the assembly.</param> /// <param name="symbolPath">A local path to the symbols.</param> /// <param name="fullName">The full name of the assembly.</param> public void SaveOrganismAssembly(string assemblyPath, string symbolPath, string fullName) { var directory = AssemblyDirectory; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } var fileName = GetFileName(fullName); var symName = Path.ChangeExtension(GetFileName(fullName), ".pdb"); if (File.Exists(fileName)) { return; } var reportPath = Path.Combine(GameConfig.ApplicationDirectory, Guid.NewGuid() + ".xml"); var validAssembly = checkAssemblyWithReporting(assemblyPath, reportPath); if (validAssembly == 0) { throw OrganismAssemblyFailedValidationException.GenerateExceptionFromXml(reportPath); } if (File.Exists(reportPath)) { File.Delete(reportPath); } var sourceStream = File.OpenRead(assemblyPath); FileStream symStream = null; try { if (!string.IsNullOrEmpty(symbolPath) && File.Exists(symbolPath)) { symStream = File.OpenRead(symbolPath); } } catch { // In case anything goes wrong with the symbols (access denied and others), we are good } // Ensure that the caller can't pass us a name that actually makes this file get created somewhere else var permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[] {directory}); try { permission.PermitOnly(); var targetStream = File.Create(fileName); try { var bytes = new byte[65536]; int bytesRead; while ((bytesRead = sourceStream.Read(bytes, 0, 65536)) > 0) { targetStream.Write(bytes, 0, bytesRead); } } catch { targetStream.Close(); // If something happens, delete the file so we don't have // a corrupted file hanging around File.Delete(fileName); throw; } finally { targetStream.Close(); } if (symStream != null) { try { targetStream = File.Create(symName); try { var bytes = new byte[65536]; int bytesRead; while ((bytesRead = symStream.Read(bytes, 0, 65536)) > 0) { targetStream.Write(bytes, 0, bytesRead); } } catch { targetStream.Close(); // If something happens, delete the file so we don't have // a corrupted file hanging around File.Delete(symName); throw; } finally { targetStream.Close(); } } catch { // No reason to crash } } } finally { CodeAccessPermission.RevertPermitOnly(); sourceStream.Close(); } OnPacAssembliesChanged(new EventArgs()); }
/// <summary> /// Determine if the assembly with the given full name exists /// within the PAC. /// </summary> /// <param name="fullName">The full name of the assembly to check for.</param> /// <returns>True if the assembly exists, false otherwise.</returns> public Boolean Exists(string fullName) { bool exists = false; var asmDir = Path.GetFullPath(AssemblyDirectory); // Make sure we can't be hacked to return whether files exist by only allowing our code // to access files in the assembly directory. var permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[] {asmDir}); try { permission.PermitOnly(); exists = File.Exists(GetFileName(fullName)); } finally { CodeAccessPermission.RevertPermitOnly(); } return exists; }
/// <summary> /// Blacklist a series of assemblies by setting their assemblies to zero length /// files. This is a way of ensuring that we don't load them again, or replace them /// with fresh working copies because the file name gets reserved with an invalid assembly. /// </summary> /// <param name="assemblies">The assemblies to be blacklisted.</param> public void BlacklistAssemblies(string[] assemblies) { // Ensure that the caller can't pass us a name that actually makes this file get created somewhere else var permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[] {AssemblyDirectory}); try { permission.PermitOnly(); if (assemblies != null) { foreach (var assembly in assemblies) { var fileName = GetFileName(assembly); try { // Replace this file with a zero length file (or create one), so we won't get it again using (var stream = File.Create(fileName)) { stream.Close(); } } catch (Exception e) { Debug.WriteLine("Error blacklisting organism:"); ErrorLog.LogHandledException(e); } } } } finally { CodeAccessPermission.RevertPermitOnly(); } }
public static void Log1(string text) { FileIOPermission p = new FileIOPermission(PermissionState.Unrestricted); p.PermitOnly(); }
public IsolatedStorageFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf) { if (path == null) throw new ArgumentNullException("path"); if (s_BackSlash == null) s_BackSlash = new String(System.IO.Path.DirectorySeparatorChar,1); if ((path.Length == 0) || path.Equals(s_BackSlash)) throw new ArgumentException( Environment.GetResourceString( "IsolatedStorage_path")); ulong oldFileSize=0, newFileSize; bool fNewFile = false, fLock=false; FileInfo fOld; if (isf == null) { m_OwnedStore = true; isf = IsolatedStorageFile.GetUserStoreForDomain(); } m_isf = isf; FileIOPermission fiop = new FileIOPermission(FileIOPermissionAccess.AllAccess, m_isf.RootDirectory); fiop.Assert(); fiop.PermitOnly(); m_GivenPath = path; m_FullPath = m_isf.GetFullPath(m_GivenPath); try { // for finally Unlocking locked store // Cache the old file size if the file size could change // Also find if we are going to create a new file. switch (mode) { case FileMode.CreateNew: // Assume new file fNewFile = true; break; case FileMode.Create: // Check for New file & Unreserve case FileMode.OpenOrCreate: // Check for new file case FileMode.Truncate: // Unreserve old file size case FileMode.Append: // Check for new file m_isf.Lock(); // oldFileSize needs to be // protected fLock = true; // Lock succeded try { fOld = new FileInfo(m_FullPath); oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)fOld.Length); } catch (FileNotFoundException) { fNewFile = true; } catch { } break; case FileMode.Open: // Open existing, else exception break; default: throw new ArgumentException( Environment.GetResourceString( "IsolatedStorage_FileOpenMode")); } if (fNewFile) m_isf.ReserveOneBlock(); try { m_fs = new FileStream(m_FullPath, mode, access, share, bufferSize, FileOptions.None, m_GivenPath, true); } catch { if (fNewFile) m_isf.UnreserveOneBlock(); throw; } // make adjustment to the Reserve / Unreserve state if ((fNewFile == false) && ((mode == FileMode.Truncate) || (mode == FileMode.Create))) { newFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)m_fs.Length); if (oldFileSize > newFileSize) m_isf.Unreserve(oldFileSize - newFileSize); else if (newFileSize > oldFileSize) // Can this happen ? m_isf.Reserve(newFileSize - oldFileSize); } } finally { if (fLock) m_isf.Unlock(); } CodeAccessPermission.RevertAll(); }
/* Method: SaveAssembly Purpose: Attemps to save a byte array as an assembly on the servers disk cache. */ public void SaveAssembly(byte[] assemblyCode, string version, string assemblyFileName) { String assemblyRoot = ServerSettings.AssemblyPath; version = new Version(version).ToString(3); DirectoryInfo path = new DirectoryInfo(assemblyRoot + "\\" + version); if (!path.Exists) path.Create(); FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new string[] { assemblyRoot + "\\" + version }); try { permission.PermitOnly(); // Use CreateNew to create so we get an exception if the file already exists -- it never should string pathToAssembly = assemblyRoot + "\\" + version + "\\" + assemblyFileName; if (File.Exists(pathToAssembly)) { throw new ApplicationException("an assembly with the same filename already exists in the server"); } using (FileStream targetStream = File.Open(pathToAssembly, FileMode.CreateNew)) { try { targetStream.Write(assemblyCode, 0, assemblyCode.Length); targetStream.Close(); } catch { targetStream.Close(); // If something happens, delete the file so we don't have // a corrupted file hanging around File.Delete(pathToAssembly); throw; } } } finally { CodeAccessPermission.RevertPermitOnly(); } }
public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf) { if (path == null) { throw new ArgumentNullException("path"); } if ((path.Length == 0) || path.Equals(@"\")) { throw new ArgumentException(Environment.GetResourceString("IsolatedStorage_Path")); } ulong num = 0L; bool flag = false; bool locked = false; if (isf == null) { this.m_OwnedStore = true; isf = IsolatedStorageFile.GetUserStoreForDomain(); } if (isf.Disposed) { throw new ObjectDisposedException(null, Environment.GetResourceString("IsolatedStorage_StoreNotOpen")); } this.m_isf = isf; FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, this.m_isf.RootDirectory); permission.Assert(); permission.PermitOnly(); this.m_GivenPath = path; this.m_FullPath = this.m_isf.GetFullPath(this.m_GivenPath); RuntimeHelpers.PrepareConstrainedRegions(); try { switch (mode) { case FileMode.CreateNew: flag = true; break; case FileMode.Create: case FileMode.OpenOrCreate: case FileMode.Truncate: case FileMode.Append: this.m_isf.Lock(ref locked); try { num = IsolatedStorageFile.RoundToBlockSize((ulong) LongPathFile.GetLength(this.m_FullPath)); } catch (FileNotFoundException) { flag = true; } catch { } break; case FileMode.Open: break; default: throw new ArgumentException(Environment.GetResourceString("IsolatedStorage_FileOpenMode")); } if (flag) { this.m_isf.ReserveOneBlock(); } try { this.m_fs = new FileStream(this.m_FullPath, mode, access, share, bufferSize, FileOptions.None, this.m_GivenPath, true, true); } catch { if (flag) { this.m_isf.UnreserveOneBlock(); } throw; } if (!flag && ((mode == FileMode.Truncate) || (mode == FileMode.Create))) { ulong num2 = IsolatedStorageFile.RoundToBlockSize((ulong) this.m_fs.Length); if (num > num2) { this.m_isf.Unreserve(num - num2); } else if (num2 > num) { this.m_isf.Reserve(num2 - num); } } } finally { if (locked) { this.m_isf.Unlock(); } } CodeAccessPermission.RevertAll(); }