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