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