/// <include file='doc\ProcessModelInfo.uex' path='docs/doc[@for="ProcessModelInfo.GetCurrentProcessInfo"]/*' /> static public ProcessInfo GetCurrentProcessInfo() { InternalSecurityPermissions.AspNetHostingPermissionLevelHigh.Demand(); HttpContext context = HttpContext.Current; if (context == null || context.WorkerRequest == null || !(context.WorkerRequest is System.Web.Hosting.ISAPIWorkerRequestOutOfProc)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Process_information_not_available)); } int dwReqExecuted = 0; int dwReqExecuting = 0; long tmCreateTime = 0; int pid = 0; int mem = 0; int iRet = UnsafeNativeMethods.PMGetCurrentProcessInfo( ref dwReqExecuted, ref dwReqExecuting, ref mem, ref tmCreateTime, ref pid); if (iRet < 0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Process_information_not_available)); } DateTime startTime = DateTime.FromFileTime(tmCreateTime); TimeSpan age = DateTime.Now.Subtract(startTime); return(new ProcessInfo(startTime, age, pid, dwReqExecuted, ProcessStatus.Alive, ProcessShutdownReason.None, mem)); }
internal bool Start(bool forGlobalCode, bool throwOnError, bool fromAnotherThread) { if (!fromAnotherThread) { Debug.Assert(!_inProgress); } IntPtr token = GetImpersonationToken(forGlobalCode, throwOnError); if (token == IntPtr.Zero) { return(false); } // Do the impersonation int rc = UnsafeNativeMethods.SetThreadToken(IntPtr.Zero, token); if (rc == 0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Cannot_impersonate)); } if (!fromAnotherThread) { _inProgress = true; } return(true); }
/*internal String MachineConfigPath { * get { * if (_wr == null) * throw new HttpException(HttpRuntime.FormatResourceString(SR.Cannot_get_config_dir)); * * return _wr.MachineConfigPath; * } * }*/ /* * Called by the URL rewrite module to modify the path for downstream modules */ /// <include file='doc\HttpContext.uex' path='docs/doc[@for="HttpContext.RewritePath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void RewritePath(String path) { // extract query string String qs = null; int iqs = path.IndexOf('?'); if (iqs >= 0) { qs = (iqs < path.Length - 1) ? path.Substring(iqs + 1) : String.Empty; path = path.Substring(0, iqs); } // resolve relative path path = UrlPath.Combine(Request.BaseDir, path); // disallow paths outside of app if (!HttpRuntime.IsPathWithinAppRoot(path)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Cross_app_not_allowed, path)); } // clear things that depend on path ConfigPath = null; // rewrite path on request Request.InternalRewritePath(path, qs); }
/// <include file='doc\MyWeb.uex' path='docs/doc[@for="MyWebManifest.Install1"]/*' /> /// <devdoc> /// <para>Marked internal for Beta 1 per ErikOls.</para> /// </devdoc> public MyWebApplication Install(String strLocation) { if (Installed) { return(null); } if (!MyWeb.IsAdminApp()) { return(null); } if (strLocation != null) { _Properties[_InstalledLocation] = strLocation; } StringBuilder strError = new StringBuilder(1024); if (NativeMethods.MyWebInstallApp(CabFile, ApplicationUrl, InstalledLocation, ManifestFile, strError, 1024) != 0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Literal, strError.ToString())); //return null; } else { _Installed = true; return(new MyWebApplication(this)); } }
/// <include file='doc\MyWeb.uex' path='docs/doc[@for="MyWebApplication.Update"]/*' /> /// <devdoc> /// <para>Marked internal for Beta 1 per ErikOls.</para> /// </devdoc> public int Update() { if (!MyWeb.IsAdminApp()) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Operation_requires_url_to_be_myweb_home)); } MyWebManifest manifest = MyWeb.GetManifest(Manifest.ApplicationUrl); if (manifest == null) { return(0); } StringBuilder strError = new StringBuilder(1024); int iReturn = 0; iReturn = NativeMethods.MyWebReInstallApp(manifest.CabFile, manifest.ApplicationUrl, manifest.InstalledLocation, manifest.ManifestFile, strError, 1024); if (iReturn != 0 && iReturn != 1) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Literal, strError.ToString())); } _Manifest = manifest; return(iReturn); }
internal void AddNewControl(string id, string parentId, string type, int viewStateSize) { VerifyStart(); DataRow row = NewRow(_requestData, SR.Trace_Control_Tree); if (id == null) { id = PAGEKEYNAME; } row[SR.Trace_Control_Id] = id; if (parentId == null) { parentId = PAGEKEYNAME; } row[SR.Trace_Parent_Id] = parentId; row[SR.Trace_Type] = type; row[SR.Trace_Viewstate_Size] = viewStateSize; row[SR.Trace_Render_Size] = 0; try { AddRow(_requestData, SR.Trace_Control_Tree, row); } catch (ConstraintException) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Duplicate_id_used, id, "Trace")); } }
internal void InstallFilter(Stream filter) { if (_filterSink == null) // have to redirect to the sink -- null means sink wasn't ever asked for { throw new HttpException(HttpRuntime.FormatResourceString(SR.Invalid_response_filter)); } _installedFilter = filter; }
private void VerifyState() { // throw exception on unexpected filter writes if (!_filtering) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Invalid_use_of_response_filter)); } }
internal int CallISAPI(UnsafeNativeMethods.CallISAPIFunc iFunction, byte [] bufIn, byte [] bufOut) { if (_wr == null || !(_wr is System.Web.Hosting.ISAPIWorkerRequest)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Cannot_call_ISAPI_functions)); } return(((System.Web.Hosting.ISAPIWorkerRequest)_wr).CallISAPI(iFunction, bufIn, bufOut)); }
internal static SafeStringResource ReadSafeStringResource(Type t) { // Module.FullyQualifiedName was changed to check for FileIOPermission regardless of the name being an existing file or not. // we need to Assert in order to succeed the Demand() (ASURT 121603) (InternalSecurityPermissions.PathDiscovery(HttpRuntime.CodegenDirInternal)).Assert(); string dllPath = t.Module.FullyQualifiedName; IntPtr hModule = UnsafeNativeMethods.GetModuleHandle(dllPath); if (hModule == (IntPtr)0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Resource_problem, "GetModuleHandle", HttpException.HResultFromLastError(Marshal.GetLastWin32Error()).ToString())); } IntPtr hrsrc = UnsafeNativeMethods.FindResource(hModule, (IntPtr)RESOURCE_ID, (IntPtr)RESOURCE_TYPE); if (hrsrc == (IntPtr)0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Resource_problem, "FindResource", HttpException.HResultFromLastError(Marshal.GetLastWin32Error()).ToString())); } int resSize = UnsafeNativeMethods.SizeofResource(hModule, hrsrc); IntPtr hglob = UnsafeNativeMethods.LoadResource(hModule, hrsrc); if (hglob == (IntPtr)0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Resource_problem, "LoadResource", HttpException.HResultFromLastError(Marshal.GetLastWin32Error()).ToString())); } IntPtr pv = UnsafeNativeMethods.LockResource(hglob); if (pv == (IntPtr)0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Resource_problem, "LockResource", HttpException.HResultFromLastError(Marshal.GetLastWin32Error()).ToString())); } // Make sure the end of the resource lies within the module. this can be an issue // if the resource has been hacked with an invalid length (ASURT 145040) if (!UnsafeNativeMethods.IsValidResource(hModule, pv, resSize)) { throw new InvalidOperationException(); } return(new SafeStringResource(pv, resSize)); }
internal void ReimpersonateIfSuspended() { if (_mode == ImpersonationMode.Client) { if (!ImpersonationSuspendContext.IsImpersonating()) { int rc = UnsafeNativeMethods.SetThreadToken((IntPtr)0, _token); if (rc == 0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Cannot_impersonate)); } _reimpersonating = true; } } }
/* * Get bytes (for filtering) */ /*public*/ byte[] IHttpResponseElement.GetBytes() { if (_size == 0) { return(new byte[0]); } byte[] data = null; FileStream f = null; try { if (_filename == null) { f = new FileStream(_fileHandle, FileAccess.Read, false); } else { f = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.Read); } long fileSize = f.Length; if (_offset < 0 || _size > fileSize - _offset) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Invalid_range)); } if (_offset > 0) { f.Seek(_offset, SeekOrigin.Begin); } data = new byte[(int)_size]; f.Read(data, 0, (int)_size); } finally { if (f != null) { f.Close(); } } return(data); }
private static IntPtr GetCurrentToken() { IntPtr token = IntPtr.Zero; if (UnsafeNativeMethods.OpenThreadToken( UnsafeNativeMethods.GetCurrentThread(), UnsafeNativeMethods.TOKEN_READ | UnsafeNativeMethods.TOKEN_IMPERSONATE, true, ref token) == 0) { // if the last error is ERROR_NO_TOKEN it is ok, otherwise throw if (Marshal.GetLastWin32Error() != UnsafeNativeMethods.ERROR_NO_TOKEN) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Cannot_impersonate)); } } return(token); }
////////////////////////////////////////////////////////////////////// // Move an app /// <include file='doc\MyWeb.uex' path='docs/doc[@for="MyWebManifest.Move"]/*' /> /// <devdoc> /// <para>Marked internal for Beta 1 per ErikOls.</para> /// </devdoc> public int Move(String strNewLocation) { if (!MyWeb.IsAdminApp()) { return(0); } int iReturn = 0; StringBuilder strError = new StringBuilder(1024); iReturn = NativeMethods.MyWebMoveApp(ApplicationUrl, strNewLocation, strError, 1024); if (iReturn != 0 && iReturn != 1) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Literal, strError.ToString())); } _Properties[_InstalledLocation] = strNewLocation; return(iReturn); }
//////////////////////////////////////////////////////////////////////// // CTor: Create from an installed app internal MyWebApplication(int iIndex) { if (!MyWeb.IsAdminApp()) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Operation_requires_url_to_be_myweb_home)); } StringBuilder strBFile = new StringBuilder(300); StringBuilder strBUrl = new StringBuilder(1024); long [] pLongs = new long[3]; if (NativeMethods.MyWebGetApplicationDetails(iIndex, strBFile, 300, strBUrl, 1024, pLongs) != 0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Unable_to_create_app_object)); } _Manifest = MyWebManifest.CreateFromFile(strBFile.ToString() + "\\myweb.osd", strBUrl.ToString(), true, true); _InstalledDate = DateTime.FromFileTime(pLongs[0]); _LastAccessDate = DateTime.FromFileTime(pLongs[1]); _LocalApplication = (pLongs[2] != 0); }
internal void Resume() { if (_token != IntPtr.Zero) { bool impersonationFailed = false; if (_revertSucceeded) { if (UnsafeNativeMethods.SetThreadToken(IntPtr.Zero, _token) == 0) { impersonationFailed = true; } } UnsafeNativeMethods.CloseHandle(_token); if (impersonationFailed) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Cannot_impersonate)); } } }
/// <include file='doc\HttpContext.uex' path='docs/doc[@for="HttpContext.RewritePath1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void RewritePath(String filePath, String pathInfo, String queryString) { // resolve relative path filePath = UrlPath.Combine(Request.BaseDir, filePath); // disallow paths outside of app if (!HttpRuntime.IsPathWithinAppRoot(filePath)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Cross_app_not_allowed, filePath)); } // patch pathInfo if (pathInfo == null) { pathInfo = String.Empty; } // clear things that depend on path ConfigPath = null; // rewrite path on request Request.InternalRewritePath(filePath, pathInfo, queryString); }
/// <include file='doc\HttpDebugHandler.uex' path='docs/doc[@for="HttpDebugHandler.ProcessRequest"]/*' /> /// <devdoc> /// <para>Drives web processing execution.</para> /// </devdoc> public void ProcessRequest(HttpContext context) { // Debugging must be enabled try { HttpDebugHandlerTimeLog.PrintTickDelta("Entered HttpDebugHandler"); if (!HttpRuntime.DebuggingEnabled) { context.Response.Write(HttpRuntime.FormatResourceString(SR.Debugging_forbidden, context.Request.Path)); context.Response.StatusCode = 403; return; } // Check to see if it's a valid debug command. string command = context.Request.Headers["Command"]; if (command == null) { Debug.Trace("AutoAttach", "No debug command!!"); context.Response.Write(HttpRuntime.FormatResourceString(SR.Invalid_Debug_Request)); context.Response.StatusCode = 500; return; } Debug.Trace("AutoAttach", "Debug command: " + command); if (string.Compare(command, "stop-debug", true, CultureInfo.InvariantCulture) == 0) { context.Response.Write("OK"); return; } if (string.Compare(command, "start-debug", true, CultureInfo.InvariantCulture) != 0) { context.Response.Write(HttpRuntime.FormatResourceString(SR.Invalid_Debug_Request)); context.Response.StatusCode = 500; return; } // Request must be NTLM authenticated string authType = context.WorkerRequest.GetServerVariable("AUTH_TYPE"); // go the metal string logonUser = context.WorkerRequest.GetServerVariable("LOGON_USER"); Debug.Trace("AutoAttach", "Authentication type string: " + ((authType != null) ? authType : "NULL")); Debug.Trace("AutoAttach", "Logon user string: " + ((logonUser != null) ? logonUser : "******")); if (logonUser == null || logonUser.Length == 0 || authType == null || authType.Length == 0 || String.Compare(authType, "basic", true, CultureInfo.InvariantCulture) == 0) { Debug.Trace("AutoAttach", "Invalid logon_user or auth_type string."); context.Response.Write(HttpRuntime.FormatResourceString(SR.Debug_Access_Denied, context.Request.Path)); context.Response.StatusCode = 401; return; } // Get the session ID String sessId = context.Request.Form["DebugSessionID"]; Debug.Trace("AutoAttach", "DebugSessionID: " + ((sessId != null) ? sessId : "NULL")); if (sessId == null || sessId.Length == 0) { context.Response.Write(HttpRuntime.FormatResourceString(SR.Invalid_Debug_ID)); context.Response.StatusCode = 500; return; } string s = sessId.Replace(';', '&'); HttpValueCollection valCol = new HttpValueCollection(s, true, true, Encoding.UTF8); string clsId = (string)valCol["autoattachclsid"]; // Verify clsId bool isClsIdOk = false; if (clsId != null) { for (int i = 0; i < validClsIds.Length; i++) { if (clsId.ToLower(System.Globalization.CultureInfo.InvariantCulture) == validClsIds[i]) { isClsIdOk = true; break; } } } if (isClsIdOk == false) { context.Response.Write(HttpRuntime.FormatResourceString(SR.Debug_Access_Denied, context.Request.Path)); context.Response.StatusCode = 401; Debug.Trace("AutoAttach", "Debug attach not attempted because of invalid CLSID."); return; } // Attach the debugger HttpDebugHandlerTimeLog.PrintTickDelta("About to call into MDM"); int rc = UnsafeNativeMethods.AttachDebugger(clsId, sessId, context.WorkerRequest.GetUserToken()); HttpDebugHandlerTimeLog.PrintTickDelta("Returned from call to MDM"); // If it's not S_OK, then we got a problem if (rc != 0) { Debug.Trace("AutoAttach", "Debug attach failed! Return code: " + rc); context.Response.Write(HttpRuntime.FormatResourceString(SR.Error_Attaching_with_MDM, "0x" + rc.ToString("X8"))); context.Response.StatusCode = 500; return; } Debug.Trace("AutoAttach", "Debug attach successful!"); // Everything ok -- increment counter, return something (not 204) PerfCounters.IncrementCounter(AppPerfCounter.DEBUGGING_REQUESTS); context.Response.Write("OK"); // Set global flag for us HttpRuntime.VSDebugAttach = true; } finally { Debug.Trace("AutoAttach", "Http Debug attach done!"); HttpDebugHandlerTimeLog.PrintTickDelta("Leaving HttpDebugHandler"); HttpDebugHandlerTimeLog.Close(); } }
///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// public void ProcessRequest(HttpContext context) { FileInfo file; HttpRequest request = context.Request; HttpResponse response = context.Response; string FileName = request.PhysicalPath; Util.Debug.Trace("GET", "Path = " + request.Path); Util.Debug.Trace("GET", "File Name = " + FileName); // // Check whether the file exists // if (!FileUtil.FileExists(FileName)) { throw new HttpException(HttpStatus.NotFound, HttpRuntime.FormatResourceString(SR.File_does_not_exist)); } try { file = new FileInfo(FileName); } catch (IOException ioEx) { if (!HttpRuntime.HasFilePermission(FileName)) { throw new HttpException(HttpStatus.NotFound, HttpRuntime.FormatResourceString(SR.Error_trying_to_enumerate_files)); } else { throw new HttpException(HttpStatus.NotFound, HttpRuntime.FormatResourceString(SR.Error_trying_to_enumerate_files), ioEx); } } catch (SecurityException secEx) { if (!HttpRuntime.HasFilePermission(FileName)) { throw new HttpException(HttpStatus.Unauthorized, HttpRuntime.FormatResourceString(SR.File_enumerator_access_denied)); } else { throw new HttpException(HttpStatus.Unauthorized, HttpRuntime.FormatResourceString(SR.File_enumerator_access_denied), secEx); } } // // To be consistent with IIS, we won't serve out hidden files // if ((((int)file.Attributes) & ((int)FileAttributes.Hidden)) != 0) { throw new HttpException(HttpStatus.NotFound, HttpRuntime.FormatResourceString(SR.File_is_hidden)); } // // To prevent the trailing dot problem, error out all file names with trailing dot. // if (FileName[FileName.Length - 1] == '.') { throw new HttpException(HttpStatus.NotFound, HttpRuntime.FormatResourceString(SR.File_does_not_exist)); } // // If the file is a directory, then it must not have a slash in // end of it (if it does have a slash suffix, then the config file // mappings are missing and we will just return 403. Otherwise, // we will redirect the client to the URL with this slash. // if ((((int)file.Attributes) & ((int)FileAttributes.Directory)) != 0) { if (request.Path.EndsWith("/")) { // // Just return 403 // throw new HttpException(HttpStatus.Forbidden, HttpRuntime.FormatResourceString(SR.Missing_star_mapping)); } else { // // Redirect to a slash suffixed URL which will be // handled by the */ handler mapper // response.Redirect(request.Path + "/"); } } else { DateTime lastModified; string strETag; // // Determine Last Modified Time. We might need it soon // if we encounter a Range: and If-Range header // lastModified = new DateTime(file.LastWriteTime.Year, file.LastWriteTime.Month, file.LastWriteTime.Day, file.LastWriteTime.Hour, file.LastWriteTime.Minute, file.LastWriteTime.Second, 0); // // Generate ETag // strETag = GenerateETag(context, lastModified); // // OK. Send the static file out either // entirely or send out the requested ranges // try { BuildFileItemResponse(context, FileName, file.Length, lastModified, strETag); } catch (Exception e) { // // Check for ERROR_ACCESS_DENIED and set the HTTP // status such that the auth modules do their thing // if ((e is ExternalException) && IsSecurityError(((ExternalException)e).ErrorCode)) { throw new HttpException(HttpStatus.Unauthorized, HttpRuntime.FormatResourceString(SR.Resource_access_forbidden)); } } context.Response.Cache.SetLastModified(lastModified); context.Response.Cache.SetETag(strETag); // // We will always set Cache-Control to public // context.Response.Cache.SetCacheability(HttpCacheability.Public); } }
public override void Remove(String name) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Cannot_modify_server_vars)); }
internal HttpRequestValidationException(string message) : base(message) { SetFormatter(new UnhandledErrorFormatter( this, HttpRuntime.FormatResourceString(SR.Dangerous_input_detected_descr), null)); }
////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Private stuff ////////////////////////////////////////////////////////////////////// // Create a manifest from a manifest file static internal MyWebManifest CreateFromFile( String strFile, String strUrl, bool installed, bool donotfail) { String [] strProperties = null; ConfigXmlDocument xmlDoc = null; ConfigXmlCursor cursor = null; int iter = 0; int iRet = 0; StringBuilder strBuf = new StringBuilder(1024); bool fFound = false; ArrayList customUrls = new ArrayList(); ArrayList customUrlDs = new ArrayList(); String strRandom = System.Web.SessionState.SessionId.Create(); //////////////////////////////////////////////////////////// // Step 1: Parse the file and get the other properties try { xmlDoc = new ConfigXmlDocument(); xmlDoc.Load(strFile); cursor = xmlDoc.GetCursor(); cursor.MoveToFirstChild(); } catch (Exception e) { if (!donotfail) { throw e; } cursor = null; } if (cursor != null) { do { if (cursor.Type == ConfigXmlElement.Element && cursor.Name.ToLower(CultureInfo.InvariantCulture).Equals("softpkg")) { fFound = true; break; } }while (cursor.MoveNext()); } if (!fFound && !donotfail) { return(null); } //////////////////////////////////////////////////////////// // Step 2: Get the non-manifest file properties strProperties = new String[NUM_PROPERTIES]; for (iter = 0; iter < NUM_PROPERTIES; iter++) { strProperties[iter] = String.Empty; } strProperties[_ApplicationUrl] = strUrl.Replace('\\', '/'); strProperties[_ManifestFile] = strFile; if (!installed) { iRet = NativeMethods.MyWebGetInstallLocationForUrl(MyWeb.GetDefaultInstallLocation(), strUrl, strRandom, strBuf, 1024); if (iRet < 0) { iRet = -iRet + 100; strBuf = new StringBuilder(iRet); iRet = NativeMethods.MyWebGetInstallLocationForUrl(MyWeb.GetDefaultInstallLocation(), strUrl, strRandom, strBuf, iRet); } if (iRet <= 0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Unable_to_get_app_location)); } strProperties[_InstalledLocation] = strBuf.ToString(); } else { strProperties[_InstalledLocation] = strFile.Substring(0, strFile.LastIndexOf('\\')); } if (cursor == null && donotfail) { return(new MyWebManifest(strProperties, installed, new String[0], new String[0])); } strProperties[_Name] = cursor.AttributeText("name"); strProperties[_Version] = cursor.AttributeText("version"); cursor.MoveToFirstChild(); do { if (cursor.Type == ConfigXmlElement.Element) { String strName = cursor.Name.ToLower(CultureInfo.InvariantCulture); if (strName.Equals("implementation")) { strProperties[_CabFile] = GetCabFileNameFromCursor(cursor); } else if (strName.Equals("license")) { strProperties[_License] = cursor.AttributeText("href"); } else if (strName.Equals("customurl")) { String strC = cursor.AttributeText("href"); String strD = cursor.AttributeText("description"); customUrls.Add(strC); customUrlDs.Add(strD); } else { for (iter = 0; iter < _OtherProperties.Length; iter++) { if (strName.Equals(_OtherProperties[iter])) { strProperties[OTHER_PROP_START + iter] = GetCursorText(cursor); break; } } } } }while (cursor.MoveNext()); return(new MyWebManifest(strProperties, installed, customUrls.ToArray(), customUrlDs.ToArray())); }
/// <include file='doc\ProcessModelInfo.uex' path='docs/doc[@for="ProcessModelInfo.GetHistory"]/*' /> static public ProcessInfo[] GetHistory(int numRecords) { InternalSecurityPermissions.AspNetHostingPermissionLevelHigh.Demand(); HttpContext context = HttpContext.Current; if (context == null || context.WorkerRequest == null || !(context.WorkerRequest is System.Web.Hosting.ISAPIWorkerRequestOutOfProc)) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Process_information_not_available)); } if (numRecords < 1) { return(null); } int [] dwPID = new int [numRecords]; int [] dwExed = new int [numRecords]; int [] dwExei = new int [numRecords]; int [] dwPend = new int [numRecords]; int [] dwReas = new int [numRecords]; long [] tmCrea = new long [numRecords]; long [] tmDeat = new long [numRecords]; int [] mem = new int [numRecords]; int iRows = UnsafeNativeMethods.PMGetHistoryTable(numRecords, dwPID, dwExed, dwPend, dwExei, dwReas, mem, tmCrea, tmDeat); if (iRows < 0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Process_information_not_available)); } ProcessInfo[] ret = new ProcessInfo[iRows]; for (int iter = 0; iter < iRows; iter++) { DateTime startTime = DateTime.FromFileTime(tmCrea[iter]); TimeSpan age = DateTime.Now.Subtract(startTime); ProcessStatus status = ProcessStatus.Alive; ProcessShutdownReason rea = ProcessShutdownReason.None; if (dwReas[iter] != 0) { if (tmDeat[iter] > 0) { age = DateTime.FromFileTime(tmDeat[iter]).Subtract(startTime); } if ((dwReas[iter] & 0x0004) != 0) { status = ProcessStatus.Terminated; } else if ((dwReas[iter] & 0x0002) != 0) { status = ProcessStatus.ShutDown; } else { status = ProcessStatus.ShuttingDown; } if ((0x0040 & dwReas[iter]) != 0) { rea = ProcessShutdownReason.IdleTimeout; } else if ((0x0080 & dwReas[iter]) != 0) { rea = ProcessShutdownReason.RequestsLimit; } else if ((0x0100 & dwReas[iter]) != 0) { rea = ProcessShutdownReason.RequestQueueLimit; } else if ((0x0020 & dwReas[iter]) != 0) { rea = ProcessShutdownReason.Timeout; } else if ((0x0200 & dwReas[iter]) != 0) { rea = ProcessShutdownReason.MemoryLimitExceeded; } else if ((0x0400 & dwReas[iter]) != 0) { rea = ProcessShutdownReason.PingFailed; } else if ((0x0800 & dwReas[iter]) != 0) { rea = ProcessShutdownReason.DeadlockSuspected; } else { rea = ProcessShutdownReason.Unexpected; } } ret[iter] = new ProcessInfo(startTime, age, dwPID[iter], dwExed[iter], status, rea, mem[iter]); } return(ret); }
internal /*public*/ string GetHtmlErrorMessage(bool dontShowSensitiveInfo) { // Give the formatter a chance to prepare its state PrepareFormatter(); StringBuilder sb = new StringBuilder(); // REVIEW: all the derived method should work directly with the string // builder instead of returning a string. sb.Append("<html>\r\n"); sb.Append(" <head>\r\n"); sb.Append(" <title>" + ErrorTitle + "</title>\r\n"); sb.Append(" <style>\r\n"); sb.Append(" body {font-family:\"Verdana\";font-weight:normal;font-size: .7em;color:black;} \r\n"); sb.Append(" p {font-family:\"Verdana\";font-weight:normal;color:black;margin-top: -5px}\r\n"); sb.Append(" b {font-family:\"Verdana\";font-weight:bold;color:black;margin-top: -5px}\r\n"); sb.Append(" H1 { font-family:\"Verdana\";font-weight:normal;font-size:18pt;color:red }\r\n"); sb.Append(" H2 { font-family:\"Verdana\";font-weight:normal;font-size:14pt;color:maroon }\r\n"); sb.Append(" pre {font-family:\"Lucida Console\";font-size: .9em}\r\n"); sb.Append(" .marker {font-weight: bold; color: black;text-decoration: none;}\r\n"); sb.Append(" .version {color: gray;}\r\n"); sb.Append(" .error {margin-bottom: 10px;}\r\n"); sb.Append(" .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }\r\n"); sb.Append(" </style>\r\n"); sb.Append(" </head>\r\n\r\n"); sb.Append(" <body bgcolor=\"white\">\r\n\r\n"); sb.Append(" <span><H1>" + HttpRuntime.FormatResourceString(SR.Error_Formatter_ASPNET_Error, HttpRuntime.AppDomainAppVirtualPath) + "<hr width=100% size=1 color=silver></H1>\r\n\r\n"); sb.Append(" <h2> <i>" + ErrorTitle + "</i> </h2></span>\r\n\r\n"); sb.Append(" <font face=\"Arial, Helvetica, Geneva, SunSans-Regular, sans-serif \">\r\n\r\n"); sb.Append(" <b> " + HttpRuntime.FormatResourceString(SR.Error_Formatter_Description) + " </b>" + Description + "\r\n"); sb.Append(" <br><br>\r\n\r\n"); if (MiscSectionTitle != null) { sb.Append(" <b> " + MiscSectionTitle + ": </b>" + MiscSectionContent + "<br><br>\r\n\r\n"); } WriteColoredSquare(sb, ColoredSquareTitle, ColoredSquareDescription, ColoredSquareContent, WrapColoredSquareContentLines); if (ShowSourceFileInfo) { string fileName = HttpRuntime.GetSafePath(SourceFileName); if (fileName == null) { fileName = HttpRuntime.FormatResourceString(SR.Error_Formatter_No_Source_File); } sb.Append(" <b> " + HttpRuntime.FormatResourceString(SR.Error_Formatter_Source_File) + " </b> " + fileName + "<b> " + HttpRuntime.FormatResourceString(SR.Error_Formatter_Line) + " </b> " + SourceFileLineNumber + "\r\n"); sb.Append(" <br><br>\r\n\r\n"); } // If it's a FileNotFoundException/FileLoadException/BadImageFormatException with a FusionLog, // write it out (ASURT 83587) if (!dontShowSensitiveInfo && Exception != null) { // (Only display the fusion log in medium or higher (ASURT 126827) if (HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { for (Exception e = Exception; e != null; e = e.InnerException) { string fusionLog = null; string filename = null; FileNotFoundException fnfException = e as FileNotFoundException; if (fnfException != null) { fusionLog = fnfException.FusionLog; filename = fnfException.FileName; } FileLoadException flException = e as FileLoadException; if (flException != null) { fusionLog = flException.FusionLog; filename = flException.FileName; } BadImageFormatException bifException = e as BadImageFormatException; if (bifException != null) { fusionLog = bifException.FusionLog; filename = bifException.FileName; } if (fusionLog != null && fusionLog.Length > 0) { WriteColoredSquare(sb, HttpRuntime.FormatResourceString(SR.Error_Formatter_FusionLog), HttpRuntime.FormatResourceString(SR.Error_Formatter_FusionLogDesc, filename), HttpUtility.HtmlEncode(fusionLog), false /*WrapColoredSquareContentLines*/); break; } } } } WriteColoredSquare(sb, ColoredSquare2Title, ColoredSquare2Description, ColoredSquare2Content, false); if (!dontShowSensitiveInfo) // don't show version for security reasons { sb.Append(" <hr width=100% size=1 color=silver>\r\n\r\n"); sb.Append(" <b>" + HttpRuntime.FormatResourceString(SR.Error_Formatter_Version) + "</b> " + HttpRuntime.FormatResourceString(SR.Error_Formatter_CLR_Build) + VersionInfo.ClrVersion + HttpRuntime.FormatResourceString(SR.Error_Formatter_ASPNET_Build) + VersionInfo.IsapiVersion + "\r\n\r\n"); sb.Append(" </font>\r\n\r\n"); } sb.Append(" </body>\r\n"); sb.Append("</html>\r\n"); sb.Append(PostMessage); return(sb.ToString()); }
/* * Return the text of the error line in the source file, with a few * lines around it. It is returned in HTML format. */ internal static string GetSourceFileLines(string fileName, Encoding encoding, string sourceCode, int lineNumber) { // Don't show any source file if the user doesn't have access to it (ASURT 122430) if (fileName != null && !HttpRuntime.HasFilePermission(fileName)) { return(HttpRuntime.FormatResourceString(SR.WithFile_No_Relevant_Line)); } // REVIEW: write directly to the main builder StringBuilder sb = new StringBuilder(); if (lineNumber <= 0) { return(HttpRuntime.FormatResourceString(SR.WithFile_No_Relevant_Line)); } TextReader reader = null; fileName = ResolveHttpFileName(fileName); try { // Open the source file reader = new StreamReader(fileName, encoding, true, 4096); } catch (Exception) { // Can't open the file? Use the dynamically generated content... reader = new StringReader(sourceCode); } try { bool fFoundLine = false; for (int i = 1; ; i++) { // Get the current line from the source file string sourceLine = reader.ReadLine(); if (sourceLine == null) { break; } // If it's the error line, make it red if (i == lineNumber) { sb.Append("<font color=red>"); } // Is it in the range we want to display if (i >= lineNumber - errorRange && i <= lineNumber + errorRange) { fFoundLine = true; String linestr = i.ToString("G"); sb.Append(HttpRuntime.FormatResourceString(SR.WithFile_Line_Num, linestr)); if (linestr.Length < 3) { sb.Append(' ', 3 - linestr.Length); } sb.Append(HttpUtility.HtmlEncode(sourceLine)); if (i != lineNumber + errorRange) { sb.Append("\r\n"); } } if (i == lineNumber) { sb.Append("</font>"); } if (i > lineNumber + errorRange) { break; } } if (!fFoundLine) { return(HttpRuntime.FormatResourceString(SR.WithFile_No_Relevant_Line)); } } finally { // Make sure we always close the reader reader.Close(); } return(sb.ToString()); }
// // constructor used by config section handler // internal CustomErrors(XmlNode node, String basePath, CustomErrors parent) { _mode = CustomErrorsMode.Off; // inherit parent settings if (parent != null) { _mode = parent._mode; _defaultRedirect = parent._defaultRedirect; if (parent._codeRedirects != null) { _codeRedirects = new Hashtable(); for (IDictionaryEnumerator e = parent._codeRedirects.GetEnumerator(); e.MoveNext();) { _codeRedirects.Add(e.Key, e.Value); } } } // add current settings XmlNode a; String redirect = null; // get default and mode from the main tag HandlerBase.GetAndRemoveStringAttribute(node, "defaultRedirect", ref redirect); if (redirect != null) { _defaultRedirect = GetAbsoluteRedirect(redirect, basePath); } int iMode = 0; a = HandlerBase.GetAndRemoveEnumAttribute(node, "mode", typeof(CustomErrorsMode), ref iMode); if (a != null) { _mode = (CustomErrorsMode)iMode; } // report errors on bad attribures HandlerBase.CheckForUnrecognizedAttributes(node); // child tags foreach (XmlNode child in node.ChildNodes) { if (HandlerBase.IsIgnorableAlsoCheckForNonElement(child)) { continue; } int status = 0; // set when req. attr. is read // only <error> is allowed if (child.Name != "error") { HandlerBase.ThrowUnrecognizedElement(child); } // status code attribure a = HandlerBase.GetAndRemoveRequiredIntegerAttribute(child, "statusCode", ref status); if (status < 100 && status > 999) { throw new ConfigurationException( HttpRuntime.FormatResourceString(SR.Customerrors_invalid_statuscode), a); } // redirect attribure redirect = HandlerBase.RemoveRequiredAttribute(child, "redirect"); // errors on other attributes HandlerBase.CheckForUnrecognizedAttributes(child); // <error> tags contain no content HandlerBase.CheckForChildNodes(child); // remember if (_codeRedirects == null) { _codeRedirects = new Hashtable(); } _codeRedirects[status.ToString()] = GetAbsoluteRedirect(redirect, basePath); } }