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