Author: alanmc
Date: 2007-05-30 13:00:27 -0400 (Wed, 30 May 2007)
New Revision: 78235

Modified:
   trunk/bitsharp/src/MonoTorrent/Client/ClientEngine.cs
   trunk/bitsharp/src/MonoTorrent/Client/ConnectionListener.cs
   trunk/bitsharp/src/MonoTorrent/Client/Managers/TrackerManager.cs
   trunk/bitsharp/src/MonoTorrent/Client/Tracker.cs
Log:
Refactor - Moved code into ConnectionListener, where it should've been.

Modified: trunk/bitsharp/src/MonoTorrent/Client/ClientEngine.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/Client/ClientEngine.cs       2007-05-30 
16:30:20 UTC (rev 78234)
+++ trunk/bitsharp/src/MonoTorrent/Client/ClientEngine.cs       2007-05-30 
17:00:27 UTC (rev 78235)
@@ -95,15 +95,6 @@
 
 
         /// <summary>
-        /// The callback to invoke when we receive a peer handshake.
-        /// </summary>
-        private AsyncCallback peerHandshakeReceived;
-
-        private EncryptorReadyHandler onEncryptorReadyHandler;
-        private EncryptorIOErrorHandler onEncryptorIOErrorHandler;
-        private EncryptorEncryptionErrorHandler 
onEncryptorEncryptionErrorHandler;
-
-        /// <summary>
         /// Returns the engines PeerID
         /// </summary>
         public string PeerId
@@ -145,7 +136,8 @@
             set { this.torrents = value; }
         }
         private TorrentManagerCollection torrents;
-        private ReaderWriterLock torrentsLock = new ReaderWriterLock();
+       
+        internal ReaderWriterLock torrentsLock = new ReaderWriterLock();
 
         #endregion
 
@@ -162,17 +154,13 @@
             if (engineSettings == null)
                 throw new ArgumentNullException("engineSettings");
 
-            this.connectionManager = new ConnectionManager(this);
             this.settings = engineSettings;
-            this.listener = new ConnectionListener(engineSettings.ListenPort, 
new AsyncCallback(this.IncomingConnectionReceived));
+
+            this.connectionManager = new ConnectionManager(this);
+            this.listener = new ConnectionListener(this);
             this.timer = new System.Timers.Timer(TickLength);
             this.timer.Elapsed += new ElapsedEventHandler(LogicTick);
             this.torrents = new TorrentManagerCollection();
-            this.peerHandshakeReceived = new 
AsyncCallback(this.onPeerHandshakeReceived);
-
-            this.onEncryptorReadyHandler = new 
EncryptorReadyHandler(onEncryptorReady);
-            this.onEncryptorIOErrorHandler = new 
EncryptorIOErrorHandler(onEncryptorError);
-            this.onEncryptorEncryptionErrorHandler = new 
EncryptorEncryptionErrorHandler(onEncryptorError);
         }
 
         #endregion
@@ -439,241 +427,6 @@
 
 
 
-        #region Move to connection listener
 
