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.Reflection;
39 using System.Security;
40 using System.Security.Permissions;
41 using System.Web.Caching;
42 using System.Web.Configuration;
43 using System.Web.Management;
45 using System.Web.Util;
49 using System.Threading;
53 using System.CodeDom.Compiler;
54 using System.Web.Compilation;
59 // CAS - no InheritanceDemand here as the class is sealed
60 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
61 public sealed class HttpRuntime
63 static bool domainUnloading;
66 static QueueManager queue_manager { get { return _runtime._queue_manager; } }
67 static TraceManager trace_manager { get { return _runtime._trace_manager; } }
68 static Cache cache { get { return _runtime._cache; } }
69 static Cache internalCache { get { return _runtime._internalCache; } }
70 static WaitCallback do_RealProcessRequest;
72 QueueManager _queue_manager;
73 TraceManager _trace_manager;
79 WebConfigurationManager.Init ();
80 _queue_manager = new QueueManager ();
81 _trace_manager = new TraceManager ();
82 _cache = new Cache ();
83 _internalCache = new Cache();
84 _internalCache.DependencyCache = _cache;
87 static HttpRuntime _runtimeInstance {
89 HttpRuntime runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
91 lock (typeof (HttpRuntime)) {
92 runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
93 if (runtime == null) {
94 runtime = new HttpRuntime ();
95 AppDomain.CurrentDomain.SetData ("HttpRuntime", runtime);
101 static HttpRuntime _runtime
105 if (HttpContext.Current != null)
106 return HttpContext.Current.HttpRuntimeInstance;
108 return _runtimeInstance;
112 static QueueManager queue_manager;
113 static TraceManager trace_manager;
115 static Cache internalCache;
116 static WaitCallback do_RealProcessRequest;
117 static Exception initialException;
118 static bool firstRun;
119 static bool assemblyMappingEnabled;
120 static object assemblyMappingLock = new object ();
121 static object appOfflineLock = new object ();
123 public HttpRuntime ()
129 static HttpRuntime ()
134 WebConfigurationManager.Init ();
136 SettingsMappingManager.Init ();
138 } catch (Exception ex) {
139 initialException = ex;
142 // The classes in whose constructors exceptions may be thrown, should be handled the same way QueueManager
143 // and TraceManager are below. The constructors themselves MUST NOT throw any exceptions - we MUST be sure
144 // the objects are created here. The exceptions will be dealt with below, in RealProcessRequest.
145 queue_manager = new QueueManager ();
146 if (queue_manager.HasException)
147 initialException = queue_manager.InitialException;
149 trace_manager = new TraceManager ();
150 if (trace_manager.HasException)
151 initialException = trace_manager.InitialException;
153 cache = new Cache ();
154 internalCache = new Cache ();
155 internalCache.DependencyCache = internalCache;
157 do_RealProcessRequest = new WaitCallback (RealProcessRequest);
160 #region AppDomain handling
161 internal static bool DomainUnloading {
162 get { return domainUnloading; }
166 // http://radio.weblogs.com/0105476/stories/2002/07/12/executingAspxPagesWithoutAWebServer.html
168 public static string AppDomainAppId {
169 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
172 // This value should not change across invocations
174 string dirname = (string) AppDomain.CurrentDomain.GetData (".appId");
175 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
176 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
182 // Physical directory for the application
183 public static string AppDomainAppPath {
185 string dirname = (string) AppDomain.CurrentDomain.GetData (".appPath");
186 if (SecurityManager.SecurityEnabled) {
187 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
193 public static string AppDomainAppVirtualPath {
195 return (string) AppDomain.CurrentDomain.GetData (".appVPath");
199 public static string AppDomainId {
200 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
202 return (string) AppDomain.CurrentDomain.GetData (".domainId");
206 public static string AspInstallDirectory {
208 string dirname = (string) AppDomain.CurrentDomain.GetData (".hostingInstallDir");
209 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
210 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
217 static string _actual_bin_directory;
218 public static string BinDirectory {
220 if (_actual_bin_directory == null) {
221 string[] parts = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split (';');
222 string mypath = AppDomainAppPath;
225 foreach (string p in parts) {
226 tmp = Path.Combine (mypath, p);
227 if (Directory.Exists (tmp)) {
228 _actual_bin_directory = tmp;
233 if (_actual_bin_directory == null)
234 _actual_bin_directory = Path.Combine (mypath, "bin");
236 if (_actual_bin_directory [_actual_bin_directory.Length - 1] != Path.DirectorySeparatorChar)
237 _actual_bin_directory += Path.DirectorySeparatorChar;
240 if (SecurityManager.SecurityEnabled)
241 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, _actual_bin_directory).Demand ();
243 return _actual_bin_directory;
247 public static Cache Cache {
253 internal static Cache InternalCache {
255 return internalCache;
259 public static string ClrInstallDirectory {
261 string dirname = Path.GetDirectoryName (typeof (Object).Assembly.Location);
262 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
263 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
269 public static string CodegenDir {
271 string dirname = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
272 if (SecurityManager.SecurityEnabled) {
273 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
279 public static bool IsOnUNCShare {
280 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
282 return RuntimeHelpers.IsUncShare;
286 public static string MachineConfigurationDirectory {
288 string dirname = Path.GetDirectoryName (ICalls.GetMachineConfigPath ());
289 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
290 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
297 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
298 public static void Close ()
300 // Remove all items from cache.
303 internal static HttpWorkerRequest QueuePendingRequest (bool started_internally)
305 HttpWorkerRequest next = queue_manager.GetNextRequest (null);
309 if (!started_internally) {
310 next.StartedInternally = true;
311 ThreadPool.QueueUserWorkItem (do_RealProcessRequest, next);
318 static readonly string[] app_offline_files = {"app_offline.htm", "App_Offline.htm", "APP_OFFLINE.HTM"};
319 static string app_offline_file;
321 static bool AppIsOffline (HttpContext context)
323 if (!HttpApplicationFactory.ApplicationDisabled || app_offline_file == null)
326 HttpResponse response = context.Response;
328 response.ContentType = "text/html";
329 response.ExpiresAbsolute = DateTime.UtcNow;
330 response.StatusCode = 503;
331 response.TransmitFile (app_offline_file, true);
333 context.Request.ReleaseResources ();
334 context.Response.ReleaseResources ();
335 HttpContext.Current = null;
336 HttpApplication.requests_total_counter.Increment ();
341 static void AppOfflineFileRenamed (object sender, RenamedEventArgs args)
343 AppOfflineFileChanged (sender, args);
346 static void AppOfflineFileChanged (object sender, FileSystemEventArgs args)
348 lock (appOfflineLock) {
351 switch (args.ChangeType) {
352 case WatcherChangeTypes.Created:
353 case WatcherChangeTypes.Changed:
357 case WatcherChangeTypes.Deleted:
361 case WatcherChangeTypes.Renamed:
362 RenamedEventArgs rargs = args as RenamedEventArgs;
365 String.Compare (rargs.Name, "app_offline.htm", StringComparison.OrdinalIgnoreCase) == 0)
375 SetOfflineMode (offline, args.FullPath);
379 static void SetOfflineMode (bool offline, string filePath)
382 app_offline_file = null;
383 if (HttpApplicationFactory.ApplicationDisabled)
384 HttpRuntime.UnloadAppDomain ();
386 app_offline_file = filePath;
387 HttpApplicationFactory.DisableWatchers ();
388 HttpApplicationFactory.ApplicationDisabled = true;
389 InternalCache.InvokePrivateCallbacks ();
390 HttpApplicationFactory.Dispose ();
394 static void SetupOfflineWatch ()
396 lock (appOfflineLock) {
397 FileSystemEventHandler seh = new FileSystemEventHandler (AppOfflineFileChanged);
398 RenamedEventHandler reh = new RenamedEventHandler (AppOfflineFileRenamed);
400 string app_dir = AppDomainAppPath;
401 ArrayList watchers = new ArrayList ();
402 FileSystemWatcher watcher;
403 string offlineFile = null, tmp;
405 foreach (string f in app_offline_files) {
406 watcher = new FileSystemWatcher ();
407 watcher.Path = Path.GetDirectoryName (app_dir);
408 watcher.Filter = Path.GetFileName (f);
409 watcher.NotifyFilter |= NotifyFilters.Size;
410 watcher.Deleted += seh;
411 watcher.Changed += seh;
412 watcher.Created += seh;
413 watcher.Renamed += reh;
414 watcher.EnableRaisingEvents = true;
416 watchers.Add (watcher);
418 tmp = Path.Combine (app_dir, f);
419 if (File.Exists (tmp))
423 if (offlineFile != null)
424 SetOfflineMode (true, offlineFile);
429 static void RealProcessRequest (object o)
431 HttpWorkerRequest req = (HttpWorkerRequest) o;
432 bool started_internally = req.StartedInternally;
435 req = QueuePendingRequest (started_internally);
436 } while (started_internally && req != null);
439 static void Process (HttpWorkerRequest req)
442 HttpContext context = HttpContext.Current;
444 context = new HttpContext (req);
446 context.SetWorkerRequest (req);
448 HttpContext context = new HttpContext (req);
450 HttpContext.Current = context;
454 SetupOfflineWatch ();
456 if (initialException != null) {
457 FinishWithException (req, HttpException.NewWithCode ("Initial exception", initialException, WebEventCodes.RuntimeErrorRequestAbort));
462 if (AppIsOffline (context))
467 // Get application instance (create or reuse an instance of the correct class)
469 HttpApplication app = null;
472 app = HttpApplicationFactory.GetApplication (context);
473 } catch (Exception e) {
474 FinishWithException (req, HttpException.NewWithCode (String.Empty, e, WebEventCodes.RuntimeErrorRequestAbort));
480 context.Request.ReleaseResources ();
481 context.Response.ReleaseResources ();
482 HttpContext.Current = null;
484 context.ApplicationInstance = app;
487 // Ask application to service the request
491 IHttpAsyncHandler ihah = app;
492 if (context.Handler == null)
493 ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
496 //ihh.ProcessRequest (context);
497 IHttpExtendedHandler extHandler = context.Handler as IHttpExtendedHandler;
498 if (extHandler != null && !extHandler.IsCompleted)
500 if (context.Error is UnifyRequestException)
503 ihah.EndProcessRequest (null);
505 IHttpHandler ihh = app;
506 // IAsyncResult appiar = ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
507 // ihah.EndProcessRequest (appiar);
508 ihh.ProcessRequest (context);
511 HttpApplicationFactory.Recycle (app);
516 // ProcessRequest method is executed in the AppDomain of the application
519 // ProcessRequest does not guarantee that `wr' will be processed synchronously,
520 // the request can be queued and processed later.
522 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
523 public static void ProcessRequest (HttpWorkerRequest wr)
526 throw new ArgumentNullException ("wr");
528 // Queue our request, fetch the next available one from the queue
530 HttpWorkerRequest request = queue_manager.GetNextRequest (wr);
534 QueuePendingRequest (false);
535 RealProcessRequest (request);
540 // Callback to be invoked by IHttpAsyncHandler.BeginProcessRequest
542 static void request_processed (IAsyncResult iar)
544 HttpContext context = (HttpContext) iar.AsyncState;
546 context.Request.ReleaseResources ();
547 context.Response.ReleaseResources ();
552 [MonoNotSupported ("UnloadAppDomain is not supported")]
553 public static void UnloadAppDomain ()
555 throw new NotImplementedException ("UnloadAppDomain is not supported");
559 // Called when we are shutting down or we need to reload an application
560 // that has been modified (touch global.asax)
562 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
563 public static void UnloadAppDomain ()
566 // TODO: call ReleaseResources
568 domainUnloading = true;
569 ThreadPool.QueueUserWorkItem (new WaitCallback (ShutdownAppDomain), null);
573 // Shuts down the AppDomain
575 static void ShutdownAppDomain (object args)
577 queue_manager.Dispose ();
578 // This will call Session_End if needed.
579 InternalCache.InvokePrivateCallbacks ();
580 // Kill our application.
581 HttpApplicationFactory.Dispose ();
582 ThreadPool.QueueUserWorkItem (new WaitCallback (DoUnload), null);
585 static void DoUnload (object state)
588 // No unload support for appdomains under Grasshopper
590 AppDomain.Unload (AppDomain.CurrentDomain);
594 static string content503 = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" +
595 "<html><head>\n<title>503 Server Unavailable</title>\n</head><body>\n" +
596 "<h1>Server Unavailable</h1>\n" +
599 static void FinishWithException (HttpWorkerRequest wr, HttpException e)
601 int code = e.GetHttpCode ();
602 wr.SendStatus (code, HttpWorkerRequest.GetStatusDescription (code));
603 wr.SendUnknownResponseHeader ("Connection", "close");
604 Encoding enc = Encoding.ASCII;
605 wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
606 string msg = e.GetHtmlErrorMessage ();
607 byte [] contentBytes = enc.GetBytes (msg);
608 wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
609 wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
610 wr.FlushResponse (true);
611 wr.CloseConnection ();
612 HttpApplication.requests_total_counter.Increment ();
616 // This is called from the QueueManager if a request
617 // can not be processed (load, no resources, or
618 // appdomain unload).
620 static internal void FinishUnavailable (HttpWorkerRequest wr)
622 wr.SendStatus (503, "Service unavailable");
623 wr.SendUnknownResponseHeader ("Connection", "close");
624 Encoding enc = Encoding.ASCII;
625 wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
626 byte [] contentBytes = enc.GetBytes (content503);
627 wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
628 wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
629 wr.FlushResponse (true);
630 wr.CloseConnection ();
631 HttpApplication.requests_total_counter.Increment ();
635 static internal void WritePreservationFile (Assembly asm, string genericNameBase)
638 throw new ArgumentNullException ("asm");
639 if (String.IsNullOrEmpty (genericNameBase))
640 throw new ArgumentNullException ("genericNameBase");
642 string compiled = Path.Combine (AppDomain.CurrentDomain.SetupInformation.DynamicBase,
643 genericNameBase + ".compiled");
644 PreservationFile pf = new PreservationFile ();
646 pf.VirtualPath = String.Concat ("/", genericNameBase, "/");
648 AssemblyName an = asm.GetName ();
649 pf.Assembly = an.Name;
650 pf.ResultType = BuildResultTypeCode.TopLevelAssembly;
652 } catch (Exception ex) {
653 throw new HttpException (
654 String.Format ("Failed to write preservation file {0}", genericNameBase + ".compiled"),
659 static Assembly ResolveAssemblyHandler(object sender, ResolveEventArgs e)
661 AssemblyName an = new AssemblyName (e.Name);
662 string dynamic_base = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
663 string compiled = Path.Combine (dynamic_base, an.Name + ".compiled");
665 if (!File.Exists (compiled))
670 pf = new PreservationFile (compiled);
671 } catch (Exception ex) {
672 throw new HttpException (
673 String.Format ("Failed to read preservation file {0}", an.Name + ".compiled"),
679 string asmPath = Path.Combine (dynamic_base, pf.Assembly + ".dll");
680 ret = Assembly.LoadFrom (asmPath);
681 } catch (Exception) {
688 internal static void EnableAssemblyMapping (bool enable)
690 lock (assemblyMappingLock) {
691 if (assemblyMappingEnabled == enable)
694 AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (ResolveAssemblyHandler);
696 AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler (ResolveAssemblyHandler);
697 assemblyMappingEnabled = enable;
700 #endif // #if !TARGET_J2EE
702 internal static TraceManager TraceManager {
704 return trace_manager;