2 // System.Net.EndPointListener
5 // Gonzalo Paniagua Javier (gonzalo.mono@gmail.com)
7 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
8 // Copyright (c) 2012 Xamarin, Inc. (http://xamarin.com)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // 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;
36 using Mono.Security.Authenticode;
40 using System.Net.Sockets;
41 using System.Collections;
42 using System.Collections.Generic;
43 using System.Security.Cryptography;
44 using System.Security.Cryptography.X509Certificates;
45 using System.Threading;
47 namespace System.Net {
48 sealed class EndPointListener
50 HttpListener listener;
53 Hashtable prefixes; // Dictionary <ListenerPrefix, HttpListener>
54 ArrayList unhandled; // List<ListenerPrefix> unhandled; host = '*'
55 ArrayList all; // List<ListenerPrefix> all; host = '+'
58 Dictionary<HttpConnection, HttpConnection> unregistered;
60 public EndPointListener (HttpListener listener, IPAddress addr, int port, bool secure)
62 this.listener = listener;
66 cert = listener.LoadCertificateAndKey (addr, port);
69 endpoint = new IPEndPoint (addr, port);
70 sock = new Socket (addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
73 SocketAsyncEventArgs args = new SocketAsyncEventArgs ();
74 args.UserToken = this;
75 args.Completed += OnAccept;
77 prefixes = new Hashtable ();
78 unregistered = new Dictionary<HttpConnection, HttpConnection> ();
81 internal HttpListener Listener {
82 get { return listener; }
85 static void Accept (Socket socket, SocketAsyncEventArgs e) {
86 e.AcceptSocket = null;
87 var asyn = socket.AcceptAsync(e);
94 static void ProcessAccept (SocketAsyncEventArgs args)
96 Socket accepted = null;
97 if (args.SocketError == SocketError.Success)
98 accepted = args.AcceptSocket;
100 EndPointListener epl = (EndPointListener) args.UserToken;
103 Accept (epl.sock, args);
104 if (accepted == null)
107 if (epl.secure && epl.cert == null) {
111 HttpConnection conn = new HttpConnection (accepted, epl, epl.secure, epl.cert);
112 lock (epl.unregistered) {
113 epl.unregistered [conn] = conn;
115 conn.BeginReadRequest ();
118 static void OnAccept (object sender, SocketAsyncEventArgs e)
123 internal void RemoveConnection (HttpConnection conn)
125 lock (unregistered) {
126 unregistered.Remove (conn);
130 public bool BindContext (HttpListenerContext context)
132 HttpListenerRequest req = context.Request;
133 ListenerPrefix prefix;
134 HttpListener listener = SearchListener (req.Url, out prefix);
135 if (listener == null)
138 context.Listener = listener;
139 context.Connection.Prefix = prefix;
143 public void UnbindContext (HttpListenerContext context)
145 if (context == null || context.Request == null)
148 context.Listener.UnregisterContext (context);
151 HttpListener SearchListener (Uri uri, out ListenerPrefix prefix)
157 string host = uri.Host;
159 string path = WebUtility.UrlDecode (uri.AbsolutePath);
160 string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
162 HttpListener best_match = null;
163 int best_length = -1;
165 if (host != null && host != "") {
166 Hashtable p_ro = prefixes;
167 foreach (ListenerPrefix p in p_ro.Keys) {
168 string ppath = p.Path;
169 if (ppath.Length < best_length)
172 if (p.Host != host || p.Port != port)
175 if (path.StartsWith (ppath) || path_slash.StartsWith (ppath)) {
176 best_length = ppath.Length;
177 best_match = (HttpListener) p_ro [p];
181 if (best_length != -1)
185 ArrayList list = unhandled;
186 best_match = MatchFromList (host, path, list, out prefix);
187 if (path != path_slash && best_match == null)
188 best_match = MatchFromList (host, path_slash, list, out prefix);
189 if (best_match != null)
193 best_match = MatchFromList (host, path, list, out prefix);
194 if (path != path_slash && best_match == null)
195 best_match = MatchFromList (host, path_slash, list, out prefix);
196 if (best_match != null)
202 HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
208 HttpListener best_match = null;
209 int best_length = -1;
211 foreach (ListenerPrefix p in list) {
212 string ppath = p.Path;
213 if (ppath.Length < best_length)
216 if (path.StartsWith (ppath)) {
217 best_length = ppath.Length;
218 best_match = p.Listener;
226 void AddSpecial (ArrayList coll, ListenerPrefix prefix)
231 foreach (ListenerPrefix p in coll) {
232 if (p.Path == prefix.Path) //TODO: code
233 throw new HttpListenerException (400, "Prefix already in use.");
238 bool RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
244 for (int i = 0; i < c; i++) {
245 ListenerPrefix p = (ListenerPrefix) coll [i];
246 if (p.Path == prefix.Path) {
254 void CheckIfRemove ()
256 if (prefixes.Count > 0)
259 ArrayList list = unhandled;
260 if (list != null && list.Count > 0)
264 if (list != null && list.Count > 0)
267 EndPointManager.RemoveEndPoint (this, endpoint);
273 lock (unregistered) {
275 // Clone the list because RemoveConnection can be called from Close
277 var connections = new List<HttpConnection> (unregistered.Keys);
279 foreach (HttpConnection c in connections)
281 unregistered.Clear ();
285 public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
289 if (prefix.Host == "*") {
292 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
293 prefix.Listener = listener;
294 AddSpecial (future, prefix);
295 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
299 if (prefix.Host == "+") {
302 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
303 prefix.Listener = listener;
304 AddSpecial (future, prefix);
305 } while (Interlocked.CompareExchange (ref all, future, current) != current);
312 if (prefs.ContainsKey (prefix)) {
313 HttpListener other = (HttpListener) prefs [prefix];
314 if (other != listener) // TODO: code.
315 throw new HttpListenerException (400, "There's another listener for " + prefix);
318 p2 = (Hashtable) prefs.Clone ();
319 p2 [prefix] = listener;
320 } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);
323 public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
327 if (prefix.Host == "*") {
330 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
331 if (!RemoveSpecial (future, prefix))
332 break; // Prefix not found
333 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
338 if (prefix.Host == "+") {
341 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
342 if (!RemoveSpecial (future, prefix))
343 break; // Prefix not found
344 } while (Interlocked.CompareExchange (ref all, future, current) != current);
352 if (!prefs.ContainsKey (prefix))
355 p2 = (Hashtable) prefs.Clone ();
357 } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);