-        /// <summary>
-        /// 
-        /// </summary>
-        /// <param name="result"></param>
-        private void IncomingConnectionReceived(IAsyncResult result)
-        {
-            PeerId id = null;
-            try
-            {
-                Socket peerSocket = 
((Socket)result.AsyncState).EndAccept(result);
-                if (!peerSocket.Connected)
-                    return;
-
-                Peer peer = new Peer(string.Empty, 
peerSocket.RemoteEndPoint.ToString());
-                peer.Connection = new TCPConnection(peerSocket, 0, new 
NoEncryption());
-                id = new PeerId(peer);
-                id.Peer.Connection.ProcessingQueue = true;
-                id.Peer.Connection.LastMessageSent = DateTime.Now;
-                id.Peer.Connection.LastMessageReceived = DateTime.Now;
-
-                ClientEngine.BufferManager.GetBuffer(ref 
id.Peer.Connection.recieveBuffer, BufferType.SmallMessageBuffer);
-                id.Peer.Connection.BytesReceived = 0;
-                id.Peer.Connection.BytesToRecieve = 68;
-                Logger.Log(id, "CE Peer incoming connection accepted");
-                
id.Peer.Connection.BeginReceive(id.Peer.Connection.recieveBuffer, 0, 
id.Peer.Connection.BytesToRecieve, SocketFlags.None, peerHandshakeReceived, id, 
out id.ErrorCode);
-            }
-            catch (SocketException)
-            {
-                if (id != null)
-                    this.CleanupSocket(id);
-            }
-            catch (ObjectDisposedException)
-            {
-            }
-            finally
-            {
-                if (!this.listener.Disposed)
-                    this.listener.BeginAccept();
-            }
-        }
-
-        /// <summary>
-        /// 
-        /// </summary>
-        /// <param name="result"></param>
-        private void onPeerHandshakeReceived(IAsyncResult result)
-        {
-            PeerId id = (PeerId)result.AsyncState;
-
-            try
-            {
-                lock (id)
-                {
-                    int bytesReceived = id.Peer.Connection.EndReceive(result, 
out id.ErrorCode);
-                    if (bytesReceived == 0)
-                    {
-                        Logger.Log(id, "CE Recieved 0 for handshake");
-                        CleanupSocket(id);
-                        return;
-                    }
-
-                    id.Peer.Connection.BytesReceived += bytesReceived;
-                    if (id.Peer.Connection.BytesReceived != 
id.Peer.Connection.BytesToRecieve)
-                    {
-                        
id.Peer.Connection.BeginReceive(id.Peer.Connection.recieveBuffer, 
id.Peer.Connection.BytesReceived, id.Peer.Connection.BytesToRecieve - 
id.Peer.Connection.BytesReceived, SocketFlags.None, peerHandshakeReceived, id, 
out id.ErrorCode);
-                        return;
-                    }
-                    Logger.Log(id, "CE Recieved handshake");
-
-                    handleHandshake(id);
-                }
-            }
-
-            catch (SocketException)
-            {
-                Logger.Log(id, "CE Exception with handshake");
-                CleanupSocket(id);
-            }
-            catch (NullReferenceException)
-            {
-                CleanupSocket(id);
-            }
-        }
-
-        private void handleHandshake(PeerId id)
-        {
-            TorrentManager man = null;
-            bool handshakeFailed = false;
-
-            HandshakeMessage handshake = new HandshakeMessage();
-            try
-            {
-                handshake.Decode(id.Peer.Connection.recieveBuffer, 0, 
id.Peer.Connection.BytesToRecieve);
-#warning call handshake.Handle to do this properly
-                if (handshake.ProtocolString != VersionInfo.ProtocolStringV100)
-                    handshakeFailed = true;
-            }
-            catch
-            {
-                handshakeFailed = true;
-            }
-
-            if (handshakeFailed)
-            {
-                if (id.Peer.Connection.Encryptor is NoEncryption && 
SupportsEncryption)
-                {
-                    // Maybe this was a Message Stream Encryption handshake. 
Parse it as such.
-                    id.Peer.Connection.Encryptor = new 
PeerBEncryption(Torrents, this.settings.MinEncryptionLevel);
-                    id.Peer.Connection.Encryptor.SetPeerConnectionID(id);
-                    id.Peer.Connection.Encryptor.onEncryptorReady += 
onEncryptorReadyHandler;
-                    id.Peer.Connection.Encryptor.onEncryptorIOError += 
onEncryptorIOErrorHandler;
-                    id.Peer.Connection.Encryptor.onEncryptorEncryptionError += 
onEncryptorEncryptionErrorHandler;
-                    
id.Peer.Connection.StartEncryption(id.Peer.Connection.recieveBuffer, 0, 
id.Peer.Connection.BytesToRecieve);
-                    return;
-                }
-                else
-                {
-                    Logger.Log(id, "CE Invalid handshake");
-                    CleanupSocket(id);
-                }
-                return;
-            }
-
-            for (int i = 0; i < this.torrents.Count; i++)
-                if (Toolbox.ByteMatch(handshake.infoHash, 
this.torrents[i].Torrent.InfoHash))
-                    man = this.torrents[i];
-
-            if (man == null)        // We're not hosting that torrent
-            {
-                Logger.Log(id, "CE Not tracking torrent");
-                CleanupSocket(id);
-                return;
-            }
-
-            id.Peer.PeerId = handshake.PeerId;
-            id.TorrentManager = man;
-
-            // If the handshake was parsed properly without encryption, then 
it definitely was not encrypted. If this is not allowed, abort
-            if ((id.Peer.Connection.Encryptor is NoEncryption && 
this.settings.MinEncryptionLevel != EncryptionType.None) && 
ClientEngine.SupportsEncryption)
-            {
-                Logger.Log(id, "CE Require crypto");
-                CleanupSocket(id);
-                return;
-            }
-
-            handshake.Handle(id);
-            Logger.Log(id, "CE Handshake successful");
-
-            ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.recieveBuffer);
-            id.Peer.Connection.ClientApp = new Software(handshake.PeerId);
-
-            handshake = new 
HandshakeMessage(id.TorrentManager.Torrent.InfoHash, this.peerId, 
VersionInfo.ProtocolStringV100);
-            BitfieldMessage bf = new 
BitfieldMessage(id.TorrentManager.Bitfield);
-
-            ClientEngine.BufferManager.GetBuffer(ref 
id.Peer.Connection.sendBuffer, BufferType.LargeMessageBuffer);
-            id.Peer.Connection.BytesSent = 0;
-            id.Peer.Connection.BytesToSend = 
handshake.Encode(id.Peer.Connection.sendBuffer, 0);
-            id.Peer.Connection.BytesToSend += 
bf.Encode(id.Peer.Connection.sendBuffer, id.Peer.Connection.BytesToSend);
-
-            Logger.Log(id, "CE Sending to torrent manager");
-            id.Peer.Connection.BeginSend(id.Peer.Connection.sendBuffer, 0, 
id.Peer.Connection.BytesToSend,
-                                         SocketFlags.None, new 
AsyncCallback(connectionManager.IncomingConnectionAccepted),
-                                         id, out id.ErrorCode);
-            id.Peer.Connection.ProcessingQueue = false;
-        }
-
-        private void onEncryptorReady(PeerId id)
-        {
-            try
-            {
-                id.Peer.Connection.BytesReceived = 0;
-                id.Peer.Connection.BytesToRecieve = 68;
-                Logger.Log(id, "CE Peer encryption handshake complete");
-                int bytesReceived = 0;
-
-                // Handshake was probably delivered as initial payload. 
Retrieve it if its' vailable
-                if (id.Peer.Connection.Encryptor.IsInitialDataAvailable())
-                    bytesReceived = 
id.Peer.Connection.Encryptor.GetInitialData(id.Peer.Connection.recieveBuffer, 
0, id.Peer.Connection.BytesToRecieve);
-
-                id.Peer.Connection.BytesReceived += bytesReceived;
-                if (id.Peer.Connection.BytesReceived != 
id.Peer.Connection.BytesToRecieve)
-                {
-                    
id.Peer.Connection.BeginReceive(id.Peer.Connection.recieveBuffer, 
id.Peer.Connection.BytesReceived, id.Peer.Connection.BytesToRecieve - 
id.Peer.Connection.BytesReceived, SocketFlags.None, peerHandshakeReceived, id, 
out id.ErrorCode);
-                    return;
-                }
-
-                // The complete handshake was in the initial payload
-                Logger.Log(id, "CE Recieved Encrypted handshake");
-
-                handleHandshake(id);
-            }
-
-            catch (SocketException)
-            {
-                Logger.Log(id, "CE Exception with handshake");
-                CleanupSocket(id);
-            }
-            catch (NullReferenceException)
-            {
-                CleanupSocket(id);
-            }
-        }
-
-        private void onEncryptorError(PeerId id)
-        {
-            CleanupSocket(id);
-        }
-
-        /// <summary>
-        /// 
-        /// </summary>
-        /// <param name="id"></param>
-        private void CleanupSocket(PeerId id)
-        {
-            if (id == null) // Sometimes onEncryptionError fires with a null id
-                return;
-
-            lock (id)
-            {
-                Logger.Log(id, "***********CE Cleaning up*************");
-                if (id.Peer.Connection != null)
-                {
-                    BufferManager.FreeBuffer(ref 
id.Peer.Connection.recieveBuffer);
-                    BufferManager.FreeBuffer(ref 
id.Peer.Connection.sendBuffer);
-                    id.Peer.Connection.Dispose();
-                }
-                else
-                {
-                    Logger.Log(id, "!!!!!!!!!!CE Already null!!!!!!!!");
-                }
-            }
-        }
-
-        #endregion
     }
 }
