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