Add TimeZoneInfo Serialization
[mono.git] / mcs / class / System.Web / System.Web / HttpRuntime.cs
1 //
2 // System.Web.HttpRuntime.cs 
3 // 
4 // Authors:
5 //      Miguel de Icaza (miguel@novell.com)
6 //      Marek Habersack <mhabersack@novell.com>
7 //
8 //
9 // Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
10 //
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:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
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.
29 //
30
31 //
32 // TODO: Call HttpRequest.CloseInputStream when we finish a request, as we are using the IntPtr stream.
33 //
34 using System.IO;
35 using System.Text;
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;
45 using System.Web.UI;
46 using System.Web.Util;
47 #if MONOWEB_DEP
48 using Mono.Web.Util;
49 #endif
50 using System.Threading;
51 #if TARGET_J2EE
52 using Mainsoft.Web;
53 #else
54 using System.CodeDom.Compiler;
55 using System.Web.Compilation;
56 #endif
57
58 namespace System.Web
59 {       
60         // CAS - no InheritanceDemand here as the class is sealed
61         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
62         public sealed class HttpRuntime
63         {
64                 static bool domainUnloading;
65                 static SplitOrderedList <string, string> registeredAssemblies;
66 #if TARGET_J2EE
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;
72                 
73                 QueueManager _queue_manager;
74                 TraceManager _trace_manager;
75                 Cache _cache;
76                 Cache _internalCache;
77
78                 public HttpRuntime ()
79                 {
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;
86                 }
87
88                 static HttpRuntime _runtimeInstance {
89                         get {
90                                 HttpRuntime runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
91                                 if (runtime == null)
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);
97                                                 }
98                                         }
99                                 return runtime;
100                         }
101                 }
102                 static HttpRuntime _runtime
103                 {
104                         get
105                         {
106                                 if (HttpContext.Current != null)
107                                         return HttpContext.Current.HttpRuntimeInstance;
108                                 else
109                                         return _runtimeInstance;
110                         }
111                 }
112 #else
113                 static QueueManager queue_manager;
114                 static TraceManager trace_manager;
115                 static Cache cache;
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;
125                 
126                 public HttpRuntime ()
127                 {
128
129                 }
130 #endif
131
132                 static HttpRuntime ()
133                 {
134 #if !TARGET_J2EE
135                         firstRun = true;
136
137                         try {
138                                 WebConfigurationManager.Init ();
139 #if MONOWEB_DEP
140                                 SettingsMappingManager.Init ();
141 #endif
142                                 runtime_section = (HttpRuntimeSection) WebConfigurationManager.GetSection ("system.web/httpRuntime");
143                         } catch (Exception ex) {
144                                 initialException = ex;
145                         }
146
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;
154                                 else {
155                                         Console.Error.WriteLine ("Exception during QueueManager initialization:");
156                                         Console.Error.WriteLine (queue_manager.InitialException);
157                                 }
158                         }
159
160                         trace_manager = new TraceManager ();
161                         if (trace_manager.HasException) {
162                                 if (initialException == null)
163                                         initialException = trace_manager.InitialException;
164                                 else {
165                                         Console.Error.WriteLine ("Exception during TraceManager initialization:");
166                                         Console.Error.WriteLine (trace_manager.InitialException);
167                                 }
168                         }
169
170                         registeredAssemblies = new SplitOrderedList <string, string> (StringComparer.Ordinal);
171                         cache = new Cache ();
172                         internalCache = new Cache ();
173                         internalCache.DependencyCache = internalCache;
174 #endif
175                         do_RealProcessRequest = new WaitCallback (state => {
176                                 try {
177                                         RealProcessRequest (state);
178                                 } catch {}
179                                 });
180                         end_of_send_cb = new HttpWorkerRequest.EndOfSendNotification (EndOfSend);
181                 }
182
183                 internal static SplitOrderedList <string, string> RegisteredAssemblies {
184                         get { return registeredAssemblies; }
185                 }
186                 
187 #region AppDomain handling
188                 internal static bool DomainUnloading {
189                         get { return domainUnloading; }
190                 }
191
192                 [MonoDocumentationNote ("Currently returns path to the application root")]
193                 public static string AspClientScriptPhysicalPath { get { return AppDomainAppPath; } }
194
195                 [MonoDocumentationNote ("Currently returns path to the application root")]
196                 public static string AspClientScriptVirtualPath { get { return AppDomainAppVirtualPath; } }
197                 
198                 //
199                 // http://radio.weblogs.com/0105476/stories/2002/07/12/executingAspxPagesWithoutAWebServer.html
200                 //
201                 public static string AppDomainAppId {
202                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
203                         get {
204                                 //
205                                 // This value should not change across invocations
206                                 //
207                                 string dirname = (string) AppDomain.CurrentDomain.GetData (".appId");
208                                 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
209                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
210                                 }
211                                 return dirname;
212                         }
213                 }
214
215                 // Physical directory for the application
216                 public static string AppDomainAppPath {
217                         get {
218                                 string dirname = (string) AppDomain.CurrentDomain.GetData (".appPath");
219                                 if (SecurityManager.SecurityEnabled) {
220                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
221                                 }
222                                 return dirname;
223                         }
224                 }
225
226                 public static string AppDomainAppVirtualPath {
227                         get {
228                                 return (string) AppDomain.CurrentDomain.GetData (".appVPath");
229                         }
230                 }
231
232                 public static string AppDomainId {
233                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
234                         get {
235                                 return (string) AppDomain.CurrentDomain.GetData (".domainId");
236                         }
237                 }
238
239                 public static string AspInstallDirectory {
240                         get {
241                                 string dirname = (string) AppDomain.CurrentDomain.GetData (".hostingInstallDir");
242                                 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
243                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
244                                 }
245                                 return dirname;
246                         }
247                 }
248 #endregion
249
250                 static string _actual_bin_directory;
251                 public static string BinDirectory {
252                         get {
253                                 if (_actual_bin_directory == null) {
254                                         string[] parts = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split (';');
255                                         string mypath = AppDomainAppPath;
256                                         string tmp;
257                                         
258                                         foreach (string p in parts) {
259                                                 tmp = Path.Combine (mypath, p);
260                                                 if (Directory.Exists (tmp)) {
261                                                         _actual_bin_directory = tmp;
262                                                         break;
263                                                 }
264                                         }
265
266                                         if (_actual_bin_directory == null)
267                                                 _actual_bin_directory = Path.Combine (mypath, "bin");
268
269                                         if (_actual_bin_directory [_actual_bin_directory.Length - 1] != Path.DirectorySeparatorChar)
270                                                 _actual_bin_directory += Path.DirectorySeparatorChar;
271                                 }
272                                 
273                                 if (SecurityManager.SecurityEnabled)
274                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, _actual_bin_directory).Demand ();
275
276                                 return _actual_bin_directory;
277                         }
278                 }
279
280                 public static Cache Cache {
281                         get {
282                                 return cache;
283                         }
284                 }
285
286                 internal static Cache InternalCache {
287                         get {
288                                 return internalCache;
289                         }
290                 }
291                 
292                 public static string ClrInstallDirectory {
293                         get {
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 ();
297                                 }
298                                 return dirname;
299                         }
300                 }
301
302                 public static string CodegenDir {
303                         get {
304                                 string dirname = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
305                                 if (SecurityManager.SecurityEnabled) {
306                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
307                                 }
308                                 return dirname;
309                         }
310                 }
311
312                 public static bool IsOnUNCShare {
313                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
314                         get {
315                                 return RuntimeHelpers.IsUncShare;
316                         }
317                 }
318
319                 public static string MachineConfigurationDirectory {
320                         get {
321                                 string dirname = Path.GetDirectoryName (ICalls.GetMachineConfigPath ());
322                                 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
323                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
324                                 }
325                                 return dirname;
326                         }
327                 }
328
329                 internal static HttpRuntimeSection Section { get { return runtime_section; } }
330
331                 public static bool UsingIntegratedPipeline { get { return false; } }
332                 
333                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
334                 public static void Close ()
335                 {
336                         // Remove all items from cache.
337                 }
338
339                 internal static HttpWorkerRequest QueuePendingRequest (bool started_internally)
340                 {
341                         HttpWorkerRequest next = queue_manager.GetNextRequest (null);
342                         if (next == null)
343                                 return null;
344
345                         if (!started_internally) {
346                                 next.StartedInternally = true;
347                                 ThreadPool.QueueUserWorkItem (do_RealProcessRequest, next);
348                                 return null;
349                         }
350                         return next;
351                 }
352
353 #if !TARGET_J2EE
354                 static readonly string[] app_offline_files = {"app_offline.htm", "App_Offline.htm", "APP_OFFLINE.HTM"};
355                 static string app_offline_file;
356                 
357                 static bool AppIsOffline (HttpContext context)
358                 {
359                         if (!HttpApplicationFactory.ApplicationDisabled || app_offline_file == null)
360                                 return false;
361
362                         HttpResponse response = context.Response;
363                         response.Clear ();
364                         response.ContentType = "text/html";
365                         response.ExpiresAbsolute = DateTime.UtcNow;
366                         response.StatusCode = 503;
367                         response.TransmitFile (app_offline_file, true);
368                         
369                         context.Request.ReleaseResources ();
370                         context.Response.ReleaseResources ();
371                         HttpContext.Current = null;
372                         HttpApplication.requests_total_counter.Increment ();
373                         
374                         return true;
375                 }
376
377                 static void AppOfflineFileRenamed (object sender, RenamedEventArgs args)
378                 {
379                         AppOfflineFileChanged (sender, args);
380                 }
381
382                 static void AppOfflineFileChanged (object sender, FileSystemEventArgs args)
383                 {
384                         lock (appOfflineLock) {
385                                 bool offline;
386                                 
387                                 switch (args.ChangeType) {
388                                         case WatcherChangeTypes.Created:
389                                         case WatcherChangeTypes.Changed:
390                                                 offline = true;
391                                                 break;
392
393                                         case WatcherChangeTypes.Deleted:
394                                                 offline = false;
395                                                 break;
396
397                                         case WatcherChangeTypes.Renamed:
398                                                 RenamedEventArgs rargs = args as RenamedEventArgs;
399
400                                                 if (rargs != null &&
401                                                     String.Compare (rargs.Name, "app_offline.htm", StringComparison.OrdinalIgnoreCase) == 0)
402                                                         offline = true;
403                                                 else
404                                                         offline = false;
405                                                 break;
406
407                                         default:
408                                                 offline = false;
409                                                 break;
410                                 }
411                                 SetOfflineMode (offline, args.FullPath);
412                         }
413                 }
414
415                 static void SetOfflineMode (bool offline, string filePath)
416                 {
417                         if (!offline) {
418                                 app_offline_file = null;
419                                 if (HttpApplicationFactory.ApplicationDisabled)
420                                         HttpRuntime.UnloadAppDomain ();
421                         } else {
422                                 app_offline_file = filePath;
423                                 HttpApplicationFactory.DisableWatchers ();
424                                 HttpApplicationFactory.ApplicationDisabled = true;
425                                 InternalCache.InvokePrivateCallbacks ();
426                                 HttpApplicationFactory.Dispose ();
427                         }
428                 }
429                 
430                 static void SetupOfflineWatch ()
431                 {
432                         lock (appOfflineLock) {
433                                 FileSystemEventHandler seh = new FileSystemEventHandler (AppOfflineFileChanged);
434                                 RenamedEventHandler reh = new RenamedEventHandler (AppOfflineFileRenamed);
435
436                                 string app_dir = AppDomainAppPath;
437                                 FileSystemWatcher watcher;
438                                 string offlineFile = null, tmp;
439                                 
440                                 foreach (string f in app_offline_files) {
441                                         watcher = new FileSystemWatcher ();
442                                         watcher.Path = Path.GetDirectoryName (app_dir);
443                                         watcher.Filter = Path.GetFileName (f);
444                                         watcher.NotifyFilter |= NotifyFilters.Size;
445                                         watcher.Deleted += seh;
446                                         watcher.Changed += seh;
447                                         watcher.Created += seh;
448                                         watcher.Renamed += reh;
449                                         watcher.EnableRaisingEvents = true;
450
451                                         tmp = Path.Combine (app_dir, f);
452                                         if (File.Exists (tmp))
453                                                 offlineFile = tmp;
454                                 }
455
456                                 if (offlineFile != null)
457                                         SetOfflineMode (true, offlineFile);
458                         }
459                 }
460 #endif
461                 
462                 static void RealProcessRequest (object o)
463                 {
464                         if (domainUnloading) {
465                                 Console.Error.WriteLine ("Domain is unloading, not processing the request.");
466                                 return;
467                         }
468
469                         HttpWorkerRequest req = (HttpWorkerRequest) o;
470                         bool started_internally = req.StartedInternally;
471                         do {
472                                 Process (req);
473                                 req = QueuePendingRequest (started_internally);
474                         } while (started_internally && req != null);
475                 }
476
477                 static void Process (HttpWorkerRequest req)
478                 {
479                         bool error = false;
480 #if TARGET_J2EE
481                         HttpContext context = HttpContext.Current;
482                         if (context == null)
483                                 context = new HttpContext (req);
484                         else
485                                 context.SetWorkerRequest (req);
486 #else
487                         if (firstRun) {
488                                 firstRun = false;
489                                 if (initialException != null) {
490                                         FinishWithException (req, HttpException.NewWithCode ("Initial exception", initialException, WebEventCodes.RuntimeErrorRequestAbort));
491                                         error = true;
492                                 }
493                                 SetupOfflineWatch ();
494                         }
495                         HttpContext context = new HttpContext (req);
496 #endif
497                         HttpContext.Current = context;
498 #if !TARGET_J2EE
499                         if (AppIsOffline (context))
500                                 return;
501 #endif
502                         
503                         //
504                         // Get application instance (create or reuse an instance of the correct class)
505                         //
506                         HttpApplication app = null;
507                         if (!error) {
508                                 try {
509                                         app = HttpApplicationFactory.GetApplication (context);
510                                 } catch (Exception e) {
511                                         FinishWithException (req, HttpException.NewWithCode (String.Empty, e, WebEventCodes.RuntimeErrorRequestAbort));
512                                         error = true;
513                                 }
514                         }
515                         
516                         if (error) {
517                                 context.Request.ReleaseResources ();
518                                 context.Response.ReleaseResources ();
519                                 HttpContext.Current = null;
520                         } else {
521                                 context.ApplicationInstance = app;
522                                 req.SetEndOfSendNotification (end_of_send_cb, context);
523
524                                 //
525                                 // Ask application to service the request
526                                 //
527                                 
528 #if TARGET_J2EE
529                                 IHttpAsyncHandler ihah = app;
530                                 if (context.Handler == null)
531                                         ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
532                                 else
533                                         app.Tick ();
534                                 //ihh.ProcessRequest (context);
535                                 IHttpExtendedHandler extHandler = context.Handler as IHttpExtendedHandler;
536                                 if (extHandler != null && !extHandler.IsCompleted)
537                                         return;
538                                 if (context.Error is UnifyRequestException)
539                                         return;
540
541                                 ihah.EndProcessRequest (null);
542 #else
543                                 IHttpHandler ihh = app;
544 //                              IAsyncResult appiar = ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
545 //                              ihah.EndProcessRequest (appiar);
546                                 ihh.ProcessRequest (context);
547 #endif
548
549                                 HttpApplicationFactory.Recycle (app);
550                         }
551                 }
552
553                 static void EndOfSend (HttpWorkerRequest ignored1, object ignored2)
554                 {
555                 }
556
557                 //
558                 // ProcessRequest method is executed in the AppDomain of the application
559                 //
560                 // Observations:
561                 //    ProcessRequest does not guarantee that `wr' will be processed synchronously,
562                 //    the request can be queued and processed later.
563                 //
564                 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
565                 public static void ProcessRequest (HttpWorkerRequest wr)
566                 {
567                         if (wr == null)
568                                 throw new ArgumentNullException ("wr");
569                         //
570                         // Queue our request, fetch the next available one from the queue
571                         //
572                         HttpWorkerRequest request = queue_manager.GetNextRequest (wr);
573                         if (request == null)
574                                 return;
575
576                         QueuePendingRequest (false);
577                         RealProcessRequest (request);
578                 }
579
580 #if TARGET_J2EE
581                 //
582                 // Callback to be invoked by IHttpAsyncHandler.BeginProcessRequest
583                 //
584                 static void request_processed (IAsyncResult iar)
585                 {
586                         HttpContext context = (HttpContext) iar.AsyncState;
587
588                         context.Request.ReleaseResources ();
589                         context.Response.ReleaseResources ();
590                 }
591 #endif
592                 
593 #if TARGET_JVM
594                 [MonoNotSupported ("UnloadAppDomain is not supported")]
595                 public static void UnloadAppDomain ()
596                 {
597                         throw new NotImplementedException ("UnloadAppDomain is not supported");
598                 }
599 #else
600                 //
601                 // Called when we are shutting down or we need to reload an application
602                 // that has been modified (touch global.asax) 
603                 //
604                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
605                 public static void UnloadAppDomain ()
606                 {
607                         //
608                         // TODO: call ReleaseResources
609                         //
610                         domainUnloading = true;
611                         HttpApplicationFactory.DisableWatchers ();
612                         ThreadPool.QueueUserWorkItem (delegate {
613                                 try {
614                                         ShutdownAppDomain ();
615                                 } catch (Exception e){
616                                         Console.Error.WriteLine (e);
617                                 }
618                         });
619                 }
620 #endif
621                 //
622                 // Shuts down the AppDomain
623                 //
624                 static void ShutdownAppDomain ()
625                 {
626                         queue_manager.Dispose ();
627                         // This will call Session_End if needed.
628                         InternalCache.InvokePrivateCallbacks ();
629                         // Kill our application.
630                         HttpApplicationFactory.Dispose ();
631                         ThreadPool.QueueUserWorkItem (delegate {
632                                 try {
633                                         DoUnload ();
634                                 } catch {
635                                 }});
636                 }
637
638                 static void DoUnload ()
639                 {
640 #if TARGET_J2EE
641                         // No unload support for appdomains under Grasshopper
642 #else
643                         AppDomain.Unload (AppDomain.CurrentDomain);
644 #endif
645                 }
646
647                 static string content503 = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" +
648                         "<html><head>\n<title>503 Server Unavailable</title>\n</head><body>\n" +
649                         "<h1>Server Unavailable</h1>\n" +
650                         "</body></html>\n";
651
652                 static void FinishWithException (HttpWorkerRequest wr, HttpException e)
653                 {
654                         int code = e.GetHttpCode ();
655                         wr.SendStatus (code, HttpWorkerRequest.GetStatusDescription (code));
656                         wr.SendUnknownResponseHeader ("Connection", "close");
657                         Encoding enc = Encoding.ASCII;
658                         wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
659                         string msg = e.GetHtmlErrorMessage ();
660                         byte [] contentBytes = enc.GetBytes (msg);
661                         wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
662                         wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
663                         wr.FlushResponse (true);
664                         wr.CloseConnection ();
665                         HttpApplication.requests_total_counter.Increment ();
666                 }
667
668                 //
669                 // This is called from the QueueManager if a request
670                 // can not be processed (load, no resources, or
671                 // appdomain unload).
672                 //
673                 static internal void FinishUnavailable (HttpWorkerRequest wr)
674                 {
675                         wr.SendStatus (503, "Service unavailable");
676                         wr.SendUnknownResponseHeader ("Connection", "close");
677                         Encoding enc = Encoding.ASCII;
678                         wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
679                         byte [] contentBytes = enc.GetBytes (content503);
680                         wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
681                         wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
682                         wr.FlushResponse (true);
683                         wr.CloseConnection ();
684                         HttpApplication.requests_total_counter.Increment ();
685                 }
686
687                 [AspNetHostingPermissionAttribute(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Unrestricted)]
688                 [MonoDocumentationNote ("Always returns null on Mono")]
689                 public static NamedPermissionSet GetNamedPermissionSet ()
690                 {
691                         return null;
692                 }
693                 
694 #if !TARGET_J2EE
695                 static internal void WritePreservationFile (Assembly asm, string genericNameBase)
696                 {
697                         if (asm == null)
698                                 throw new ArgumentNullException ("asm");
699                         if (String.IsNullOrEmpty (genericNameBase))
700                                 throw new ArgumentNullException ("genericNameBase");
701
702                         string compiled = Path.Combine (AppDomain.CurrentDomain.SetupInformation.DynamicBase,
703                                                         genericNameBase + ".compiled");
704                         PreservationFile pf = new PreservationFile ();
705                         try {
706                                 pf.VirtualPath = String.Concat ("/", genericNameBase, "/");
707
708                                 AssemblyName an = asm.GetName ();
709                                 pf.Assembly = an.Name;
710                                 pf.ResultType = BuildResultTypeCode.TopLevelAssembly;
711                                 pf.Save (compiled);
712                         } catch (Exception ex) {
713                                 throw new HttpException (
714                                         String.Format ("Failed to write preservation file {0}", genericNameBase + ".compiled"),
715                                         ex);
716                         }
717                 }
718                 
719                 static Assembly ResolveAssemblyHandler(object sender, ResolveEventArgs e)
720                 {
721                         AssemblyName an = new AssemblyName (e.Name);
722                         string dynamic_base = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
723                         string compiled = Path.Combine (dynamic_base, an.Name + ".compiled");
724                         string asmPath;
725
726                         if (!File.Exists (compiled)) {
727                                 string fn = an.FullName;
728                                 if (!RegisteredAssemblies.Find ((uint)fn.GetHashCode (), fn, out asmPath))
729                                         return null;
730                         } else {
731                                 PreservationFile pf;
732                                 try {
733                                         pf = new PreservationFile (compiled);
734                                 } catch (Exception ex) {
735                                         throw new HttpException (
736                                                 String.Format ("Failed to read preservation file {0}", an.Name + ".compiled"),
737                                                 ex);
738                                 }
739                                 asmPath = Path.Combine (dynamic_base, pf.Assembly + ".dll");
740                         }
741
742                         if (String.IsNullOrEmpty (asmPath))
743                                 return null;
744                         
745                         Assembly ret = null;
746                         try {
747                                 ret = Assembly.LoadFrom (asmPath);
748                         } catch (Exception) {
749                                 // ignore
750                         }
751                         
752                         return ret;
753                 }
754                 
755                 internal static void EnableAssemblyMapping (bool enable)
756                 {
757                         lock (assemblyMappingLock) {
758                                 if (assemblyMappingEnabled == enable)
759                                         return;
760                                 if (enable)
761                                         AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (ResolveAssemblyHandler);
762                                 else
763                                         AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler (ResolveAssemblyHandler);
764                                 assemblyMappingEnabled = enable;
765                         }
766                 }
767 #endif // #if !TARGET_J2EE
768                 
769                 internal static TraceManager TraceManager {
770                         get {
771                                 return trace_manager;
772                         }
773                 }
774         }
775 }