Merge pull request #2721 from ludovic-henry/fix-mono_ms_ticks
[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                         Accept (sock, 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 Accept (Socket socket, SocketAsyncEventArgs e) {
86                         e.AcceptSocket = null;
87                         var asyn = socket.AcceptAsync(e);
88                         if (!asyn) {
89                                 ProcessAccept(e);
90                         }
91                 }
92
93
94                 static void ProcessAccept (SocketAsyncEventArgs args) 
95                 {
96                         Socket accepted = null;
97                         if (args.SocketError == SocketError.Success)
98                                 accepted = args.AcceptSocket;
99
100                         EndPointListener epl = (EndPointListener) args.UserToken;
101
102
103                         Accept (epl.sock, args);
104                         if (accepted == null)
105                                 return;
106
107                         if (epl.secure && epl.cert == null) {
108                                 accepted.Close ();
109                                 return;
110                         }
111                         HttpConnection conn = new HttpConnection (accepted, epl, epl.secure, epl.cert);
112                         lock (epl.unregistered) {
113                                 epl.unregistered [conn] = conn;
114                         }
115                         conn.BeginReadRequest ();
116                 }
117
118                 static void OnAccept (object sender, SocketAsyncEventArgs e) 
119                 {
120                         ProcessAccept (e);
121                 }
122
123                 internal void RemoveConnection (HttpConnection conn) 
124                 {
125                         lock (unregistered) {
126                                 unregistered.Remove (conn);
127                         }
128                 }
129
130                 public bool BindContext (HttpListenerContext context)
131                 {
132                         HttpListenerRequest req = context.Request;
133                         ListenerPrefix prefix;
134                         HttpListener listener = SearchListener (req.Url, out prefix);
135                         if (listener == null)
136                                 return false;
137
138                         context.Listener = listener;
139                         context.Connection.Prefix = prefix;
140                         return true;
141                 }
142
143                 public void UnbindContext (HttpListenerContext context)
144                 {
145                         if (context == null || context.Request == null)
146                                 return;
147
148                         context.Listener.UnregisterContext (context);
149                 }
150
151                 HttpListener SearchListener (Uri uri, out ListenerPrefix prefix)
152                 {
153                         prefix = null;
154                         if (uri == null)
155                                 return null;
156
157                         string host = uri.Host;
158                         int port = uri.Port;
159                         string path = WebUtility.UrlDecode (uri.AbsolutePath);
160                         string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
161                         
162                         HttpListener best_match = null;
163                         int best_length = -1;
164
165                         if (host != null && host != "") {
166                                 Hashtable p_ro = prefixes;
167                                 foreach (ListenerPrefix p in p_ro.Keys) {
168                                         string ppath = p.Path;
169                                         if (ppath.Length < best_length)
170                                                 continue;
171
172                                         if (p.Host != host || p.Port != port)
173                                                 continue;
174
175                                         if (path.StartsWith (ppath) || path_slash.StartsWith (ppath)) {
176                                                 best_length = ppath.Length;
177                                                 best_match = (HttpListener) p_ro [p];
178                                                 prefix = p;
179                                         }
180                                 }
181                                 if (best_length != -1)
182                                         return best_match;
183                         }
184
185                         ArrayList list = unhandled;
186                         best_match = MatchFromList (host, path, list, out prefix);
187                         if (path != path_slash && best_match == null)
188                                 best_match = MatchFromList (host, path_slash, list, out prefix);
189                         if (best_match != null)
190                                 return best_match;
191
192                         list = all;
193                         best_match = MatchFromList (host, path, list, out prefix);
194                         if (path != path_slash && best_match == null)
195                                 best_match = MatchFromList (host, path_slash, list, out prefix);
196                         if (best_match != null)
197                                 return best_match;
198
199                         return null;
200                 }
201
202                 HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
203                 {
204                         prefix = null;
205                         if (list == null)
206                                 return null;
207
208                         HttpListener best_match = null;
209                         int best_length = -1;
210                         
211                         foreach (ListenerPrefix p in list) {
212                                 string ppath = p.Path;
213                                 if (ppath.Length < best_length)
214                                         continue;
215
216                                 if (path.StartsWith (ppath)) {
217                                         best_length = ppath.Length;
218                                         best_match = p.Listener;
219                                         prefix = p;
220                                 }
221                         }
222
223                         return best_match;
224                 }
225
226                 void AddSpecial (ArrayList coll, ListenerPrefix prefix)
227                 {
228                         if (coll == null)
229                                 return;
230
231                         foreach (ListenerPrefix p in coll) {
232                                 if (p.Path == prefix.Path) //TODO: code
233                                         throw new HttpListenerException (400, "Prefix already in use.");
234                         }
235                         coll.Add (prefix);
236                 }
237
238                 bool RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
239                 {
240                         if (coll == null)
241                                 return false;
242
243                         int c = coll.Count;
244                         for (int i = 0; i < c; i++) {
245                                 ListenerPrefix p = (ListenerPrefix) coll [i];
246                                 if (p.Path == prefix.Path) {
247                                         coll.RemoveAt (i);
248                                         return true;
249                                 }
250                         }
251                         return false;
252                 }
253
254                 void CheckIfRemove ()
255                 {
256                         if (prefixes.Count > 0)
257                                 return;
258
259                         ArrayList list = unhandled;
260                         if (list != null && list.Count > 0)
261                                 return;
262
263                         list = all;
264                         if (list != null && list.Count > 0)
265                                 return;
266
267                         EndPointManager.RemoveEndPoint (this, endpoint);
268                 }
269
270                 public void Close ()
271                 {
272                         sock.Close ();
273                         lock (unregistered) {
274                                 //
275                                 // Clone the list because RemoveConnection can be called from Close
276                                 //
277                                 var connections = new List<HttpConnection> (unregistered.Keys);
278
279                                 foreach (HttpConnection c in connections)
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