/// <summary>
 ///   Create new instance of PeerConnectionFailedEventArgs for peer from given torrent.
 /// </summary>
 /// <param name="manager"> </param>
 /// <param name="peer"> </param>
 /// <param name="direction"> Which direction the connection attempt was </param>
 /// <param name="message"> Message associated with the failure </param>
 public PeerConnectionFailedEventArgs(TorrentManager manager, Peer peer, Direction direction, String message)
     : base(manager)
 {
     _peer = peer;
     _connectionDirection = direction;
     _message = message;
 }
Exemple #2
0
 public void CompactPeerTest()
 {
     string peerId = "12345abcde12345abcde";
     Uri uri = new Uri("tcp://192.168.0.5:12345");
     Peer p = new Peer(peerId, uri);
     byte[] compact = p.CompactPeer();
     Peer peer = Peer.Decode((BEncoding.BEncodedString)compact)[0];
     Assert.AreEqual(p.ConnectionUri, peer.ConnectionUri);
 }
        public NewConnectionEventArgs(Peer peer, IConnection connection, TorrentManager manager)
            : base(manager)
        {
            if (!connection.IsIncoming && manager == null)
                throw new InvalidOperationException(
                    "An outgoing connection must specify the torrent manager it belongs to");

            _connection = connection;
            _peer = peer;
        }
Exemple #4
0
        public void CompactPeer()
        {
            const string peerId = "12345abcde12345abcde";

            var uri = new Uri("tcp://192.168.0.5:12345");
            var p = new Peer(peerId, uri);

            var compact = p.CompactPeer();
            var peer = Peer.Decode(compact)[0];

            Assert.AreEqual(p.ConnectionUri, peer.ConnectionUri, "#1");
        }
Exemple #5
0
 public PeerId CreatePeer(bool processingQueue, bool supportsFastPeer)
 {
     StringBuilder sb = new StringBuilder();
     for (int i = 0; i < 20; i++)
         sb.Append((char)Random.Next((int)'a', (int)'z'));
     Peer peer = new Peer(sb.ToString(), new Uri("tcp://127.0.0.1:" + (port++)));
     PeerId id = new PeerId(peer, Manager);
     id.SupportsFastPeer = supportsFastPeer;
     id.ProcessingQueue = processingQueue;
     return id;
 }
Exemple #6
0
 public void AddPeer(Peer p)
 {
     TrackerConnectionID id = new TrackerConnectionID(this, false, TorrentEvent.None, new ManualResetEvent(false));
     AnnounceResponseEventArgs e = new AnnounceResponseEventArgs(this, id, true);
     e.Peers.Add(p);
     RaiseAnnounceComplete(e);
     Assert.IsTrue(id.WaitHandle.WaitOne(1000, true), "#1 Tracker never raised the AnnounceComplete event");
 }
        private void OnReceiveCallBack(IAsyncResult asyncResult)
        {
            var udpClient = (UdpClient) asyncResult.AsyncState;
            var endPoint = new IPEndPoint(IPAddress.Any, 0);
            try
            {
                var receiveBytes = udpClient.EndReceive(asyncResult, ref endPoint);
                var receiveString = Encoding.ASCII.GetString(receiveBytes);

                var exp = new Regex("BT-SEARCH \\* HTTP/1.1\\r\\nHost: 239.192.152.143:6771\\r\\nPort: (?<port>[^@]+)\\r\\nInfohash: (?<hash>[^@]+)\\r\\n\\r\\n\\r\\n");
                var match = exp.Match(receiveString);

                if (!match.Success)
                    return;

                var portcheck = Convert.ToInt32(match.Groups["port"].Value);
                if (portcheck < 0 || portcheck > 65535)
                    return;

                TorrentManager manager = null;
                var matchHash = InfoHash.FromHex(match.Groups["hash"].Value);
                for (var i = 0; manager == null && i < _engine.Torrents.Count; i++)
                    if (_engine.Torrents[i].InfoHash == matchHash)
                        manager = _engine.Torrents[i];

                if (manager == null)
                    return;

                var uri = new Uri(string.Format("tcp://{0}{1}{2}", endPoint.Address, ':', match.Groups["port"].Value));
                var peer = new Peer("", uri, EncryptionTypes.All);

                // Add new peer to matched Torrent
                if (!manager.HasMetadata || !manager.Torrent.IsPrivate)
                {
                    ClientEngine.MainLoop.Queue(() =>
                                                    {
                                                        var count = manager.AddPeersCore(peer);
                                                        manager.RaisePeersFound(new LocalPeersAdded(manager, count, 1));
                                                    });
                }
            }
            catch
            {
                // Failed to receive data, ignore
            }
            finally
            {
                try
                {
                    udpClient.BeginReceive(OnReceiveCallBack, asyncResult.AsyncState);
                }
                catch
                {
                    // It's closed
                }
            }
        }
        internal bool ShouldBanPeer(Peer peer)
        {
            if (BanPeer == null)
                return false;

            var e = new AttemptConnectionEventArgs(peer);
            BanPeer(this, e);
            return e.BanPeer;
        }
