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