Facilitate the merge
[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                                 if (epl.sock != null)
87                                         accepted = epl.sock.EndAccept (ares);
88                         } catch {
89                                 // Anything to do here?
90                         } finally {
91                                 try {
92                                         if (epl.sock != null)
93                                                 epl.sock.BeginAccept (OnAccept, epl);
94                                 } catch {
95                                         if (accepted != null) {
96                                                 try {
97                                                         accepted.Close ();
98                                                 } catch {}
99                                                 accepted = null;
100                                         }
101                                 } 
102                         }
103
104                         if (accepted == null)
105                                 return;
106
107                         if (epl.secure && (epl.cert == null || epl.key == null)) {
108                                 accepted.Close ();
109                                 return;
110                         }
111                         HttpConnection conn = new HttpConnection (accepted, epl, epl.secure, epl.cert, epl.key);
112                         conn.BeginReadRequest ();
113                 }
114
115                 public bool BindContext (HttpListenerContext context)
116                 {
117                         HttpListenerRequest req = context.Request;
118                         ListenerPrefix prefix;
119                         HttpListener listener = SearchListener (req.UserHostName, req.Url, out prefix);
120                         if (listener == null)
121                                 return false;
122
123                         context.Listener = listener;
124                         context.Connection.Prefix = prefix;
125                         listener.RegisterContext (context);
126                         return true;
127                 }
128
129                 public void UnbindContext (HttpListenerContext context)
130                 {
131                         if (context == null || context.Request == null)
132                                 return;
133
134                         HttpListenerRequest req = context.Request;
135                         ListenerPrefix prefix;
136                         HttpListener listener = SearchListener (req.UserHostName, req.Url, out prefix);
137                         if (listener != null)
138                                 listener.UnregisterContext (context);
139                 }
140
141                 HttpListener SearchListener (string host, Uri uri, out ListenerPrefix prefix)
142                 {
143                         prefix = null;
144                         if (uri == null)
145                                 return null;
146
147                         //TODO: We should use a ReaderWriterLock between this and the add/remove operations.
148                         if (host != null) {
149                                 int colon = host.IndexOf (':');
150                                 if (colon >= 0)
151                                         host = host.Substring (0, colon);
152                         }
153
154                         string path = HttpUtility.UrlDecode (uri.AbsolutePath);
155                         string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
156                         
157                         HttpListener best_match = null;
158                         int best_length = -1;
159
160                         lock (prefixes) {
161                                 if (host != null && host != "") {
162                                         foreach (ListenerPrefix p in prefixes.Keys) {
163                                                 string ppath = p.Path;
164                                                 if (ppath.Length < best_length)
165                                                         continue;
166
167                                                 if (p.Host == host && (path.StartsWith (ppath) || path_slash.StartsWith (ppath))) {
168                                                         best_length = ppath.Length;
169                                                         best_match = (HttpListener) prefixes [p];
170                                                         prefix = p;
171                                                 }
172                                         }
173                                         if (best_length != -1)
174                                                 return best_match;
175                                 }
176
177                                 best_match = MatchFromList (host, path, unhandled, out prefix);
178                                 if (best_match != null)
179                                         return best_match;
180
181                                 best_match = MatchFromList (host, path, all, out prefix);
182                                 if (best_match != null)
183                                         return best_match;
184                         }
185                         return null;
186                 }
187
188                 HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
189                 {
190                         prefix = null;
191                         if (list == null)
192                                 return null;
193
194                         HttpListener best_match = null;
195                         int best_length = -1;
196                         
197                         foreach (ListenerPrefix p in list) {
198                                 string ppath = p.Path;
199                                 if (ppath.Length < best_length)
200                                         continue;
201
202                                 if (path.StartsWith (ppath)) {
203                                         best_length = ppath.Length;
204                                         best_match = p.Listener;
205                                         prefix = p;
206                                 }
207                         }
208
209                         return best_match;
210                 }
211
212                 void AddSpecial (ArrayList coll, ListenerPrefix prefix)
213                 {
214                         if (coll == null)
215                                 return;
216
217                         foreach (ListenerPrefix p in coll) {
218                                 if (p.Path == prefix.Path) //TODO: code
219                                         throw new HttpListenerException (400, "Prefix already in use.");
220                         }
221
222                         coll.Add (prefix);
223                 }
224
225                 void RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
226                 {
227                         if (coll == null)
228                                 return;
229
230                         int c = coll.Count;
231                         for (int i = 0; i < c; i++) {
232                                 ListenerPrefix p = (ListenerPrefix) coll [i];
233                                 if (p.Path == prefix.Path) {
234                                         coll.RemoveAt (i);
235                                         CheckIfRemove ();
236                                         return;
237                                 }
238                         }
239                 }
240
241                 void CheckIfRemove ()
242                 {
243                         if (prefixes.Count > 0)
244                                 return;
245
246                         if (unhandled != null && unhandled.Count > 0)
247                                 return;
248
249                         if (all != null && all.Count > 0)
250                                 return;
251
252                         EndPointManager.RemoveEndPoint (this, endpoint);
253                 }
254
255                 public void Close ()
256                 {
257                         sock.Close ();
258                 }
259
260                 public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
261                 {
262                         lock (prefixes) {
263                                 if (prefix.Host == "*") {
264                                         if (unhandled == null)
265                                                 unhandled = new ArrayList ();
266
267                                         prefix.Listener = listener;
268                                         AddSpecial (unhandled, prefix);
269                                         return;
270                                 }
271
272                                 if (prefix.Host == "+") {
273                                         if (all == null)
274                                                 all = new ArrayList ();
275                                         prefix.Listener = listener;
276                                         AddSpecial (all, prefix);
277                                         return;
278                                 }
279
280                                 if (prefixes.ContainsKey (prefix)) {
281                                         HttpListener other = (HttpListener) prefixes [prefix];
282                                         if (other != listener) // TODO: code.
283                                                 throw new HttpListenerException (400, "There's another listener for " + prefix);
284                                         return;
285                                 }
286
287                                 prefixes [prefix] = listener;
288                         }
289                 }
290
291                 public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
292                 {
293                         lock (prefixes) {
294                                 if (prefix.Host == "*") {
295                                         RemoveSpecial (unhandled, prefix);
296                                         return;
297                                 }
298
299                                 if (prefix.Host == "+") {
300                                         RemoveSpecial (all, prefix);
301                                         return;
302                                 }
303
304                                 if (prefixes.ContainsKey (prefix)) {
305                                         prefixes.Remove (prefix);
306                                         CheckIfRemove ();
307                                 }
308                         }
309                 }
310         }
311 }
312 #endif
313