\ No newline at end of file

Modified: trunk/bitsharp/src/MonoTorrent/Client/ConnectionListener.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/Client/ConnectionListener.cs 2007-05-30 
16:30:20 UTC (rev 78234)
+++ trunk/bitsharp/src/MonoTorrent/Client/ConnectionListener.cs 2007-05-30 
17:00:27 UTC (rev 78235)
@@ -31,6 +31,9 @@
 using System;
 using System.Net;
 using System.Net.Sockets;
+using MonoTorrent.Client.Encryption;
+using MonoTorrent.Client.PeerMessages;
+using MonoTorrent.Common;
 
 namespace MonoTorrent.Client
 {
@@ -40,17 +43,29 @@
     internal class ConnectionListener : IDisposable
     {
         #region Member Variables
+
+        private ClientEngine engine;
+        private bool disposed;
+        private bool isListening;
+        private IPEndPoint listenEndPoint;
+        private AsyncCallback newConnectionCallback;
+        private EncryptorReadyHandler onEncryptorReadyHandler;
+        private EncryptorIOErrorHandler onEncryptorIOErrorHandler;
+        private EncryptorEncryptionErrorHandler 
onEncryptorEncryptionErrorHandler;
+        private AsyncCallback peerHandshakeReceived; // The callback to invoke 
when we receive a peer handshake.
         private Socket socket;
 
-        /// <summary>
-        /// The Endpoint the listener should listen for connections on
-        /// </summary>
-        public static IPEndPoint ListenEndPoint
+        #endregion
+
+
+        #region Properties
+
+        internal bool Disposed
         {
-            get { return listenEndPoint; }
+            get { return this.disposed; }
         }
-        private static IPEndPoint listenEndPoint;
 
+        
         /// <summary>
         /// Returns True if the listener is listening for incoming connections.
         /// </summary>
@@ -58,123 +73,332 @@
         {
             get { return this.isListening; }
         }
-        private bool isListening;
 
+
         /// <summary>
+        /// The Endpoint the listener should listen for connections on
+        /// </summary>
+        public IPEndPoint ListenEndPoint
+        {
+            get { return listenEndPoint; }
+        }
+
+
+        /// <summary>
         /// The AsyncCallback to invoke when a new connection is Received
         /// </summary>
         public AsyncCallback NewConnectionCallback
         {
             get { return this.newConnectionCallback; }
         }
-        private AsyncCallback newConnectionCallback;
+
         #endregion
 
 
         #region Constructors
-        /// <summary>
-        /// Creates a new connection listener listening at the specified port 
on any IP address
-        /// </summary>
-        /// <param name="listenPort">The port to listen on</param>
-        /// <param name="newConnectionCallback">The callback to invoke when a 
connection is Received</param>
-        public ConnectionListener(int listenPort, AsyncCallback 
newConnectionCallback)
-            : this(listenPort, newConnectionCallback, IPAddress.Any)
+
+        public ConnectionListener(ClientEngine engine)
         {
+            this.engine = engine;
+            this.onEncryptorReadyHandler = new 
EncryptorReadyHandler(onEncryptorReady);
+            this.onEncryptorIOErrorHandler = new 
EncryptorIOErrorHandler(onEncryptorError);
+            this.onEncryptorEncryptionErrorHandler = new 
EncryptorEncryptionErrorHandler(onEncryptorError);
+            this.peerHandshakeReceived = new 
AsyncCallback(this.onPeerHandshakeReceived);
+            this.socket = new Socket(AddressFamily.InterNetwork, 
SocketType.Stream, ProtocolType.Tcp);
         }
 
+        #endregion
 
-        /// <summary>
-        /// Creates a new connection listener listening at the specified port 
and IPAddress
-        /// </summary>
-        /// <param name="listenPort">The port to listen on</param>
-        /// <param name="newConnectionCallback">The callback to invoke when a 
connection is Received</param>
-        /// <param name="listenAddress">The address to listen on</param>
-        public ConnectionListener(int listenPort, AsyncCallback 
newConnectionCallback, IPAddress listenAddress)
-            : this(new IPEndPoint(listenAddress, listenPort), 
newConnectionCallback)
+
+        #region Methods
+
+        private void BeginAccept()
         {
+            this.socket.BeginAccept(this.newConnectionCallback, this.socket);
         }
 
 
         /// <summary>
-        /// Creates a new connection listener listening at the specified 
IPEndpoint
+        /// 
         /// </summary>
-        /// <param name="endPoint">The IPEndpoint to listen at</param>
-        /// <param name="newConnectionCallback">The callback to invoke when a 
new connection is Received</param>
-        public ConnectionListener(IPEndPoint endPoint, AsyncCallback 
newConnectionCallback)
+        /// <param name="id"></param>
+        private void CleanupSocket(PeerId id)
         {
-            listenEndPoint = endPoint;
-            this.newConnectionCallback = newConnectionCallback;
-            this.isListening = false;
-            this.socket = new Socket(AddressFamily.InterNetwork, 
SocketType.Stream, ProtocolType.Tcp);
+            if (id == null) // Sometimes onEncryptionError fires with a null id
+                return;
+
+            lock (id)
+            {
+                Logger.Log(id, "***********CE Cleaning up*************");
+                if (id.Peer.Connection != null)
+                {
+                    ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.recieveBuffer);
+                    ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.sendBuffer);
+                    id.Peer.Connection.Dispose();
+                }
+                else
+                {
+                    Logger.Log(id, "!!!!!!!!!!CE Already null!!!!!!!!");
+                }
+            }
         }
