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.
30 #if NET_2_0 && SECURITY_DEP
33 using System.Net.Sockets;
34 using System.Collections;
35 using System.Security.Cryptography;
36 using System.Security.Cryptography.X509Certificates;
37 using System.Threading;
38 using Mono.Security.Authenticode;
40 namespace System.Net {
41 sealed class EndPointListener
45 Hashtable prefixes; // Dictionary <ListenerPrefix, HttpListener>
46 ArrayList unhandled; // List<ListenerPrefix> unhandled; host = '*'
47 ArrayList all; // List<ListenerPrefix> all; host = '+'
48 X509Certificate2 cert;
49 AsymmetricAlgorithm key;
51 Hashtable unregistered;
53 public EndPointListener (IPAddress addr, int port, bool secure)
57 LoadCertificateAndKey (addr, port);
60 endpoint = new IPEndPoint (addr, port);
61 sock = new Socket (addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
64 SocketAsyncEventArgs args = new SocketAsyncEventArgs ();
65 args.UserToken = this;
66 args.Completed += OnAccept;
67 sock.AcceptAsync (args);
68 prefixes = new Hashtable ();
69 unregistered = new Hashtable ();
72 void LoadCertificateAndKey (IPAddress addr, int port)
74 // Actually load the certificate
76 string dirname = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
77 string path = Path.Combine (dirname, ".mono");
78 path = Path.Combine (path, "httplistener");
79 string cert_file = Path.Combine (path, String.Format ("{0}.cer", port));
80 if (!File.Exists (cert_file))
82 string pvk_file = Path.Combine (path, String.Format ("{0}.pvk", port));
83 if (!File.Exists (pvk_file))
85 cert = new X509Certificate2 (cert_file);
86 key = PrivateKey.CreateFromFile (pvk_file).RSA;
92 static void OnAccept (object sender, EventArgs e)
94 SocketAsyncEventArgs args = (SocketAsyncEventArgs) e;
95 EndPointListener epl = (EndPointListener) args.UserToken;
96 Socket accepted = null;
97 if (args.SocketError == SocketError.Success) {
98 accepted = args.AcceptSocket;
99 args.AcceptSocket = null;
103 if (epl.sock != null)
104 epl.sock.AcceptAsync (args);
106 if (accepted != null) {
114 if (accepted == null)
117 if (epl.secure && (epl.cert == null || epl.key == null)) {
121 HttpConnection conn = new HttpConnection (accepted, epl, epl.secure, epl.cert, epl.key);
122 lock (epl.unregistered) {
123 epl.unregistered [conn] = conn;
125 conn.BeginReadRequest ();
128 internal void RemoveConnection (HttpConnection conn)
130 lock (unregistered) {
131 unregistered.Remove (conn);
135 public bool BindContext (HttpListenerContext context)
137 HttpListenerRequest req = context.Request;
138 ListenerPrefix prefix;
139 HttpListener listener = SearchListener (req.Url, out prefix);
140 if (listener == null)
143 context.Listener = listener;
144 context.Connection.Prefix = prefix;
148 public void UnbindContext (HttpListenerContext context)
150 if (context == null || context.Request == null)
153 context.Listener.UnregisterContext (context);
156 HttpListener SearchListener (Uri uri, out ListenerPrefix prefix)
162 string host = uri.Host;
164 string path = HttpUtility.UrlDecode (uri.AbsolutePath);
165 string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
167 HttpListener best_match = null;
168 int best_length = -1;
170 if (host != null && host != "") {
171 Hashtable p_ro = prefixes;
172 foreach (ListenerPrefix p in p_ro.Keys) {
173 string ppath = p.Path;
174 if (ppath.Length < best_length)
177 if (p.Host != host || p.Port != port)
180 if (path.StartsWith (ppath) || path_slash.StartsWith (ppath)) {
181 best_length = ppath.Length;
182 best_match = (HttpListener) p_ro [p];
186 if (best_length != -1)
190 ArrayList list = unhandled;
191 best_match = MatchFromList (host, path, list, out prefix);
192 if (path != path_slash && best_match == null)
193 best_match = MatchFromList (host, path_slash, list, out prefix);
194 if (best_match != null)
198 best_match = MatchFromList (host, path, list, out prefix);
199 if (path != path_slash && best_match == null)
200 best_match = MatchFromList (host, path_slash, list, out prefix);
201 if (best_match != null)
207 HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
213 HttpListener best_match = null;
214 int best_length = -1;
216 foreach (ListenerPrefix p in list) {
217 string ppath = p.Path;
218 if (ppath.Length < best_length)
221 if (path.StartsWith (ppath)) {
222 best_length = ppath.Length;
223 best_match = p.Listener;
231 void AddSpecial (ArrayList coll, ListenerPrefix prefix)
236 foreach (ListenerPrefix p in coll) {
237 if (p.Path == prefix.Path) //TODO: code
238 throw new HttpListenerException (400, "Prefix already in use.");
243 bool RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
249 for (int i = 0; i < c; i++) {
250 ListenerPrefix p = (ListenerPrefix) coll [i];
251 if (p.Path == prefix.Path) {
259 void CheckIfRemove ()
261 if (prefixes.Count > 0)
264 ArrayList list = unhandled;
265 if (list != null && list.Count > 0)
269 if (list != null && list.Count > 0)
272 EndPointManager.RemoveEndPoint (this, endpoint);
278 lock (unregistered) {
279 foreach (HttpConnection c in unregistered.Keys)
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);