2009-07-11 Michael Barker <mike@middlesoft.co.uk>
[mono.git] / mcs / class / System / System.Net / EndPointListener.cs
1 //
2 // System.Net.EndPointListener
3 //
4 // Author:
5 //      Gonzalo Paniagua Javier (gonzalo@novell.com)
6 //
7 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
8 //
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:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
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.
27 //
28
29 #if NET_2_0 && SECURITY_DEP
30
31 using System.IO;
32 using System.Net.Sockets;
33 using System.Collections;
34 using System.Security.Cryptography;
35 using System.Security.Cryptography.X509Certificates;
36 using Mono.Security.Authenticode;
37
38 namespace System.Net {
39         sealed class EndPointListener
40         {
41                 IPEndPoint endpoint;
42                 Socket sock;
43                 Hashtable prefixes;  // Dictionary <ListenerPrefix, HttpListener>
44                 ArrayList unhandled; // List<ListenerPrefix> unhandled; host = '*'
45                 ArrayList all;       // List<ListenerPrefix> all;  host = '+'
46                 X509Certificate2 cert;
47                 AsymmetricAlgorithm key;
48                 bool secure;
49
50                 public EndPointListener (IPAddress addr, int port, bool secure)
51                 {
52                         if (secure) {
53                                 this.secure = secure;
54                                 LoadCertificateAndKey (addr, port);
55                         }
56
57                         endpoint = new IPEndPoint (addr, port);
58                         sock = new Socket (addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
59                         sock.Bind (endpoint);
60                         sock.Listen (500);
61                         sock.BeginAccept (OnAccept, this);
62                         prefixes = new Hashtable ();
63                 }
64
65                 void LoadCertificateAndKey (IPAddress addr, int port)
66                 {
67                         // Actually load the certificate
68                         try {
69                                 string dirname = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
70                                 string path = Path.Combine (dirname, ".mono");
71                                 path = Path.Combine (path, "httplistener");
72                                 string cert_file = Path.Combine (path, String.Format ("{0}.cer", port));
73                                 string pvk_file = Path.Combine (path, String.Format ("{0}.pvk", port));
74                                 cert = new X509Certificate2 (cert_file);
75                                 key = PrivateKey.CreateFromFile (pvk_file).RSA;
76                         } catch {
77                                 // ignore errors
78                         }
79                 }
80
81                 static void OnAccept (IAsyncResult ares)
82                 {
83                         EndPointListener epl = (EndPointListener) ares.AsyncState;
84                         Socket accepted = null;
85                         try {
86                                 accepted = epl.sock.EndAccept (ares);
87                         } catch {
88                                 // Anything to do here?
89                         } finally {
90                                 try {
91                                         epl.sock.BeginAccept (OnAccept, epl);
92                                 } catch {
93                                         if (accepted != null) {
94                                                 try {
95                                                         accepted.Close ();
96                                                 } catch {}
97                                                 accepted = null;
98                                         }
99                                 } 
100                         }
101
102                         if (accepted == null)
103                                 return;
104
105                         if (epl.secure && (epl.cert == null || epl.key == null)) {
106                                 accepted.Close ();
107                                 return;
108                         }
109                         HttpConnection conn = new HttpConnection (accepted, epl, epl.secure, epl.cert, epl.key);
110                         conn.BeginReadRequest ();
111                 }
112
113                 public bool BindContext (HttpListenerContext context)
114                 {
115                         HttpListenerRequest req = context.Request;
116                         ListenerPrefix prefix;
117                         HttpListener listener = SearchListener (req.UserHostName, req.RawUrl, out prefix);
118                         if (listener == null)
119                                 return false;
120
121                         context.Listener = listener;
122                         context.Connection.Prefix = prefix;
123                         listener.RegisterContext (context);
124                         return true;
125                 }
126
127                 public void UnbindContext (HttpListenerContext context)
128                 {
129                         if (context == null || context.Request == null)
130                                 return;
131
132                         HttpListenerRequest req = context.Request;
133                         ListenerPrefix prefix;
134                         HttpListener listener = SearchListener (req.UserHostName, req.RawUrl, out prefix);
135                         if (listener != null)
136                                 listener.UnregisterContext (context);
137                 }
138
139                 HttpListener SearchListener (string host, string raw_url, out ListenerPrefix prefix)
140                 {
141                         prefix = null;
142                         if (raw_url == null)
143                                 return null;
144
145                         //TODO: We should use a ReaderWriterLock between this and the add/remove operations.
146                         if (host != null) {
147                                 int colon = host.IndexOf (':');
148                                 if (colon >= 0)
149                                         host = host.Substring (0, colon);
150                         }
151
152                         string path;
153                         Uri raw_uri;
154                         if (Uri.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
155                                 path = raw_uri.PathAndQuery;
156                         else
157                                 path = HttpUtility.UrlDecode (raw_url);
158                         
159                         string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
160                         
161                         HttpListener best_match = null;
162                         int best_length = -1;
163
164                         lock (prefixes) {
165                                 if (host != null && host != "") {
166                                         foreach (ListenerPrefix p in prefixes.Keys) {
167                                                 string ppath = p.Path;
168                                                 if (ppath.Length < best_length)
169                                                         continue;
170
171                                                 if (p.Host == host && (path.StartsWith (ppath) || path_slash.StartsWith (ppath))) {
172                                                         best_length = ppath.Length;
173                                                         best_match = (HttpListener) prefixes [p];
174                                                         prefix = p;
175                                                 }
176                                         }
177                                         if (best_length != -1)
178                                                 return best_match;
179                                 }
180
181                                 best_match = MatchFromList (host, path, unhandled, out prefix);
182                                 if (best_match != null)
183                                         return best_match;
184
185                                 best_match = MatchFromList (host, path, all, out prefix);
186                                 if (best_match != null)
187                                         return best_match;
188                         }
189                         return null;
190                 }
191
192                 HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
193                 {
194                         prefix = null;
195                         if (list == null)
196                                 return null;
197
198                         HttpListener best_match = null;
199                         int best_length = -1;
200                         
201                         foreach (ListenerPrefix p in list) {
202                                 string ppath = p.Path;
203                                 if (ppath.Length < best_length)
204                                         continue;
205
206                                 if (path.StartsWith (ppath)) {
207                                         best_length = ppath.Length;
208                                         best_match = p.Listener;
209                                         prefix = p;
210                                 }
211                         }
212
213                         return best_match;
214                 }
215
216                 void AddSpecial (ArrayList coll, ListenerPrefix prefix)
217                 {
218                         if (coll == null)
219                                 return;
220
221                         foreach (ListenerPrefix p in coll) {
222                                 if (p.Path == prefix.Path) //TODO: code
223                                         throw new HttpListenerException (400, "Prefix already in use.");
224                         }
225
226                         coll.Add (prefix);
227                 }
228
229                 void RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
230                 {
231                         if (coll == null)
232                                 return;
233
234                         int c = coll.Count;
235                         for (int i = 0; i < c; i++) {
236                                 ListenerPrefix p = (ListenerPrefix) coll [i];
237                                 if (p.Path == prefix.Path) {
238                                         coll.RemoveAt (i);
239                                         CheckIfRemove ();
240                                         return;
241                                 }
242                         }
243                 }
244
245                 void CheckIfRemove ()
246                 {
247                         if (prefixes.Count > 0)
248                                 return;
249
250                         if (unhandled != null && unhandled.Count > 0)
251                                 return;
252
253                         if (all != null && all.Count > 0)
254                                 return;
255
256                         EndPointManager.RemoveEndPoint (this, endpoint);
257                 }
258
259                 public void Close ()
260                 {
261                         sock.Close ();
262                 }
263
264                 public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
265                 {
266                         lock (prefixes) {
267                                 if (prefix.Host == "*") {
268                                         if (unhandled == null)
269                                                 unhandled = new ArrayList ();
270
271                                         prefix.Listener = listener;
272                                         AddSpecial (unhandled, prefix);
273                                         return;
274                                 }
275
276                                 if (prefix.Host == "+") {
277                                         if (all == null)
278                                                 all = new ArrayList ();
279                                         prefix.Listener = listener;
280                                         AddSpecial (all, prefix);
281                                         return;
282                                 }
283
284                                 if (prefixes.ContainsKey (prefix)) {
285                                         HttpListener other = (HttpListener) prefixes [prefix];
286                                         if (other != listener) // TODO: code.
287                                                 throw new HttpListenerException (400, "There's another listener for " + prefix);
288                                         return;
289                                 }
290
291                                 prefixes [prefix] = listener;
292                         }
293                 }
294
295                 public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
296                 {
297                         lock (prefixes) {
298                                 if (prefix.Host == "*") {
299                                         RemoveSpecial (unhandled, prefix);
300                                         return;
301                                 }
302
303                                 if (prefix.Host == "+") {
304                                         RemoveSpecial (all, prefix);
305                                         return;
306                                 }
307
308                                 if (prefixes.ContainsKey (prefix)) {
309                                         prefixes.Remove (prefix);
310                                         CheckIfRemove ();
311                                 }
312                         }
313                 }
314         }
315 }
316 #endif
317