-        #endregion
 
 
-        #region Methods
         /// <summary>
-        /// Begin listening for incoming connections
+        /// 
         /// </summary>
-        public void Start()
+        public void Dispose()
         {
-            if (this.isListening)
-                throw new ListenerException("The Listener is already 
listening");
+            if (disposed)
+                throw new ObjectDisposedException(this.ToString());
 
-            if (this.newConnectionCallback == null)
-                throw new ArgumentNullException("newConnectionCallback");
+            this.socket.Close();
+            this.disposed = true;
+        }
 
-            this.isListening = true;
-            this.socket = new Socket(AddressFamily.InterNetwork, 
SocketType.Stream, ProtocolType.Tcp);
-            this.socket.Bind(listenEndPoint);
-            this.socket.Listen(10);             // FIXME: Will this break on 
windows XP systems?
-            this.socket.BeginAccept(newConnectionCallback, this.socket);
+
+        private void handleHandshake(PeerId id)
+        {
+            TorrentManager man = null;
+            bool handshakeFailed = false;
+
+            HandshakeMessage handshake = new HandshakeMessage();
+            try
+            {
+                handshake.Decode(id.Peer.Connection.recieveBuffer, 0, 
id.Peer.Connection.BytesToRecieve);
+#warning call handshake.Handle to do this properly
+                if (handshake.ProtocolString != VersionInfo.ProtocolStringV100)
+                    handshakeFailed = true;
+            }
+            catch
+            {
+                handshakeFailed = true;
+            }
+
+            if (handshakeFailed)
+            {
+                if (id.Peer.Connection.Encryptor is NoEncryption && 
ClientEngine.SupportsEncryption)
+                {
+                    // Maybe this was a Message Stream Encryption handshake. 
Parse it as such.
+                    id.Peer.Connection.Encryptor = new 
PeerBEncryption(engine.Torrents, engine.Settings.MinEncryptionLevel);
+                    id.Peer.Connection.Encryptor.SetPeerConnectionID(id);
+                    id.Peer.Connection.Encryptor.onEncryptorReady += 
onEncryptorReadyHandler;
+                    id.Peer.Connection.Encryptor.onEncryptorIOError += 
onEncryptorIOErrorHandler;
+                    id.Peer.Connection.Encryptor.onEncryptorEncryptionError += 
onEncryptorEncryptionErrorHandler;
+                    
id.Peer.Connection.StartEncryption(id.Peer.Connection.recieveBuffer, 0, 
id.Peer.Connection.BytesToRecieve);
+                    return;
+                }
+                else
+                {
+                    Logger.Log(id, "CE Invalid handshake");
+                    CleanupSocket(id);
+                }
+                return;
+            }
+
+            using (new ReaderLock(engine.torrentsLock))
+                for (int i = 0; i < engine.Torrents.Count; i++)
+                    if (Toolbox.ByteMatch(handshake.infoHash, 
engine.Torrents[i].Torrent.InfoHash))
+                        man = engine.Torrents[i];
+
+            if (man == null)        // We're not hosting that torrent
+            {
+                Logger.Log(id, "CE Not tracking torrent");
+                CleanupSocket(id);
+                return;
+            }
+
+            id.Peer.PeerId = handshake.PeerId;
+            id.TorrentManager = man;
+
+            // If the handshake was parsed properly without encryption, then 
it definitely was not encrypted. If this is not allowed, abort
+            if ((id.Peer.Connection.Encryptor is NoEncryption && 
engine.Settings.MinEncryptionLevel != EncryptionType.None) && 
ClientEngine.SupportsEncryption)
+            {
+                Logger.Log(id, "CE Require crypto");
+                CleanupSocket(id);
+                return;
+            }
+
+            handshake.Handle(id);
+            Logger.Log(id, "CE Handshake successful");
+
+            ClientEngine.BufferManager.FreeBuffer(ref 
id.Peer.Connection.recieveBuffer);
+            id.Peer.Connection.ClientApp = new Software(handshake.PeerId);
+
+            handshake = new 
HandshakeMessage(id.TorrentManager.Torrent.InfoHash, engine.PeerId, 
VersionInfo.ProtocolStringV100);
+            BitfieldMessage bf = new 
BitfieldMessage(id.TorrentManager.Bitfield);
+
+            ClientEngine.BufferManager.GetBuffer(ref 
id.Peer.Connection.sendBuffer, BufferType.LargeMessageBuffer);
+            id.Peer.Connection.BytesSent = 0;
+            id.Peer.Connection.BytesToSend = 
handshake.Encode(id.Peer.Connection.sendBuffer, 0);
+            id.Peer.Connection.BytesToSend += 
bf.Encode(id.Peer.Connection.sendBuffer, id.Peer.Connection.BytesToSend);
+
+            Logger.Log(id, "CE Sending to torrent manager");
+            id.Peer.Connection.BeginSend(id.Peer.Connection.sendBuffer, 0, 
id.Peer.Connection.BytesToSend,
+                                         SocketFlags.None, new 
AsyncCallback(engine.ConnectionManager.IncomingConnectionAccepted),
+                                         id, out id.ErrorCode);
+            id.Peer.Connection.ProcessingQueue = false;
         }
 
 
         /// <summary>
-        /// Stop listening for incoming connections
+        /// 
         /// </summary>
-        public void Stop()
+        /// <param name="result"></param>
+        private void IncomingConnectionReceived(IAsyncResult result)
         {
-            this.disposed = true;
-            this.isListening = false;
-            this.socket.Close();
+            PeerId id = null;
+            try
+            {
+                Socket peerSocket = 
((Socket)result.AsyncState).EndAccept(result);
+                if (!peerSocket.Connected)
+                    return;
+
+                Peer peer = new Peer(string.Empty, 
peerSocket.RemoteEndPoint.ToString());
+                peer.Connection = new TCPConnection(peerSocket, 0, new 
NoEncryption());
+                id = new PeerId(peer);
+                id.Peer.Connection.ProcessingQueue = true;
+                id.Peer.Connection.LastMessageSent = DateTime.Now;
+                id.Peer.Connection.LastMessageReceived = DateTime.Now;
+
+                ClientEngine.BufferManager.GetBuffer(ref 
id.Peer.Connection.recieveBuffer, BufferType.SmallMessageBuffer);
+                id.Peer.Connection.BytesReceived = 0;
+                id.Peer.Connection.BytesToRecieve = 68;
+                Logger.Log(id, "CE Peer incoming connection accepted");
+                
id.Peer.Connection.BeginReceive(id.Peer.Connection.recieveBuffer, 0, 
id.Peer.Connection.BytesToRecieve, SocketFlags.None, peerHandshakeReceived, id, 
out id.ErrorCode);
+            }
+            catch (SocketException)
+            {
+                if (id != null)
+                    this.CleanupSocket(id);
+            }
+            catch (ObjectDisposedException)
+            {
+            }
+            finally
+            {
+                if (!Disposed)
+                    BeginAccept();
+            }
         }
 
 
-        public void BeginAccept()
+        private void onEncryptorReady(PeerId id)
         {
-            this.socket.BeginAccept(this.newConnectionCallback, this.socket);
+            try
+            {
+                id.Peer.Connection.BytesReceived = 0;
+                id.Peer.Connection.BytesToRecieve = 68;
+                Logger.Log(id, "CE Peer encryption handshake complete");
+                int bytesReceived = 0;
+
+                // Handshake was probably delivered as initial payload. 
Retrieve it if its' vailable
+                if (id.Peer.Connection.Encryptor.IsInitialDataAvailable())
+                    bytesReceived = 
id.Peer.Connection.Encryptor.GetInitialData(id.Peer.Connection.recieveBuffer, 
0, id.Peer.Connection.BytesToRecieve);
+
+                id.Peer.Connection.BytesReceived += bytesReceived;
+                if (id.Peer.Connection.BytesReceived != 
id.Peer.Connection.BytesToRecieve)
+                {
+                    
id.Peer.Connection.BeginReceive(id.Peer.Connection.recieveBuffer, 
id.Peer.Connection.BytesReceived, id.Peer.Connection.BytesToRecieve - 
id.Peer.Connection.BytesReceived, SocketFlags.None, peerHandshakeReceived, id, 
out id.ErrorCode);
+                    return;
+                }
+
+                // The complete handshake was in the initial payload
+                Logger.Log(id, "CE Recieved Encrypted handshake");
+
+                handleHandshake(id);
+            }
+
+            catch (SocketException)
+            {
+                Logger.Log(id, "CE Exception with handshake");
+                CleanupSocket(id);
+            }
+            catch (NullReferenceException)
+            {
+                CleanupSocket(id);
+            }
         }
 
 
+        private void onEncryptorError(PeerId id)
+        {
+            CleanupSocket(id);
+        }
+
+
         /// <summary>
         /// 
         /// </summary>
-        public void Dispose()
+        /// <param name="result"></param>
+        private void onPeerHandshakeReceived(IAsyncResult result)
         {
-            this.Dispose(true);
+            PeerId id = (PeerId)result.AsyncState;
+
+            try
+            {
+                lock (id)
+                {
+                    int bytesReceived = id.Peer.Connection.EndReceive(result, 
out id.ErrorCode);
+                    if (bytesReceived == 0)
+                    {
+                        Logger.Log(id, "CE Recieved 0 for handshake");
+                        CleanupSocket(id);
+                        return;
+                    }
+
+                    id.Peer.Connection.BytesReceived += bytesReceived;
+                    if (id.Peer.Connection.BytesReceived != 
id.Peer.Connection.BytesToRecieve)
+                    {
+                        
id.Peer.Connection.BeginReceive(id.Peer.Connection.recieveBuffer, 
id.Peer.Connection.BytesReceived, id.Peer.Connection.BytesToRecieve - 
id.Peer.Connection.BytesReceived, SocketFlags.None, peerHandshakeReceived, id, 
out id.ErrorCode);
+                        return;
+                    }
+                    Logger.Log(id, "CE Recieved handshake");
+
+                    handleHandshake(id);
+                }
+            }
+
+            catch (SocketException)
+            {
+                Logger.Log(id, "CE Exception with handshake");
+                CleanupSocket(id);
+            }
+            catch (NullReferenceException)
+            {
+                CleanupSocket(id);
+            }
         }
 
 
         /// <summary>
-        /// 
+        /// Begin listening for incoming connections
         /// </summary>
-        /// <param name="disposing"></param>
-        public void Dispose(bool disposing)
+        internal void Start()
         {
-            if (disposed)
-                throw new ObjectDisposedException(this.ToString());
+            if (this.isListening)
+                throw new ListenerException("The Listener is already 
listening");
 
-            this.socket.Close();
-            this.disposed = true;
+            this.newConnectionCallback = new 
AsyncCallback(IncomingConnectionReceived);
+            this.listenEndPoint = new IPEndPoint(IPAddress.Any, 
engine.Settings.ListenPort);
+            this.isListening = true;
+            this.socket = new Socket(AddressFamily.InterNetwork, 
SocketType.Stream, ProtocolType.Tcp);
+            this.socket.Bind(listenEndPoint);
+            this.socket.Listen(10);             // FIXME: Will this break on 
windows XP systems?
+            this.socket.BeginAccept(newConnectionCallback, this.socket);
         }
 
 
-        internal bool Disposed
+        /// <summary>
+        /// Stop listening for incoming connections
+        /// </summary>
+        internal void Stop()
         {
-            get { return this.disposed; }
+            this.disposed = true;
+            this.isListening = false;
+            this.socket.Close();
         }
-        private bool disposed;
+
         #endregion
     }
 }
