2 // System.Web.HttpRuntime.cs
5 // Miguel de Icaza (miguel@novell.com)
8 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 // TODO: Call HttpRequest.CloseInputStream when we finish a request, as we are using the IntPtr stream.
35 using System.Globalization;
36 using System.Collections;
37 using System.Reflection;
38 using System.Security;
39 using System.Security.Permissions;
40 using System.Web.Caching;
41 using System.Web.Configuration;
43 using System.Web.Util;
47 using System.Threading;
52 #if NET_2_0 && !TARGET_JVM
53 using System.CodeDom.Compiler;
54 using System.Web.Compilation;
57 namespace System.Web {
59 // CAS - no InheritanceDemand here as the class is sealed
60 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
61 public sealed class HttpRuntime {
62 static bool caseInsensitive;
63 static bool runningOnWindows;
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;
121 static bool assemblyMappingEnabled;
122 static object assemblyMappingLock = new object ();
123 static object appOfflineLock = new object ();
127 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
129 public HttpRuntime ()
135 static HttpRuntime ()
137 PlatformID pid = Environment.OSVersion.Platform;
138 runningOnWindows = ((int) pid != 128
140 && pid != PlatformID.Unix && pid != PlatformID.MacOSX
144 if (runningOnWindows) {
145 caseInsensitive = true;
146 isunc = new Uri (AppDomainAppPath).IsUnc;
148 string mono_iomap = Environment.GetEnvironmentVariable ("MONO_IOMAP");
149 if (mono_iomap != null) {
150 if (mono_iomap == "all")
151 caseInsensitive = true;
153 string[] parts = mono_iomap.Split (':');
154 foreach (string p in parts) {
155 if (p == "all" || p == "case") {
156 caseInsensitive = true;
168 WebConfigurationManager.Init ();
170 SettingsMappingManager.Init ();
172 } catch (Exception ex) {
173 initialException = ex;
177 // The classes in whose constructors exceptions may be thrown, should be handled the same way QueueManager
178 // and TraceManager are below. The constructors themselves MUST NOT throw any exceptions - we MUST be sure
179 // the objects are created here. The exceptions will be dealt with below, in RealProcessRequest.
180 queue_manager = new QueueManager ();
181 if (queue_manager.HasException)
182 initialException = queue_manager.InitialException;
184 trace_manager = new TraceManager ();
185 if (trace_manager.HasException)
186 initialException = trace_manager.InitialException;
188 cache = new Cache ();
189 internalCache = new Cache ();
190 internalCache.DependencyCache = cache;
192 do_RealProcessRequest = new WaitCallback (RealProcessRequest);
195 #region AppDomain handling
197 // http://radio.weblogs.com/0105476/stories/2002/07/12/executingAspxPagesWithoutAWebServer.html
199 public static string AppDomainAppId {
200 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
203 // This value should not change across invocations
205 string dirname = (string) AppDomain.CurrentDomain.GetData (".appId");
206 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
207 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
213 // Physical directory for the application
214 public static string AppDomainAppPath {
216 string dirname = (string) AppDomain.CurrentDomain.GetData (".appPath");
217 if (SecurityManager.SecurityEnabled) {
218 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
224 public static string AppDomainAppVirtualPath {
226 return (string) AppDomain.CurrentDomain.GetData (".appVPath");
230 public static string AppDomainId {
231 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
233 return (string) AppDomain.CurrentDomain.GetData (".domainId");
237 public static string AspInstallDirectory {
239 string dirname = (string) AppDomain.CurrentDomain.GetData (".hostingInstallDir");
240 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
241 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
248 static string _actual_bin_directory;
249 public static string BinDirectory {
251 if (_actual_bin_directory == null) {
252 string[] parts = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split (';');
253 string mypath = AppDomainAppPath;
256 foreach (string p in parts) {
257 tmp = Path.Combine (mypath, p);
258 if (Directory.Exists (tmp)) {
259 _actual_bin_directory = tmp;
264 if (_actual_bin_directory == null)
265 _actual_bin_directory = Path.Combine (mypath, "bin");
267 if (_actual_bin_directory [_actual_bin_directory.Length - 1] != Path.DirectorySeparatorChar)
268 _actual_bin_directory += Path.DirectorySeparatorChar;
271 if (SecurityManager.SecurityEnabled)
272 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, _actual_bin_directory).Demand ();
274 return _actual_bin_directory;
278 public static Cache Cache {
284 internal static Cache InternalCache {
286 return internalCache;
290 public static string ClrInstallDirectory {
292 string dirname = Path.GetDirectoryName (typeof (Object).Assembly.Location);
293 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
294 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
300 public static string CodegenDir {
302 string dirname = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
303 if (SecurityManager.SecurityEnabled) {
304 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
310 public static bool IsOnUNCShare {
311 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
317 public static string MachineConfigurationDirectory {
319 string dirname = Path.GetDirectoryName (ICalls.GetMachineConfigPath ());
320 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
321 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
328 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
329 public static void Close ()
331 // Remove all items from cache.
334 static void QueuePendingRequests ()
336 HttpWorkerRequest request = queue_manager.GetNextRequest (null);
339 ThreadPool.QueueUserWorkItem (do_RealProcessRequest, request);
344 static readonly string[] app_offline_files = {"app_offline.htm", "App_Offline.htm", "APP_OFFLINE.HTM"};
345 static string app_offline_file;
347 static bool AppIsOffline (HttpContext context)
349 if (!HttpApplicationFactory.ApplicationDisabled || app_offline_file == null)
352 HttpResponse response = context.Response;
354 response.ContentType = "text/html";
355 response.ExpiresAbsolute = DateTime.UtcNow;
356 response.StatusCode = 503;
357 response.TransmitFile (app_offline_file, true);
359 context.Request.ReleaseResources ();
360 context.Response.ReleaseResources ();
361 HttpContext.Current = null;
362 HttpApplication.requests_total_counter.Increment ();
367 static void AppOfflineFileRenamed (object sender, RenamedEventArgs args)
369 AppOfflineFileChanged (sender, args);
372 static void AppOfflineFileChanged (object sender, FileSystemEventArgs args)
374 lock (appOfflineLock) {
377 switch (args.ChangeType) {
378 case WatcherChangeTypes.Created:
379 case WatcherChangeTypes.Changed:
383 case WatcherChangeTypes.Deleted:
387 case WatcherChangeTypes.Renamed:
388 RenamedEventArgs rargs = args as RenamedEventArgs;
391 String.Compare (rargs.Name, "app_offline.htm", StringComparison.OrdinalIgnoreCase) == 0)
401 SetOfflineMode (offline, args.FullPath);
405 static void SetOfflineMode (bool offline, string filePath)
408 app_offline_file = null;
409 if (HttpApplicationFactory.ApplicationDisabled)
410 HttpRuntime.UnloadAppDomain ();
412 app_offline_file = filePath;
413 HttpApplicationFactory.DisableWatchers ();
414 HttpApplicationFactory.ApplicationDisabled = true;
415 InternalCache.InvokePrivateCallbacks ();
416 HttpApplicationFactory.Dispose ();
420 static void SetupOfflineWatch ()
422 lock (appOfflineLock) {
423 FileSystemEventHandler seh = new FileSystemEventHandler (AppOfflineFileChanged);
424 RenamedEventHandler reh = new RenamedEventHandler (AppOfflineFileRenamed);
426 string app_dir = AppDomainAppPath;
427 ArrayList watchers = new ArrayList ();
428 FileSystemWatcher watcher;
429 string offlineFile = null, tmp;
431 foreach (string f in app_offline_files) {
432 watcher = new FileSystemWatcher ();
433 watcher.Path = Path.GetDirectoryName (app_dir);
434 watcher.Filter = Path.GetFileName (f);
435 watcher.NotifyFilter |= NotifyFilters.Size;
436 watcher.Deleted += seh;
437 watcher.Changed += seh;
438 watcher.Created += seh;
439 watcher.Renamed += reh;
440 watcher.EnableRaisingEvents = true;
442 watchers.Add (watcher);
444 tmp = Path.Combine (app_dir, f);
445 if (File.Exists (tmp))
449 if (offlineFile != null)
450 SetOfflineMode (true, offlineFile);
456 static void RealProcessRequest (object o)
459 HttpContext context = HttpContext.Current;
461 context = new HttpContext ((HttpWorkerRequest) o);
463 context.SetWorkerRequest ((HttpWorkerRequest) o);
465 HttpContext context = new HttpContext ((HttpWorkerRequest) o);
467 HttpContext.Current = context;
472 SetupOfflineWatch ();
475 if (initialException != null) {
476 FinishWithException ((HttpWorkerRequest) o, new HttpException ("Initial exception", initialException));
482 if (AppIsOffline (context))
488 // Get application instance (create or reuse an instance of the correct class)
490 HttpApplication app = null;
493 app = HttpApplicationFactory.GetApplication (context);
494 } catch (Exception e) {
495 FinishWithException ((HttpWorkerRequest) o, new HttpException ("", e));
501 context.Request.ReleaseResources ();
502 context.Response.ReleaseResources ();
503 HttpContext.Current = null;
505 context.ApplicationInstance = app;
508 // Ask application to service the request
512 IHttpAsyncHandler ihah = app;
513 if (context.Handler == null)
514 ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
517 //ihh.ProcessRequest (context);
518 IHttpExtendedHandler extHandler = context.Handler as IHttpExtendedHandler;
519 if (extHandler != null && !extHandler.IsCompleted)
521 if (context.Error is UnifyRequestException)
524 ihah.EndProcessRequest (null);
526 IHttpHandler ihh = app;
527 // IAsyncResult appiar = ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
528 // ihah.EndProcessRequest (appiar);
529 ihh.ProcessRequest (context);
532 HttpApplicationFactory.Recycle (app);
535 QueuePendingRequests ();
539 // ProcessRequest method is executed in the AppDomain of the application
542 // ProcessRequest does not guarantee that `wr' will be processed synchronously,
543 // the request can be queued and processed later.
545 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
546 public static void ProcessRequest (HttpWorkerRequest wr)
549 throw new ArgumentNullException ("wr");
551 // Queue our request, fetch the next available one from the queue
553 HttpWorkerRequest request = queue_manager.GetNextRequest (wr);
557 RealProcessRequest (request);
562 // Callback to be invoked by IHttpAsyncHandler.BeginProcessRequest
564 static void request_processed (IAsyncResult iar)
566 HttpContext context = (HttpContext) iar.AsyncState;
568 context.Request.ReleaseResources ();
569 context.Response.ReleaseResources ();
574 [MonoNotSupported ("UnloadAppDomain is not supported")]
575 public static void UnloadAppDomain ()
577 throw new NotImplementedException ("UnloadAppDomain is not supported");
581 // Called when we are shutting down or we need to reload an application
582 // that has been modified (touch global.asax)
584 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
585 public static void UnloadAppDomain ()
588 // TODO: call ReleaseResources
590 ThreadPool.QueueUserWorkItem (new WaitCallback (ShutdownAppDomain), null);
594 // Shuts down the AppDomain
596 static void ShutdownAppDomain (object args)
598 queue_manager.Dispose ();
599 // This will call Session_End if needed.
600 InternalCache.InvokePrivateCallbacks ();
601 // Kill our application.
602 HttpApplicationFactory.Dispose ();
603 ThreadPool.QueueUserWorkItem (new WaitCallback (DoUnload), null);
606 static void DoUnload (object state)
608 if (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") == null)
609 System.Web.Hosting.ApplicationHost.ClearDynamicBaseDirectory (
610 AppDomain.CurrentDomain.SetupInformation.DynamicBase
613 // No unload support for appdomains under Grasshopper
615 AppDomain.Unload (AppDomain.CurrentDomain);
619 static string content503 = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" +
620 "<html><head>\n<title>503 Server Unavailable</title>\n</head><body>\n" +
621 "<h1>Server Unavailable</h1>\n" +
624 static void FinishWithException (HttpWorkerRequest wr, HttpException e)
626 int code = e.GetHttpCode ();
627 wr.SendStatus (code, HttpWorkerRequest.GetStatusDescription (code));
628 wr.SendUnknownResponseHeader ("Connection", "close");
629 Encoding enc = Encoding.ASCII;
630 wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
631 string msg = e.GetHtmlErrorMessage ();
632 byte [] contentBytes = enc.GetBytes (msg);
633 wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
634 wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
635 wr.FlushResponse (true);
636 wr.CloseConnection ();
637 HttpApplication.requests_total_counter.Increment ();
641 // This is called from the QueueManager if a request
642 // can not be processed (load, no resources, or
643 // appdomain unload).
645 static internal void FinishUnavailable (HttpWorkerRequest wr)
647 wr.SendStatus (503, "Service unavailable");
648 wr.SendUnknownResponseHeader ("Connection", "close");
649 Encoding enc = Encoding.ASCII;
650 wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
651 byte [] contentBytes = enc.GetBytes (content503);
652 wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
653 wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
654 wr.FlushResponse (true);
655 wr.CloseConnection ();
656 HttpApplication.requests_total_counter.Increment ();
661 static internal void WritePreservationFile (Assembly asm, string genericNameBase)
664 throw new ArgumentNullException ("asm");
665 if (String.IsNullOrEmpty (genericNameBase))
666 throw new ArgumentNullException ("genericNameBase");
668 string compiled = Path.Combine (AppDomain.CurrentDomain.SetupInformation.DynamicBase,
669 genericNameBase + ".compiled");
670 PreservationFile pf = new PreservationFile ();
672 pf.VirtualPath = String.Concat ("/", genericNameBase, "/");
674 AssemblyName an = asm.GetName ();
675 pf.Assembly = an.Name;
676 pf.ResultType = BuildResultTypeCode.TopLevelAssembly;
678 } catch (Exception ex) {
679 throw new HttpException (
680 String.Format ("Failed to write preservation file {0}", genericNameBase + ".compiled"),
685 static Assembly ResolveAssemblyHandler(object sender, ResolveEventArgs e)
687 AssemblyName an = new AssemblyName (e.Name);
688 string dynamic_base = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
689 string compiled = Path.Combine (dynamic_base, an.Name + ".compiled");
691 if (!File.Exists (compiled))
696 pf = new PreservationFile (compiled);
697 } catch (Exception ex) {
698 throw new HttpException (
699 String.Format ("Failed to read preservation file {0}", an.Name + ".compiled"),
705 string asmPath = Path.Combine (dynamic_base, pf.Assembly + ".dll");
706 ret = Assembly.LoadFrom (asmPath);
707 } catch (Exception) {
714 internal static void EnableAssemblyMapping (bool enable)
716 lock (assemblyMappingLock) {
717 if (assemblyMappingEnabled == enable)
720 AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (ResolveAssemblyHandler);
722 AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler (ResolveAssemblyHandler);
725 #endif // #if !TARGET_J2EE
727 internal static bool RunningOnWindows {
728 get { return runningOnWindows; }
731 internal static bool CaseInsensitive {
732 get { return caseInsensitive; }
736 internal static TraceManager TraceManager {
738 return trace_manager;