Merge pull request #687 from miniBill/master
[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 #if NET_4_5
334                 public static IISVersion {
335                         get { return null; } // Null means not hosted by IIS
336                 }
337 #endif
338                 
339                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
340                 public static void Close ()
341                 {
342                         // Remove all items from cache.
343                 }
344
345                 internal static HttpWorkerRequest QueuePendingRequest (bool started_internally)
346                 {
347                         HttpWorkerRequest next = queue_manager.GetNextRequest (null);
348                         if (next == null)
349                                 return null;
350
351                         if (!started_internally) {
352                                 next.StartedInternally = true;
353                                 ThreadPool.QueueUserWorkItem (do_RealProcessRequest, next);
354                                 return null;
355                         }
356                         return next;
357                 }
358
359 #if !TARGET_J2EE
360                 static readonly string[] app_offline_files = {"app_offline.htm", "App_Offline.htm", "APP_OFFLINE.HTM"};
361                 static string app_offline_file;
362                 
363                 static bool AppIsOffline (HttpContext context)
364                 {
365                         if (!HttpApplicationFactory.ApplicationDisabled || app_offline_file == null)
366                                 return false;
367
368                         HttpResponse response = context.Response;
369                         response.Clear ();
370                         response.ContentType = "text/html";
371                         response.ExpiresAbsolute = DateTime.UtcNow;
372                         response.StatusCode = 503;
373                         response.TransmitFile (app_offline_file, true);
374                         
375                         context.Request.ReleaseResources ();
376                         context.Response.ReleaseResources ();
377                         HttpContext.Current = null;
378                         HttpApplication.requests_total_counter.Increment ();
379                         
380                         return true;
381                 }
382
383                 static void AppOfflineFileRenamed (object sender, RenamedEventArgs args)
384                 {
385                         AppOfflineFileChanged (sender, args);
386                 }
387
388                 static void AppOfflineFileChanged (object sender, FileSystemEventArgs args)
389                 {
390                         lock (appOfflineLock) {
391                                 bool offline;
392                                 
393                                 switch (args.ChangeType) {
394                                         case WatcherChangeTypes.Created:
395                                         case WatcherChangeTypes.Changed:
396                                                 offline = true;
397                                                 break;
398
399                                         case WatcherChangeTypes.Deleted:
400                                                 offline = false;
401                                                 break;
402
403                                         case WatcherChangeTypes.Renamed:
404                                                 RenamedEventArgs rargs = args as RenamedEventArgs;
405
406                                                 if (rargs != null &&
407                                                     String.Compare (rargs.Name, "app_offline.htm", StringComparison.OrdinalIgnoreCase) == 0)
408                                                         offline = true;
409                                                 else
410                                                         offline = false;
411                                                 break;
412
413                                         default:
414                                                 offline = false;
415                                                 break;
416                                 }
417                                 SetOfflineMode (offline, args.FullPath);
418                         }
419                 }
420
421                 static void SetOfflineMode (bool offline, string filePath)
422                 {
423                         if (!offline) {
424                                 app_offline_file = null;
425                                 if (HttpApplicationFactory.ApplicationDisabled)
426                                         HttpRuntime.UnloadAppDomain ();
427                         } else {
428                                 app_offline_file = filePath;
429                                 HttpApplicationFactory.DisableWatchers ();
430                                 HttpApplicationFactory.ApplicationDisabled = true;
431                                 InternalCache.InvokePrivateCallbacks ();
432                                 HttpApplicationFactory.Dispose ();
433                         }
434                 }
435                 
436                 static void SetupOfflineWatch ()
437                 {
438                         lock (appOfflineLock) {
439                                 FileSystemEventHandler seh = new FileSystemEventHandler (AppOfflineFileChanged);
440                                 RenamedEventHandler reh = new RenamedEventHandler (AppOfflineFileRenamed);
441
442                                 string app_dir = AppDomainAppPath;
443                                 FileSystemWatcher watcher;
444                                 string offlineFile = null, tmp;
445                                 
446                                 foreach (string f in app_offline_files) {
447                                         watcher = new FileSystemWatcher ();
448                                         watcher.Path = Path.GetDirectoryName (app_dir);
449                                         watcher.Filter = Path.GetFileName (f);
450                                         watcher.NotifyFilter |= NotifyFilters.Size;
451                                         watcher.Deleted += seh;
452                                         watcher.Changed += seh;
453                                         watcher.Created += seh;
454                                         watcher.Renamed += reh;
455                                         watcher.EnableRaisingEvents = true;
456
457                                         tmp = Path.Combine (app_dir, f);
458                                         if (File.Exists (tmp))
459                                                 offlineFile = tmp;
460                                 }
461
462                                 if (offlineFile != null)
463                                         SetOfflineMode (true, offlineFile);
464                         }
465                 }
466 #endif
467                 
468                 static void RealProcessRequest (object o)
469                 {
470                         if (domainUnloading) {
471                                 Console.Error.WriteLine ("Domain is unloading, not processing the request.");
472                                 return;
473                         }
474
475                         HttpWorkerRequest req = (HttpWorkerRequest) o;
476                         bool started_internally = req.StartedInternally;
477                         do {
478                                 Process (req);
479                                 req = QueuePendingRequest (started_internally);
480                         } while (started_internally && req != null);
481                 }
482
483                 static void Process (HttpWorkerRequest req)
484                 {
485                         bool error = false;
486 #if TARGET_J2EE
487                         HttpContext context = HttpContext.Current;
488                         if (context == null)
489                                 context = new HttpContext (req);
490                         else
491                                 context.SetWorkerRequest (req);
492 #else
493                         if (firstRun) {
494                                 firstRun = false;
495                                 if (initialException != null) {
496                                         FinishWithException (req, HttpException.NewWithCode ("Initial exception", initialException, WebEventCodes.RuntimeErrorRequestAbort));
497                                         error = true;
498                                 }
499                                 SetupOfflineWatch ();
500                         }
501                         HttpContext context = new HttpContext (req);
502 #endif
503                         HttpContext.Current = context;
504 #if !TARGET_J2EE
505                         if (AppIsOffline (context))
506                                 return;
507 #endif
508                         
509                         //
510                         // Get application instance (create or reuse an instance of the correct class)
511                         //
512                         HttpApplication app = null;
513                         if (!error) {
514                                 try {
515                                         app = HttpApplicationFactory.GetApplication (context);
516                                 } catch (Exception e) {
517                                         FinishWithException (req, HttpException.NewWithCode (String.Empty, e, WebEventCodes.RuntimeErrorRequestAbort));
518                                         error = true;
519                                 }
520                         }
521                         
522                         if (error) {
523                                 context.Request.ReleaseResources ();
524                                 context.Response.ReleaseResources ();
525                                 HttpContext.Current = null;
526                         } else {
527                                 context.ApplicationInstance = app;
528                                 req.SetEndOfSendNotification (end_of_send_cb, context);
529
530                                 //
531                                 // Ask application to service the request
532                                 //
533                                 
534 #if TARGET_J2EE
535                                 IHttpAsyncHandler ihah = app;
536                                 if (context.Handler == null)
537                                         ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
538                                 else
539                                         app.Tick ();
540                                 //ihh.ProcessRequest (context);
541                                 IHttpExtendedHandler extHandler = context.Handler as IHttpExtendedHandler;
542                                 if (extHandler != null && !extHandler.IsCompleted)
543                                         return;
544                                 if (context.Error is UnifyRequestException)
545                                         return;
546
547                                 ihah.EndProcessRequest (null);
548 #else
549                                 IHttpHandler ihh = app;
550 //                              IAsyncResult appiar = ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
551 //                              ihah.EndProcessRequest (appiar);
552                                 ihh.ProcessRequest (context);
553 #endif
554
555                                 HttpApplicationFactory.Recycle (app);
556                         }
557                 }
558
559                 static void EndOfSend (HttpWorkerRequest ignored1, object ignored2)
560                 {
561                 }
562
563                 //
564                 // ProcessRequest method is executed in the AppDomain of the application
565                 //
566                 // Observations:
567                 //    ProcessRequest does not guarantee that `wr' will be processed synchronously,
568                 //    the request can be queued and processed later.
569                 //
570                 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
571                 public static void ProcessRequest (HttpWorkerRequest wr)
572                 {
573                         if (wr == null)
574                                 throw new ArgumentNullException ("wr");
575                         //
576                         // Queue our request, fetch the next available one from the queue
577                         //
578                         HttpWorkerRequest request = queue_manager.GetNextRequest (wr);
579                         if (request == null)
580                                 return;
581
582                         QueuePendingRequest (false);
583                         RealProcessRequest (request);
584                 }
585
586 #if TARGET_J2EE
587                 //
588                 // Callback to be invoked by IHttpAsyncHandler.BeginProcessRequest
589                 //
590                 static void request_processed (IAsyncResult iar)
591                 {
592                         HttpContext context = (HttpContext) iar.AsyncState;
593
594                         context.Request.ReleaseResources ();
595                         context.Response.ReleaseResources ();
596                 }
597 #endif
598                 
599 #if TARGET_JVM
600                 [MonoNotSupported ("UnloadAppDomain is not supported")]
601                 public static void UnloadAppDomain ()
602                 {
603                         throw new NotImplementedException ("UnloadAppDomain is not supported");
604                 }
605 #else
606                 //
607                 // Called when we are shutting down or we need to reload an application
608                 // that has been modified (touch global.asax) 
609                 //
610                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
611                 public static void UnloadAppDomain ()
612                 {
613                         //
614                         // TODO: call ReleaseResources
615                         //
616                         domainUnloading = true;
617                         HttpApplicationFactory.DisableWatchers ();
618                         ThreadPool.QueueUserWorkItem (delegate {
619                                 try {
620                                         ShutdownAppDomain ();
621                                 } catch (Exception e){
622                                         Console.Error.WriteLine (e);
623                                 }
624                         });
625                 }
626 #endif
627                 //
628                 // Shuts down the AppDomain
629                 //
630                 static void ShutdownAppDomain ()
631                 {
632                         queue_manager.Dispose ();
633                         // This will call Session_End if needed.
634                         InternalCache.InvokePrivateCallbacks ();
635                         // Kill our application.
636                         HttpApplicationFactory.Dispose ();
637                         ThreadPool.QueueUserWorkItem (delegate {
638                                 try {
639                                         DoUnload ();
640                                 } catch {
641                                 }});
642                 }
643
644                 static void DoUnload ()
645                 {
646 #if TARGET_J2EE
647                         // No unload support for appdomains under Grasshopper
648 #else
649                         AppDomain.Unload (AppDomain.CurrentDomain);
650 #endif
651                 }
652
653                 static string content503 = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" +
654                         "<html><head>\n<title>503 Server Unavailable</title>\n</head><body>\n" +
655                         "<h1>Server Unavailable</h1>\n" +
656                         "</body></html>\n";
657
658                 static void FinishWithException (HttpWorkerRequest wr, HttpException e)
659                 {
660                         int code = e.GetHttpCode ();
661                         wr.SendStatus (code, HttpWorkerRequest.GetStatusDescription (code));
662                         wr.SendUnknownResponseHeader ("Connection", "close");
663                         Encoding enc = Encoding.ASCII;
664                         wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
665                         string msg = e.GetHtmlErrorMessage ();
666                         byte [] contentBytes = enc.GetBytes (msg);
667                         wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
668                         wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
669                         wr.FlushResponse (true);
670                         wr.CloseConnection ();
671                         HttpApplication.requests_total_counter.Increment ();
672                 }
673
674                 //
675                 // This is called from the QueueManager if a request
676                 // can not be processed (load, no resources, or
677                 // appdomain unload).
678                 //
679                 static internal void FinishUnavailable (HttpWorkerRequest wr)
680                 {
681                         wr.SendStatus (503, "Service unavailable");
682                         wr.SendUnknownResponseHeader ("Connection", "close");
683                         Encoding enc = Encoding.ASCII;
684                         wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
685                         byte [] contentBytes = enc.GetBytes (content503);
686                         wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
687                         wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
688                         wr.FlushResponse (true);
689                         wr.CloseConnection ();
690                         HttpApplication.requests_total_counter.Increment ();
691                 }
692
693                 [AspNetHostingPermissionAttribute(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Unrestricted)]
694                 [MonoDocumentationNote ("Always returns null on Mono")]
695                 public static NamedPermissionSet GetNamedPermissionSet ()
696                 {
697                         return null;
698                 }
699                 
700 #if !TARGET_J2EE
701                 static internal void WritePreservationFile (Assembly asm, string genericNameBase)
702                 {
703                         if (asm == null)
704                                 throw new ArgumentNullException ("asm");
705                         if (String.IsNullOrEmpty (genericNameBase))
706                                 throw new ArgumentNullException ("genericNameBase");
707
708                         string compiled = Path.Combine (AppDomain.CurrentDomain.SetupInformation.DynamicBase,
709                                                         genericNameBase + ".compiled");
710                         PreservationFile pf = new PreservationFile ();
711                         try {
712                                 pf.VirtualPath = String.Concat ("/", genericNameBase, "/");
713
714                                 AssemblyName an = asm.GetName ();
715                                 pf.Assembly = an.Name;
716                                 pf.ResultType = BuildResultTypeCode.TopLevelAssembly;
717                                 pf.Save (compiled);
718                         } catch (Exception ex) {
719                                 throw new HttpException (
720                                         String.Format ("Failed to write preservation file {0}", genericNameBase + ".compiled"),
721                                         ex);
722                         }
723                 }
724                 
725                 static Assembly ResolveAssemblyHandler(object sender, ResolveEventArgs e)
726                 {
727                         AssemblyName an = new AssemblyName (e.Name);
728                         string dynamic_base = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
729                         string compiled = Path.Combine (dynamic_base, an.Name + ".compiled");
730                         string asmPath;
731
732                         if (!File.Exists (compiled)) {
733                                 string fn = an.FullName;
734                                 if (!RegisteredAssemblies.Find ((uint)fn.GetHashCode (), fn, out asmPath))
735                                         return null;
736                         } else {
737                                 PreservationFile pf;
738                                 try {
739                                         pf = new PreservationFile (compiled);
740                                 } catch (Exception ex) {
741                                         throw new HttpException (
742                                                 String.Format ("Failed to read preservation file {0}", an.Name + ".compiled"),
743                                                 ex);
744                                 }
745                                 asmPath = Path.Combine (dynamic_base, pf.Assembly + ".dll");
746                         }
747
748                         if (String.IsNullOrEmpty (asmPath))
749                                 return null;
750                         
751                         Assembly ret = null;
752                         try {
753                                 ret = Assembly.LoadFrom (asmPath);
754                         } catch (Exception) {
755                                 // ignore
756                         }
757                         
758                         return ret;
759                 }
760                 
761                 internal static void EnableAssemblyMapping (bool enable)
762                 {
763                         lock (assemblyMappingLock) {
764                                 if (assemblyMappingEnabled == enable)
765                                         return;
766                                 if (enable)
767                                         AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (ResolveAssemblyHandler);
768                                 else
769                                         AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler (ResolveAssemblyHandler);
770                                 assemblyMappingEnabled = enable;
771                         }
772                 }
773 #endif // #if !TARGET_J2EE
774                 
775                 internal static TraceManager TraceManager {
776                         get {
777                                 return trace_manager;
778                         }
779                 }
780         }
781 }