2 // System.Net.HttpListener
5 // Gonzalo Paniagua Javier (gonzalo@novell.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
9 // Copyright 2011 Xamarin Inc.
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
32 using System.Collections;
33 using System.Threading;
34 using System.Threading.Tasks;
35 using System.Net.Security;
36 using System.Security.Authentication.ExtendedProtection;
37 using System.Security.Cryptography;
38 using System.Security.Cryptography.X509Certificates;
41 namespace System.Net {
42 public sealed partial class HttpListener : IDisposable {
43 AuthenticationSchemes auth_schemes;
44 HttpListenerPrefixCollection prefixes;
45 AuthenticationSchemeSelector auth_selector;
47 bool ignore_write_exceptions;
48 bool unsafe_ntlm_auth;
52 readonly object _internalLock; // don't rename to match CoreFx
54 Hashtable registry; // Dictionary<HttpListenerContext,HttpListenerContext>
55 ArrayList ctx_queue; // List<HttpListenerContext> ctx_queue;
56 ArrayList wait_queue; // List<ListenerAsyncResult> wait_queue;
57 Hashtable connections;
59 ServiceNameStore defaultServiceNames;
60 ExtendedProtectionPolicy extendedProtectionPolicy;
61 ExtendedProtectionSelector extendedProtectionSelectorDelegate;
63 public delegate ExtendedProtectionPolicy ExtendedProtectionSelector (HttpListenerRequest request);
65 public HttpListener ()
67 _internalLock = new object ();
68 prefixes = new HttpListenerPrefixCollection (this);
69 registry = new Hashtable ();
70 connections = Hashtable.Synchronized (new Hashtable ());
71 ctx_queue = new ArrayList ();
72 wait_queue = new ArrayList ();
73 auth_schemes = AuthenticationSchemes.Anonymous;
74 defaultServiceNames = new ServiceNameStore ();
75 extendedProtectionPolicy = new ExtendedProtectionPolicy (PolicyEnforcement.Never);
79 // TODO: Digest, NTLM and Negotiate require ControlPrincipal
80 public AuthenticationSchemes AuthenticationSchemes {
81 get { return auth_schemes; }
88 public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate {
89 get { return auth_selector; }
92 auth_selector = value;
96 public ExtendedProtectionSelector ExtendedProtectionSelectorDelegate
98 get { return extendedProtectionSelectorDelegate; }
102 throw new ArgumentNullException ();
104 if (!AuthenticationManager.OSSupportsExtendedProtection)
105 throw new PlatformNotSupportedException (SR.GetString (SR.security_ExtendedProtection_NoOSSupport));
107 extendedProtectionSelectorDelegate = value;
111 public bool IgnoreWriteExceptions {
112 get { return ignore_write_exceptions; }
115 ignore_write_exceptions = value;
119 public bool IsListening {
120 get { return listening; }
123 public static bool IsSupported {
127 public HttpListenerPrefixCollection Prefixes {
135 public HttpListenerTimeoutManager TimeoutManager {
137 throw new NotImplementedException ();
141 [MonoTODO ("not used anywhere in the implementation")]
142 public ExtendedProtectionPolicy ExtendedProtectionPolicy
145 return extendedProtectionPolicy;
151 throw new ArgumentNullException ("value");
153 if (!AuthenticationManager.OSSupportsExtendedProtection && value.PolicyEnforcement == PolicyEnforcement.Always)
154 throw new PlatformNotSupportedException (SR.GetString(SR.security_ExtendedProtection_NoOSSupport));
156 if (value.CustomChannelBinding != null)
157 throw new ArgumentException (SR.GetString (SR.net_listener_cannot_set_custom_cbt), "CustomChannelBinding");
159 extendedProtectionPolicy = value;
163 public ServiceNameCollection DefaultServiceNames
166 return defaultServiceNames.ServiceNames;
171 public string Realm {
172 get { return realm; }
179 [MonoTODO ("Support for NTLM needs some loving.")]
180 public bool UnsafeConnectionNtlmAuthentication {
181 get { return unsafe_ntlm_auth; }
184 unsafe_ntlm_auth = value;
214 void Close (bool force)
217 EndPointManager.RemoveListener (this);
221 void Cleanup (bool close_existing)
223 lock (_internalLock) {
224 if (close_existing) {
225 // Need to copy this since closing will call UnregisterContext
226 ICollection keys = registry.Keys;
227 var all = new HttpListenerContext [keys.Count];
228 keys.CopyTo (all, 0);
230 for (int i = all.Length - 1; i >= 0; i--)
231 all [i].Connection.Close (true);
234 lock (connections.SyncRoot) {
235 ICollection keys = connections.Keys;
236 var conns = new HttpConnection [keys.Count];
237 keys.CopyTo (conns, 0);
238 connections.Clear ();
239 for (int i = conns.Length - 1; i >= 0; i--)
240 conns [i].Close (true);
243 var ctxs = (HttpListenerContext []) ctx_queue.ToArray (typeof (HttpListenerContext));
245 for (int i = ctxs.Length - 1; i >= 0; i--)
246 ctxs [i].Connection.Close (true);
250 Exception exc = new ObjectDisposedException ("listener");
251 foreach (ListenerAsyncResult ares in wait_queue) {
259 public IAsyncResult BeginGetContext (AsyncCallback callback, Object state)
263 throw new InvalidOperationException ("Please, call Start before using this method.");
265 ListenerAsyncResult ares = new ListenerAsyncResult (callback, state);
267 // lock wait_queue early to avoid race conditions
270 HttpListenerContext ctx = GetContextFromQueue ();
272 ares.Complete (ctx, true);
277 wait_queue.Add (ares);
283 public HttpListenerContext EndGetContext (IAsyncResult asyncResult)
286 if (asyncResult == null)
287 throw new ArgumentNullException ("asyncResult");
289 ListenerAsyncResult ares = asyncResult as ListenerAsyncResult;
291 throw new ArgumentException ("Wrong IAsyncResult.", "asyncResult");
293 throw new ArgumentException ("Cannot reuse this IAsyncResult");
294 ares.EndCalled = true;
296 if (!ares.IsCompleted)
297 ares.AsyncWaitHandle.WaitOne ();
300 int idx = wait_queue.IndexOf (ares);
302 wait_queue.RemoveAt (idx);
305 HttpListenerContext context = ares.GetContext ();
306 context.ParseAuthentication (SelectAuthenticationScheme (context));
307 return context; // This will throw on error.
310 internal AuthenticationSchemes SelectAuthenticationScheme (HttpListenerContext context)
312 if (AuthenticationSchemeSelectorDelegate != null)
313 return AuthenticationSchemeSelectorDelegate (context.Request);
318 public HttpListenerContext GetContext ()
320 // The prefixes are not checked when using the async interface!?
321 if (prefixes.Count == 0)
322 throw new InvalidOperationException ("Please, call AddPrefix before using this method.");
324 ListenerAsyncResult ares = (ListenerAsyncResult) BeginGetContext (null, null);
326 return EndGetContext (ares);
335 EndPointManager.AddListener (this);
346 void IDisposable.Dispose ()
351 Close (true); //TODO: Should we force here or not?
355 public Task<HttpListenerContext> GetContextAsync ()
357 return Task<HttpListenerContext>.Factory.FromAsync (BeginGetContext, EndGetContext, null);
360 internal void CheckDisposed ()
363 throw new ObjectDisposedException (GetType ().ToString ());
366 // Must be called with a lock on ctx_queue
367 HttpListenerContext GetContextFromQueue ()
369 if (ctx_queue.Count == 0)
372 HttpListenerContext context = (HttpListenerContext) ctx_queue [0];
373 ctx_queue.RemoveAt (0);
377 internal void RegisterContext (HttpListenerContext context)
380 registry [context] = context;
382 ListenerAsyncResult ares = null;
384 if (wait_queue.Count == 0) {
386 ctx_queue.Add (context);
388 ares = (ListenerAsyncResult) wait_queue [0];
389 wait_queue.RemoveAt (0);
393 ares.Complete (context);
396 internal void UnregisterContext (HttpListenerContext context)
399 registry.Remove (context);
401 int idx = ctx_queue.IndexOf (context);
403 ctx_queue.RemoveAt (idx);
407 internal void AddConnection (HttpConnection cnc)
409 connections [cnc] = cnc;
412 internal void RemoveConnection (HttpConnection cnc)
414 connections.Remove (cnc);