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 domainUnloading;
65 static QueueManager queue_manager { get { return _runtime._queue_manager; } }
66 static TraceManager trace_manager { get { return _runtime._trace_manager; } }
67 static Cache cache { get { return _runtime._cache; } }
68 static Cache internalCache { get { return _runtime._internalCache; } }
69 static WaitCallback do_RealProcessRequest;
71 QueueManager _queue_manager;
72 TraceManager _trace_manager;
78 WebConfigurationManager.Init ();
79 _queue_manager = new QueueManager ();
80 _trace_manager = new TraceManager ();
81 _cache = new Cache ();
82 _internalCache = new Cache();
83 _internalCache.DependencyCache = _cache;
86 static HttpRuntime _runtimeInstance {
88 HttpRuntime runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
90 lock (typeof (HttpRuntime)) {
91 runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
92 if (runtime == null) {
93 runtime = new HttpRuntime ();
94 AppDomain.CurrentDomain.SetData ("HttpRuntime", runtime);
100 static HttpRuntime _runtime
104 if (HttpContext.Current != null)
105 return HttpContext.Current.HttpRuntimeInstance;
107 return _runtimeInstance;
111 static QueueManager queue_manager;
112 static TraceManager trace_manager;
114 static Cache internalCache;
115 static WaitCallback do_RealProcessRequest;
116 static Exception initialException;
117 static bool firstRun;
118 static bool assemblyMappingEnabled;
119 static object assemblyMappingLock = new object ();
120 static object appOfflineLock = new object ();
122 public HttpRuntime ()
128 static HttpRuntime ()
133 WebConfigurationManager.Init ();
135 SettingsMappingManager.Init ();
137 } catch (Exception ex) {
138 initialException = ex;
141 // The classes in whose constructors exceptions may be thrown, should be handled the same way QueueManager
142 // and TraceManager are below. The constructors themselves MUST NOT throw any exceptions - we MUST be sure
143 // the objects are created here. The exceptions will be dealt with below, in RealProcessRequest.
144 queue_manager = new QueueManager ();
145 if (queue_manager.HasException)
146 initialException = queue_manager.InitialException;
148 trace_manager = new TraceManager ();
149 if (trace_manager.HasException)
150 initialException = trace_manager.InitialException;
152 cache = new Cache ();
153 internalCache = new Cache ();
154 internalCache.DependencyCache = internalCache;
156 do_RealProcessRequest = new WaitCallback (RealProcessRequest);
159 #region AppDomain handling
160 internal static bool DomainUnloading {
161 get { return domainUnloading; }
165 // http://radio.weblogs.com/0105476/stories/2002/07/12/executingAspxPagesWithoutAWebServer.html
167 public static string AppDomainAppId {
168 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
171 // This value should not change across invocations
173 string dirname = (string) AppDomain.CurrentDomain.GetData (".appId");
174 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
175 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
181 // Physical directory for the application
182 public static string AppDomainAppPath {
184 string dirname = (string) AppDomain.CurrentDomain.GetData (".appPath");
185 if (SecurityManager.SecurityEnabled) {
186 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
192 public static string AppDomainAppVirtualPath {
194 return (string) AppDomain.CurrentDomain.GetData (".appVPath");
198 public static string AppDomainId {
199 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
201 return (string) AppDomain.CurrentDomain.GetData (".domainId");
205 public static string AspInstallDirectory {
207 string dirname = (string) AppDomain.CurrentDomain.GetData (".hostingInstallDir");
208 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
209 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
216 static string _actual_bin_directory;
217 public static string BinDirectory {
219 if (_actual_bin_directory == null) {
220 string[] parts = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split (';');
221 string mypath = AppDomainAppPath;
224 foreach (string p in parts) {
225 tmp = Path.Combine (mypath, p);
226 if (Directory.Exists (tmp)) {
227 _actual_bin_directory = tmp;
232 if (_actual_bin_directory == null)
233 _actual_bin_directory = Path.Combine (mypath, "bin");
235 if (_actual_bin_directory [_actual_bin_directory.Length - 1] != Path.DirectorySeparatorChar)
236 _actual_bin_directory += Path.DirectorySeparatorChar;
239 if (SecurityManager.SecurityEnabled)
240 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, _actual_bin_directory).Demand ();
242 return _actual_bin_directory;
246 public static Cache Cache {
252 internal static Cache InternalCache {
254 return internalCache;
258 public static string ClrInstallDirectory {
260 string dirname = Path.GetDirectoryName (typeof (Object).Assembly.Location);
261 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
262 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
268 public static string CodegenDir {
270 string dirname = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
271 if (SecurityManager.SecurityEnabled) {
272 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
278 public static bool IsOnUNCShare {
279 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
281 return RuntimeHelpers.IsUncShare;
285 public static string MachineConfigurationDirectory {
287 string dirname = Path.GetDirectoryName (ICalls.GetMachineConfigPath ());
288 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
289 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
296 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
297 public static void Close ()
299 // Remove all items from cache.
302 internal static HttpWorkerRequest QueuePendingRequest (bool started_internally)
304 HttpWorkerRequest next = queue_manager.GetNextRequest (null);
308 if (!started_internally) {
309 next.StartedInternally = true;
310 ThreadPool.QueueUserWorkItem (do_RealProcessRequest, next);
317 static readonly string[] app_offline_files = {"app_offline.htm", "App_Offline.htm", "APP_OFFLINE.HTM"};
318 static string app_offline_file;
320 static bool AppIsOffline (HttpContext context)
322 if (!HttpApplicationFactory.ApplicationDisabled || app_offline_file == null)
325 HttpResponse response = context.Response;
327 response.ContentType = "text/html";
328 response.ExpiresAbsolute = DateTime.UtcNow;
329 response.StatusCode = 503;
330 response.TransmitFile (app_offline_file, true);
332 context.Request.ReleaseResources ();
333 context.Response.ReleaseResources ();
334 HttpContext.Current = null;
335 HttpApplication.requests_total_counter.Increment ();
340 static void AppOfflineFileRenamed (object sender, RenamedEventArgs args)
342 AppOfflineFileChanged (sender, args);
345 static void AppOfflineFileChanged (object sender, FileSystemEventArgs args)
347 lock (appOfflineLock) {
350 switch (args.ChangeType) {
351 case WatcherChangeTypes.Created:
352 case WatcherChangeTypes.Changed:
356 case WatcherChangeTypes.Deleted:
360 case WatcherChangeTypes.Renamed:
361 RenamedEventArgs rargs = args as RenamedEventArgs;
364 String.Compare (rargs.Name, "app_offline.htm", StringComparison.OrdinalIgnoreCase) == 0)
374 SetOfflineMode (offline, args.FullPath);
378 static void SetOfflineMode (bool offline, string filePath)
381 app_offline_file = null;
382 if (HttpApplicationFactory.ApplicationDisabled)
383 HttpRuntime.UnloadAppDomain ();
385 app_offline_file = filePath;
386 HttpApplicationFactory.DisableWatchers ();
387 HttpApplicationFactory.ApplicationDisabled = true;
388 InternalCache.InvokePrivateCallbacks ();
389 HttpApplicationFactory.Dispose ();
393 static void SetupOfflineWatch ()
395 lock (appOfflineLock) {
396 FileSystemEventHandler seh = new FileSystemEventHandler (AppOfflineFileChanged);
397 RenamedEventHandler reh = new RenamedEventHandler (AppOfflineFileRenamed);
399 string app_dir = AppDomainAppPath;
400 ArrayList watchers = new ArrayList ();
401 FileSystemWatcher watcher;
402 string offlineFile = null, tmp;
404 foreach (string f in app_offline_files) {
405 watcher = new FileSystemWatcher ();
406 watcher.Path = Path.GetDirectoryName (app_dir);
407 watcher.Filter = Path.GetFileName (f);
408 watcher.NotifyFilter |= NotifyFilters.Size;
409 watcher.Deleted += seh;
410 watcher.Changed += seh;
411 watcher.Created += seh;
412 watcher.Renamed += reh;
413 watcher.EnableRaisingEvents = true;
415 watchers.Add (watcher);
417 tmp = Path.Combine (app_dir, f);
418 if (File.Exists (tmp))
422 if (offlineFile != null)
423 SetOfflineMode (true, offlineFile);
428 static void RealProcessRequest (object o)
430 HttpWorkerRequest req = (HttpWorkerRequest) o;
431 bool started_internally = req.StartedInternally;
434 req = QueuePendingRequest (started_internally);
435 } while (started_internally && req != null);
438 static void Process (HttpWorkerRequest req)
441 HttpContext context = HttpContext.Current;
443 context = new HttpContext (req);
445 context.SetWorkerRequest (req);
447 HttpContext context = new HttpContext (req);
449 HttpContext.Current = context;
453 SetupOfflineWatch ();
455 if (initialException != null) {
456 FinishWithException (req, new HttpException ("Initial exception", initialException));
461 if (AppIsOffline (context))
466 // Get application instance (create or reuse an instance of the correct class)
468 HttpApplication app = null;
471 app = HttpApplicationFactory.GetApplication (context);
472 } catch (Exception e) {
473 FinishWithException (req, new HttpException ("", e));
479 context.Request.ReleaseResources ();
480 context.Response.ReleaseResources ();
481 HttpContext.Current = null;
483 context.ApplicationInstance = app;
486 // Ask application to service the request
490 IHttpAsyncHandler ihah = app;
491 if (context.Handler == null)
492 ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
495 //ihh.ProcessRequest (context);
496 IHttpExtendedHandler extHandler = context.Handler as IHttpExtendedHandler;
497 if (extHandler != null && !extHandler.IsCompleted)
499 if (context.Error is UnifyRequestException)
502 ihah.EndProcessRequest (null);
504 IHttpHandler ihh = app;
505 // IAsyncResult appiar = ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
506 // ihah.EndProcessRequest (appiar);
507 ihh.ProcessRequest (context);
510 HttpApplicationFactory.Recycle (app);
515 // ProcessRequest method is executed in the AppDomain of the application
518 // ProcessRequest does not guarantee that `wr' will be processed synchronously,
519 // the request can be queued and processed later.
521 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
522 public static void ProcessRequest (HttpWorkerRequest wr)
525 throw new ArgumentNullException ("wr");
527 // Queue our request, fetch the next available one from the queue
529 HttpWorkerRequest request = queue_manager.GetNextRequest (wr);
533 QueuePendingRequest (false);
534 RealProcessRequest (request);
539 // Callback to be invoked by IHttpAsyncHandler.BeginProcessRequest
541 static void request_processed (IAsyncResult iar)
543 HttpContext context = (HttpContext) iar.AsyncState;
545 context.Request.ReleaseResources ();
546 context.Response.ReleaseResources ();
551 [MonoNotSupported ("UnloadAppDomain is not supported")]
552 public static void UnloadAppDomain ()
554 throw new NotImplementedException ("UnloadAppDomain is not supported");
558 // Called when we are shutting down or we need to reload an application
559 // that has been modified (touch global.asax)
561 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
562 public static void UnloadAppDomain ()
565 // TODO: call ReleaseResources
567 domainUnloading = true;
568 ThreadPool.QueueUserWorkItem (new WaitCallback (ShutdownAppDomain), null);
572 // Shuts down the AppDomain
574 static void ShutdownAppDomain (object args)
576 queue_manager.Dispose ();
577 // This will call Session_End if needed.
578 InternalCache.InvokePrivateCallbacks ();
579 // Kill our application.
580 HttpApplicationFactory.Dispose ();
581 ThreadPool.QueueUserWorkItem (new WaitCallback (DoUnload), null);
584 static void DoUnload (object state)
587 // No unload support for appdomains under Grasshopper
589 AppDomain.Unload (AppDomain.CurrentDomain);
593 static string content503 = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" +
594 "<html><head>\n<title>503 Server Unavailable</title>\n</head><body>\n" +
595 "<h1>Server Unavailable</h1>\n" +
598 static void FinishWithException (HttpWorkerRequest wr, HttpException e)
600 int code = e.GetHttpCode ();
601 wr.SendStatus (code, HttpWorkerRequest.GetStatusDescription (code));
602 wr.SendUnknownResponseHeader ("Connection", "close");
603 Encoding enc = Encoding.ASCII;
604 wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
605 string msg = e.GetHtmlErrorMessage ();
606 byte [] contentBytes = enc.GetBytes (msg);
607 wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
608 wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
609 wr.FlushResponse (true);
610 wr.CloseConnection ();
611 HttpApplication.requests_total_counter.Increment ();
615 // This is called from the QueueManager if a request
616 // can not be processed (load, no resources, or
617 // appdomain unload).
619 static internal void FinishUnavailable (HttpWorkerRequest wr)
621 wr.SendStatus (503, "Service unavailable");
622 wr.SendUnknownResponseHeader ("Connection", "close");
623 Encoding enc = Encoding.ASCII;
624 wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
625 byte [] contentBytes = enc.GetBytes (content503);
626 wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
627 wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
628 wr.FlushResponse (true);
629 wr.CloseConnection ();
630 HttpApplication.requests_total_counter.Increment ();
634 static internal void WritePreservationFile (Assembly asm, string genericNameBase)
637 throw new ArgumentNullException ("asm");
638 if (String.IsNullOrEmpty (genericNameBase))
639 throw new ArgumentNullException ("genericNameBase");
641 string compiled = Path.Combine (AppDomain.CurrentDomain.SetupInformation.DynamicBase,
642 genericNameBase + ".compiled");
643 PreservationFile pf = new PreservationFile ();
645 pf.VirtualPath = String.Concat ("/", genericNameBase, "/");
647 AssemblyName an = asm.GetName ();
648 pf.Assembly = an.Name;
649 pf.ResultType = BuildResultTypeCode.TopLevelAssembly;
651 } catch (Exception ex) {
652 throw new HttpException (
653 String.Format ("Failed to write preservation file {0}", genericNameBase + ".compiled"),
658 static Assembly ResolveAssemblyHandler(object sender, ResolveEventArgs e)
660 AssemblyName an = new AssemblyName (e.Name);
661 string dynamic_base = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
662 string compiled = Path.Combine (dynamic_base, an.Name + ".compiled");
664 if (!File.Exists (compiled))
669 pf = new PreservationFile (compiled);
670 } catch (Exception ex) {
671 throw new HttpException (
672 String.Format ("Failed to read preservation file {0}", an.Name + ".compiled"),
678 string asmPath = Path.Combine (dynamic_base, pf.Assembly + ".dll");
679 ret = Assembly.LoadFrom (asmPath);
680 } catch (Exception) {
687 internal static void EnableAssemblyMapping (bool enable)
689 lock (assemblyMappingLock) {
690 if (assemblyMappingEnabled == enable)
693 AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (ResolveAssemblyHandler);
695 AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler (ResolveAssemblyHandler);
696 assemblyMappingEnabled = enable;
699 #endif // #if !TARGET_J2EE
701 internal static TraceManager TraceManager {
703 return trace_manager;