\ No newline at end of file

Modified: trunk/bitsharp/src/MonoTorrent/Client/Managers/TrackerManager.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/Client/Managers/TrackerManager.cs    
2007-05-30 16:30:20 UTC (rev 78234)
+++ trunk/bitsharp/src/MonoTorrent/Client/Managers/TrackerManager.cs    
2007-05-30 17:00:27 UTC (rev 78235)
@@ -156,10 +156,13 @@
             this.lastUpdated = DateTime.Now;
             UpdateState(tracker, TrackerState.Announcing);
             bool supportsEncryption = ClientEngine.SupportsEncryption && 
manager.Engine.Settings.MinEncryptionLevel != EncryptionType.None;
+
+#warning Fix this. It's nasty looking.
             WaitHandle handle = 
tracker.Announce(this.manager.Monitor.DataBytesDownloaded,
                                                 
this.manager.Monitor.DataBytesUploaded,
                                                 (long)((1 - 
this.manager.Bitfield.PercentComplete / 100.0) * this.manager.Torrent.Size),
-                                                clientEvent, this.infoHash, 
id, supportsEncryption, manager.Engine.PeerId);
+                                                clientEvent, this.infoHash, 
id, supportsEncryption, manager.Engine.PeerId,
+                                                null, 
manager.Engine.Settings.ListenPort);
             return handle;
         }
 

