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