Merge pull request #409 from Alkarex/patch-1
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel.Channels.Http / HttpListenerManager.cs
1 //
2 // HttpListenerManager.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2010 Novell, Inc.  http://www.novell.com
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 using System;
29 using System.Collections.Generic;
30 using System.Collections.ObjectModel;
31 using System.Linq;
32 using System.Net;
33 using System.Net.Security;
34 using System.ServiceModel;
35 using System.ServiceModel.Channels;
36 using System.ServiceModel.Description;
37 using System.ServiceModel.Dispatcher;
38 using System.ServiceModel.Security;
39 using System.Text;
40 using System.Threading;
41
42 namespace System.ServiceModel.Channels.Http
43 {
44         internal abstract class HttpListenerManager
45         {
46                 protected HttpListenerManager ()
47                 {
48                         Entries = new List<HttpChannelListenerEntry> ();
49                 }
50
51                 public List<HttpChannelListenerEntry> Entries { get; private set; }
52
53                 public abstract void RegisterListener (ChannelDispatcher channel, HttpTransportBindingElement element, TimeSpan timeout);
54                 public abstract void UnregisterListener (ChannelDispatcher channel, TimeSpan timeout);
55
56                 protected void RegisterListenerCommon (ChannelDispatcher channel, TimeSpan timeout)
57                 {
58                         Entries.Add (new HttpChannelListenerEntry (channel, new AutoResetEvent (false)));
59
60                         Entries.Sort (HttpChannelListenerEntry.CompareEntries);
61                 }
62
63                 protected void UnregisterListenerCommon (ChannelDispatcher channel, TimeSpan timeout)
64                 {
65                         var entry = Entries.First (e => e.ChannelDispatcher == channel);
66                         Entries.Remove (entry);
67
68                         entry.WaitHandle.Set (); // make sure to finish pending requests.
69                 }
70
71                 public void ProcessNewContext (HttpContextInfo ctxi)
72                 {
73                         var ce = SelectChannel (ctxi);
74                         if (ce == null)
75                                 throw new InvalidOperationException ("HttpListenerContext does not match any of the registered channels");
76                         ce.ContextQueue.Enqueue (ctxi);
77                         ce.WaitHandle.Set ();
78                 }
79
80                 HttpChannelListenerEntry SelectChannel (HttpContextInfo ctx)
81                 {
82                         foreach (var e in Entries)
83                                 if (e.FilterHttpContext (ctx))
84                                         return e;
85                         return null;
86                 }
87
88                 public bool TryDequeueRequest (ChannelDispatcher channel, TimeSpan timeout, out HttpContextInfo context)
89                 {
90                         DateTime start = DateTime.Now;
91
92                         context = null;
93                         var ce = Entries.FirstOrDefault (e => e.ChannelDispatcher == channel);
94                         if (ce == null)
95                                 return false;
96                         lock (ce.RetrieverLock) {
97                                 var q = ce.ContextQueue;
98                                 if (q.Count == 0) {
99                                         if (timeout.TotalMilliseconds < 0) return false;
100                                         TimeSpan waitTimeout = timeout;
101                                         if (timeout == TimeSpan.MaxValue)
102                                                 waitTimeout = TimeSpan.FromMilliseconds (int.MaxValue);
103                                         bool ret = ce.WaitHandle.WaitOne (waitTimeout);
104                                         return ret && TryDequeueRequest (channel, waitTimeout - (DateTime.Now - start), out context); // recurse, am lazy :/
105                                 }
106                                 context = q.Dequeue ();
107                                 return true;
108                         }
109                 }
110         }
111
112         internal class HttpStandaloneListenerManager : HttpListenerManager
113         {
114                 public HttpStandaloneListenerManager (Uri uri, HttpTransportBindingElement element)
115                 {
116                         var l = new HttpListener ();
117
118                         string uriString = element.HostNameComparisonMode == HostNameComparisonMode.Exact ? uri.ToString () : uri.Scheme + "://*" + uri.GetComponents (UriComponents.Port | UriComponents.Path, UriFormat.SafeUnescaped);
119                         if (!uriString.EndsWith ("/", StringComparison.Ordinal))
120                                 uriString += "/"; // HttpListener requires this mess.
121
122                         l.Prefixes.Add (uriString);
123
124                         this.listener = l;
125                 }
126                 
127                 HttpListener listener;
128
129                 Thread loop;
130
131                 // FIXME: use timeout
132                 public override void RegisterListener (ChannelDispatcher channel, HttpTransportBindingElement element, TimeSpan timeout)
133                 {
134                         RegisterListenerCommon (channel, timeout);
135
136                         if (Entries.Count != 1)
137                                 return;
138
139                         if (element != null) {
140                                 var l = listener;
141                                 l.AuthenticationSchemeSelectorDelegate = delegate (HttpListenerRequest req) {
142                                         return element.AuthenticationScheme;
143                                 };
144                                 l.Realm = element.Realm;
145                                 l.UnsafeConnectionNtlmAuthentication = element.UnsafeConnectionNtlmAuthentication;
146                         }
147
148                         // Start here. It is shared between channel listeners
149                         // that share the same listen Uri. So there is no other appropriate place.
150 #if USE_SEPARATE_LOOP // this cannot be enabled because it causes infinite loop when ChannelDispatcher is not involved.
151                         loop = new Thread (new ThreadStart (delegate {
152                                 listener.Start ();
153                                 try {
154                                         while (true)
155                                                 ProcessNewContext (listener.GetContext ());
156                                 } catch (ThreadAbortException) {
157                                         Thread.ResetAbort ();
158                                 }
159                                 listener.Stop ();
160                         }));
161                         loop.Start ();
162 #else
163                         listener.Start ();
164                         listener.BeginGetContext (GetContextCompleted, null);
165 #endif
166                 }
167
168                 // FIXME: use timeout
169                 public override void UnregisterListener (ChannelDispatcher channel, TimeSpan timeout)
170                 {
171                         UnregisterListenerCommon (channel, timeout);
172
173                         // stop the server if there is no more registered listener.
174                         if (Entries.Count > 0)
175                                 return;
176
177 #if USE_SEPARATE_LOOP
178                         loop.Abort ();
179 #else
180                         this.listener.Stop ();
181 #endif
182                 }
183                 
184                 void GetContextCompleted (IAsyncResult result)
185                 {
186                         var ctx = listener.EndGetContext (result);
187                         ProcessNewContext (ctx);
188                         // start another listening
189                         listener.BeginGetContext (GetContextCompleted, null);
190                 }
191
192                 void ProcessNewContext (HttpListenerContext ctx)
193                 {
194                         if (ctx == null)
195                                 return;
196                         ProcessNewContext (new HttpStandaloneContextInfo (ctx));
197                 }
198         }
199
200         internal class AspNetHttpListenerManager : HttpListenerManager
201         {
202                 public AspNetHttpListenerManager (Uri uri)
203                 {
204                 }
205
206                 public override void RegisterListener (ChannelDispatcher channel, HttpTransportBindingElement element, TimeSpan timeout)
207                 {
208                         RegisterListenerCommon (channel, timeout);
209                 }
210
211                 public override void UnregisterListener (ChannelDispatcher channel, TimeSpan timeout)
212                 {
213                         UnregisterListenerCommon (channel, timeout);
214                 }
215         }
216 }
217