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 MONOTOUCH || MONODROID
33 using Mono.Security.Authenticode;
35 extern alias MonoSecurity;
36 using MonoSecurity::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
52 Hashtable prefixes; // Dictionary <ListenerPrefix, HttpListener>
53 ArrayList unhandled; // List<ListenerPrefix> unhandled; host = '*'
54 ArrayList all; // List<ListenerPrefix> all; host = '+'
55 X509Certificate2 cert;
56 AsymmetricAlgorithm key;
58 Dictionary<HttpConnection, HttpConnection> unregistered;
60 public EndPointListener (IPAddress addr, int port, bool secure)
64 LoadCertificateAndKey (addr, port);
67 endpoint = new IPEndPoint (addr, port);
68 sock = new Socket (addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
71 SocketAsyncEventArgs args = new SocketAsyncEventArgs ();
72 args.UserToken = this;
73 args.Completed += OnAccept;
74 sock.AcceptAsync (args);
75 prefixes = new Hashtable ();
76 unregistered = new Dictionary<HttpConnection, HttpConnection> ();
79 void LoadCertificateAndKey (IPAddress addr, int port)
81 // Actually load the certificate
83 string dirname = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
84 string path = Path.Combine (dirname, ".mono");
85 path = Path.Combine (path, "httplistener");
86 string cert_file = Path.Combine (path, String.Format ("{0}.cer", port));
87 if (!File.Exists (cert_file))
89 string pvk_file = Path.Combine (path, String.Format ("{0}.pvk", port));
90 if (!File.Exists (pvk_file))
92 cert = new X509Certificate2 (cert_file);
93 key = PrivateKey.CreateFromFile (pvk_file).RSA;
99 static void OnAccept (object sender, EventArgs e)
101 SocketAsyncEventArgs args = (SocketAsyncEventArgs) e;
102 EndPointListener epl = (EndPointListener) args.UserToken;
103 Socket accepted = null;
104 if (args.SocketError == SocketError.Success) {
105 accepted = args.AcceptSocket;
106 args.AcceptSocket = null;
110 if (epl.sock != null)
111 epl.sock.AcceptAsync (args);
113 if (accepted != null) {
121 if (accepted == null)
124 if (epl.secure && (epl.cert == null || epl.key == null)) {
128 HttpConnection conn = new HttpConnection (accepted, epl, epl.secure, epl.cert, epl.key);
129 lock (epl.unregistered) {
130 epl.unregistered [conn] = conn;
132 conn.BeginReadRequest ();
135 internal void RemoveConnection (HttpConnection conn)
137 lock (unregistered) {
138 unregistered.Remove (conn);
142 public bool BindContext (HttpListenerContext context)
144 HttpListenerRequest req = context.Request;
145 ListenerPrefix prefix;
146 HttpListener listener = SearchListener (req.Url, out prefix);
147 if (listener == null)
150 context.Listener = listener;
151 context.Connection.Prefix = prefix;
155 public void UnbindContext (HttpListenerContext context)
157 if (context == null || context.Request == null)
160 context.Listener.UnregisterContext (context);
163 HttpListener SearchListener (Uri uri, out ListenerPrefix prefix)
169 string host = uri.Host;
171 string path = HttpUtility.UrlDecode (uri.AbsolutePath);
172 string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
174 HttpListener best_match = null;
175 int best_length = -1;
177 if (host != null && host != "") {
178 Hashtable p_ro = prefixes;
179 foreach (ListenerPrefix p in p_ro.Keys) {
180 string ppath = p.Path;
181 if (ppath.Length < best_length)
184 if (p.Host != host || p.Port != port)
187 if (path.StartsWith (ppath) || path_slash.StartsWith (ppath)) {
188 best_length = ppath.Length;
189 best_match = (HttpListener) p_ro [p];
193 if (best_length != -1)
197 ArrayList list = unhandled;
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)
205 best_match = MatchFromList (host, path, list, out prefix);
206 if (path != path_slash && best_match == null)
207 best_match = MatchFromList (host, path_slash, list, out prefix);
208 if (best_match != null)
214 HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
220 HttpListener best_match = null;
221 int best_length = -1;
223 foreach (ListenerPrefix p in list) {
224 string ppath = p.Path;
225 if (ppath.Length < best_length)
228 if (path.StartsWith (ppath)) {
229 best_length = ppath.Length;
230 best_match = p.Listener;
238 void AddSpecial (ArrayList coll, ListenerPrefix prefix)
243 foreach (ListenerPrefix p in coll) {
244 if (p.Path == prefix.Path) //TODO: code
245 throw new HttpListenerException (400, "Prefix already in use.");
250 bool RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
256 for (int i = 0; i < c; i++) {
257 ListenerPrefix p = (ListenerPrefix) coll [i];
258 if (p.Path == prefix.Path) {
266 void CheckIfRemove ()
268 if (prefixes.Count > 0)
271 ArrayList list = unhandled;
272 if (list != null && list.Count > 0)
276 if (list != null && list.Count > 0)
279 EndPointManager.RemoveEndPoint (this, endpoint);
285 lock (unregistered) {
287 // Clone the list because RemoveConnection can be called from Close
289 var connections = new List<HttpConnection> (unregistered.Keys);
291 foreach (HttpConnection c in connections)
293 unregistered.Clear ();
297 public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
301 if (prefix.Host == "*") {
304 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
305 prefix.Listener = listener;
306 AddSpecial (future, prefix);
307 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
311 if (prefix.Host == "+") {
314 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
315 prefix.Listener = listener;
316 AddSpecial (future, prefix);
317 } while (Interlocked.CompareExchange (ref all, future, current) != current);
324 if (prefs.ContainsKey (prefix)) {
325 HttpListener other = (HttpListener) prefs [prefix];
326 if (other != listener) // TODO: code.
327 throw new HttpListenerException (400, "There's another listener for " + prefix);
330 p2 = (Hashtable) prefs.Clone ();
331 p2 [prefix] = listener;
332 } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);
335 public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
339 if (prefix.Host == "*") {
342 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
343 if (!RemoveSpecial (future, prefix))
344 break; // Prefix not found
345 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
350 if (prefix.Host == "+") {
353 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
354 if (!RemoveSpecial (future, prefix))
355 break; // Prefix not found
356 } while (Interlocked.CompareExchange (ref all, future, current) != current);
364 if (!prefs.ContainsKey (prefix))
367 p2 = (Hashtable) prefs.Clone ();
369 } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);