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; } }
334 public static IISVersion {
335 get { return null; } // Null means not hosted by IIS
339 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
340 public static void Close ()
342 // Remove all items from cache.
345 internal static HttpWorkerRequest QueuePendingRequest (bool started_internally)
347 HttpWorkerRequest next = queue_manager.GetNextRequest (null);
351 if (!started_internally) {
352 next.StartedInternally = true;
353 ThreadPool.QueueUserWorkItem (do_RealProcessRequest, next);
360 static readonly string[] app_offline_files = {"app_offline.htm", "App_Offline.htm", "APP_OFFLINE.HTM"};
361 static string app_offline_file;
363 static bool AppIsOffline (HttpContext context)
365 if (!HttpApplicationFactory.ApplicationDisabled || app_offline_file == null)
368 HttpResponse response = context.Response;
370 response.ContentType = "text/html";
371 response.ExpiresAbsolute = DateTime.UtcNow;
372 response.StatusCode = 503;
373 response.TransmitFile (app_offline_file, true);
375 context.Request.ReleaseResources ();
376 context.Response.ReleaseResources ();
377 HttpContext.Current = null;
378 HttpApplication.requests_total_counter.Increment ();
383 static void AppOfflineFileRenamed (object sender, RenamedEventArgs args)
385 AppOfflineFileChanged (sender, args);
388 static void AppOfflineFileChanged (object sender, FileSystemEventArgs args)
390 lock (appOfflineLock) {
393 switch (args.ChangeType) {
394 case WatcherChangeTypes.Created:
395 case WatcherChangeTypes.Changed:
399 case WatcherChangeTypes.Deleted:
403 case WatcherChangeTypes.Renamed:
404 RenamedEventArgs rargs = args as RenamedEventArgs;
407 String.Compare (rargs.Name, "app_offline.htm", StringComparison.OrdinalIgnoreCase) == 0)
417 SetOfflineMode (offline, args.FullPath);
421 static void SetOfflineMode (bool offline, string filePath)
424 app_offline_file = null;
425 if (HttpApplicationFactory.ApplicationDisabled)
426 HttpRuntime.UnloadAppDomain ();
428 app_offline_file = filePath;
429 HttpApplicationFactory.DisableWatchers ();
430 HttpApplicationFactory.ApplicationDisabled = true;
431 InternalCache.InvokePrivateCallbacks ();
432 HttpApplicationFactory.Dispose ();
436 static void SetupOfflineWatch ()
438 lock (appOfflineLock) {
439 FileSystemEventHandler seh = new FileSystemEventHandler (AppOfflineFileChanged);
440 RenamedEventHandler reh = new RenamedEventHandler (AppOfflineFileRenamed);
442 string app_dir = AppDomainAppPath;
443 FileSystemWatcher watcher;
444 string offlineFile = null, tmp;
446 foreach (string f in app_offline_files) {
447 watcher = new FileSystemWatcher ();
448 watcher.Path = Path.GetDirectoryName (app_dir);
449 watcher.Filter = Path.GetFileName (f);
450 watcher.NotifyFilter |= NotifyFilters.Size;
451 watcher.Deleted += seh;
452 watcher.Changed += seh;
453 watcher.Created += seh;
454 watcher.Renamed += reh;
455 watcher.EnableRaisingEvents = true;
457 tmp = Path.Combine (app_dir, f);
458 if (File.Exists (tmp))
462 if (offlineFile != null)
463 SetOfflineMode (true, offlineFile);
468 static void RealProcessRequest (object o)
470 if (domainUnloading) {
471 Console.Error.WriteLine ("Domain is unloading, not processing the request.");
475 HttpWorkerRequest req = (HttpWorkerRequest) o;
476 bool started_internally = req.StartedInternally;
479 req = QueuePendingRequest (started_internally);
480 } while (started_internally && req != null);
483 static void Process (HttpWorkerRequest req)
487 HttpContext context = HttpContext.Current;
489 context = new HttpContext (req);
491 context.SetWorkerRequest (req);
495 if (initialException != null) {
496 FinishWithException (req, HttpException.NewWithCode ("Initial exception", initialException, WebEventCodes.RuntimeErrorRequestAbort));
499 SetupOfflineWatch ();
501 HttpContext context = new HttpContext (req);
503 HttpContext.Current = context;
505 if (AppIsOffline (context))
510 // Get application instance (create or reuse an instance of the correct class)
512 HttpApplication app = null;
515 app = HttpApplicationFactory.GetApplication (context);
516 } catch (Exception e) {
517 FinishWithException (req, HttpException.NewWithCode (String.Empty, e, WebEventCodes.RuntimeErrorRequestAbort));
523 context.Request.ReleaseResources ();
524 context.Response.ReleaseResources ();
525 HttpContext.Current = null;
527 context.ApplicationInstance = app;
528 req.SetEndOfSendNotification (end_of_send_cb, context);
531 // Ask application to service the request
535 IHttpAsyncHandler ihah = app;
536 if (context.Handler == null)
537 ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
540 //ihh.ProcessRequest (context);
541 IHttpExtendedHandler extHandler = context.Handler as IHttpExtendedHandler;
542 if (extHandler != null && !extHandler.IsCompleted)
544 if (context.Error is UnifyRequestException)
547 ihah.EndProcessRequest (null);
549 IHttpHandler ihh = app;
550 // IAsyncResult appiar = ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
551 // ihah.EndProcessRequest (appiar);
552 ihh.ProcessRequest (context);
555 HttpApplicationFactory.Recycle (app);
559 static void EndOfSend (HttpWorkerRequest ignored1, object ignored2)
564 // ProcessRequest method is executed in the AppDomain of the application
567 // ProcessRequest does not guarantee that `wr' will be processed synchronously,
568 // the request can be queued and processed later.
570 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
571 public static void ProcessRequest (HttpWorkerRequest wr)
574 throw new ArgumentNullException ("wr");
576 // Queue our request, fetch the next available one from the queue
578 HttpWorkerRequest request = queue_manager.GetNextRequest (wr);
582 QueuePendingRequest (false);
583 RealProcessRequest (request);
588 // Callback to be invoked by IHttpAsyncHandler.BeginProcessRequest
590 static void request_processed (IAsyncResult iar)
592 HttpContext context = (HttpContext) iar.AsyncState;
594 context.Request.ReleaseResources ();
595 context.Response.ReleaseResources ();
600 [MonoNotSupported ("UnloadAppDomain is not supported")]
601 public static void UnloadAppDomain ()
603 throw new NotImplementedException ("UnloadAppDomain is not supported");
607 // Called when we are shutting down or we need to reload an application
608 // that has been modified (touch global.asax)
610 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
611 public static void UnloadAppDomain ()
614 // TODO: call ReleaseResources
616 domainUnloading = true;
617 HttpApplicationFactory.DisableWatchers ();
618 ThreadPool.QueueUserWorkItem (delegate {
620 ShutdownAppDomain ();
621 } catch (Exception e){
622 Console.Error.WriteLine (e);
628 // Shuts down the AppDomain
630 static void ShutdownAppDomain ()
632 queue_manager.Dispose ();
633 // This will call Session_End if needed.
634 InternalCache.InvokePrivateCallbacks ();
635 // Kill our application.
636 HttpApplicationFactory.Dispose ();
637 ThreadPool.QueueUserWorkItem (delegate {
644 static void DoUnload ()
647 // No unload support for appdomains under Grasshopper
649 AppDomain.Unload (AppDomain.CurrentDomain);
653 static string content503 = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" +
654 "<html><head>\n<title>503 Server Unavailable</title>\n</head><body>\n" +
655 "<h1>Server Unavailable</h1>\n" +
658 static void FinishWithException (HttpWorkerRequest wr, HttpException e)
660 int code = e.GetHttpCode ();
661 wr.SendStatus (code, HttpWorkerRequest.GetStatusDescription (code));
662 wr.SendUnknownResponseHeader ("Connection", "close");
663 Encoding enc = Encoding.ASCII;
664 wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
665 string msg = e.GetHtmlErrorMessage ();
666 byte [] contentBytes = enc.GetBytes (msg);
667 wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
668 wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
669 wr.FlushResponse (true);
670 wr.CloseConnection ();
671 HttpApplication.requests_total_counter.Increment ();
675 // This is called from the QueueManager if a request
676 // can not be processed (load, no resources, or
677 // appdomain unload).
679 static internal void FinishUnavailable (HttpWorkerRequest wr)
681 wr.SendStatus (503, "Service unavailable");
682 wr.SendUnknownResponseHeader ("Connection", "close");
683 Encoding enc = Encoding.ASCII;
684 wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
685 byte [] contentBytes = enc.GetBytes (content503);
686 wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
687 wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
688 wr.FlushResponse (true);
689 wr.CloseConnection ();
690 HttpApplication.requests_total_counter.Increment ();
693 [AspNetHostingPermissionAttribute(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Unrestricted)]
694 [MonoDocumentationNote ("Always returns null on Mono")]
695 public static NamedPermissionSet GetNamedPermissionSet ()
701 static internal void WritePreservationFile (Assembly asm, string genericNameBase)
704 throw new ArgumentNullException ("asm");
705 if (String.IsNullOrEmpty (genericNameBase))
706 throw new ArgumentNullException ("genericNameBase");
708 string compiled = Path.Combine (AppDomain.CurrentDomain.SetupInformation.DynamicBase,
709 genericNameBase + ".compiled");
710 PreservationFile pf = new PreservationFile ();
712 pf.VirtualPath = String.Concat ("/", genericNameBase, "/");
714 AssemblyName an = asm.GetName ();
715 pf.Assembly = an.Name;
716 pf.ResultType = BuildResultTypeCode.TopLevelAssembly;
718 } catch (Exception ex) {
719 throw new HttpException (
720 String.Format ("Failed to write preservation file {0}", genericNameBase + ".compiled"),
725 static Assembly ResolveAssemblyHandler(object sender, ResolveEventArgs e)
727 AssemblyName an = new AssemblyName (e.Name);
728 string dynamic_base = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
729 string compiled = Path.Combine (dynamic_base, an.Name + ".compiled");
732 if (!File.Exists (compiled)) {
733 string fn = an.FullName;
734 if (!RegisteredAssemblies.Find ((uint)fn.GetHashCode (), fn, out asmPath))
739 pf = new PreservationFile (compiled);
740 } catch (Exception ex) {
741 throw new HttpException (
742 String.Format ("Failed to read preservation file {0}", an.Name + ".compiled"),
745 asmPath = Path.Combine (dynamic_base, pf.Assembly + ".dll");
748 if (String.IsNullOrEmpty (asmPath))
753 ret = Assembly.LoadFrom (asmPath);
754 } catch (Exception) {
761 internal static void EnableAssemblyMapping (bool enable)
763 lock (assemblyMappingLock) {
764 if (assemblyMappingEnabled == enable)
767 AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (ResolveAssemblyHandler);
769 AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler (ResolveAssemblyHandler);
770 assemblyMappingEnabled = enable;
773 #endif // #if !TARGET_J2EE
775 internal static TraceManager TraceManager {
777 return trace_manager;