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.
33 using System.Net.Sockets;
34 using System.Collections;
35 using System.Collections.Generic;
36 using System.Security.Cryptography;
37 using System.Security.Cryptography.X509Certificates;
38 using System.Threading;
39 using Mono.Security.Authenticode;
41 namespace System.Net {
42 sealed class EndPointListener
46 Hashtable prefixes; // Dictionary <ListenerPrefix, HttpListener>
47 ArrayList unhandled; // List<ListenerPrefix> unhandled; host = '*'
48 ArrayList all; // List<ListenerPrefix> all; host = '+'
49 X509Certificate2 cert;
50 AsymmetricAlgorithm key;
52 Dictionary<HttpConnection, HttpConnection> unregistered;
54 public EndPointListener (IPAddress addr, int port, bool secure)
58 LoadCertificateAndKey (addr, port);
61 endpoint = new IPEndPoint (addr, port);
62 sock = new Socket (addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
65 SocketAsyncEventArgs args = new SocketAsyncEventArgs ();
66 args.UserToken = this;
67 args.Completed += OnAccept;
68 sock.AcceptAsync (args);
69 prefixes = new Hashtable ();
70 unregistered = new Dictionary<HttpConnection, HttpConnection> ();
73 void LoadCertificateAndKey (IPAddress addr, int port)
75 // Actually load the certificate
77 string dirname = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
78 string path = Path.Combine (dirname, ".mono");
79 path = Path.Combine (path, "httplistener");
80 string cert_file = Path.Combine (path, String.Format ("{0}.cer", port));
81 if (!File.Exists (cert_file))
83 string pvk_file = Path.Combine (path, String.Format ("{0}.pvk", port));
84 if (!File.Exists (pvk_file))
86 cert = new X509Certificate2 (cert_file);
87 key = PrivateKey.CreateFromFile (pvk_file).RSA;
93 static void OnAccept (object sender, EventArgs e)
95 SocketAsyncEventArgs args = (SocketAsyncEventArgs) e;
96 EndPointListener epl = (EndPointListener) args.UserToken;
97 Socket accepted = null;
98 if (args.SocketError == SocketError.Success) {
99 accepted = args.AcceptSocket;
100 args.AcceptSocket = null;
104 if (epl.sock != null)
105 epl.sock.AcceptAsync (args);
107 if (accepted != null) {
115 if (accepted == null)
118 if (epl.secure && (epl.cert == null || epl.key == null)) {
122 HttpConnection conn = new HttpConnection (accepted, epl, epl.secure, epl.cert, epl.key);
123 lock (epl.unregistered) {
124 epl.unregistered [conn] = conn;
126 conn.BeginReadRequest ();
129 internal void RemoveConnection (HttpConnection conn)
131 lock (unregistered) {
132 unregistered.Remove (conn);
136 public bool BindContext (HttpListenerContext context)
138 HttpListenerRequest req = context.Request;
139 ListenerPrefix prefix;
140 HttpListener listener = SearchListener (req.Url, out prefix);
141 if (listener == null)
144 context.Listener = listener;
145 context.Connection.Prefix = prefix;
149 public void UnbindContext (HttpListenerContext context)
151 if (context == null || context.Request == null)
154 context.Listener.UnregisterContext (context);
157 HttpListener SearchListener (Uri uri, out ListenerPrefix prefix)
163 string host = uri.Host;
165 string path = HttpUtility.UrlDecode (uri.AbsolutePath);
166 string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
168 HttpListener best_match = null;
169 int best_length = -1;
171 if (host != null && host != "") {
172 Hashtable p_ro = prefixes;
173 foreach (ListenerPrefix p in p_ro.Keys) {
174 string ppath = p.Path;
175 if (ppath.Length < best_length)
178 if (p.Host != host || p.Port != port)
181 if (path.StartsWith (ppath) || path_slash.StartsWith (ppath)) {
182 best_length = ppath.Length;
183 best_match = (HttpListener) p_ro [p];
187 if (best_length != -1)
191 ArrayList list = unhandled;
192 best_match = MatchFromList (host, path, list, out prefix);
193 if (path != path_slash && best_match == null)
194 best_match = MatchFromList (host, path_slash, list, out prefix);
195 if (best_match != null)
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)
208 HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
214 HttpListener best_match = null;
215 int best_length = -1;
217 foreach (ListenerPrefix p in list) {
218 string ppath = p.Path;
219 if (ppath.Length < best_length)
222 if (path.StartsWith (ppath)) {
223 best_length = ppath.Length;
224 best_match = p.Listener;
232 void AddSpecial (ArrayList coll, ListenerPrefix prefix)
237 foreach (ListenerPrefix p in coll) {
238 if (p.Path == prefix.Path) //TODO: code
239 throw new HttpListenerException (400, "Prefix already in use.");
244 bool RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
250 for (int i = 0; i < c; i++) {
251 ListenerPrefix p = (ListenerPrefix) coll [i];
252 if (p.Path == prefix.Path) {
260 void CheckIfRemove ()
262 if (prefixes.Count > 0)
265 ArrayList list = unhandled;
266 if (list != null && list.Count > 0)
270 if (list != null && list.Count > 0)
273 EndPointManager.RemoveEndPoint (this, endpoint);
279 lock (unregistered) {
281 // Clone the list because RemoveConnection can be called from Close
283 var connections = new List<HttpConnection> (unregistered.Keys);
285 foreach (HttpConnection c in connections)
287 unregistered.Clear ();
291 public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
295 if (prefix.Host == "*") {
298 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
299 prefix.Listener = listener;
300 AddSpecial (future, prefix);
301 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
305 if (prefix.Host == "+") {
308 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
309 prefix.Listener = listener;
310 AddSpecial (future, prefix);
311 } while (Interlocked.CompareExchange (ref all, future, current) != current);
318 if (prefs.ContainsKey (prefix)) {
319 HttpListener other = (HttpListener) prefs [prefix];
320 if (other != listener) // TODO: code.
321 throw new HttpListenerException (400, "There's another listener for " + prefix);
324 p2 = (Hashtable) prefs.Clone ();
325 p2 [prefix] = listener;
326 } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);
329 public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
333 if (prefix.Host == "*") {
336 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
337 if (!RemoveSpecial (future, prefix))
338 break; // Prefix not found
339 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
344 if (prefix.Host == "+") {
347 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
348 if (!RemoveSpecial (future, prefix))
349 break; // Prefix not found
350 } while (Interlocked.CompareExchange (ref all, future, current) != current);
358 if (!prefs.ContainsKey (prefix))
361 p2 = (Hashtable) prefs.Clone ();
363 } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);