Merge pull request #1695 from gregoryyoung/master
[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 #if MONOTOUCH || MONODROID
33 using Mono.Security.Authenticode;
34 #else
35 extern alias MonoSecurity;
36 using MonoSecurity::Mono.Security.Authenticode;
37 #endif
38
39 using System.IO;
40 using System.Net.Sockets;
41 using System.Collections;
42 using System.Collections.Generic;
43 using System.Security.Cryptography;
44 using System.Security.Cryptography.X509Certificates;
45 using System.Threading;
46
47 namespace System.Net {
48         sealed class EndPointListener
49         {
50                 IPEndPoint endpoint;
51                 Socket sock;
52                 Hashtable prefixes;  // Dictionary <ListenerPrefix, HttpListener>
53                 ArrayList unhandled; // List<ListenerPrefix> unhandled; host = '*'
54                 ArrayList all;       // List<ListenerPrefix> all;  host = '+'
55                 X509Certificate2 cert;
56                 AsymmetricAlgorithm key;
57                 bool secure;
58                 Dictionary<HttpConnection, HttpConnection> unregistered;
59
60                 public EndPointListener (IPAddress addr, int port, bool secure)
61                 {
62                         if (secure) {
63                                 this.secure = secure;
64                                 LoadCertificateAndKey (addr, port);
65                         }
66
67                         endpoint = new IPEndPoint (addr, port);
68                         sock = new Socket (addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
69                         sock.Bind (endpoint);
70                         sock.Listen (500);
71                         SocketAsyncEventArgs args = new SocketAsyncEventArgs ();
72                         args.UserToken = this;
73                         args.Completed += OnAccept;
74                         sock.AcceptAsync (args);
75                         prefixes = new Hashtable ();
76                         unregistered = new Dictionary<HttpConnection, HttpConnection> ();
77                 }
78
79                 void LoadCertificateAndKey (IPAddress addr, int port)
80                 {
81                         // Actually load the certificate
82                         try {
83                                 string dirname = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
84                                 string path = Path.Combine (dirname, ".mono");
85                                 path = Path.Combine (path, "httplistener");
86                                 string cert_file = Path.Combine (path, String.Format ("{0}.cer", port));
87                                 if (!File.Exists (cert_file))
88                                         return;
89                                 string pvk_file = Path.Combine (path, String.Format ("{0}.pvk", port));
90                                 if (!File.Exists (pvk_file))
91                                         return;
92                                 cert = new X509Certificate2 (cert_file);
93                                 key = PrivateKey.CreateFromFile (pvk_file).RSA;
94                         } catch {
95                                 // ignore errors
96                         }
97                 }
98
99                 static void OnAccept (object sender, EventArgs e)
100                 {
101                         SocketAsyncEventArgs args = (SocketAsyncEventArgs) e;
102                         EndPointListener epl = (EndPointListener) args.UserToken;
103                         Socket accepted = null;
104                         if (args.SocketError == SocketError.Success) {
105                                 accepted = args.AcceptSocket;
106                                 args.AcceptSocket = null;
107                         }
108
109                         try {
110                                 if (epl.sock != null)
111                                         epl.sock.AcceptAsync (args);
112                         } catch {
113                                 if (accepted != null) {
114                                         try {
115                                                 accepted.Close ();
116                                         } catch {}
117                                         accepted = null;
118                                 }
119                         } 
120
121                         if (accepted == null)
122                                 return;
123
124                         if (epl.secure && (epl.cert == null || epl.key == null)) {
125                                 accepted.Close ();
126                                 return;
127                         }
128                         HttpConnection conn = new HttpConnection (accepted, epl, epl.secure, epl.cert, epl.key);
129                         lock (epl.unregistered) {
130                                 epl.unregistered [conn] = conn;
131                         }
132                         conn.BeginReadRequest ();
133                 }
134
135                 internal void RemoveConnection (HttpConnection conn)
136                 {
137                         lock (unregistered) {
138                                 unregistered.Remove (conn);
139                         }
140                 }
141
142                 public bool BindContext (HttpListenerContext context)
143                 {
144                         HttpListenerRequest req = context.Request;
145                         ListenerPrefix prefix;
146                         HttpListener listener = SearchListener (req.Url, out prefix);
147                         if (listener == null)
148                                 return false;
149
150                         context.Listener = listener;
151                         context.Connection.Prefix = prefix;
152                         return true;
153                 }
154
155                 public void UnbindContext (HttpListenerContext context)
156                 {
157                         if (context == null || context.Request == null)
158                                 return;
159
160                         context.Listener.UnregisterContext (context);
161                 }
162
163                 HttpListener SearchListener (Uri uri, out ListenerPrefix prefix)
164                 {
165                         prefix = null;
166                         if (uri == null)
167                                 return null;
168
169                         string host = uri.Host;
170                         int port = uri.Port;
171                         string path = HttpUtility.UrlDecode (uri.AbsolutePath);
172                         string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
173                         
174                         HttpListener best_match = null;
175                         int best_length = -1;
176
177                         if (host != null && host != "") {
178                                 Hashtable p_ro = prefixes;
179                                 foreach (ListenerPrefix p in p_ro.Keys) {
180                                         string ppath = p.Path;
181                                         if (ppath.Length < best_length)
182                                                 continue;
183
184                                         if (p.Host != host || p.Port != port)
185                                                 continue;
186
187                                         if (path.StartsWith (ppath) || path_slash.StartsWith (ppath)) {
188                                                 best_length = ppath.Length;
189                                                 best_match = (HttpListener) p_ro [p];
190                                                 prefix = p;
191                                         }
192                                 }
193                                 if (best_length != -1)
194                                         return best_match;
195                         }
196
197                         ArrayList list = unhandled;
198                         best_match = MatchFromList (host, path, list, out prefix);
199                         if (path != path_slash && best_match == null)
200                                 best_match = MatchFromList (host, path_slash, list, out prefix);
201                         if (best_match != null)
202                                 return best_match;
203
204                         list = all;
205                         best_match = MatchFromList (host, path, list, out prefix);
206                         if (path != path_slash && best_match == null)
207                                 best_match = MatchFromList (host, path_slash, list, out prefix);
208                         if (best_match != null)
209                                 return best_match;
210
211                         return null;
212                 }
213
214                 HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
215                 {
216                         prefix = null;
217                         if (list == null)
218                                 return null;
219
220                         HttpListener best_match = null;
221                         int best_length = -1;
222                         
223                         foreach (ListenerPrefix p in list) {
224                                 string ppath = p.Path;
225                                 if (ppath.Length < best_length)
226                                         continue;
227
228                                 if (path.StartsWith (ppath)) {
229                                         best_length = ppath.Length;
230                                         best_match = p.Listener;
231                                         prefix = p;
232                                 }
233                         }
234
235                         return best_match;
236                 }
237
238                 void AddSpecial (ArrayList coll, ListenerPrefix prefix)
239                 {
240                         if (coll == null)
241                                 return;
242
243                         foreach (ListenerPrefix p in coll) {
244                                 if (p.Path == prefix.Path) //TODO: code
245                                         throw new HttpListenerException (400, "Prefix already in use.");
246                         }
247                         coll.Add (prefix);
248                 }
249
250                 bool RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
251                 {
252                         if (coll == null)
253                                 return false;
254
255                         int c = coll.Count;
256                         for (int i = 0; i < c; i++) {
257                                 ListenerPrefix p = (ListenerPrefix) coll [i];
258                                 if (p.Path == prefix.Path) {
259                                         coll.RemoveAt (i);
260                                         return true;
261                                 }
262                         }
263                         return false;
264                 }
265
266                 void CheckIfRemove ()
267                 {
268                         if (prefixes.Count > 0)
269                                 return;
270
271                         ArrayList list = unhandled;
272                         if (list != null && list.Count > 0)
273                                 return;
274
275                         list = all;
276                         if (list != null && list.Count > 0)
277                                 return;
278
279                         EndPointManager.RemoveEndPoint (this, endpoint);
280                 }
281
282                 public void Close ()
283                 {
284                         sock.Close ();
285                         lock (unregistered) {
286                                 //
287                                 // Clone the list because RemoveConnection can be called from Close
288                                 //
289                                 var connections = new List<HttpConnection> (unregistered.Keys);
290
291                                 foreach (HttpConnection c in connections)
292                                         c.Close (true);
293                                 unregistered.Clear ();
294                         }
295                 }
296
297                 public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
298                 {
299                         ArrayList current;
300                         ArrayList future;
301                         if (prefix.Host == "*") {
302                                 do {
303                                         current = unhandled;
304                                         future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
305                                         prefix.Listener = listener;
306                                         AddSpecial (future, prefix);
307                                 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
308                                 return;
309                         }
310
311                         if (prefix.Host == "+") {
312                                 do {
313                                         current = all;
314                                         future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
315                                         prefix.Listener = listener;
316                                         AddSpecial (future, prefix);
317                                 } while (Interlocked.CompareExchange (ref all, future, current) != current);
318                                 return;
319                         }
320
321                         Hashtable prefs, p2;
322                         do {
323                                 prefs = prefixes;
324                                 if (prefs.ContainsKey (prefix)) {
325                                         HttpListener other = (HttpListener) prefs [prefix];
326                                         if (other != listener) // TODO: code.
327                                                 throw new HttpListenerException (400, "There's another listener for " + prefix);
328                                         return;
329                                 }
330                                 p2 = (Hashtable) prefs.Clone ();
331                                 p2 [prefix] = listener;
332                         } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);
333                 }
334
335                 public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
336                 {
337                         ArrayList current;
338                         ArrayList future;
339                         if (prefix.Host == "*") {
340                                 do {
341                                         current = unhandled;
342                                         future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
343                                         if (!RemoveSpecial (future, prefix))
344                                                 break; // Prefix not found
345                                 } while (Interlocked.CompareExchange (ref unhandled, future, current) != current);
346                                 CheckIfRemove ();
347                                 return;
348                         }
349
350                         if (prefix.Host == "+") {
351                                 do {
352                                         current = all;
353                                         future = (current != null) ? (ArrayList) current.Clone () : new ArrayList ();
354                                         if (!RemoveSpecial (future, prefix))
355                                                 break; // Prefix not found
356                                 } while (Interlocked.CompareExchange (ref all, future, current) != current);
357                                 CheckIfRemove ();
358                                 return;
359                         }
360
361                         Hashtable prefs, p2;
362                         do {
363                                 prefs = prefixes;
364                                 if (!prefs.ContainsKey (prefix))
365                                         break;
366
367                                 p2 = (Hashtable) prefs.Clone ();
368                                 p2.Remove (prefix);
369                         } while (Interlocked.CompareExchange (ref prefixes, p2, prefs) != prefs);
370                         CheckIfRemove ();
371                 }
372         }
373 }
374 #endif
375