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 #if MONO_SECURITY_ALIAS
33 extern alias MonoSecurity;
34 using MonoSecurity::Mono.Security.Authenticode;
35 using MSI = MonoSecurity::Mono.Security.Interface;
37 using Mono.Security.Authenticode;
38 using MSI = Mono.Security.Interface;
42 using System.Collections;
43 using System.Threading;
44 using System.Threading.Tasks;
45 using System.Security.Cryptography;
46 using System.Security.Cryptography.X509Certificates;
48 using Mono.Net.Security;
52 namespace System.Net {
53 public sealed class HttpListener : IDisposable {
54 AuthenticationSchemes auth_schemes;
55 HttpListenerPrefixCollection prefixes;
56 AuthenticationSchemeSelector auth_selector;
58 bool ignore_write_exceptions;
59 bool unsafe_ntlm_auth;
63 IMonoTlsProvider tlsProvider;
64 MSI.MonoTlsSettings tlsSettings;
65 X509Certificate certificate;
67 Hashtable registry; // Dictionary<HttpListenerContext,HttpListenerContext>
68 ArrayList ctx_queue; // List<HttpListenerContext> ctx_queue;
69 ArrayList wait_queue; // List<ListenerAsyncResult> wait_queue;
70 Hashtable connections;
72 public HttpListener ()
74 prefixes = new HttpListenerPrefixCollection (this);
75 registry = new Hashtable ();
76 connections = Hashtable.Synchronized (new Hashtable ());
77 ctx_queue = new ArrayList ();
78 wait_queue = new ArrayList ();
79 auth_schemes = AuthenticationSchemes.Anonymous;
82 internal HttpListener (X509Certificate certificate, IMonoTlsProvider tlsProvider, MSI.MonoTlsSettings tlsSettings)
85 this.certificate = certificate;
86 this.tlsProvider = tlsProvider;
87 this.tlsSettings = tlsSettings;
90 internal X509Certificate LoadCertificateAndKey (IPAddress addr, int port)
93 if (certificate != null)
96 // Actually load the certificate
98 string dirname = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
99 string path = Path.Combine (dirname, ".mono");
100 path = Path.Combine (path, "httplistener");
101 string cert_file = Path.Combine (path, String.Format ("{0}.cer", port));
102 if (!File.Exists (cert_file))
104 string pvk_file = Path.Combine (path, String.Format ("{0}.pvk", port));
105 if (!File.Exists (pvk_file))
107 var cert = new X509Certificate2 (cert_file);
108 cert.PrivateKey = PrivateKey.CreateFromFile (pvk_file).RSA;
119 internal IMonoSslStream CreateSslStream (Stream innerStream, bool ownsStream, MSI.MonoRemoteCertificateValidationCallback callback)
122 if (tlsProvider == null)
123 tlsProvider = MonoTlsProviderFactory.GetProviderInternal ();
124 if (tlsSettings == null)
125 tlsSettings = MSI.MonoTlsSettings.CopyDefaultSettings ();
126 if (tlsSettings.RemoteCertificateValidationCallback == null)
127 tlsSettings.RemoteCertificateValidationCallback = callback;
128 return tlsProvider.CreateSslStream (innerStream, ownsStream, tlsSettings);
132 // TODO: Digest, NTLM and Negotiate require ControlPrincipal
133 public AuthenticationSchemes AuthenticationSchemes {
134 get { return auth_schemes; }
137 auth_schemes = value;
141 public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate {
142 get { return auth_selector; }
145 auth_selector = value;
149 public bool IgnoreWriteExceptions {
150 get { return ignore_write_exceptions; }
153 ignore_write_exceptions = value;
157 public bool IsListening {
158 get { return listening; }
161 public static bool IsSupported {
165 public HttpListenerPrefixCollection Prefixes {
173 public string Realm {
174 get { return realm; }
181 [MonoTODO ("Support for NTLM needs some loving.")]
182 public bool UnsafeConnectionNtlmAuthentication {
183 get { return unsafe_ntlm_auth; }
186 unsafe_ntlm_auth = value;
216 void Close (bool force)
219 EndPointManager.RemoveListener (this);
223 void Cleanup (bool close_existing)
226 if (close_existing) {
227 // Need to copy this since closing will call UnregisterContext
228 ICollection keys = registry.Keys;
229 var all = new HttpListenerContext [keys.Count];
230 keys.CopyTo (all, 0);
232 for (int i = all.Length - 1; i >= 0; i--)
233 all [i].Connection.Close (true);
236 lock (connections.SyncRoot) {
237 ICollection keys = connections.Keys;
238 var conns = new HttpConnection [keys.Count];
239 keys.CopyTo (conns, 0);
240 connections.Clear ();
241 for (int i = conns.Length - 1; i >= 0; i--)
242 conns [i].Close (true);
245 var ctxs = (HttpListenerContext []) ctx_queue.ToArray (typeof (HttpListenerContext));
247 for (int i = ctxs.Length - 1; i >= 0; i--)
248 ctxs [i].Connection.Close (true);
252 Exception exc = new ObjectDisposedException ("listener");
253 foreach (ListenerAsyncResult ares in wait_queue) {
261 public IAsyncResult BeginGetContext (AsyncCallback callback, Object state)
265 throw new InvalidOperationException ("Please, call Start before using this method.");
267 ListenerAsyncResult ares = new ListenerAsyncResult (callback, state);
269 // lock wait_queue early to avoid race conditions
272 HttpListenerContext ctx = GetContextFromQueue ();
274 ares.Complete (ctx, true);
279 wait_queue.Add (ares);
285 public HttpListenerContext EndGetContext (IAsyncResult asyncResult)
288 if (asyncResult == null)
289 throw new ArgumentNullException ("asyncResult");
291 ListenerAsyncResult ares = asyncResult as ListenerAsyncResult;
293 throw new ArgumentException ("Wrong IAsyncResult.", "asyncResult");
295 throw new ArgumentException ("Cannot reuse this IAsyncResult");
296 ares.EndCalled = true;
298 if (!ares.IsCompleted)
299 ares.AsyncWaitHandle.WaitOne ();
302 int idx = wait_queue.IndexOf (ares);
304 wait_queue.RemoveAt (idx);
307 HttpListenerContext context = ares.GetContext ();
308 context.ParseAuthentication (SelectAuthenticationScheme (context));
309 return context; // This will throw on error.
312 internal AuthenticationSchemes SelectAuthenticationScheme (HttpListenerContext context)
314 if (AuthenticationSchemeSelectorDelegate != null)
315 return AuthenticationSchemeSelectorDelegate (context.Request);
320 public HttpListenerContext GetContext ()
322 // The prefixes are not checked when using the async interface!?
323 if (prefixes.Count == 0)
324 throw new InvalidOperationException ("Please, call AddPrefix before using this method.");
326 ListenerAsyncResult ares = (ListenerAsyncResult) BeginGetContext (null, null);
328 return EndGetContext (ares);
337 EndPointManager.AddListener (this);
348 void IDisposable.Dispose ()
353 Close (true); //TODO: Should we force here or not?
357 public Task<HttpListenerContext> GetContextAsync ()
359 return Task<HttpListenerContext>.Factory.FromAsync (BeginGetContext, EndGetContext, null);
362 internal void CheckDisposed ()
365 throw new ObjectDisposedException (GetType ().ToString ());
368 // Must be called with a lock on ctx_queue
369 HttpListenerContext GetContextFromQueue ()
371 if (ctx_queue.Count == 0)
374 HttpListenerContext context = (HttpListenerContext) ctx_queue [0];
375 ctx_queue.RemoveAt (0);
379 internal void RegisterContext (HttpListenerContext context)
382 registry [context] = context;
384 ListenerAsyncResult ares = null;
386 if (wait_queue.Count == 0) {
388 ctx_queue.Add (context);
390 ares = (ListenerAsyncResult) wait_queue [0];
391 wait_queue.RemoveAt (0);
395 ares.Complete (context);
398 internal void UnregisterContext (HttpListenerContext context)
401 registry.Remove (context);
403 int idx = ctx_queue.IndexOf (context);
405 ctx_queue.RemoveAt (idx);
409 internal void AddConnection (HttpConnection cnc)
411 connections [cnc] = cnc;
414 internal void RemoveConnection (HttpConnection cnc)
416 connections.Remove (cnc);
420 #else // SECURITY_DEP
423 public sealed class HttpListener