Exemple #9
0
 public AsyncConnectState(TorrentManager manager, Peer peer, IConnection connection)
 {
     Manager = manager;
     Peer = peer;
     Connection = connection;
 }
 public void AddPeer(Peer p)
 {
     TrackerConnectionID id = new TrackerConnectionID(this, false, TorrentEvent.None, null);
     AnnounceResponseEventArgs e = new AnnounceResponseEventArgs(this, null, true);
     e.Peers.Add(p);
     e.Successful = true;
     RaiseAnnounceComplete(e);
 }
Exemple #11
0
 public virtual bool ShouldConnect(Peer peer)
 {
     return true;
 }
Exemple #12
0
 public override bool ShouldConnect(Peer peer)
 {
     return !(peer.IsSeeder && Manager.HasMetadata && Manager.Complete);
 }
Exemple #13
0
        internal PeerId(Peer peer, TorrentManager manager)
        {
            if (peer == null)
                throw new ArgumentNullException("peer");

            suggestedPieces = new MonoTorrentCollection<int>();
            amChoking = true;
            isChoking = true;

            isAllowedFastPieces = new MonoTorrentCollection<int>();
            amAllowedFastPieces = new MonoTorrentCollection<int>();
            lastMessageReceived = DateTime.Now;
            lastMessageSent = DateTime.Now;
            this.peer = peer;
            maxPendingRequests = 2;
            maxSupportedPendingRequests = 50;
            monitor = new ConnectionMonitor();
            sendQueue = new MonoTorrentCollection<PeerMessage>(12);
            ExtensionSupports = new ExtensionSupports();
            TorrentManager = manager;
            InitializeTyrant();
        }
Exemple #14
0
 internal bool Contains(Peer peer)
 {
     return(All.Any(peer.Equals));
 }
Exemple #15
0
 internal bool Contains(Peer peer)
 {
     return All.Any(peer.Equals);
 }
 public void Add(TorrentManager manager, IConnection connection)
 {
     var peer = new Peer(string.Empty, new Uri("tcp://12.123.123.1:2342"), EncryptionTypes.All);
     base.RaiseConnectionReceived(peer, connection, manager);
 }
