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;
44 using System.Web.Util;
48 using System.Threading;
52 using System.CodeDom.Compiler;
53 using System.Web.Compilation;
58 // CAS - no InheritanceDemand here as the class is sealed
59 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
60 public sealed class HttpRuntime
62 static bool caseInsensitive;
63 static bool runningOnWindows;
65 static string monoVersion;
68 static QueueManager queue_manager { get { return _runtime._queue_manager; } }
69 static TraceManager trace_manager { get { return _runtime._trace_manager; } }
70 static Cache cache { get { return _runtime._cache; } }
71 static Cache internalCache { get { return _runtime._internalCache; } }
72 static WaitCallback do_RealProcessRequest;
74 QueueManager _queue_manager;
75 TraceManager _trace_manager;
81 WebConfigurationManager.Init ();
82 _queue_manager = new QueueManager ();
83 _trace_manager = new TraceManager ();
84 _cache = new Cache ();
85 _internalCache = new Cache();
86 _internalCache.DependencyCache = _cache;
89 static HttpRuntime _runtimeInstance {
91 HttpRuntime runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
93 lock (typeof (HttpRuntime)) {
94 runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
95 if (runtime == null) {
96 runtime = new HttpRuntime ();
97 AppDomain.CurrentDomain.SetData ("HttpRuntime", runtime);
103 static HttpRuntime _runtime
107 if (HttpContext.Current != null)
108 return HttpContext.Current.HttpRuntimeInstance;
110 return _runtimeInstance;
114 static QueueManager queue_manager;
115 static TraceManager trace_manager;
117 static Cache internalCache;
118 static WaitCallback do_RealProcessRequest;
119 static Exception initialException;
120 static bool firstRun;
121 static bool assemblyMappingEnabled;
122 static object assemblyMappingLock = new object ();
123 static object appOfflineLock = new object ();
125 public HttpRuntime ()
131 static HttpRuntime ()
133 PlatformID pid = Environment.OSVersion.Platform;
134 runningOnWindows = ((int) pid != 128 && pid != PlatformID.Unix && pid != PlatformID.MacOSX);
136 if (runningOnWindows) {
137 caseInsensitive = true;
138 if (AppDomainAppPath != null)
139 isunc = new Uri (AppDomainAppPath).IsUnc;
141 string mono_iomap = Environment.GetEnvironmentVariable ("MONO_IOMAP");
142 if (mono_iomap != null) {
143 if (mono_iomap == "all")
144 caseInsensitive = true;
146 string[] parts = mono_iomap.Split (':');
147 foreach (string p in parts) {
148 if (p == "all" || p == "case") {
149 caseInsensitive = true;
157 Type monoRuntime = Type.GetType ("Mono.Runtime", false);
159 if (monoRuntime != null) {
160 MethodInfo mi = monoRuntime.GetMethod ("GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic);
162 monoVersion = mi.Invoke (null, new object [0]) as string;
165 if (monoVersion == null)
166 monoVersion = Environment.Version.ToString ();
171 WebConfigurationManager.Init ();
173 SettingsMappingManager.Init ();
175 } catch (Exception ex) {
176 initialException = ex;
179 // The classes in whose constructors exceptions may be thrown, should be handled the same way QueueManager
180 // and TraceManager are below. The constructors themselves MUST NOT throw any exceptions - we MUST be sure
181 // the objects are created here. The exceptions will be dealt with below, in RealProcessRequest.
182 queue_manager = new QueueManager ();
183 if (queue_manager.HasException)
184 initialException = queue_manager.InitialException;
186 trace_manager = new TraceManager ();
187 if (trace_manager.HasException)
188 initialException = trace_manager.InitialException;
190 cache = new Cache ();
191 internalCache = new Cache ();
192 internalCache.DependencyCache = internalCache;
194 do_RealProcessRequest = new WaitCallback (RealProcessRequest);
197 #region AppDomain handling
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)]
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 ();
330 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
331 public static void Close ()
333 // Remove all items from cache.
336 internal static HttpWorkerRequest QueuePendingRequest (bool started_internally)
338 HttpWorkerRequest next = queue_manager.GetNextRequest (null);
342 if (!started_internally) {
343 next.StartedInternally = true;
344 ThreadPool.QueueUserWorkItem (do_RealProcessRequest, next);
351 static readonly string[] app_offline_files = {"app_offline.htm", "App_Offline.htm", "APP_OFFLINE.HTM"};
352 static string app_offline_file;
354 static bool AppIsOffline (HttpContext context)
356 if (!HttpApplicationFactory.ApplicationDisabled || app_offline_file == null)
359 HttpResponse response = context.Response;
361 response.ContentType = "text/html";
362 response.ExpiresAbsolute = DateTime.UtcNow;
363 response.StatusCode = 503;
364 response.TransmitFile (app_offline_file, true);
366 context.Request.ReleaseResources ();
367 context.Response.ReleaseResources ();
368 HttpContext.Current = null;
369 HttpApplication.requests_total_counter.Increment ();
374 static void AppOfflineFileRenamed (object sender, RenamedEventArgs args)
376 AppOfflineFileChanged (sender, args);
379 static void AppOfflineFileChanged (object sender, FileSystemEventArgs args)
381 lock (appOfflineLock) {
384 switch (args.ChangeType) {
385 case WatcherChangeTypes.Created:
386 case WatcherChangeTypes.Changed:
390 case WatcherChangeTypes.Deleted:
394 case WatcherChangeTypes.Renamed:
395 RenamedEventArgs rargs = args as RenamedEventArgs;
398 String.Compare (rargs.Name, "app_offline.htm", StringComparison.OrdinalIgnoreCase) == 0)
408 SetOfflineMode (offline, args.FullPath);
412 static void SetOfflineMode (bool offline, string filePath)
415 app_offline_file = null;
416 if (HttpApplicationFactory.ApplicationDisabled)
417 HttpRuntime.UnloadAppDomain ();
419 app_offline_file = filePath;
420 HttpApplicationFactory.DisableWatchers ();
421 HttpApplicationFactory.ApplicationDisabled = true;
422 InternalCache.InvokePrivateCallbacks ();
423 HttpApplicationFactory.Dispose ();
427 static void SetupOfflineWatch ()
429 lock (appOfflineLock) {
430 FileSystemEventHandler seh = new FileSystemEventHandler (AppOfflineFileChanged);
431 RenamedEventHandler reh = new RenamedEventHandler (AppOfflineFileRenamed);
433 string app_dir = AppDomainAppPath;
434 ArrayList watchers = new ArrayList ();
435 FileSystemWatcher watcher;
436 string offlineFile = null, tmp;
438 foreach (string f in app_offline_files) {
439 watcher = new FileSystemWatcher ();
440 watcher.Path = Path.GetDirectoryName (app_dir);
441 watcher.Filter = Path.GetFileName (f);
442 watcher.NotifyFilter |= NotifyFilters.Size;
443 watcher.Deleted += seh;
444 watcher.Changed += seh;
445 watcher.Created += seh;
446 watcher.Renamed += reh;
447 watcher.EnableRaisingEvents = true;
449 watchers.Add (watcher);
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 HttpWorkerRequest req = (HttpWorkerRequest) o;
465 bool started_internally = req.StartedInternally;
468 req = QueuePendingRequest (started_internally);
469 } while (started_internally && req != null);
472 static void Process (HttpWorkerRequest req)
475 HttpContext context = HttpContext.Current;
477 context = new HttpContext (req);
479 context.SetWorkerRequest (req);
481 HttpContext context = new HttpContext (req);
483 HttpContext.Current = context;
487 SetupOfflineWatch ();
489 if (initialException != null) {
490 FinishWithException (req, new HttpException ("Initial exception", initialException));
495 if (AppIsOffline (context))
500 // Get application instance (create or reuse an instance of the correct class)
502 HttpApplication app = null;
505 app = HttpApplicationFactory.GetApplication (context);
506 } catch (Exception e) {
507 FinishWithException (req, new HttpException ("", e));
513 context.Request.ReleaseResources ();
514 context.Response.ReleaseResources ();
515 HttpContext.Current = null;
517 context.ApplicationInstance = app;
520 // Ask application to service the request
524 IHttpAsyncHandler ihah = app;
525 if (context.Handler == null)
526 ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
529 //ihh.ProcessRequest (context);
530 IHttpExtendedHandler extHandler = context.Handler as IHttpExtendedHandler;
531 if (extHandler != null && !extHandler.IsCompleted)
533 if (context.Error is UnifyRequestException)
536 ihah.EndProcessRequest (null);
538 IHttpHandler ihh = app;
539 // IAsyncResult appiar = ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
540 // ihah.EndProcessRequest (appiar);
541 ihh.ProcessRequest (context);
544 HttpApplicationFactory.Recycle (app);
549 // ProcessRequest method is executed in the AppDomain of the application
552 // ProcessRequest does not guarantee that `wr' will be processed synchronously,
553 // the request can be queued and processed later.
555 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
556 public static void ProcessRequest (HttpWorkerRequest wr)
559 throw new ArgumentNullException ("wr");
561 // Queue our request, fetch the next available one from the queue
563 HttpWorkerRequest request = queue_manager.GetNextRequest (wr);
567 QueuePendingRequest (false);
568 RealProcessRequest (request);
573 // Callback to be invoked by IHttpAsyncHandler.BeginProcessRequest
575 static void request_processed (IAsyncResult iar)
577 HttpContext context = (HttpContext) iar.AsyncState;
579 context.Request.ReleaseResources ();
580 context.Response.ReleaseResources ();
585 [MonoNotSupported ("UnloadAppDomain is not supported")]
586 public static void UnloadAppDomain ()
588 throw new NotImplementedException ("UnloadAppDomain is not supported");
592 // Called when we are shutting down or we need to reload an application
593 // that has been modified (touch global.asax)
595 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
596 public static void UnloadAppDomain ()
599 // TODO: call ReleaseResources
601 ThreadPool.QueueUserWorkItem (new WaitCallback (ShutdownAppDomain), null);
605 // Shuts down the AppDomain
607 static void ShutdownAppDomain (object args)
609 queue_manager.Dispose ();
610 // This will call Session_End if needed.
611 InternalCache.InvokePrivateCallbacks ();
612 // Kill our application.
613 HttpApplicationFactory.Dispose ();
614 ThreadPool.QueueUserWorkItem (new WaitCallback (DoUnload), null);
617 static void DoUnload (object state)
620 // No unload support for appdomains under Grasshopper
622 AppDomain.Unload (AppDomain.CurrentDomain);
626 static string content503 = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" +
627 "<html><head>\n<title>503 Server Unavailable</title>\n</head><body>\n" +
628 "<h1>Server Unavailable</h1>\n" +
631 static void FinishWithException (HttpWorkerRequest wr, HttpException e)
633 int code = e.GetHttpCode ();
634 wr.SendStatus (code, HttpWorkerRequest.GetStatusDescription (code));
635 wr.SendUnknownResponseHeader ("Connection", "close");
636 Encoding enc = Encoding.ASCII;
637 wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
638 string msg = e.GetHtmlErrorMessage ();
639 byte [] contentBytes = enc.GetBytes (msg);
640 wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
641 wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
642 wr.FlushResponse (true);
643 wr.CloseConnection ();
644 HttpApplication.requests_total_counter.Increment ();
648 // This is called from the QueueManager if a request
649 // can not be processed (load, no resources, or
650 // appdomain unload).
652 static internal void FinishUnavailable (HttpWorkerRequest wr)
654 wr.SendStatus (503, "Service unavailable");
655 wr.SendUnknownResponseHeader ("Connection", "close");
656 Encoding enc = Encoding.ASCII;
657 wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
658 byte [] contentBytes = enc.GetBytes (content503);
659 wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
660 wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
661 wr.FlushResponse (true);
662 wr.CloseConnection ();
663 HttpApplication.requests_total_counter.Increment ();
667 static internal void WritePreservationFile (Assembly asm, string genericNameBase)
670 throw new ArgumentNullException ("asm");
671 if (String.IsNullOrEmpty (genericNameBase))
672 throw new ArgumentNullException ("genericNameBase");
674 string compiled = Path.Combine (AppDomain.CurrentDomain.SetupInformation.DynamicBase,
675 genericNameBase + ".compiled");
676 PreservationFile pf = new PreservationFile ();
678 pf.VirtualPath = String.Concat ("/", genericNameBase, "/");
680 AssemblyName an = asm.GetName ();
681 pf.Assembly = an.Name;
682 pf.ResultType = BuildResultTypeCode.TopLevelAssembly;
684 } catch (Exception ex) {
685 throw new HttpException (
686 String.Format ("Failed to write preservation file {0}", genericNameBase + ".compiled"),
691 static Assembly ResolveAssemblyHandler(object sender, ResolveEventArgs e)
693 AssemblyName an = new AssemblyName (e.Name);
694 string dynamic_base = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
695 string compiled = Path.Combine (dynamic_base, an.Name + ".compiled");
697 if (!File.Exists (compiled))
702 pf = new PreservationFile (compiled);
703 } catch (Exception ex) {
704 throw new HttpException (
705 String.Format ("Failed to read preservation file {0}", an.Name + ".compiled"),
711 string asmPath = Path.Combine (dynamic_base, pf.Assembly + ".dll");
712 ret = Assembly.LoadFrom (asmPath);
713 } catch (Exception) {
720 internal static void EnableAssemblyMapping (bool enable)
722 lock (assemblyMappingLock) {
723 if (assemblyMappingEnabled == enable)
726 AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (ResolveAssemblyHandler);
728 AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler (ResolveAssemblyHandler);
729 assemblyMappingEnabled = enable;
732 #endif // #if !TARGET_J2EE
734 internal static string MonoVersion {
735 get { return monoVersion; }
738 internal static bool RunningOnWindows {
739 get { return runningOnWindows; }
742 internal static bool CaseInsensitive {
743 get { return caseInsensitive; }
746 internal static bool IsDebuggingEnabled {
748 CompilationSection cs = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
756 internal static TraceManager TraceManager {
758 return trace_manager;