2006-02-01 Chris Toshok <toshok@ximian.com>
[mono.git] / mcs / class / System.Web / System.Web / HttpApplication.cs
1 //
2 // System.Web.HttpApplication.cs 
3 //
4 // Author:
5 //      Miguel de Icaza (miguel@novell.com)
6 //      Gonzalo Paniagua (gonzalo@ximian.com)
7 //    
8 //
9 // Copyright (C) 2005 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 // The Application Processing Pipeline.
31 // 
32 //     The Http application pipeline implemented in this file is a
33 //     beautiful thing.  The application pipeline invokes a number of
34 //     hooks at various stages of the processing of a request.  These
35 //     hooks can be either synchronous or can be asynchronous.
36 //     
37 //     The pipeline must ensure that every step is completed before
38 //     moving to the next step.  A trivial thing for synchronous
39 //     hooks, but asynchronous hooks introduce an extra layer of
40 //     complexity: when the hook is invoked, the thread must
41 //     relinquish its control so that the thread can be reused in
42 //     another operation while waiting.
43 //
44 //     To implement this functionality we used C# iterators manually;
45 //     we drive the pipeline by executing the various hooks from the
46 //     `RunHooks' routine which is an enumerator that will yield the
47 //     value `false' if execution must proceed or `true' if execution
48 //     must be stopped.
49 //
50 //     By yielding values we can suspend execution of RunHooks.
51 //
52 //     Special attention must be given to `in_begin' and `must_yield'
53 //     variables.  These are used in the case that an async hook
54 //     completes synchronously as its important to not yield in that
55 //     case or we would hang.
56 //    
57 //     Many of Mono modules used to be declared async, but they would
58 //     actually be completely synchronous, this might resurface in the
59 //     future with other modules.
60 //
61 // TODO:
62 //    Events Disposed
63 //
64
65 using System.IO;
66 using System.Collections;
67 using System.ComponentModel;
68 using System.Configuration;
69 using System.Globalization;
70 using System.Security.Permissions;
71 using System.Security.Principal;
72 using System.Threading;
73 using System.Web.Configuration;
74 using System.Web.SessionState;
75 using System.Web.UI;
76         
77 namespace System.Web {
78
79         // CAS
80         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
81         [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
82         // attributes
83         [ToolboxItem(false)]
84         public class HttpApplication : IHttpAsyncHandler, IHttpHandler, IComponent, IDisposable {
85                 HttpContext context;
86                 HttpSessionState session;
87                 ISite isite;
88
89                 // The source, and the exposed API (cache).
90                 HttpModuleCollection modcoll;
91
92                 string assemblyLocation;
93
94                 //
95                 // The factory for the handler currently running.
96                 //
97                 IHttpHandlerFactory factory;
98                 
99                 //
100                 // Whether the pipeline should be stopped
101                 //
102                 bool stop_processing;
103
104                 //
105                 // The Pipeline
106                 //
107                 IEnumerator pipeline;
108
109                 // To flag when we are done processing a request from BeginProcessRequest.
110                 ManualResetEvent done;
111
112                 // The current IAsyncResult for the running async request handler in the pipeline
113                 AsyncRequestState begin_iar;
114
115                 // Tracks the current AsyncInvocation being dispatched
116                 AsyncInvoker current_ai;
117
118                 // We don't use the EventHandlerList here, but derived classes might do
119                 EventHandlerList events;
120
121                 // Culture and IPrincipal
122                 CultureInfo app_culture;
123                 CultureInfo appui_culture;
124                 CultureInfo prev_app_culture;
125                 CultureInfo prev_appui_culture;
126                 IPrincipal prev_user;
127 #if NET_2_0
128                 static Exception initialization_exception;
129 #endif
130
131                 //
132                 // These are used to detect the case where the EndXXX method is invoked
133                 // from within the BeginXXXX delegate, so we detect whether we kick the
134                 // pipeline from here, or from the the RunHook routine
135                 //
136                 bool must_yield;
137                 bool in_begin;
138
139                 public HttpApplication ()
140                 {
141                         done = new ManualResetEvent (false);
142                 }
143
144                 internal void InitOnce (bool full_init)
145                 {
146                         lock (this) {
147                                 if (modcoll != null)
148                                         return;
149
150 #if NET_2_0
151                                 HttpModulesSection modules;
152                                 modules = (HttpModulesSection) WebConfigurationManager.GetSection ("system.web/httpModules");
153 #else
154                                 ModulesConfiguration modules;
155
156                                 modules = (ModulesConfiguration) HttpContext.GetAppConfig ("system.web/httpModules");
157 #endif
158
159                                 modcoll = modules.LoadModules (this);
160
161                                 if (full_init)
162                                         HttpApplicationFactory.AttachEvents (this);
163
164 #if NET_2_0
165                                 GlobalizationSection cfg;
166                                 cfg = (GlobalizationSection) WebConfigurationManager.GetSection ("system.web/globalization");
167                                 app_culture = cfg.GetCulture();
168                                 appui_culture = cfg.GetUICulture();
169 #else
170                                 GlobalizationConfiguration cfg;
171                                 cfg = GlobalizationConfiguration.GetInstance (null);
172                                 if (cfg != null) {
173                                         app_culture = cfg.Culture;
174                                         appui_culture = cfg.UICulture;
175                                 }
176 #endif
177                         }
178                 }
179
180                 internal string AssemblyLocation {
181                         get {
182                                 if (assemblyLocation == null)
183                                         assemblyLocation = GetType ().Assembly.Location;
184                                 return assemblyLocation;
185                         }
186                 }
187
188 #if NET_2_0
189                 internal static Exception InitializationException {
190                         get { return initialization_exception; }
191                 }
192 #endif
193
194                 [Browsable (false)]
195                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
196                 public HttpApplicationState Application {
197                         get {
198                                 return HttpApplicationFactory.ApplicationState;
199                         }
200                 }
201
202                 [Browsable (false)]
203                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
204                 public HttpContext Context {
205                         get {
206                                 return context;
207                         }
208                 }
209                                          
210                 protected EventHandlerList Events {
211                         get {
212                                 if (events == null)
213                                         events = new EventHandlerList ();
214
215                                 return events;
216                         }
217                 }
218
219                 [Browsable (false)]
220                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
221                 public HttpModuleCollection Modules {
222                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
223                         get {
224                                 if (modcoll == null)
225                                         modcoll = new HttpModuleCollection ();
226                                 
227                                 return modcoll;
228                         }
229                 }
230
231                 [Browsable (false)]
232                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
233                 public HttpRequest Request {
234                         get {
235                                 if (context == null)
236                                         throw new HttpException (Locale.GetText ("No context is available."));
237
238                                 if (false == HttpApplicationFactory.ContextAvailable)
239                                         throw new HttpException (Locale.GetText ("Request is not available in this context."));
240
241                                 return context.Request;
242                         }
243                 }
244
245                 [Browsable (false)]
246                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
247                 public HttpResponse Response {
248                         get {
249                                 if (context == null)
250                                         throw new HttpException (Locale.GetText ("No context is available."));
251
252                                 if (false == HttpApplicationFactory.ContextAvailable)
253                                         throw new HttpException (Locale.GetText ("Response is not available in this context."));
254
255                                 return context.Response;
256                         }
257                 }
258
259                 [Browsable (false)]
260                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
261                 public HttpServerUtility Server {
262                         get {
263                                 if (context != null)
264                                         return context.Server;
265
266                                 //
267                                 // This is so we can get the Server and call a few methods
268                                 // which are not context sensitive, see HttpServerUtilityTest
269                                 //
270                                 return new HttpServerUtility ((HttpContext) null);
271                         }
272                 }
273
274                 [Browsable (false)]
275                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
276                 public HttpSessionState Session {
277                         get {
278                                 // Only used for Session_End
279                                 if (session != null)
280                                         return session;
281
282                                 if (context == null)
283                                         throw new HttpException (Locale.GetText ("No context is available."));
284                                 return context.Session;
285                         }
286                 }
287
288                 [Browsable (false)]
289                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
290 #if NET_2_0
291                 public ISite Site {
292 #else
293                 public virtual ISite Site {
294 #endif
295                         get {
296                                 return isite;
297                         }
298
299                         set {
300                                 isite = value;
301                         }
302                 }
303
304                 [Browsable (false)]
305                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
306                 public IPrincipal User {
307                         get {
308                                 if (context == null)
309                                         throw new HttpException (Locale.GetText ("No context is available."));
310                                 if (context.User == null)
311                                         throw new HttpException (Locale.GetText ("No currently authenticated user."));
312                                 
313                                 return context.User;
314                         }
315                 }
316                 
317                 public virtual event EventHandler Disposed;
318                 public virtual event EventHandler Error;
319
320                 public event EventHandler PreSendRequestHeaders;
321                 internal void TriggerPreSendRequestHeaders ()
322                 {
323                         if (PreSendRequestHeaders != null)
324                                 PreSendRequestHeaders (this, EventArgs.Empty);
325                 }
326
327                 public event EventHandler PreSendRequestContent;
328                 internal void TriggerPreSendRequestContent ()
329                 {
330                         if (PreSendRequestContent != null)
331                                 PreSendRequestContent (this, EventArgs.Empty);
332                 }
333                 
334                 public event EventHandler AcquireRequestState;
335                 public void AddOnAcquireRequestStateAsync (BeginEventHandler bh, EndEventHandler eh)
336                 {
337                         AsyncInvoker invoker = new AsyncInvoker (bh, eh);
338                         AcquireRequestState += new EventHandler (invoker.Invoke);
339                 }
340
341                 public event EventHandler AuthenticateRequest;
342                 public void AddOnAuthenticateRequestAsync (BeginEventHandler bh, EndEventHandler eh)
343                 {
344                         AsyncInvoker invoker = new AsyncInvoker (bh, eh);
345                         AuthenticateRequest += new EventHandler (invoker.Invoke);
346                 }
347
348                 public event EventHandler AuthorizeRequest;
349                 public void AddOnAuthorizeRequestAsync (BeginEventHandler bh, EndEventHandler eh)
350                 {
351                         AsyncInvoker invoker = new AsyncInvoker (bh, eh);
352                         AuthorizeRequest += new EventHandler (invoker.Invoke);
353                 }
354
355                 public event EventHandler BeginRequest;
356                 public void AddOnBeginRequestAsync (BeginEventHandler bh, EndEventHandler eh)
357                 {
358                         AsyncInvoker invoker = new AsyncInvoker (bh, eh);
359                         BeginRequest += new EventHandler (invoker.Invoke);
360                 }
361
362                 public event EventHandler EndRequest;
363                 public void AddOnEndRequestAsync (BeginEventHandler bh, EndEventHandler eh)
364                 {
365                         AsyncInvoker invoker = new AsyncInvoker (bh, eh);
366                         EndRequest += new EventHandler (invoker.Invoke);
367                 }
368                 
369                 public event EventHandler PostRequestHandlerExecute;
370                 public void AddOnPostRequestHandlerExecuteAsync (BeginEventHandler bh, EndEventHandler eh)
371                 {
372                         AsyncInvoker invoker = new AsyncInvoker (bh, eh);
373                         PostRequestHandlerExecute += new EventHandler (invoker.Invoke);
374                 }
375
376                 public event EventHandler PreRequestHandlerExecute;
377                 public void AddOnPreRequestHandlerExecuteAsync (BeginEventHandler bh, EndEventHandler eh)
378                 {
379                         AsyncInvoker invoker = new AsyncInvoker (bh, eh);
380                         PreRequestHandlerExecute += new EventHandler (invoker.Invoke);
381                 }
382
383                 public event EventHandler ReleaseRequestState;
384                 public void AddOnReleaseRequestStateAsync (BeginEventHandler bh, EndEventHandler eh)
385                 {
386                         AsyncInvoker invoker = new AsyncInvoker (bh, eh);
387                         ReleaseRequestState += new EventHandler (invoker.Invoke);
388                 }
389
390                 public event EventHandler ResolveRequestCache;
391                 public void AddOnResolveRequestCacheAsync (BeginEventHandler bh, EndEventHandler eh)
392                 {
393                         AsyncInvoker invoker = new AsyncInvoker (bh, eh);
394                         ResolveRequestCache += new EventHandler (invoker.Invoke);
395                 }
396
397                 public event EventHandler UpdateRequestCache;
398                 public void AddOnUpdateRequestCacheAsync (BeginEventHandler bh, EndEventHandler eh)
399                 {
400                         AsyncInvoker invoker = new AsyncInvoker (bh, eh);
401                         UpdateRequestCache += new EventHandler (invoker.Invoke);
402                 }
403
404 #if NET_2_0
405                 public event EventHandler PostAuthenticateRequest;
406                 public void AddOnPostAuthenticateRequestAsync (BeginEventHandler bh, EndEventHandler eh)
407                 {
408                         AddOnPostAuthenticateRequestAsync (bh, eh, null);
409                 }
410                         
411                 public void AddOnPostAuthenticateRequestAsync (BeginEventHandler bh, EndEventHandler eh, object data)
412                 {
413                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
414                         PostAuthenticateRequest += new EventHandler (invoker.Invoke);
415                 }
416                 
417                 public event EventHandler PostAuthorizeRequest;
418                 public void AddOnPostAuthorizeRequestAsync (BeginEventHandler bh, EndEventHandler eh)
419                 {
420                         AddOnPostAuthorizeRequestAsync (bh, eh, null);
421                 }
422                 
423                 public void AddOnPostAuthorizeRequestAsync (BeginEventHandler bh, EndEventHandler eh, object data)
424                 {
425                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
426                         PostAuthorizeRequest += new EventHandler (invoker.Invoke);
427                 }
428
429                 public event EventHandler PostResolveRequestCache;
430                 public void AddOnPostResolveRequestCacheAsync (BeginEventHandler bh, EndEventHandler eh)
431                 {
432                         AddOnPostResolveRequestCacheAsync (bh, eh, null);
433                 }
434                 
435                 public void AddOnPostResolveRequestCacheAsync (BeginEventHandler bh, EndEventHandler eh, object data)
436                 {
437                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
438                         PostResolveRequestCache += new EventHandler (invoker.Invoke);
439                 }
440
441                 public event EventHandler PostMapRequestHandler;
442                 public void AddOnPostMapRequestHandlerAsync (BeginEventHandler bh, EndEventHandler eh)
443                 {
444                         AddOnPostMapRequestHandlerAsync (bh, eh, null);
445                 }
446                 
447                 public void AddOnPostMapRequestHandlerAsync (BeginEventHandler bh, EndEventHandler eh, object data)
448                 {
449                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
450                         PostMapRequestHandler += new EventHandler (invoker.Invoke);
451                 }
452                 
453                 public event EventHandler PostAcquireRequestState;
454                 public void AddOnPostAcquireRequestStateAsync (BeginEventHandler bh, EndEventHandler eh)
455                 {
456                         AddOnPostAcquireRequestStateAsync (bh, eh, null);
457                 }
458                 
459                 public void AddOnPostAcquireRequestStateAsync (BeginEventHandler bh, EndEventHandler eh, object data)
460                 {
461                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
462                         PostAcquireRequestState += new EventHandler (invoker.Invoke);
463                 }
464                 
465                 public event EventHandler PostReleaseRequestState;
466                 public void AddOnPostReleaseRequestStateAsync (BeginEventHandler bh, EndEventHandler eh)
467                 {
468                         AddOnPostReleaseRequestStateAsync (bh, eh, null);
469                 }
470                 
471                 public void AddOnPostReleaseRequestStateAsync (BeginEventHandler bh, EndEventHandler eh, object data)
472                 {
473                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
474                         PostReleaseRequestState += new EventHandler (invoker.Invoke);
475                 }
476
477                 public event EventHandler PostUpdateRequestCache;
478                 public void AddOnPostUpdateRequestCacheAsync (BeginEventHandler bh, EndEventHandler eh)
479                 {
480                         AddOnPostUpdateRequestCacheAsync (bh, eh, null);
481                 }
482                 
483                 public void AddOnPostUpdateRequestCacheAsync (BeginEventHandler bh, EndEventHandler eh, object data)
484                 {
485                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
486                         PostUpdateRequestCache += new EventHandler (invoker.Invoke);
487                 }
488
489                 //
490                 // The new overloads that take a data parameter
491                 //
492                 public void AddOnAcquireRequestStateAsync (BeginEventHandler bh, EndEventHandler eh, object data)
493                 {
494                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
495                         AcquireRequestState += new EventHandler (invoker.Invoke);
496                 }
497
498                 public void AddOnAuthenticateRequestAsync (BeginEventHandler bh, EndEventHandler eh, object data)
499                 {
500                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
501                         AuthenticateRequest += new EventHandler (invoker.Invoke);
502                 }
503
504                 public void AddOnAuthorizeRequestAsync (BeginEventHandler bh, EndEventHandler eh, object data)
505                 {
506                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
507                         AuthorizeRequest += new EventHandler (invoker.Invoke);
508                 }
509
510                 public void AddOnBeginRequestAsync (BeginEventHandler bh, EndEventHandler eh, object data)
511                 {
512                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
513                         BeginRequest += new EventHandler (invoker.Invoke);
514                 }
515
516                 public void AddOnEndRequestAsync (BeginEventHandler bh, EndEventHandler eh, object data)
517                 {
518                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
519                         EndRequest += new EventHandler (invoker.Invoke);
520                 }
521                 
522                 public void AddOnPostRequestHandlerExecuteAsync (BeginEventHandler bh, EndEventHandler eh, object data)
523                 {
524                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
525                         PostRequestHandlerExecute += new EventHandler (invoker.Invoke);
526                 }
527
528                 public void AddOnPreRequestHandlerExecuteAsync (BeginEventHandler bh, EndEventHandler eh, object data)
529                 {
530                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
531                         PreRequestHandlerExecute += new EventHandler (invoker.Invoke);
532                 }
533
534                 public void AddOnReleaseRequestStateAsync (BeginEventHandler bh, EndEventHandler eh, object data)
535                 {
536                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
537                         ReleaseRequestState += new EventHandler (invoker.Invoke);
538                 }
539
540                 public void AddOnResolveRequestCacheAsync (BeginEventHandler bh, EndEventHandler eh, object data)
541                 {
542                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
543                         ResolveRequestCache += new EventHandler (invoker.Invoke);
544                 }
545
546                 public void AddOnUpdateRequestCacheAsync (BeginEventHandler bh, EndEventHandler eh, object data)
547                 {
548                         AsyncInvoker invoker = new AsyncInvoker (bh, eh, data);
549                         UpdateRequestCache += new EventHandler (invoker.Invoke);
550                 }
551 #endif
552                 
553                 internal event EventHandler DefaultAuthentication;
554                 
555                 //
556                 // Bypass all the event on the Http pipeline and go directly to EndRequest
557                 //
558                 public void CompleteRequest ()
559                 {
560                         stop_processing = true;
561                 }
562
563                 internal bool RequestCompleted {
564                         set { stop_processing = value; }
565                 }
566
567                 public virtual void Dispose ()
568                 {
569                         if (modcoll != null) {
570                                 for (int i = modcoll.Count; i >= 0; i--) {
571                                         modcoll.Get (i).Dispose ();
572                                 }
573                                 modcoll = null;
574                         }
575
576                         if (Disposed != null)
577                                 Disposed (this, EventArgs.Empty);
578                         
579                         done.Close ();
580                         done = null;
581                 }
582
583                 public virtual string GetVaryByCustomString (HttpContext context, string custom)
584                 {
585                         if (custom == null) // Sigh
586                                 throw new NullReferenceException ();
587
588                         if (0 == String.Compare (custom, "browser", true, CultureInfo.InvariantCulture))
589                                 return context.Request.Browser.Type;
590
591                         return null;
592                 }
593
594                 //
595                 // If we catch an error, queue this error
596                 //
597                 void ProcessError (Exception e)
598                 {
599                         bool first = context.Error == null;
600                         
601                         context.AddError (e);
602                         if (first){
603                                 if (Error != null){
604                                         try {
605                                                 Error (this, EventArgs.Empty);
606                                         } catch (ThreadAbortException ee){
607                                                 // This happens on Redirect() or End()
608                                                 Thread.ResetAbort ();
609                                         } catch (Exception ee){
610                                                 context.AddError (ee);
611                                         }
612                                 }
613                         }
614                         stop_processing = true;
615                 }
616                 
617                 //
618                 // Ticks the clock: next step on the pipeline.
619                 //
620                 void Tick ()
621                 {
622                         try {
623                                 if (pipeline.MoveNext ()){
624                                         if ((bool)pipeline.Current)
625                                                 PipelineDone ();
626                                 }
627                         } catch (Exception e) {
628                                 Console.WriteLine ("Tick caught an exception that has not been propagated:\n" + e);
629                         }
630                 }
631
632                 void Resume ()
633                 {
634                         if (in_begin)
635                                 must_yield = false;
636                         else
637                                 Tick ();
638                 }
639                 
640                 //
641                 // Invoked when our async callback called from RunHooks completes,
642                 // we restart the pipeline here.
643                 //
644                 void async_callback_completed_cb (IAsyncResult ar)
645                 {
646                         if (current_ai.end != null){
647                                 try {
648                                         current_ai.end (ar);
649                                 } catch (Exception e) {
650                                         ProcessError (e);
651                                 }
652                         }
653
654                         Resume ();
655                 }
656
657                 void async_handler_complete_cb (IAsyncResult ar)
658                 {
659                         IHttpAsyncHandler async_handler = ((IHttpAsyncHandler) ar.AsyncState);
660
661                         try {
662                                 async_handler.EndProcessRequest (ar);
663                         } catch (Exception e){
664                                 ProcessError (e);
665                         }
666                         
667                         Resume ();
668                 }
669                 
670                 //
671                 // This enumerator yields whether processing must be stopped:
672                 //    true:  processing of the pipeline must be stopped
673                 //    false: processing of the pipeline must not be stopped
674                 //
675                 IEnumerable RunHooks (Delegate list)
676                 {
677                         Delegate [] delegates = list.GetInvocationList ();
678
679                         foreach (EventHandler d in delegates){
680                                 if (d.Target != null && (d.Target is AsyncInvoker)){
681                                         current_ai = (AsyncInvoker) d.Target;
682
683                                         try {
684                                                 must_yield = true;
685                                                 in_begin = true;
686                                                 context.BeginTimeoutPossible ();
687                                                 current_ai.begin (this, EventArgs.Empty, async_callback_completed_cb, current_ai.data);
688                                         } catch (ThreadAbortException taex){
689                                                 object obj = taex.ExceptionState;
690                                                 Thread.ResetAbort ();
691                                                 stop_processing = true;
692                                                 if (obj is StepTimeout)
693                                                         ProcessError (new HttpException ("The request timed out."));
694                                         } catch (Exception e){
695                                                 ProcessError (e);
696                                         } finally {
697                                                 in_begin = false;
698                                                 context.EndTimeoutPossible ();
699                                         }
700
701                                         //
702                                         // If things are still moving forward, yield this
703                                         // thread now
704                                         //
705                                         if (must_yield)
706                                                 yield return stop_processing;
707                                         else if (stop_processing)
708                                                 yield return true;
709                                 } else {
710                                         try {
711                                                 context.BeginTimeoutPossible ();
712                                                 d (this, EventArgs.Empty);
713                                         } catch (ThreadAbortException taex){
714                                                 object obj = taex.ExceptionState;
715                                                 Thread.ResetAbort ();
716                                                 stop_processing = true;
717                                                 if (obj is StepTimeout)
718                                                         ProcessError (new HttpException ("The request timed out."));
719                                         } catch (Exception e){
720                                                 ProcessError (e);
721                                         } finally {
722                                                 context.EndTimeoutPossible ();
723                                         }
724                                         if (stop_processing)
725                                                 yield return true;
726                                 }
727                         }
728                 }
729
730                 static void FinalErrorWrite (HttpResponse response, string error)
731                 {
732                         try {
733                                 response.Write (error);
734                                 response.Flush (true);
735                         } catch {
736                                 response.Close ();
737                         }
738                 }
739
740                 void OutputPage ()
741                 {
742                         if (context.Error == null){
743                                 try {
744                                         context.Response.Flush (true);
745                                 } catch (Exception e){
746                                         context.AddError (e);
747                                 }
748                         }
749
750                         Exception error = context.Error;
751                         if (error != null){
752                                 HttpResponse response = context.Response;
753
754                                 if (!response.HeadersSent){
755                                         response.ClearHeaders ();
756                                         response.ClearContent ();
757
758                                         if (error is HttpException){
759                                                 response.StatusCode = ((HttpException)error).GetHttpCode ();
760                                         } else {
761                                                 error = new HttpException ("", error);
762                                                 response.StatusCode = 500;
763                                         }
764                                         if (!RedirectCustomError ())
765                                                 FinalErrorWrite (response, ((HttpException) error).GetHtmlErrorMessage ());
766                                         else
767                                                 response.Flush (true);
768                                 } else {
769                                         if (!(error is HttpException))
770                                                 error = new HttpException ("", error);
771                                         FinalErrorWrite (response, ((HttpException) error).GetHtmlErrorMessage ());
772                                 }
773                         }
774                         
775                 }
776                 
777                 //
778                 // Invoked at the end of the pipeline execution
779                 //
780                 void PipelineDone ()
781                 {
782                         try {
783                                 if (EndRequest != null)
784                                         EndRequest (this, EventArgs.Empty);
785                         } catch (Exception e){
786                                 ProcessError (e);
787                         }
788
789                         try {
790
791                                 OutputPage ();
792                         } catch (Exception e) {
793                                 Console.WriteLine ("Internal error: OutputPage threw an exception " + e);
794                         } finally {
795                                 context.WorkerRequest.EndOfRequest();
796                                 if (begin_iar != null){
797                                         try {
798                                                 begin_iar.Complete ();
799                                         } catch {
800                                                 //
801                                                 // TODO: if this throws an error, we have no way of reporting it
802                                                 // Not really too bad, since the only failure might be
803                                                 // `HttpRuntime.request_processed'
804                                                 //
805                                         }
806                                 }
807                                 
808                                 done.Set ();
809
810                                 if (factory != null && context.Handler != null){
811                                         factory.ReleaseHandler (context.Handler);
812                                         factory = null;
813                                 }
814                                 
815                                 context.Handler = null;
816                                 // context = null; -> moved to PostDone
817                                 pipeline = null;
818                                 current_ai = null;
819                         }
820                         PostDone ();
821                 }
822
823                 //
824                 // Events fired as described in `Http Runtime Support, HttpModules,
825                 // Handling Public Events'
826                 //
827                 IEnumerator Pipeline ()
828                 {
829                         if (stop_processing)
830                                 yield return true;
831
832                         if (BeginRequest != null)
833                                 foreach (bool stop in RunHooks (BeginRequest))
834                                         yield return stop;
835
836                         if (AuthenticateRequest != null)
837                                 foreach (bool stop in RunHooks (AuthenticateRequest))
838                                         yield return stop;
839
840                         if (DefaultAuthentication != null)
841                                 foreach (bool stop in RunHooks (DefaultAuthentication))
842                                         yield return stop;
843
844 #if NET_2_0
845                         if (PostAuthenticateRequest != null)
846                                 foreach (bool stop in RunHooks (AuthenticateRequest))
847                                         yield return stop;
848 #endif
849                         if (AuthorizeRequest != null)
850                                 foreach (bool stop in RunHooks (AuthorizeRequest))
851                                         yield return stop;
852 #if NET_2_0
853                         if (PostAuthorizeRequest != null)
854                                 foreach (bool stop in RunHooks (PostAuthorizeRequest))
855                                         yield return stop;
856 #endif
857
858                         if (ResolveRequestCache != null)
859                                 foreach (bool stop in RunHooks (ResolveRequestCache))
860                                         yield return stop;
861
862                         // Obtain the handler for the request.
863                         IHttpHandler handler = null;
864                         try {
865                                 handler = GetHandler (context);
866                         } catch (FileNotFoundException fnf){
867                                 if (context.Request.IsLocal)
868                                         ProcessError (new HttpException (404, String.Format ("File not found {0}", fnf.FileName), fnf));
869                                 else
870                                         ProcessError (new HttpException (404, "File not found", fnf));
871                         } catch (DirectoryNotFoundException dnf){
872                                 ProcessError (new HttpException (404, "Directory not found", dnf));
873                         } catch (Exception e) {
874                                 ProcessError (e);
875                         }
876
877                         if (stop_processing)
878                                 yield return true;
879
880 #if NET_2_0
881                         if (PostResolveRequestCache != null)
882                                 foreach (bool stop in RunHooks (PostResolveRequestCache))
883                                         yield return stop;
884
885                         if (PostMapRequestHandler != null)
886                                 foreach (bool stop in RunHooks (PostMapRequestHandler))
887                                         yield return stop;
888                         
889 #endif
890                         if (AcquireRequestState != null){
891                                 foreach (bool stop in RunHooks (AcquireRequestState))
892                                         yield return stop;
893                         }
894
895 #if NET_2_0
896                         if (PostAcquireRequestState != null){
897                                 foreach (bool stop in RunHooks (PostAcquireRequestState))
898                                         yield return stop;
899                         }
900 #endif
901                         
902                         //
903                         // From this point on, we need to ensure that we call
904                         // ReleaseRequestState, so the code below jumps to
905                         // `release:' to guarantee it rather than yielding.
906                         //
907                         if (PreRequestHandlerExecute != null)
908                                 foreach (bool stop in RunHooks (PreRequestHandlerExecute))
909                                         if (stop)
910                                                 goto release;
911                                 
912                         try {
913                                 context.BeginTimeoutPossible ();
914                                 if (handler != null){
915                                         IHttpAsyncHandler async_handler = handler as IHttpAsyncHandler;
916                                         
917                                         if (async_handler != null){
918                                                 must_yield = true;
919                                                 in_begin = true;
920                                                 async_handler.BeginProcessRequest (context, async_handler_complete_cb, handler);
921                                         } else {
922                                                 must_yield = false;
923                                                 handler.ProcessRequest (context);
924                                         }
925                                 }
926                         } catch (ThreadAbortException taex){
927                                 object obj = taex.ExceptionState;
928                                 Thread.ResetAbort ();
929                                 stop_processing = true;
930                                 if (obj is StepTimeout)
931                                         ProcessError (new HttpException ("The request timed out."));
932                         } catch (Exception e){
933                                 ProcessError (e);
934                         } finally {
935                                 in_begin = false;
936                                 context.EndTimeoutPossible ();
937                         }
938                         if (must_yield)
939                                 yield return stop_processing;
940                         else if (stop_processing)
941                                 goto release;
942                         
943                         // These are executed after the application has returned
944                         
945                         if (PostRequestHandlerExecute != null)
946                                 foreach (bool stop in RunHooks (PostRequestHandlerExecute))
947                                         if (stop)
948                                                 goto release;
949                         
950                 release:
951                         if (ReleaseRequestState != null){
952 #pragma warning disable 168
953                                 foreach (bool stop in RunHooks (ReleaseRequestState)){
954                                         //
955                                         // Ignore the stop signal while release the state
956                                         //
957                                         
958                                 }
959 #pragma warning restore 168
960                         }
961                         
962                         if (stop_processing)
963                                 yield return true;
964
965 #if NET_2_0
966                         if (PostReleaseRequestState != null)
967                                 foreach (bool stop in RunHooks (PostReleaseRequestState))
968                                         yield return stop;
969 #endif
970
971                         if (context.Error == null)
972                                 context.Response.DoFilter (true);
973
974                         if (UpdateRequestCache != null)
975                                 foreach (bool stop in RunHooks (UpdateRequestCache))
976                                         yield return stop;
977
978 #if NET_2_0
979                         if (PostUpdateRequestCache != null)
980                                 foreach (bool stop in RunHooks (PostUpdateRequestCache))
981                                         yield return stop;
982 #endif
983                         PipelineDone ();
984                 }
985
986                 void PreStart ()
987                 {
988 #if !TARGET_J2EE
989                         HttpRuntime.TimeoutManager.Add (context);
990 #endif
991                         Thread th = Thread.CurrentThread;
992                         if (app_culture != null) {
993                                 prev_app_culture = th.CurrentCulture;
994                                 th.CurrentCulture = app_culture;
995                         }
996
997                         if (appui_culture != null) {
998                                 prev_appui_culture = th.CurrentUICulture;
999                                 th.CurrentUICulture = appui_culture;
1000                         }
1001
1002 #if !TARGET_JVM
1003                         prev_user = Thread.CurrentPrincipal;
1004 #endif
1005                 }
1006
1007                 void PostDone ()
1008                 {
1009                         Thread th = Thread.CurrentThread;
1010 #if !TARGET_JVM
1011                         if (Thread.CurrentPrincipal != prev_user)
1012                                 Thread.CurrentPrincipal = prev_user;
1013 #endif
1014                         if (prev_appui_culture != null && prev_appui_culture != th.CurrentUICulture)
1015                                 th.CurrentUICulture = prev_appui_culture;
1016                         if (prev_app_culture != null && prev_app_culture != th.CurrentCulture)
1017                                 th.CurrentCulture = prev_app_culture;
1018
1019 #if !TARGET_J2EE
1020                         HttpRuntime.TimeoutManager.Remove (context);
1021 #endif
1022                         context = null;
1023                         session = null;
1024                         HttpContext.Current = null;
1025                 }
1026
1027                 void Start (object x)
1028                 {
1029                         try {
1030                                 InitOnce (true);
1031                         } catch (Exception e) {
1032 #if NET_2_0
1033                                 initialization_exception = e;
1034 #endif
1035                                 FinalErrorWrite (context.Response, new HttpException ("", e).GetHtmlErrorMessage ());
1036                                 return;
1037                         }
1038
1039                         PreStart ();
1040                         pipeline = Pipeline ();
1041                         Tick ();
1042                 }
1043         
1044                 // Used by HttpServerUtility.Execute
1045                 internal IHttpHandler GetHandler (HttpContext context)
1046                 {
1047                         HttpRequest request = context.Request;
1048                         string verb = request.RequestType;
1049                         string url = request.FilePath;
1050                         
1051                         IHttpHandler handler = null;
1052 #if NET_2_0
1053                         HttpHandlersSection section = (HttpHandlersSection) WebConfigurationManager.GetSection ("system.web/httpHandlers");
1054                         object o = section.LocateHandler (verb, url);
1055 #else
1056                         HandlerFactoryConfiguration factory_config = (HandlerFactoryConfiguration) HttpContext.GetAppConfig ("system.web/httpHandlers");
1057                         object o = factory_config.LocateHandler (verb, url);
1058 #endif
1059
1060                         factory = o as IHttpHandlerFactory;
1061                         
1062                         if (factory == null) {
1063                                 handler = (IHttpHandler) o;
1064                         } else {
1065                                 handler = factory.GetHandler (context, verb, url, request.PhysicalPath);
1066                         }
1067                         context.Handler = handler;
1068
1069                         return handler;
1070                 }
1071                 
1072                 void IHttpHandler.ProcessRequest (HttpContext context)
1073                 {
1074                         begin_iar = null;
1075                         this.context = context;
1076                         done.Reset ();
1077
1078                         Start (null);
1079                         done.WaitOne ();
1080                 }
1081
1082                 //
1083                 // This is used by FireOnAppStart, when we init the application
1084                 // as the context is required to be set at that point (the user
1085                 // might call methods that require it on that hook).
1086                 //
1087                 internal void SetContext (HttpContext context)
1088                 {
1089                         this.context = context;
1090                 }
1091
1092                 internal void SetSession (HttpSessionState session)
1093                 {
1094                         this.session = session;
1095                 }
1096
1097                 IAsyncResult IHttpAsyncHandler.BeginProcessRequest (HttpContext context, AsyncCallback cb, object extraData)
1098                 {
1099                         this.context = context;
1100                         done.Reset ();
1101                         
1102                         begin_iar = new AsyncRequestState (done, cb, extraData);
1103
1104                         if (Thread.CurrentThread.IsThreadPoolThread)
1105                                 Start (null);
1106                         else
1107                                 ThreadPool.QueueUserWorkItem (new WaitCallback (Start), null);
1108                         
1109                         return begin_iar;
1110                 }
1111
1112                 void IHttpAsyncHandler.EndProcessRequest (IAsyncResult result)
1113                 {
1114                         if (!result.IsCompleted)
1115                                 result.AsyncWaitHandle.WaitOne ();
1116                         begin_iar = null;
1117                 }
1118
1119                 public virtual void Init ()
1120                 {
1121                 }
1122
1123                 bool IHttpHandler.IsReusable {
1124                         get {
1125                                 return true;
1126                         }
1127                 }
1128                 
1129 #region internals
1130                 internal void ClearError ()
1131                 {
1132                         context.ClearError ();
1133                 }
1134
1135                 bool RedirectErrorPage (string error_page)
1136                 {
1137                         if (context.Request.QueryString ["aspxerrorpath"] != null)
1138                                 return false;
1139
1140                         Response.Redirect (error_page + "?aspxerrorpath=" + Request.Path, false);
1141                         return true;
1142                 }
1143                                                         
1144                 bool RedirectCustomError ()
1145                 {
1146                         if (!context.IsCustomErrorEnabled)
1147                                 return false;
1148                         
1149 #if NET_2_0
1150                         CustomErrorsSection config = (CustomErrorsSection)WebConfigurationManager.GetSection ("system.web/customErrors");
1151 #else
1152                         CustomErrorsConfig config = null;
1153                         try {
1154                                 config = (CustomErrorsConfig) context.GetConfig ("system.web/customErrors");
1155                         } catch { }
1156 #endif
1157                         
1158                         if (config == null) {
1159                                 if (context.ErrorPage != null)
1160                                         return RedirectErrorPage (context.ErrorPage);
1161                                 
1162                                 return false;
1163                         }
1164                         
1165 #if NET_2_0
1166                         CustomError err = config.Errors [context.Response.StatusCode.ToString()];
1167                         string redirect = err == null ? null : err.Redirect;
1168 #else
1169                         string redirect =  config [context.Response.StatusCode];
1170 #endif
1171                         if (redirect == null) {
1172                                 redirect = context.ErrorPage;
1173                                 if (redirect == null)
1174                                         redirect = config.DefaultRedirect;
1175                         }
1176                         
1177                         if (redirect == null)
1178                                 return false;
1179                         
1180                         return RedirectErrorPage (redirect);
1181                 }
1182 #endregion
1183         }
1184
1185         //
1186         // Based on Fritz' Onion's AsyncRequestState class for asynchronous IHttpAsyncHandlers
1187         // 
1188         class AsyncRequestState : IAsyncResult {
1189                 AsyncCallback cb;
1190                 object cb_data;
1191                 bool completed;
1192                 ManualResetEvent complete_event = null;
1193                 
1194                 internal AsyncRequestState (ManualResetEvent complete_event, AsyncCallback cb, object cb_data)
1195                 {
1196                         this.cb = cb;
1197                         this.cb_data = cb_data;
1198                         this.complete_event = complete_event;
1199                 }
1200
1201                 internal void Complete ()
1202                 {
1203                         completed = true;
1204                         if (cb != null)
1205                                 cb (this);
1206                         
1207                         complete_event.Set ();
1208                 }
1209
1210                 public object AsyncState {
1211                         get {
1212                                 return cb_data;
1213                         }
1214                 }
1215
1216                 public bool CompletedSynchronously {
1217                         get {
1218                                 return false;
1219                         }
1220                 }
1221
1222                 public bool IsCompleted {
1223                         get {
1224                                 return completed;
1225                         }
1226                 }
1227
1228                 public WaitHandle AsyncWaitHandle {
1229                         get {
1230                                 return complete_event;
1231                         }
1232                 }
1233         }
1234
1235 #region Helper classes
1236         
1237         //
1238         // A wrapper to keep track of begin/end pairs
1239         //
1240         class AsyncInvoker {
1241                 public BeginEventHandler begin;
1242                 public EndEventHandler end;
1243                 public object data;
1244                 
1245                 public AsyncInvoker (BeginEventHandler bh, EndEventHandler eh, object d)
1246                 {
1247                         begin = bh;
1248                         end = eh;
1249                         data = d;
1250                 }
1251
1252                 public AsyncInvoker (BeginEventHandler bh, EndEventHandler eh)
1253                 {
1254                         begin = bh;
1255                         end = eh;
1256                 }
1257                 
1258                 public void Invoke (object sender, EventArgs e)
1259                 {
1260                         throw new Exception ("This is just a dummy");
1261                 }
1262         }
1263 #endregion
1264 }
1265