2 // HttpListenerManager.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2010 Novell, Inc. http://www.novell.com
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:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
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.
29 using System.Collections.Generic;
30 using System.Collections.ObjectModel;
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;
40 using System.Threading;
42 namespace System.ServiceModel.Channels.Http
44 internal abstract class HttpListenerManager
46 protected HttpListenerManager ()
48 Entries = new List<HttpChannelListenerEntry> ();
51 public List<HttpChannelListenerEntry> Entries { get; private set; }
53 public abstract void RegisterListener (ChannelDispatcher channel, HttpTransportBindingElement element, TimeSpan timeout);
54 public abstract void UnregisterListener (ChannelDispatcher channel, TimeSpan timeout);
56 protected void RegisterListenerCommon (ChannelDispatcher channel, TimeSpan timeout)
58 Entries.Add (new HttpChannelListenerEntry (channel, new AutoResetEvent (false)));
60 Entries.Sort (HttpChannelListenerEntry.CompareEntries);
63 protected void UnregisterListenerCommon (ChannelDispatcher channel, TimeSpan timeout)
65 var entry = Entries.First (e => e.ChannelDispatcher == channel);
66 Entries.Remove (entry);
68 entry.WaitHandle.Set (); // make sure to finish pending requests.
71 public void ProcessNewContext (HttpContextInfo ctxi)
73 var ce = SelectChannel (ctxi);
75 throw new InvalidOperationException ("HttpListenerContext does not match any of the registered channels");
76 ce.ContextQueue.Enqueue (ctxi);
80 HttpChannelListenerEntry SelectChannel (HttpContextInfo ctx)
82 foreach (var e in Entries)
83 if (e.FilterHttpContext (ctx))
88 public bool TryDequeueRequest (ChannelDispatcher channel, TimeSpan timeout, out HttpContextInfo context)
90 DateTime start = DateTime.Now;
93 var ce = Entries.FirstOrDefault (e => e.ChannelDispatcher == channel);
96 lock (ce.RetrieverLock) {
97 var q = ce.ContextQueue;
99 TimeSpan waitTimeout = timeout;
100 if (timeout == TimeSpan.MaxValue)
101 waitTimeout = TimeSpan.FromMilliseconds (int.MaxValue);
102 bool ret = ce.WaitHandle.WaitOne (waitTimeout);
103 return ret && TryDequeueRequest (channel, waitTimeout - (DateTime.Now - start), out context); // recurse, am lazy :/
105 context = q.Dequeue ();
111 internal class HttpStandaloneListenerManager : HttpListenerManager
113 public HttpStandaloneListenerManager (Uri uri, HttpTransportBindingElement element)
115 var l = new HttpListener ();
117 string uriString = element.HostNameComparisonMode == HostNameComparisonMode.Exact ? uri.ToString () : uri.Scheme + "://*" + uri.GetComponents (UriComponents.Port | UriComponents.Path, UriFormat.SafeUnescaped);
118 if (!uriString.EndsWith ("/", StringComparison.Ordinal))
119 uriString += "/"; // HttpListener requires this mess.
121 l.Prefixes.Add (uriString);
126 HttpListener listener;
130 // FIXME: use timeout
131 public override void RegisterListener (ChannelDispatcher channel, HttpTransportBindingElement element, TimeSpan timeout)
133 RegisterListenerCommon (channel, timeout);
135 if (Entries.Count != 1)
138 if (element != null) {
140 l.AuthenticationSchemeSelectorDelegate = delegate (HttpListenerRequest req) {
141 return element.AuthenticationScheme;
143 l.Realm = element.Realm;
144 l.UnsafeConnectionNtlmAuthentication = element.UnsafeConnectionNtlmAuthentication;
147 // Start here. It is shared between channel listeners
148 // that share the same listen Uri. So there is no other appropriate place.
149 #if USE_SEPARATE_LOOP // this cannot be enabled because it causes infinite loop when ChannelDispatcher is not involved.
150 loop = new Thread (new ThreadStart (delegate {
154 ProcessNewContext (listener.GetContext ());
155 } catch (ThreadAbortException) {
156 Thread.ResetAbort ();
163 listener.BeginGetContext (GetContextCompleted, null);
167 // FIXME: use timeout
168 public override void UnregisterListener (ChannelDispatcher channel, TimeSpan timeout)
170 UnregisterListenerCommon (channel, timeout);
172 // stop the server if there is no more registered listener.
173 if (Entries.Count > 0)
176 #if USE_SEPARATE_LOOP
179 this.listener.Stop ();
183 void GetContextCompleted (IAsyncResult result)
185 var ctx = listener.EndGetContext (result);
186 ProcessNewContext (ctx);
187 // start another listening
188 listener.BeginGetContext (GetContextCompleted, null);
191 void ProcessNewContext (HttpListenerContext ctx)
195 ProcessNewContext (new HttpStandaloneContextInfo (ctx));
199 internal class AspNetHttpListenerManager : HttpListenerManager
201 public AspNetHttpListenerManager (Uri uri)
205 public override void RegisterListener (ChannelDispatcher channel, HttpTransportBindingElement element, TimeSpan timeout)
207 RegisterListenerCommon (channel, timeout);
210 public override void UnregisterListener (ChannelDispatcher channel, TimeSpan timeout)
212 UnregisterListenerCommon (channel, timeout);