2007-02-16 Geoff Norton <gnorton@customerdna.com>
[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.Generic;
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                 Dictionary<ListenerPrefix, HttpListener> prefixes;
44                 List<ListenerPrefix> unhandled; // host = '*'
45                 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 Dictionary<ListenerPrefix, HttpListener> ();
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 = HttpUtility.UrlDecode (raw_url);
153                         HttpListener best_match = null;
154                         int best_length = -1;
155
156                         lock (prefixes) {
157                                 if (host != null && host != "") {
158                                         foreach (ListenerPrefix p in prefixes.Keys) {
159                                                 string ppath = p.Path;
160                                                 if (ppath.Length < best_length)
161                                                         continue;
162
163                                                 if (p.Host == host && path.StartsWith (ppath)) {
164                                                         best_length = ppath.Length;
165                                                         best_match = prefixes [p];
166                                                         prefix = p;
167                                                 }
168                                         }
169                                         if (best_length != -1)
170                                                 return best_match;
171                                 }
172
173                                 best_match = MatchFromList (host, path, unhandled, out prefix);
174                                 if (best_match != null)
175                                         return best_match;
176
177                                 best_match = MatchFromList (host, path, all, out prefix);
178                                 if (best_match != null)
179                                         return best_match;
180                         }
181                         return null;
182                 }
183
184                 HttpListener MatchFromList (string host, string path, List<ListenerPrefix> list, out ListenerPrefix prefix)
185                 {
186                         prefix = null;
187                         if (list == null)
188                                 return null;
189
190                         HttpListener best_match = null;
191                         int best_length = -1;
192                         
193                         foreach (ListenerPrefix p in list) {
194                                 string ppath = p.Path;
195                                 if (ppath.Length < best_length)
196                                         continue;
197
198                                 if (path.StartsWith (ppath)) {
199                                         best_length = ppath.Length;
200                                         best_match = p.Listener;
201                                         prefix = p;
202                                 }
203                         }
204
205                         return best_match;
206                 }
207
208                 void AddSpecial (List<ListenerPrefix> coll, ListenerPrefix prefix)
209                 {
210                         if (coll == null)
211                                 return;
212
213                         foreach (ListenerPrefix p in coll) {
214                                 if (p.Path == prefix.Path) //TODO: code
215                                         throw new HttpListenerException (400, "Prefix already in use.");
216                         }
217
218                         coll.Add (prefix);
219                 }
220
221                 void RemoveSpecial (List<ListenerPrefix> coll, ListenerPrefix prefix)
222                 {
223                         if (coll == null)
224                                 return;
225
226                         int c = coll.Count;
227                         for (int i = 0; i < c; i++) {
228                                 ListenerPrefix p = coll [i];
229                                 if (p.Path == prefix.Path) {
230                                         coll.RemoveAt (i);
231                                         CheckIfRemove ();
232                                         return;
233                                 }
234                         }
235                 }
236
237                 void CheckIfRemove ()
238                 {
239                         if (prefixes.Count > 0)
240                                 return;
241
242                         if (unhandled != null && unhandled.Count > 0)
243                                 return;
244
245                         if (all != null && all.Count > 0)
246                                 return;
247
248                         EndPointManager.RemoveEndPoint (this, endpoint);
249                 }
250
251                 public void Close ()
252                 {
253                         sock.Close ();
254                 }
255
256                 public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
257                 {
258                         lock (prefixes) {
259                                 if (prefix.Host == "*") {
260                                         if (unhandled == null)
261                                                 unhandled = new List<ListenerPrefix> ();
262
263                                         prefix.Listener = listener;
264                                         AddSpecial (unhandled, prefix);
265                                         return;
266                                 }
267
268                                 if (prefix.Host == "+") {
269                                         if (all == null)
270                                                 all = new List<ListenerPrefix> ();
271                                         prefix.Listener = listener;
272                                         AddSpecial (all, prefix);
273                                         return;
274                                 }
275
276                                 if (prefixes.ContainsKey (prefix)) {
277                                         HttpListener other = prefixes [prefix];
278                                         if (other != listener) // TODO: code.
279                                                 throw new HttpListenerException (400, "There's another listener for " + prefix);
280                                         return;
281                                 }
282
283                                 prefixes [prefix] = listener;
284                         }
285                 }
286
287                 public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
288                 {
289                         lock (prefixes) {
290                                 if (prefix.Host == "*") {
291                                         RemoveSpecial (unhandled, prefix);
292                                         return;
293                                 }
294
295                                 if (prefix.Host == "+") {
296                                         RemoveSpecial (all, prefix);
297                                         return;
298                                 }
299
300                                 if (prefixes.ContainsKey (prefix)) {
301                                         prefixes.Remove (prefix);
302                                 }
303                         }
304                 }
305         }
306 }
307 #endif
308