Fix GetConsumingEnumerable exception handling in BlockingCollection
[mono.git] / mcs / class / System / System.Net / EndPointListener.cs
index 9a6fc5d6611ab689d95e80394c9b6cf7a2e0ee15..22edac0778179d55d71a061319bcaa082f0c9b83 100644 (file)
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if NET_2_0
+
+#if NET_2_0 && SECURITY_DEP
+
 using System.IO;
 using System.Net.Sockets;
-using System.Collections.Generic;
+using System.Collections;
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using System.Threading;
+using Mono.Security.Authenticode;
+
 namespace System.Net {
        sealed class EndPointListener
        {
                IPEndPoint endpoint;
                Socket sock;
-               Dictionary<ListenerPrefix, HttpListener> prefixes;
-               List<ListenerPrefix> unhandled; // host = '*'
-               List<ListenerPrefix> all; // host = '+'
-               bool secure; // Can a port have listeners for secure and not secure at the same time? No!
+               ReaderWriterLock plock;
+               Hashtable prefixes;  // Dictionary <ListenerPrefix, HttpListener>
+               ArrayList unhandled; // List<ListenerPrefix> unhandled; host = '*'
+               ArrayList all;       // List<ListenerPrefix> all;  host = '+'
+               X509Certificate2 cert;
+               AsymmetricAlgorithm key;
+               bool secure;
 
                public EndPointListener (IPAddress addr, int port, bool secure)
                {
+                       if (secure) {
+                               this.secure = secure;
+                               LoadCertificateAndKey (addr, port);
+                       }
+
                        endpoint = new IPEndPoint (addr, port);
                        sock = new Socket (addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                        sock.Bind (endpoint);
                        sock.Listen (500);
-                       sock.BeginAccept (OnAccept, this);
-                       prefixes = new Dictionary<ListenerPrefix, HttpListener> ();
-                       this.secure = secure;
+                       SocketAsyncEventArgs args = new SocketAsyncEventArgs ();
+                       args.UserToken = this;
+                       args.Completed += OnAccept;
+                       sock.AcceptAsync (args);
+                       prefixes = new Hashtable ();
+                       plock = new ReaderWriterLock ();
                }
 
-               static void OnAccept (IAsyncResult ares)
+               void LoadCertificateAndKey (IPAddress addr, int port)
                {
-                       EndPointListener epl = (EndPointListener) ares.AsyncState;
-                       Socket accepted = null;
+                       // Actually load the certificate
                        try {
-                               accepted = epl.sock.EndAccept (ares);
+                               string dirname = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
+                               string path = Path.Combine (dirname, ".mono");
+                               path = Path.Combine (path, "httplistener");
+                               string cert_file = Path.Combine (path, String.Format ("{0}.cer", port));
+                               string pvk_file = Path.Combine (path, String.Format ("{0}.pvk", port));
+                               cert = new X509Certificate2 (cert_file);
+                               key = PrivateKey.CreateFromFile (pvk_file).RSA;
                        } catch {
-                               // Anything to do here?
-                       } finally {
-                               try {
-                                       epl.sock.BeginAccept (OnAccept, epl);
-                               } catch {
-                                       if (accepted != null) {
-                                               try {
-                                                       accepted.Close ();
-                                               } catch {}
-                                               accepted = null;
-                                       }
-                               } 
+                               // ignore errors
                        }
+               }
+
+               static void OnAccept (object sender, EventArgs e)
+               {
+                       SocketAsyncEventArgs args = (SocketAsyncEventArgs) e;
+                       EndPointListener epl = (EndPointListener) args.UserToken;
+                       Socket accepted = null;
+                       if (args.SocketError == SocketError.Success) {
+                               accepted = args.AcceptSocket;
+                               args.AcceptSocket = null;
+                       }
+
+                       try {
+                               if (epl.sock != null)
+                                       epl.sock.AcceptAsync (args);
+                       } catch {
+                               if (accepted != null) {
+                                       try {
+                                               accepted.Close ();
+                                       } catch {}
+                                       accepted = null;
+                               }
+                       } 
 
                        if (accepted == null)
                                return;
-                       HttpConnection conn = new HttpConnection (accepted, epl, epl.secure);
+
+                       if (epl.secure && (epl.cert == null || epl.key == null)) {
+                               accepted.Close ();
+                               return;
+                       }
+                       HttpConnection conn = new HttpConnection (accepted, epl, epl.secure, epl.cert, epl.key);
                        conn.BeginReadRequest ();
                }
 
@@ -81,7 +121,7 @@ namespace System.Net {
                {
                        HttpListenerRequest req = context.Request;
                        ListenerPrefix prefix;
-                       HttpListener listener = SearchListener (req.UserHostName, req.RawUrl, out prefix);
+                       HttpListener listener = SearchListener (req.UserHostName, req.Url, out prefix);
                        if (listener == null)
                                return false;
 
@@ -98,15 +138,15 @@ namespace System.Net {
 
                        HttpListenerRequest req = context.Request;
                        ListenerPrefix prefix;
-                       HttpListener listener = SearchListener (req.UserHostName, req.RawUrl, out prefix);
+                       HttpListener listener = SearchListener (req.UserHostName, req.Url, out prefix);
                        if (listener != null)
                                listener.UnregisterContext (context);
                }
 
-               HttpListener SearchListener (string host, string raw_url, out ListenerPrefix prefix)
+               HttpListener SearchListener (string host, Uri uri, out ListenerPrefix prefix)
                {
                        prefix = null;
-                       if (raw_url == null)
+                       if (uri == null)
                                return null;
 
                        //TODO: We should use a ReaderWriterLock between this and the add/remove operations.
@@ -116,20 +156,23 @@ namespace System.Net {
                                        host = host.Substring (0, colon);
                        }
 
-                       string path = HttpUtility.UrlDecode (raw_url);
+                       string path = HttpUtility.UrlDecode (uri.AbsolutePath);
+                       string path_slash = path [path.Length - 1] == '/' ? path : path + "/";
+                       
                        HttpListener best_match = null;
                        int best_length = -1;
 
-                       lock (prefixes) {
+                       try {
+                               plock.AcquireReaderLock (-1);
                                if (host != null && host != "") {
                                        foreach (ListenerPrefix p in prefixes.Keys) {
                                                string ppath = p.Path;
                                                if (ppath.Length < best_length)
                                                        continue;
 
-                                               if (p.Host == host && path.StartsWith (ppath)) {
+                                               if (p.Host == host && (path.StartsWith (ppath) || path_slash.StartsWith (ppath))) {
                                                        best_length = ppath.Length;
-                                                       best_match = prefixes [p];
+                                                       best_match = (HttpListener) prefixes [p];
                                                        prefix = p;
                                                }
                                        }
@@ -144,11 +187,15 @@ namespace System.Net {
                                best_match = MatchFromList (host, path, all, out prefix);
                                if (best_match != null)
                                        return best_match;
+                       } finally {
+                               try {
+                                       plock.ReleaseReaderLock ();
+                               } catch {}
                        }
                        return null;
                }
 
-               HttpListener MatchFromList (string host, string path, List<ListenerPrefix> list, out ListenerPrefix prefix)
+               HttpListener MatchFromList (string host, string path, ArrayList list, out ListenerPrefix prefix)
                {
                        prefix = null;
                        if (list == null)
@@ -172,35 +219,51 @@ namespace System.Net {
                        return best_match;
                }
 
-               void AddSpecial (List<ListenerPrefix> coll, ListenerPrefix prefix)
+               void AddSpecial (ArrayList coll, ListenerPrefix prefix)
                {
                        if (coll == null)
                                return;
 
-                       foreach (ListenerPrefix p in coll) {
-                               if (p.Path == prefix.Path) //TODO: code
-                                       throw new HttpListenerException (400, "Prefix already in use.");
+                       try {
+                               plock.AcquireReaderLock (-1);
+                               foreach (ListenerPrefix p in coll) {
+                                       if (p.Path == prefix.Path) //TODO: code
+                                               throw new HttpListenerException (400, "Prefix already in use.");
+                               }
+                               plock.UpgradeToWriterLock (-1);
+                               coll.Add (prefix);
+                       } finally {
+                               try {
+                                       plock.ReleaseReaderLock (); // This releases the writer lock if held.
+                               } catch { }
                        }
-
-                       coll.Add (prefix);
                }
 
-               void RemoveSpecial (List<ListenerPrefix> coll, ListenerPrefix prefix)
+               void RemoveSpecial (ArrayList coll, ListenerPrefix prefix)
                {
                        if (coll == null)
                                return;
 
-                       int c = coll.Count;
-                       for (int i = 0; i < c; i++) {
-                               ListenerPrefix p = coll [i];
-                               if (p.Path == prefix.Path) {
-                                       coll.RemoveAt (i);
-                                       CheckIfRemove ();
-                                       return;
+                       try {
+                               plock.AcquireReaderLock (-1);
+                               int c = coll.Count;
+                               for (int i = 0; i < c; i++) {
+                                       ListenerPrefix p = (ListenerPrefix) coll [i];
+                                       if (p.Path == prefix.Path) {
+                                               plock.UpgradeToWriterLock (-1);
+                                               coll.RemoveAt (i);
+                                               CheckIfRemove ();
+                                               return;
+                                       }
                                }
+                       } finally {
+                               try {
+                                       plock.ReleaseReaderLock (); // Releases the writer lock if held
+                               } catch {}
                        }
                }
 
+               // Writer lock held when calling (could use just reader)
                void CheckIfRemove ()
                {
                        if (prefixes.Count > 0)
@@ -222,51 +285,63 @@ namespace System.Net {
 
                public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
                {
-                       lock (prefixes) {
-                               if (prefix.Host == "*") {
-                                       if (unhandled == null)
-                                               unhandled = new List<ListenerPrefix> ();
+                       if (prefix.Host == "*") {
+                               if (unhandled == null)
+                                       unhandled = new ArrayList ();
 
-                                       prefix.Listener = listener;
-                                       AddSpecial (unhandled, prefix);
-                                       return;
-                               }
+                               prefix.Listener = listener;
+                               AddSpecial (unhandled, prefix);
+                               return;
+                       }
 
-                               if (prefix.Host == "+") {
-                                       if (all == null)
-                                               all = new List<ListenerPrefix> ();
-                                       prefix.Listener = listener;
-                                       AddSpecial (all, prefix);
-                                       return;
-                               }
+                       if (prefix.Host == "+") {
+                               if (all == null)
+                                       all = new ArrayList ();
+                               prefix.Listener = listener;
+                               AddSpecial (all, prefix);
+                               return;
+                       }
 
+                       try { 
+                               plock.AcquireReaderLock (-1);
                                if (prefixes.ContainsKey (prefix)) {
-                                       HttpListener other = prefixes [prefix];
+                                       HttpListener other = (HttpListener) prefixes [prefix];
                                        if (other != listener) // TODO: code.
                                                throw new HttpListenerException (400, "There's another listener for " + prefix);
                                        return;
                                }
-
+                               plock.UpgradeToWriterLock (-1);
                                prefixes [prefix] = listener;
+                       } finally {
+                               try {
+                                       plock.ReleaseReaderLock ();
+                               } catch {}
                        }
                }
 
                public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
                {
-                       lock (prefixes) {
-                               if (prefix.Host == "*") {
-                                       RemoveSpecial (unhandled, prefix);
-                                       return;
-                               }
+                       if (prefix.Host == "*") {
+                               RemoveSpecial (unhandled, prefix);
+                               return;
+                       }
 
-                               if (prefix.Host == "+") {
-                                       RemoveSpecial (all, prefix);
-                                       return;
-                               }
+                       if (prefix.Host == "+") {
+                               RemoveSpecial (all, prefix);
+                               return;
+                       }
 
+                       try {
+                               plock.AcquireReaderLock (-1);
                                if (prefixes.ContainsKey (prefix)) {
+                                       plock.UpgradeToWriterLock (-1);
                                        prefixes.Remove (prefix);
+                                       CheckIfRemove ();
                                }
+                       } finally {
+                               try {
+                                       plock.ReleaseReaderLock ();
+                               } catch {}
                        }
                }
        }