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 extern alias MonoSecurity;
35 using System.Net.Sockets;
36 using System.Collections;
37 using System.Collections.Generic;
38 using System.Security.Cryptography;
39 using System.Security.Cryptography.X509Certificates;
40 using System.Threading;
41 using MonoSecurity::Mono.Security.Authenticode;
43 namespace System.Net {
44 sealed class EndPointListener
48 Hashtable prefixes; // Dictionary <ListenerPrefix, HttpListener>
49 ArrayList unhandled; // List<ListenerPrefix> unhandled; host = '*'
50 ArrayList all; // List<ListenerPrefix> all; host = '+'
51 X509Certificate2 cert;
52 AsymmetricAlgorithm key;
54 Dictionary<HttpConnection, HttpConnection> unregistered;
56 public EndPointListener (IPAddress addr, int port, bool secure)
60 LoadCertificateAndKey (addr, port);
63 endpoint = new IPEndPoint (addr, port);
64 sock = new Socket (addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
67 SocketAsyncEventArgs args = new SocketAsyncEventArgs ();
68 args.UserToken = this;
69 args.Completed += OnAccept;
70 sock.AcceptAsync (args);
71 prefixes = new Hashtable ();
72 unregistered = new Dictionary<HttpConnection, HttpConnection> ();
75 void LoadCertificateAndKey (IPAddress addr, int port)
77 // Actually load the certificate
79 string dirname = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
80 string path = Path.Combine (dirname, ".mono");
81 path = Path.Combine (path, "httplistener");
82 string cert_file = Path.Combine (path, String.Format ("{0}.cer", port));
83 if (!File.Exists (cert_file))
85 string pvk_file = Path.Combine (path, String.Format ("{0}.pvk", port));
86 if (!File.Exists (pvk_file))
88 cert = new X509Certificate2 (cert_file);
89 key = PrivateKey.CreateFromFile (pvk_file).RSA;
95 static void OnAccept (object sender, EventArgs e)
97 SocketAsyncEventArgs args = (SocketAsyncEventArgs) e;
98 EndPointListener epl = (EndPointListener) args.UserToken;
99 Socket accepted = null;
100 if (args.SocketError == SocketError.Success) {
101 accepted = args.AcceptSocket;
102 args.AcceptSocket = null;
106 if (epl.sock != null)
107 epl.sock.AcceptAsync (args);
109 if (accepted != null) {
117 if (accepted == null)
120 if (epl.secure && (epl.cert == null || epl.key == null)) {
124 HttpConnection conn = new HttpConnection (accepted, epl, epl.secure, epl.cert, epl.key);
125 lock (epl.unregistered) {
126 epl.unregistered [conn] = conn;
128 conn.BeginReadRequest ();
131 internal void RemoveConnection (HttpConnection conn)
133 lock (unregistered) {
134 unregistered.Remove (conn);
138 public bool BindContext (HttpListenerContext context)
140 HttpListenerRequest req = context.Request;
141 ListenerPrefix prefix;
142 HttpListener listener = SearchListener (req.Url, out prefix);
143 if (listener == null)
146 context.Listener = listener;
147 context.Connection.Prefix = prefix;
151 public void UnbindContext (HttpListenerContext context)
153 if (context == null || context.Request == null)
156 context.Listener.UnregisterContext (context);
159 HttpListener SearchListener (Uri uri, out ListenerPrefix prefix)
165 string host = uri.Host;
167 string path = HttpUtility.UrlDecode (uri.AbsolutePath);
168 string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
170 HttpListener best_match = null;
171 int best_length = -1;
173 if (host != null && host != "") {
174 Hashtable p_ro = prefixes;
175 foreach (ListenerPrefix p in p_ro.Keys) {
176 string ppath = p.Path;
177 if (ppath.Length < best_length)
180 if (p.Host != host || p.Port != port)
183 if (path.StartsWith (ppath) || path_slash.StartsWith (ppath)) {
184 best_length = ppath.Length;
185 best_match = (HttpListener) p_ro [p];
189 if (best_length != -1)
193 ArrayList list = unhandled;
194 best_match = MatchFromList (host, path, list, out prefix);
195 if (path != path_slash && best_match == null)
196 best_match = MatchFromList (host, path_slash, list, out prefix);
197 if (best_match != null)
201 best_match = MatchFromList (host, path, list, out prefix);
202 if (path != path_slash && best_match == null)
203 best_match = MatchFromList (host, path_slash, list, out prefix);
204 if (best_match != null)
210 HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
216 HttpListener best_match = null;
217 int best_length = -1;
219 foreach (ListenerPrefix p in list) {
220 string ppath = p.Path;
221 if (ppath.Length < best_length)
224 if (path.StartsWith (ppath)) {
225 best_length = ppath.Length;
226 best_match = p.Listener;
234 void AddSpecial (ArrayList coll, ListenerPrefix prefix)
239 foreach (ListenerPrefix p in coll) {
240 if (p.Path == prefix.Path) //TODO: code
241 throw new HttpListenerException (400, "Prefix already in use.");
246 bool RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
252 for (int i = 0; i < c; i++) {
253 ListenerPrefix p = (ListenerPrefix) coll [i];
254 if (p.Path == prefix.Path) {
262 void CheckIfRemove ()
264 if (prefixes.Count > 0)
267 ArrayList list = unhandled;
268 if (list != null && list.Count > 0)
272 if (list != null && list.Count > 0)
275 EndPointManager.RemoveEndPoint (this, endpoint);
281 lock (unregistered) {
283 // Clone the list because RemoveConnection can be called from Close
285 var connections = new List<HttpConnection> (unregistered.Keys);
287 foreach (HttpConnection c in connections)
289 unregistered.Clear ();
293 public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
297 if (prefix.Host == "*") {
300 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
301 prefix.Listener = listener;
302 AddSpecial (future, prefix);
303 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
307 if (prefix.Host == "+") {
310 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
311 prefix.Listener = listener;
312 AddSpecial (future, prefix);
313 } while (Interlocked.CompareExchange (ref all, future, current) != current);
320 if (prefs.ContainsKey (prefix)) {
321 HttpListener other = (HttpListener) prefs [prefix];
322 if (other != listener) // TODO: code.
323 throw new HttpListenerException (400, "There's another listener for " + prefix);
326 p2 = (Hashtable) prefs.Clone ();
327 p2 [prefix] = listener;
328 } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);
331 public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
335 if (prefix.Host == "*") {
338 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
339 if (!RemoveSpecial (future, prefix))
340 break; // Prefix not found
341 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
346 if (prefix.Host == "+") {
349 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
350 if (!RemoveSpecial (future, prefix))
351 break; // Prefix not found
352 } while (Interlocked.CompareExchange (ref all, future, current) != current);
360 if (!prefs.ContainsKey (prefix))
363 p2 = (Hashtable) prefs.Clone ();
365 } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);