* Makefile: Add a System.Core.dll reference; embed monodoc.xml as a
[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         sealed class EndPointListener : IHttpListenerContextBinder
42         {
43                 IPEndPoint endpoint;
44                 Socket sock;
45                 Hashtable prefixes;  // Dictionary <ListenerPrefix, HttpListener>
46                 ArrayList unhandled; // List<ListenerPrefix> unhandled; host = '*'
47                 ArrayList all;       // List<ListenerPrefix> all;  host = '+'
48                 
49                 AsymmetricAlgorithm key;
50                 bool secure;
51
52                 public EndPointListener (IPAddress addr, int port, bool secure)
53                 {
54 #if !EMBEDDED_IN_1_0
55                         if (secure) {
56                                 this.secure = secure;
57                                 LoadCertificateAndKey (addr, port);
58                         }
59 #endif
60
61                         endpoint = new IPEndPoint (addr, port);
62                         sock = new Socket (addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
63                         sock.Bind (endpoint);
64                         sock.Listen (500);
65                         sock.BeginAccept (OnAccept, this);
66                         prefixes = new Hashtable ();
67                 }
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
87                 static void OnAccept (IAsyncResult ares)
88                 {
89                         EndPointListener epl = (EndPointListener) ares.AsyncState;
90                         Socket accepted = null;
91                         try {
92                                 accepted = epl.sock.EndAccept (ares);
93                         } catch {
94                                 // Anything to do here?
95                         } finally {
96                                 try {
97                                         epl.sock.BeginAccept (OnAccept, epl);
98                                 } catch {
99                                         if (accepted != null) {
100                                                 try {
101                                                         accepted.Close ();
102                                                 } catch {}
103                                                 accepted = null;
104                                         }
105                                 } 
106                         }
107
108                         if (accepted == null)
109                                 return;
110
111                         if (epl.secure && (epl.key == null)) {
112                                 accepted.Close ();
113                                 return;
114                         }
115                         HttpConnection conn = new HttpConnection (accepted, epl);
116                         conn.BeginReadRequest ();
117                 }
118
119                 public bool BindContext (HttpListenerContext context)
120                 {
121                         HttpListenerRequest req = context.Request;
122                         ListenerPrefix prefix;
123                         HttpListener listener = SearchListener (req.UserHostName, req.RawUrl, out prefix);
124                         if (listener == null)
125                                 return false;
126
127                         context.Listener = listener;
128                         context.Connection.Prefix = prefix;
129                         listener.RegisterContext (context);
130                         return true;
131                 }
132
133                 public void UnbindContext (HttpListenerContext context)
134                 {
135                         if (context == null || context.Request == null)
136                                 return;
137
138                         HttpListenerRequest req = context.Request;
139                         ListenerPrefix prefix;
140                         HttpListener listener = SearchListener (req.UserHostName, req.RawUrl, out prefix);
141                         if (listener != null)
142                                 listener.UnregisterContext (context);
143                 }
144
145                 HttpListener SearchListener (string host, string raw_url, out ListenerPrefix prefix)
146                 {
147                         prefix = null;
148                         if (raw_url == null)
149                                 return null;
150
151                         //TODO: We should use a ReaderWriterLock between this and the add/remove operations.
152                         if (host != null) {
153                                 int colon = host.IndexOf (':');
154                                 if (colon >= 0)
155                                         host = host.Substring (0, colon);
156                         }
157
158                         string path;
159                         Uri raw_uri;
160                         #if NET_2_0
161 if (MonoHttp.Utility.MaybeUri (raw_url) && Uri.TryCreate (raw_url, UriKind.Absolute, out raw_uri))
162 #else
163 try { raw_uri = new Uri (raw_url); } catch { raw_uri = null; } if (raw_uri != null)
164 #endif
165
166                                 path = raw_uri.PathAndQuery;
167                         else
168                                 path = HttpUtility.UrlDecode (raw_url);
169                         
170                         string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
171                         
172                         HttpListener best_match = null;
173                         int best_length = -1;
174
175                         lock (prefixes) {
176                                 if (host != null && host != "") {
177                                         foreach (ListenerPrefix p in prefixes.Keys) {
178                                                 string ppath = p.Path;
179                                                 if (ppath.Length < best_length)
180                                                         continue;
181
182                                                 if (p.Host == host && (path.StartsWith (ppath) || path_slash.StartsWith (ppath))) {
183                                                         best_length = ppath.Length;
184                                                         best_match = (HttpListener) prefixes [p];
185                                                         prefix = p;
186                                                 }
187                                         }
188                                         if (best_length != -1)
189                                                 return best_match;
190                                 }
191
192                                 best_match = MatchFromList (host, path, unhandled, out prefix);
193                                 if (best_match != null)
194                                         return best_match;
195
196                                 best_match = MatchFromList (host, path, all, out prefix);
197                                 if (best_match != null)
198                                         return best_match;
199                         }
200                         return null;
201                 }
202
203                 HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
204                 {
205                         prefix = null;
206                         if (list == null)
207                                 return null;
208
209                         HttpListener best_match = null;
210                         int best_length = -1;
211                         
212                         foreach (ListenerPrefix p in list) {
213                                 string ppath = p.Path;
214                                 if (ppath.Length < best_length)
215                                         continue;
216
217                                 if (path.StartsWith (ppath)) {
218                                         best_length = ppath.Length;
219                                         best_match = p.Listener;
220                                         prefix = p;
221                                 }
222                         }
223
224                         return best_match;
225                 }
226
227                 void AddSpecial (ArrayList coll, ListenerPrefix prefix)
228                 {
229                         if (coll == null)
230                                 return;
231
232                         foreach (ListenerPrefix p in coll) {
233                                 if (p.Path == prefix.Path) //TODO: code
234                                         throw new HttpListenerException (400, "Prefix already in use.");
235                         }
236
237                         coll.Add (prefix);
238                 }
239
240                 void RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
241                 {
242                         if (coll == null)
243                                 return;
244
245                         int c = coll.Count;
246                         for (int i = 0; i < c; i++) {
247                                 ListenerPrefix p = (ListenerPrefix) coll [i];
248                                 if (p.Path == prefix.Path) {
249                                         coll.RemoveAt (i);
250                                         CheckIfRemove ();
251                                         return;
252                                 }
253                         }
254                 }
255
256                 void CheckIfRemove ()
257                 {
258                         if (prefixes.Count > 0)
259                                 return;
260
261                         if (unhandled != null && unhandled.Count > 0)
262                                 return;
263
264                         if (all != null && all.Count > 0)
265                                 return;
266
267                         EndPointManager.RemoveEndPoint (this, endpoint);
268                 }
269
270                 public void Close ()
271                 {
272                         sock.Close ();
273                 }
274
275                 public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
276                 {
277                         lock (prefixes) {
278                                 if (prefix.Host == "*") {
279                                         if (unhandled == null)
280                                                 unhandled = new ArrayList ();
281
282                                         prefix.Listener = listener;
283                                         AddSpecial (unhandled, prefix);
284                                         return;
285                                 }
286
287                                 if (prefix.Host == "+") {
288                                         if (all == null)
289                                                 all = new ArrayList ();
290                                         prefix.Listener = listener;
291                                         AddSpecial (all, prefix);
292                                         return;
293                                 }
294
295                                 if (prefixes.ContainsKey (prefix)) {
296                                         HttpListener other = (HttpListener) prefixes [prefix];
297                                         if (other != listener) // TODO: code.
298                                                 throw new HttpListenerException (400, "There's another listener for " + prefix);
299                                         return;
300                                 }
301
302                                 prefixes [prefix] = listener;
303                         }
304                 }
305
306                 public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
307                 {
308                         lock (prefixes) {
309                                 if (prefix.Host == "*") {
310                                         RemoveSpecial (unhandled, prefix);
311                                         return;
312                                 }
313
314                                 if (prefix.Host == "+") {
315                                         RemoveSpecial (all, prefix);
316                                         return;
317                                 }
318
319                                 if (prefixes.ContainsKey (prefix)) {
320                                         prefixes.Remove (prefix);
321                                         CheckIfRemove ();
322                                 }
323                         }
324                 }
325         }
326 }
327 #endif
328