2 // System.Web.HttpRuntime.cs
5 // Miguel de Icaza (miguel@novell.com)
6 // Marek Habersack <mhabersack@novell.com>
9 // Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
32 // TODO: Call HttpRequest.CloseInputStream when we finish a request, as we are using the IntPtr stream.
36 using System.Globalization;
37 using System.Collections;
38 using System.Collections.Concurrent;
39 using System.Reflection;
40 using System.Security;
41 using System.Security.Permissions;
42 using System.Web.Caching;
43 using System.Web.Configuration;
44 using System.Web.Management;
46 using System.Web.Util;
50 using System.Threading;
54 using System.CodeDom.Compiler;
55 using System.Web.Compilation;
60 // CAS - no InheritanceDemand here as the class is sealed
61 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
62 public sealed class HttpRuntime
64 static bool domainUnloading;
65 static SplitOrderedList <string, string> registeredAssemblies;
67 static QueueManager queue_manager { get { return _runtime._queue_manager; } }
68 static TraceManager trace_manager { get { return _runtime._trace_manager; } }
69 static Cache cache { get { return _runtime._cache; } }
70 static Cache internalCache { get { return _runtime._internalCache; } }
71 static WaitCallback do_RealProcessRequest;
73 QueueManager _queue_manager;
74 TraceManager _trace_manager;
80 WebConfigurationManager.Init ();
81 _queue_manager = new QueueManager ();
82 _trace_manager = new TraceManager ();
83 _cache = new Cache ();
84 _internalCache = new Cache();
85 _internalCache.DependencyCache = _cache;
88 static HttpRuntime _runtimeInstance {
90 HttpRuntime runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
92 lock (typeof (HttpRuntime)) {
93 runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
94 if (runtime == null) {
95 runtime = new HttpRuntime ();
96 AppDomain.CurrentDomain.SetData ("HttpRuntime", runtime);
102 static HttpRuntime _runtime
106 if (HttpContext.Current != null)
107 return HttpContext.Current.HttpRuntimeInstance;
109 return _runtimeInstance;
113 static QueueManager queue_manager;
114 static TraceManager trace_manager;
116 static Cache internalCache;
117 static WaitCallback do_RealProcessRequest;
118 static HttpWorkerRequest.EndOfSendNotification end_of_send_cb;
119 static Exception initialException;
120 static bool firstRun;
121 static bool assemblyMappingEnabled;
122 static object assemblyMappingLock = new object ();
123 static object appOfflineLock = new object ();
124 static HttpRuntimeSection runtime_section;
126 public HttpRuntime ()
132 static HttpRuntime ()
138 WebConfigurationManager.Init ();
140 SettingsMappingManager.Init ();
142 runtime_section = (HttpRuntimeSection) WebConfigurationManager.GetSection ("system.web/httpRuntime");
143 } catch (Exception ex) {
144 initialException = ex;
147 // The classes in whose constructors exceptions may be thrown, should be handled the same way QueueManager
148 // and TraceManager are below. The constructors themselves MUST NOT throw any exceptions - we MUST be sure
149 // the objects are created here. The exceptions will be dealt with below, in RealProcessRequest.
150 queue_manager = new QueueManager ();
151 if (queue_manager.HasException) {
152 if (initialException == null)
153 initialException = queue_manager.InitialException;
155 Console.Error.WriteLine ("Exception during QueueManager initialization:");
156 Console.Error.WriteLine (queue_manager.InitialException);
160 trace_manager = new TraceManager ();
161 if (trace_manager.HasException) {
162 if (initialException == null)
163 initialException = trace_manager.InitialException;
165 Console.Error.WriteLine ("Exception during TraceManager initialization:");
166 Console.Error.WriteLine (trace_manager.InitialException);
170 registeredAssemblies = new SplitOrderedList <string, string> (StringComparer.Ordinal);
171 cache = new Cache ();
172 internalCache = new Cache ();
173 internalCache.DependencyCache = internalCache;
175 do_RealProcessRequest = new WaitCallback (state => {
177 RealProcessRequest (state);
180 end_of_send_cb = new HttpWorkerRequest.EndOfSendNotification (EndOfSend);
183 internal static SplitOrderedList <string, string> RegisteredAssemblies {
184 get { return registeredAssemblies; }
187 #region AppDomain handling
188 internal static bool DomainUnloading {
189 get { return domainUnloading; }
192 [MonoDocumentationNote ("Currently returns path to the application root")]
193 public static string AspClientScriptPhysicalPath { get { return AppDomainAppPath; } }
195 [MonoDocumentationNote ("Currently returns path to the application root")]
196 public static string AspClientScriptVirtualPath { get { return AppDomainAppVirtualPath; } }
199 // http://radio.weblogs.com/0105476/stories/2002/07/12/executingAspxPagesWithoutAWebServer.html
201 public static string AppDomainAppId {
202 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
205 // This value should not change across invocations
207 string dirname = (string) AppDomain.CurrentDomain.GetData (".appId");
208 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
209 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
215 // Physical directory for the application
216 public static string AppDomainAppPath {
218 string dirname = (string) AppDomain.CurrentDomain.GetData (".appPath");
219 if (SecurityManager.SecurityEnabled) {
220 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
226 public static string AppDomainAppVirtualPath {
228 return (string) AppDomain.CurrentDomain.GetData (".appVPath");
232 public static string AppDomainId {
233 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
235 return (string) AppDomain.CurrentDomain.GetData (".domainId");
239 public static string AspInstallDirectory {
241 string dirname = (string) AppDomain.CurrentDomain.GetData (".hostingInstallDir");
242 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
243 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
250 static string _actual_bin_directory;
251 public static string BinDirectory {
253 if (_actual_bin_directory == null) {
254 string[] parts = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split (';');
255 string mypath = AppDomainAppPath;
258 foreach (string p in parts) {
259 tmp = Path.Combine (mypath, p);
260 if (Directory.Exists (tmp)) {
261 _actual_bin_directory = tmp;
266 if (_actual_bin_directory == null)
267 _actual_bin_directory = Path.Combine (mypath, "bin");
269 if (_actual_bin_directory [_actual_bin_directory.Length - 1] != Path.DirectorySeparatorChar)
270 _actual_bin_directory += Path.DirectorySeparatorChar;
273 if (SecurityManager.SecurityEnabled)
274 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, _actual_bin_directory).Demand ();
276 return _actual_bin_directory;
280 public static Cache Cache {
286 internal static Cache InternalCache {
288 return internalCache;
292 public static string ClrInstallDirectory {
294 string dirname = Path.GetDirectoryName (typeof (Object).Assembly.Location);
295 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
296 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
302 public static string CodegenDir {
304 string dirname = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
305 if (SecurityManager.SecurityEnabled) {
306 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
312 public static bool IsOnUNCShare {
313 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
315 return RuntimeHelpers.IsUncShare;
319 public static string MachineConfigurationDirectory {
321 string dirname = Path.GetDirectoryName (ICalls.GetMachineConfigPath ());
322 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
323 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
329 internal static HttpRuntimeSection Section { get { return runtime_section; } }
331 public static bool UsingIntegratedPipeline { get { return false; } }
333 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
334 public static void Close ()
336 // Remove all items from cache.
339 internal static HttpWorkerRequest QueuePendingRequest (bool started_internally)
341 HttpWorkerRequest next = queue_manager.GetNextRequest (null);
345 if (!started_internally) {
346 next.StartedInternally = true;
347 ThreadPool.QueueUserWorkItem (do_RealProcessRequest, next);
354 static readonly string[] app_offline_files = {"app_offline.htm", "App_Offline.htm", "APP_OFFLINE.HTM"};
355 static string app_offline_file;
357 static bool AppIsOffline (HttpContext context)
359 if (!HttpApplicationFactory.ApplicationDisabled || app_offline_file == null)
362 HttpResponse response = context.Response;
364 response.ContentType = "text/html";
365 response.ExpiresAbsolute = DateTime.UtcNow;
366 response.StatusCode = 503;
367 response.TransmitFile (app_offline_file, true);
369 context.Request.ReleaseResources ();
370 context.Response.ReleaseResources ();
371 HttpContext.Current = null;
372 HttpApplication.requests_total_counter.Increment ();
377 static void AppOfflineFileRenamed (object sender, RenamedEventArgs args)
379 AppOfflineFileChanged (sender, args);
382 static void AppOfflineFileChanged (object sender, FileSystemEventArgs args)
384 lock (appOfflineLock) {
387 switch (args.ChangeType) {
388 case WatcherChangeTypes.Created:
389 case WatcherChangeTypes.Changed:
393 case WatcherChangeTypes.Deleted:
397 case WatcherChangeTypes.Renamed:
398 RenamedEventArgs rargs = args as RenamedEventArgs;
401 String.Compare (rargs.Name, "app_offline.htm", StringComparison.OrdinalIgnoreCase) == 0)
411 SetOfflineMode (offline, args.FullPath);
415 static void SetOfflineMode (bool offline, string filePath)
418 app_offline_file = null;
419 if (HttpApplicationFactory.ApplicationDisabled)
420 HttpRuntime.UnloadAppDomain ();
422 app_offline_file = filePath;
423 HttpApplicationFactory.DisableWatchers ();
424 HttpApplicationFactory.ApplicationDisabled = true;
425 InternalCache.InvokePrivateCallbacks ();
426 HttpApplicationFactory.Dispose ();
430 static void SetupOfflineWatch ()
432 lock (appOfflineLock) {
433 FileSystemEventHandler seh = new FileSystemEventHandler (AppOfflineFileChanged);
434 RenamedEventHandler reh = new RenamedEventHandler (AppOfflineFileRenamed);
436 string app_dir = AppDomainAppPath;
437 FileSystemWatcher watcher;
438 string offlineFile = null, tmp;
440 foreach (string f in app_offline_files) {
441 watcher = new FileSystemWatcher ();
442 watcher.Path = Path.GetDirectoryName (app_dir);
443 watcher.Filter = Path.GetFileName (f);
444 watcher.NotifyFilter |= NotifyFilters.Size;
445 watcher.Deleted += seh;
446 watcher.Changed += seh;
447 watcher.Created += seh;
448 watcher.Renamed += reh;
449 watcher.EnableRaisingEvents = true;
451 tmp = Path.Combine (app_dir, f);
452 if (File.Exists (tmp))
456 if (offlineFile != null)
457 SetOfflineMode (true, offlineFile);
462 static void RealProcessRequest (object o)
464 if (domainUnloading) {
465 Console.Error.WriteLine ("Domain is unloading, not processing the request.");
469 HttpWorkerRequest req = (HttpWorkerRequest) o;
470 bool started_internally = req.StartedInternally;
473 req = QueuePendingRequest (started_internally);
474 } while (started_internally && req != null);
477 static void Process (HttpWorkerRequest req)
481 HttpContext context = HttpContext.Current;
483 context = new HttpContext (req);
485 context.SetWorkerRequest (req);
489 if (initialException != null) {
490 FinishWithException (req, HttpException.NewWithCode ("Initial exception", initialException, WebEventCodes.RuntimeErrorRequestAbort));
493 SetupOfflineWatch ();
495 HttpContext context = new HttpContext (req);
497 HttpContext.Current = context;
499 if (AppIsOffline (context))
504 // Get application instance (create or reuse an instance of the correct class)
506 HttpApplication app = null;
509 app = HttpApplicationFactory.GetApplication (context);
510 } catch (Exception e) {
511 FinishWithException (req, HttpException.NewWithCode (String.Empty, e, WebEventCodes.RuntimeErrorRequestAbort));
517 context.Request.ReleaseResources ();
518 context.Response.ReleaseResources ();
519 HttpContext.Current = null;
521 context.ApplicationInstance = app;
522 req.SetEndOfSendNotification (end_of_send_cb, context);
525 // Ask application to service the request
529 IHttpAsyncHandler ihah = app;
530 if (context.Handler == null)
531 ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
534 //ihh.ProcessRequest (context);
535 IHttpExtendedHandler extHandler = context.Handler as IHttpExtendedHandler;
536 if (extHandler != null && !extHandler.IsCompleted)
538 if (context.Error is UnifyRequestException)
541 ihah.EndProcessRequest (null);
543 IHttpHandler ihh = app;
544 // IAsyncResult appiar = ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
545 // ihah.EndProcessRequest (appiar);
546 ihh.ProcessRequest (context);
549 HttpApplicationFactory.Recycle (app);
553 static void EndOfSend (HttpWorkerRequest ignored1, object ignored2)
558 // ProcessRequest method is executed in the AppDomain of the application
561 // ProcessRequest does not guarantee that `wr' will be processed synchronously,
562 // the request can be queued and processed later.
564 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
565 public static void ProcessRequest (HttpWorkerRequest wr)
568 throw new ArgumentNullException ("wr");
570 // Queue our request, fetch the next available one from the queue
572 HttpWorkerRequest request = queue_manager.GetNextRequest (wr);
576 QueuePendingRequest (false);
577 RealProcessRequest (request);
582 // Callback to be invoked by IHttpAsyncHandler.BeginProcessRequest
584 static void request_processed (IAsyncResult iar)
586 HttpContext context = (HttpContext) iar.AsyncState;
588 context.Request.ReleaseResources ();
589 context.Response.ReleaseResources ();
594 [MonoNotSupported ("UnloadAppDomain is not supported")]
595 public static void UnloadAppDomain ()
597 throw new NotImplementedException ("UnloadAppDomain is not supported");
601 // Called when we are shutting down or we need to reload an application
602 // that has been modified (touch global.asax)
604 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
605 public static void UnloadAppDomain ()
608 // TODO: call ReleaseResources
610 domainUnloading = true;
611 HttpApplicationFactory.DisableWatchers ();
612 ThreadPool.QueueUserWorkItem (delegate {
614 ShutdownAppDomain ();
615 } catch (Exception e){
616 Console.Error.WriteLine (e);
622 // Shuts down the AppDomain
624 static void ShutdownAppDomain ()
626 queue_manager.Dispose ();
627 // This will call Session_End if needed.
628 InternalCache.InvokePrivateCallbacks ();
629 // Kill our application.
630 HttpApplicationFactory.Dispose ();
631 ThreadPool.QueueUserWorkItem (delegate {
638 static void DoUnload ()
641 // No unload support for appdomains under Grasshopper
643 AppDomain.Unload (AppDomain.CurrentDomain);
647 static string content503 = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" +
648 "<html><head>\n<title>503 Server Unavailable</title>\n</head><body>\n" +
649 "<h1>Server Unavailable</h1>\n" +
652 static void FinishWithException (HttpWorkerRequest wr, HttpException e)
654 int code = e.GetHttpCode ();
655 wr.SendStatus (code, HttpWorkerRequest.GetStatusDescription (code));
656 wr.SendUnknownResponseHeader ("Connection", "close");
657 Encoding enc = Encoding.ASCII;
658 wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
659 string msg = e.GetHtmlErrorMessage ();
660 byte [] contentBytes = enc.GetBytes (msg);
661 wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
662 wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
663 wr.FlushResponse (true);
664 wr.CloseConnection ();
665 HttpApplication.requests_total_counter.Increment ();
669 // This is called from the QueueManager if a request
670 // can not be processed (load, no resources, or
671 // appdomain unload).
673 static internal void FinishUnavailable (HttpWorkerRequest wr)
675 wr.SendStatus (503, "Service unavailable");
676 wr.SendUnknownResponseHeader ("Connection", "close");
677 Encoding enc = Encoding.ASCII;
678 wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
679 byte [] contentBytes = enc.GetBytes (content503);
680 wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
681 wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
682 wr.FlushResponse (true);
683 wr.CloseConnection ();
684 HttpApplication.requests_total_counter.Increment ();
687 [AspNetHostingPermissionAttribute(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Unrestricted)]
688 [MonoDocumentationNote ("Always returns null on Mono")]
689 public static NamedPermissionSet GetNamedPermissionSet ()
695 static internal void WritePreservationFile (Assembly asm, string genericNameBase)
698 throw new ArgumentNullException ("asm");
699 if (String.IsNullOrEmpty (genericNameBase))
700 throw new ArgumentNullException ("genericNameBase");
702 string compiled = Path.Combine (AppDomain.CurrentDomain.SetupInformation.DynamicBase,
703 genericNameBase + ".compiled");
704 PreservationFile pf = new PreservationFile ();
706 pf.VirtualPath = String.Concat ("/", genericNameBase, "/");
708 AssemblyName an = asm.GetName ();
709 pf.Assembly = an.Name;
710 pf.ResultType = BuildResultTypeCode.TopLevelAssembly;
712 } catch (Exception ex) {
713 throw new HttpException (
714 String.Format ("Failed to write preservation file {0}", genericNameBase + ".compiled"),
719 static Assembly ResolveAssemblyHandler(object sender, ResolveEventArgs e)
721 AssemblyName an = new AssemblyName (e.Name);
722 string dynamic_base = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
723 string compiled = Path.Combine (dynamic_base, an.Name + ".compiled");
726 if (!File.Exists (compiled)) {
727 string fn = an.FullName;
728 if (!RegisteredAssemblies.Find ((uint)fn.GetHashCode (), fn, out asmPath))
733 pf = new PreservationFile (compiled);
734 } catch (Exception ex) {
735 throw new HttpException (
736 String.Format ("Failed to read preservation file {0}", an.Name + ".compiled"),
739 asmPath = Path.Combine (dynamic_base, pf.Assembly + ".dll");
742 if (String.IsNullOrEmpty (asmPath))
747 ret = Assembly.LoadFrom (asmPath);
748 } catch (Exception) {
755 internal static void EnableAssemblyMapping (bool enable)
757 lock (assemblyMappingLock) {
758 if (assemblyMappingEnabled == enable)
761 AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (ResolveAssemblyHandler);
763 AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler (ResolveAssemblyHandler);
764 assemblyMappingEnabled = enable;
767 #endif // #if !TARGET_J2EE
769 internal static TraceManager TraceManager {
771 return trace_manager;