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 Accept (sock, args, ref dummy);
78 prefixes = new Hashtable ();
79 unregistered = new Dictionary<HttpConnection, HttpConnection> ();
82 internal HttpListener Listener {
83 get { return listener; }
86 static void Accept (Socket socket, SocketAsyncEventArgs e, ref Socket accepted) {
87 e.AcceptSocket = null;
90 asyn = socket.AcceptAsync(e);
92 if (accepted != null) {
107 static void ProcessAccept (SocketAsyncEventArgs args)
109 Socket accepted = null;
110 if (args.SocketError == SocketError.Success)
111 accepted = args.AcceptSocket;
113 EndPointListener epl = (EndPointListener) args.UserToken;
116 Accept (epl.sock, args, ref accepted);
117 if (accepted == null)
120 if (epl.secure && epl.cert == null) {
124 HttpConnection conn = new HttpConnection (accepted, epl, epl.secure, epl.cert);
125 lock (epl.unregistered) {
126 epl.unregistered [conn] = conn;
128 conn.BeginReadRequest ();
131 static void OnAccept (object sender, SocketAsyncEventArgs e)
136 internal void RemoveConnection (HttpConnection conn)
138 lock (unregistered) {
139 unregistered.Remove (conn);
143 public bool BindContext (HttpListenerContext context)
145 HttpListenerRequest req = context.Request;
146 ListenerPrefix prefix;
147 HttpListener listener = SearchListener (req.Url, out prefix);
148 if (listener == null)
151 context.Listener = listener;
152 context.Connection.Prefix = prefix;
156 public void UnbindContext (HttpListenerContext context)
158 if (context == null || context.Request == null)
161 context.Listener.UnregisterContext (context);
164 HttpListener SearchListener (Uri uri, out ListenerPrefix prefix)
170 string host = uri.Host;
172 string path = WebUtility.UrlDecode (uri.AbsolutePath);
173 string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
175 HttpListener best_match = null;
176 int best_length = -1;
178 if (host != null && host != "") {
179 Hashtable p_ro = prefixes;
180 foreach (ListenerPrefix p in p_ro.Keys) {
181 string ppath = p.Path;
182 if (ppath.Length < best_length)
185 if (p.Host != host || p.Port != port)
188 if (path.StartsWith (ppath) || path_slash.StartsWith (ppath)) {
189 best_length = ppath.Length;
190 best_match = (HttpListener) p_ro [p];
194 if (best_length != -1)
198 ArrayList list = unhandled;
199 best_match = MatchFromList (host, path, list, out prefix);
200 if (path != path_slash && best_match == null)
201 best_match = MatchFromList (host, path_slash, list, out prefix);
202 if (best_match != null)
206 best_match = MatchFromList (host, path, list, out prefix);
207 if (path != path_slash && best_match == null)
208 best_match = MatchFromList (host, path_slash, list, out prefix);
209 if (best_match != null)
215 HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
221 HttpListener best_match = null;
222 int best_length = -1;
224 foreach (ListenerPrefix p in list) {
225 string ppath = p.Path;
226 if (ppath.Length < best_length)
229 if (path.StartsWith (ppath)) {
230 best_length = ppath.Length;
231 best_match = p.Listener;
239 void AddSpecial (ArrayList coll, ListenerPrefix prefix)
244 foreach (ListenerPrefix p in coll) {
245 if (p.Path == prefix.Path) //TODO: code
246 throw new HttpListenerException (400, "Prefix already in use.");
251 bool RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
257 for (int i = 0; i < c; i++) {
258 ListenerPrefix p = (ListenerPrefix) coll [i];
259 if (p.Path == prefix.Path) {
267 void CheckIfRemove ()
269 if (prefixes.Count > 0)
272 ArrayList list = unhandled;
273 if (list != null && list.Count > 0)
277 if (list != null && list.Count > 0)
280 EndPointManager.RemoveEndPoint (this, endpoint);
286 lock (unregistered) {
288 // Clone the list because RemoveConnection can be called from Close
290 var connections = new List<HttpConnection> (unregistered.Keys);
292 foreach (HttpConnection c in connections)
294 unregistered.Clear ();
298 public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
302 if (prefix.Host == "*") {
305 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
306 prefix.Listener = listener;
307 AddSpecial (future, prefix);
308 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
312 if (prefix.Host == "+") {
315 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
316 prefix.Listener = listener;
317 AddSpecial (future, prefix);
318 } while (Interlocked.CompareExchange (ref all, future, current) != current);
325 if (prefs.ContainsKey (prefix)) {
326 HttpListener other = (HttpListener) prefs [prefix];
327 if (other != listener) // TODO: code.
328 throw new HttpListenerException (400, "There's another listener for " + prefix);
331 p2 = (Hashtable) prefs.Clone ();
332 p2 [prefix] = listener;
333 } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);
336 public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
340 if (prefix.Host == "*") {
343 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
344 if (!RemoveSpecial (future, prefix))
345 break; // Prefix not found
346 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
351 if (prefix.Host == "+") {
354 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
355 if (!RemoveSpecial (future, prefix))
356 break; // Prefix not found
357 } while (Interlocked.CompareExchange (ref all, future, current) != current);
365 if (!prefs.ContainsKey (prefix))
368 p2 = (Hashtable) prefs.Clone ();
370 } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);