2 // System.Net.EndPointListener
5 // Gonzalo Paniagua Javier (gonzalo@novell.com)
7 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 #if NET_2_0 && SECURITY_DEP
32 using System.Net.Sockets;
33 using System.Collections;
34 using System.Security.Cryptography;
35 using System.Security.Cryptography.X509Certificates;
36 using System.Threading;
37 using Mono.Security.Authenticode;
39 namespace System.Net {
40 sealed class EndPointListener
44 Hashtable prefixes; // Dictionary <ListenerPrefix, HttpListener>
45 ArrayList unhandled; // List<ListenerPrefix> unhandled; host = '*'
46 ArrayList all; // List<ListenerPrefix> all; host = '+'
47 X509Certificate2 cert;
48 AsymmetricAlgorithm key;
50 Hashtable unregistered;
52 public EndPointListener (IPAddress addr, int port, bool secure)
56 LoadCertificateAndKey (addr, port);
59 endpoint = new IPEndPoint (addr, port);
60 sock = new Socket (addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
63 SocketAsyncEventArgs args = new SocketAsyncEventArgs ();
64 args.UserToken = this;
65 args.Completed += OnAccept;
66 sock.AcceptAsync (args);
67 prefixes = new Hashtable ();
68 unregistered = new Hashtable ();
71 void LoadCertificateAndKey (IPAddress addr, int port)
73 // Actually load the certificate
75 string dirname = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
76 string path = Path.Combine (dirname, ".mono");
77 path = Path.Combine (path, "httplistener");
78 string cert_file = Path.Combine (path, String.Format ("{0}.cer", port));
79 string pvk_file = Path.Combine (path, String.Format ("{0}.pvk", port));
80 cert = new X509Certificate2 (cert_file);
81 key = PrivateKey.CreateFromFile (pvk_file).RSA;
87 static void OnAccept (object sender, EventArgs e)
89 SocketAsyncEventArgs args = (SocketAsyncEventArgs) e;
90 EndPointListener epl = (EndPointListener) args.UserToken;
91 Socket accepted = null;
92 if (args.SocketError == SocketError.Success) {
93 accepted = args.AcceptSocket;
94 args.AcceptSocket = null;
99 epl.sock.AcceptAsync (args);
101 if (accepted != null) {
109 if (accepted == null)
112 if (epl.secure && (epl.cert == null || epl.key == null)) {
116 HttpConnection conn = new HttpConnection (accepted, epl, epl.secure, epl.cert, epl.key);
117 lock (epl.unregistered) {
118 epl.unregistered [conn] = conn;
120 conn.BeginReadRequest ();
123 internal void RemoveConnection (HttpConnection conn)
125 lock (unregistered) {
126 unregistered.Remove (conn);
130 public bool BindContext (HttpListenerContext context)
132 HttpListenerRequest req = context.Request;
133 ListenerPrefix prefix;
134 HttpListener listener = SearchListener (req.Url, out prefix);
135 if (listener == null)
138 context.Listener = listener;
139 context.Connection.Prefix = prefix;
143 public void UnbindContext (HttpListenerContext context)
145 if (context == null || context.Request == null)
148 context.Listener.UnregisterContext (context);
151 HttpListener SearchListener (Uri uri, out ListenerPrefix prefix)
157 string host = uri.Host;
159 string path = HttpUtility.UrlDecode (uri.AbsolutePath);
160 string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
162 HttpListener best_match = null;
163 int best_length = -1;
165 if (host != null && host != "") {
166 Hashtable p_ro = prefixes;
167 foreach (ListenerPrefix p in p_ro.Keys) {
168 string ppath = p.Path;
169 if (ppath.Length < best_length)
172 if (p.Host != host || p.Port != port)
175 if (path.StartsWith (ppath) || path_slash.StartsWith (ppath)) {
176 best_length = ppath.Length;
177 best_match = (HttpListener) p_ro [p];
181 if (best_length != -1)
185 ArrayList list = unhandled;
186 best_match = MatchFromList (host, path, list, out prefix);
187 if (path != path_slash && best_match == null)
188 best_match = MatchFromList (host, path_slash, list, out prefix);
189 if (best_match != null)
193 best_match = MatchFromList (host, path, list, out prefix);
194 if (path != path_slash && best_match == null)
195 best_match = MatchFromList (host, path_slash, list, out prefix);
196 if (best_match != null)
202 HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
208 HttpListener best_match = null;
209 int best_length = -1;
211 foreach (ListenerPrefix p in list) {
212 string ppath = p.Path;
213 if (ppath.Length < best_length)
216 if (path.StartsWith (ppath)) {
217 best_length = ppath.Length;
218 best_match = p.Listener;
226 void AddSpecial (ArrayList coll, ListenerPrefix prefix)
231 foreach (ListenerPrefix p in coll) {
232 if (p.Path == prefix.Path) //TODO: code
233 throw new HttpListenerException (400, "Prefix already in use.");
238 bool RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
244 for (int i = 0; i < c; i++) {
245 ListenerPrefix p = (ListenerPrefix) coll [i];
246 if (p.Path == prefix.Path) {
254 void CheckIfRemove ()
256 if (prefixes.Count > 0)
259 ArrayList list = unhandled;
260 if (list != null && list.Count > 0)
264 if (list != null && list.Count > 0)
267 EndPointManager.RemoveEndPoint (this, endpoint);
273 lock (unregistered) {
274 foreach (HttpConnection c in unregistered.Keys)
276 unregistered.Clear ();
280 public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
284 if (prefix.Host == "*") {
287 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
288 prefix.Listener = listener;
289 AddSpecial (future, prefix);
290 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
294 if (prefix.Host == "+") {
297 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
298 prefix.Listener = listener;
299 AddSpecial (future, prefix);
300 } while (Interlocked.CompareExchange (ref all, future, current) != current);
307 if (prefs.ContainsKey (prefix)) {
308 HttpListener other = (HttpListener) prefs [prefix];
309 if (other != listener) // TODO: code.
310 throw new HttpListenerException (400, "There's another listener for " + prefix);
313 p2 = (Hashtable) prefs.Clone ();
314 p2 [prefix] = listener;
315 } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);
318 public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
322 if (prefix.Host == "*") {
325 future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
326 if (!RemoveSpecial (future, prefix))
327 break; // Prefix not found
328 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
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 all, future, current) != current);
347 if (!prefs.ContainsKey (prefix))
350 p2 = (Hashtable) prefs.Clone ();
352 } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);