Exemple #17
0
        private void DownloadLogic(int counter)
        {
            // FIXME: Hardcoded 15kB/sec - is this ok?
            if ((DateTime.Now - _manager.StartTime) > TimeSpan.FromMinutes(1) && _manager.Monitor.DownloadSpeed < 15*1024)
            {
                foreach (var s in _manager.Torrent.GetRightHttpSeeds)
                {
                    var peerId = "-WebSeed-";
                    peerId = peerId + (_webseedCount++).ToString().PadLeft(20 - peerId.Length, '0');

                    var uri = new Uri(s);
                    var peer = new Peer(peerId, uri);
                    var id = new PeerId(peer, _manager);
                    var connection = new HttpConnection(new Uri(s));
                    connection.Manager = _manager;
                    peer.IsSeeder = true;
                    id.BitField.SetAll(true);
                    id.Encryptor = new PlainTextEncryption();
                    id.Decryptor = new PlainTextEncryption();
                    id.IsChoking = false;
                    id.AmInterested = !_manager.Complete;
                    id.Connection = connection;
                    id.ClientApp = new Software(id.PeerID);
                    _manager.Peers.ConnectedPeers.Add(id);
                    _manager.RaisePeerConnected(new PeerConnectionEventArgs(_manager, id, Direction.Outgoing));
                    PeerIO.EnqueueReceiveMessage(id.Connection, id.Decryptor, Manager.DownloadLimiter, id.Monitor,
                                                 id.TorrentManager, id.ConnectionManager.MessageReceivedCallback, id);
                }

                // FIXME: In future, don't clear out this list. It may be useful to keep the list of HTTP seeds
                // Add a boolean or something so that we don't add them twice.
                _manager.Torrent.GetRightHttpSeeds.Clear();
            }

            // Remove inactive peers we haven't heard from if we're downloading
            if (_manager.State == TorrentState.Downloading &&
                _manager.lastCalledInactivePeerManager + TimeSpan.FromSeconds(5) < DateTime.Now)
            {
                _manager.InactivePeerManager.TimePassed();
                _manager.lastCalledInactivePeerManager = DateTime.Now;
            }

            // Now choke/unchoke peers; first instantiate the choke/unchoke manager if we haven't done so already
            if (_manager.chokeUnchoker == null)
                _manager.chokeUnchoker = new ChokeUnchokeManager(_manager, _manager.Settings.MinimumTimeBetweenReviews,
                                                                _manager.Settings.PercentOfMaxRateToSkipReview);
            _manager.chokeUnchoker.UnchokeReview();
        }
Exemple #18
0
 protected virtual void RaiseConnectionReceived(Peer peer, IConnection connection, TorrentManager manager)
 {
     if (ConnectionReceived != null)
         Toolbox.RaiseAsyncEvent(ConnectionReceived, this, new NewConnectionEventArgs(peer, connection, manager));
 }
        private void EndAccept(IAsyncResult result)
        {
            Socket peerSocket = null;
            try
            {
                var listener = (Socket)result.AsyncState;
                peerSocket = listener.EndAccept(result);

                var endpoint = (IPEndPoint)peerSocket.RemoteEndPoint;
                var uri = new Uri(string.Format("tcp://{0}{1}{2}", endpoint.Address, ':', endpoint.Port));
                var peer = new Peer("", uri, EncryptionTypes.All);
                var connection = peerSocket.AddressFamily == AddressFamily.InterNetwork
                                     ? (IConnection) new IPV4Connection(peerSocket, true)
                                     : new IPV6Connection(peerSocket, true);

                RaiseConnectionReceived(peer, connection, null);
            }
            catch (SocketException)
            {
                // Just dump the connection
                if (peerSocket != null)
                    peerSocket.Close();
            }
            catch (ObjectDisposedException)
            {
                // We've stopped listening
            }
            finally
            {
                try
                {
                    if (Status == ListenerStatus.Listening)
                        _listener.BeginAccept(_endAcceptCallback, _listener);
                }
                catch (ObjectDisposedException)
                {

                }
            }
        }
Exemple #20
0
        public bool Equals(Peer other)
        {
            if (other == null)
                return false;

            // FIXME: Don't compare the port, just compare the IP
            if (string.IsNullOrEmpty(PeerId) && string.IsNullOrEmpty(other.PeerId))
                return _connectionUri.Host.Equals(other._connectionUri.Host);

            return PeerId == other.PeerId;
        }
        internal void ConnectToPeer(TorrentManager manager, Peer peer)
        {
            // Connect to the peer.
            var connection = ConnectionFactory.Create(peer.ConnectionUri);
            if (connection == null)
                return;

            peer.LastConnectionAttempt = DateTime.Now;
            var c = new AsyncConnectState(manager, peer, connection);
            _pendingConnects.Add(c);

            manager.Peers.ConnectingToPeers.Add(peer);
            NetworkIO.EnqueueConnect(connection, _endCreateConnectionCallback, c);
        }