Modified: trunk/bitsharp/src/MonoTorrent/Client/Tracker.cs
===================================================================
--- trunk/bitsharp/src/MonoTorrent/Client/Tracker.cs    2007-05-30 16:30:20 UTC 
(rev 78234)
+++ trunk/bitsharp/src/MonoTorrent/Client/Tracker.cs    2007-05-30 17:00:27 UTC 
(rev 78235)
@@ -244,19 +244,14 @@
 
         internal WaitHandle Announce(long bytesDownloaded, long bytesUploaded, 
long bytesLeft,
                                     TorrentEvent clientEvent, string infohash, 
TrackerConnectionID id,
-                                    bool requireEncryption, string peerId)
+                                    bool requireEncryption, string peerId, 
string ipaddress, int port)
         {
-            IPAddress ipAddress;
             HttpWebRequest request;
             StringBuilder sb = new StringBuilder(256);
 
             this.updateSucceeded = true;        // If the update ends up 
failing, reset this to false.
             this.lastUpdated = DateTime.Now;
 
-            ipAddress = ConnectionListener.ListenEndPoint.Address;
-            if (ipAddress != null && (ipAddress == IPAddress.Any || ipAddress 
== IPAddress.Loopback))
-                ipAddress = null;
-
             sb.Append(this.announceUrl);
             sb.Append((this.announceUrl.IndexOf('?') == -1) ? '?' : '&');
             sb.Append("info_hash=");
@@ -264,7 +259,7 @@
             sb.Append("&peer_id=");
             sb.Append(peerId);
             sb.Append("&port=");
-            sb.Append(ConnectionListener.ListenEndPoint.Port);
+            sb.Append(port);
             sb.Append("&supportcrypto=");
             sb.Append(ClientEngine.SupportsEncryption ? 1 : 0);
             sb.Append("&requirecrypto=");
@@ -278,10 +273,10 @@
             sb.Append("&compact=1");    // Always use compact response
             sb.Append("&numwant=");
             sb.Append(100);
-            if (ipAddress != null)
+            if (ipaddress != null)
             {
                 sb.Append("&ip=");
-                sb.Append(ipAddress.ToString());
+                sb.Append(ipaddress.ToString());
             }
 
             // If we have not successfully sent the started event to this 
tier, override the passed in started event

_______________________________________________
Mono-patches maillist  -  [email protected]
http://lists.ximian.com/mailman/listinfo/mono-patches

Reply via email to