internal PeerConnectionEventArgs(TorrentManager manager, PeerId id, Direction direction, string message)
     : base(manager)
 {
     PeerID = id;
     ConnectionDirection = direction;
     Message = message;
 }
 protected override void AppendBitfieldMessage(PeerId id, MessageBundle bundle)
 {
     if (id.SupportsFastPeer)
         bundle.Messages.Add(new HaveNoneMessage());
     else
         bundle.Messages.Add(new BitfieldMessage(zero));
 }
Exemplo n.º 3
0
        private void ConnectionReceived(object sender, NewConnectionEventArgs e)
        {
            if (Engine.ConnectionManager.ShouldBanPeer(e.Peer))
            {
                e.Connection.Dispose();
                return;
            }
            var id = new PeerId(e.Peer, e.TorrentManager) {Connection = e.Connection};

            //Debug.WriteLine("ListenManager - ConnectionReceived: {0}", id.Connection);

            if (id.Connection.IsIncoming)
            {
                var skeys = new List<InfoHash>();

                ClientEngine.MainLoop.QueueWait(delegate { skeys.AddRange(Engine.Torrents.Select(t => t.InfoHash)); });

                EncryptorFactory.BeginCheckEncryption(id, HandshakeMessage.HandshakeLength, _endCheckEncryptionCallback,
                    id, skeys.ToArray());
            }
            else
            {
                ClientEngine.MainLoop.Queue(delegate { Engine.ConnectionManager.ProcessFreshConnection(id); });
            }
        }
 /// <summary>
 /// Creates a new PeerMessageEventArgs
 /// </summary>
 /// <param name="manager">The manager.</param>
 /// <param name="message">The peer message involved</param>
 /// <param name="direction">The direction of the message</param>
 /// <param name="id">The identifier.</param>
 internal PeerMessageEventArgs(TorrentManager manager, PeerMessage message, Direction direction, PeerId id)
     : base(manager)
 {
     Direction = direction;
     ID = id;
     Message = message;
 }
Exemplo n.º 5
0
 public virtual void Unchoke(PeerId peerToUnchoke)
 {
     peerToUnchoke.AmChoking = false;
     peerToUnchoke.TorrentManager.UploadingTo++;
     peerToUnchoke.Enqueue(new UnchokeMessage());
     peerToUnchoke.LastUnchoked = DateTime.Now;
 }
        public PeerExchangePeersAdded(TorrentManager manager, int count, int total, PeerId id)
            : base(manager, count, total)
        {
            if (id == null)
                throw new ArgumentNullException(nameof(id));

            Id = id;
        }
        internal static IAsyncResult BeginCheckEncryption(PeerId id, int bytesToReceive, AsyncCallback callback,
            object state, InfoHash[] sKeys)
        {
            var result = new EncryptorAsyncResult(id, callback, state) {SKeys = sKeys};

            var c = id.Connection;
            ClientEngine.MainLoop.QueueTimeout(TimeSpan.FromSeconds(10), delegate
            {
                if (id.Encryptor == null || id.Decryptor == null)
                    id.CloseConnection();
                return false;
            });

            try
            {
                // If the connection is incoming, receive the handshake before
                // trying to decide what encryption to use
                if (id.Connection.IsIncoming)
                {
                    result.Buffer = new byte[bytesToReceive];
                    NetworkIO.EnqueueReceive(c, result.Buffer, 0, result.Buffer.Length, null, null, null,
                        HandshakeReceivedCallback, result);
                }
                else
                {
                    var usable = CheckRc4(id);
                    var hasPlainText = Toolbox.HasEncryption(usable, EncryptionTypes.PlainText);
                    var hasRc4 = Toolbox.HasEncryption(usable, EncryptionTypes.RC4Full) ||
                                 Toolbox.HasEncryption(usable, EncryptionTypes.RC4Header);
                    if (id.Engine.Settings.PreferEncryption)
                    {
                        if (hasRc4)
                        {
                            result.EncSocket = new PeerAEncryption(id.TorrentManager.InfoHash, usable);
                            result.EncSocket.BeginHandshake(id.Connection, CompletedEncryptedHandshakeCallback, result);
                        }
                        result.Complete();
                    }
                    else
                    {
                        if (hasPlainText)
                        {
                            result.Complete();
                        }
                        else
                        {
                            result.EncSocket = new PeerAEncryption(id.TorrentManager.InfoHash, usable);
                            result.EncSocket.BeginHandshake(id.Connection, CompletedEncryptedHandshakeCallback, result);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Complete(ex);
            }
            return result;
        }
        internal PeerExchangeManager(PeerId id)
        {
            _id = id;

            _addedPeers = new List<Peer>();
            _droppedPeers = new List<Peer>();
            id.TorrentManager.OnPeerFound += OnAdd;
            Start();
        }
Exemplo n.º 9
0
 public override MessageBundle PickPiece(PeerId id, BitField peerBitfield, List<PeerId> otherPeers, int count,
     int startIndex, int endIndex)
 {
     // Invert 'bitfield' and AND it with the peers bitfield
     // Any pieces which are 'true' in the bitfield will not be downloaded
     _temp.From(peerBitfield).NAnd(_bitfield);
     if (_temp.AllFalse)
         return null;
     return base.PickPiece(id, _temp, otherPeers, count, startIndex, endIndex);
 }
Exemplo n.º 10
0
        private static EncryptionTypes CheckRc4(PeerId id)
        {
            // If the connection is *not* incoming, then it will be associated with an Engine
            // so we can check what encryption levels the engine allows.
            var t = id.Connection.IsIncoming ? EncryptionTypes.All : id.TorrentManager.Engine.Settings.AllowedEncryption;

            // We're allowed use encryption if the engine settings allow it and the peer supports it
            // Binary AND both the engine encryption and peer encryption and check what levels are supported
            t &= id.Peer.Encryption;
            return t;
        }
Exemplo n.º 11
0
        public override MessageBundle PickPiece(PeerId id, BitField peerBitfield, List<PeerId> otherPeers, int count,
            int startIndex, int endIndex)
        {
            if (peerBitfield.AllFalse)
                return null;

            if (count > 1)
                return base.PickPiece(id, peerBitfield, otherPeers, count, startIndex, endIndex);

            var midpoint = _random.Next(startIndex, endIndex);
            return base.PickPiece(id, peerBitfield, otherPeers, count, midpoint, endIndex) ??
                   base.PickPiece(id, peerBitfield, otherPeers, count, startIndex, midpoint);
        }
Exemplo n.º 12
0
        public override MessageBundle PickPiece(PeerId id, BitField peerBitfield, List<PeerId> otherPeers, int count,
            int startIndex, int endIndex)
        {
            if (peerBitfield.AllFalse)
                return null;

            if (count > 1)
                return base.PickPiece(id, peerBitfield, otherPeers, count, startIndex, endIndex);

            GenerateRarestFirst(peerBitfield, otherPeers);

            while (_rarest.Count > 0)
            {
                var current = _rarest.Pop();
                var bundle = base.PickPiece(id, current, otherPeers, count, startIndex, endIndex);
                _spares.Push(current);

                if (bundle != null)
                    return bundle;
            }

            return null;
        }
        public override MessageBundle PickPiece(PeerId id, BitField peerBitfield, List<PeerId> otherPeers, int count,
            int startIndex, int endIndex)
        {
            MessageBundle bundle;
            int start, end;

            if (HighPrioritySetStart >= startIndex && HighPrioritySetStart <= endIndex)
            {
                start = HighPrioritySetStart;
                end = Math.Min(endIndex, HighPrioritySetStart + HighPrioritySetSize - 1);
                if ((bundle = base.PickPiece(id, peerBitfield, otherPeers, count, start, end)) != null)
                    return bundle;
            }

            if (MediumPrioritySetStart >= startIndex && MediumPrioritySetStart <= endIndex)
            {
                start = MediumPrioritySetStart;
                end = Math.Min(endIndex, MediumPrioritySetStart + MediumPrioritySetSize - 1);
                if ((bundle = base.PickPiece(id, peerBitfield, otherPeers, count, start, end)) != null)
                    return bundle;
            }

            return base.PickPiece(id, peerBitfield, otherPeers, count, startIndex, endIndex);
        }
Exemplo n.º 14
0
 protected override void HandlePeerExchangeMessage(PeerId id, PeerExchangeMessage message)
 {
     // Nothing
 }
Exemplo n.º 15
0
 public LTChat(PeerId peer, string message)
     : this()
 {
     ExtensionId = peer.ExtensionSupports.MessageId(Support);
     Message = message;
 }
Exemplo n.º 16
0
        private void NextPeer()
        {
            var flag = false;

            foreach (var id in Manager.Peers.ConnectedPeers.Where(id => id.SupportsLTMessages && id.ExtensionSupports.Supports(LTMetadata.Support.Name)))
            {
                if (Equals(id, _currentId))
                    flag = true;
                else if (flag)
                {
                    _currentId = id;
                    return;
                }
            }
            //second pass without removing the currentid and previous ones
            foreach (var id in Manager.Peers.ConnectedPeers.Where(id => id.SupportsLTMessages && id.ExtensionSupports.Supports(LTMetadata.Support.Name)))
            {
                _currentId = id;
                return;
            }
            _currentId = null;
        }
Exemplo n.º 17
0
 internal static IAsyncResult BeginCheckEncryption(PeerId id, int bytesToReceive, AsyncCallback callback,
     object state)
 {
     return BeginCheckEncryption(id, bytesToReceive, callback, state, null);
 }
Exemplo n.º 18
0
 public void Add(PeerId peer)
 {
     _peers.Add(peer);
 }
Exemplo n.º 19
0
 public EncryptorAsyncResult(PeerId id, AsyncCallback callback, object state)
     : base(callback, state)
 {
     Id = id;
     Decryptor = new PlainTextEncryption();
     Encryptor = new PlainTextEncryption();
 }
Exemplo n.º 20
0
 private static int CompareNascentPeers(PeerId p1, PeerId p2)
 {
     //Comparer for nascent peers
     //Sort most recent first
     if (p1.LastUnchoked > p2.LastUnchoked)
         return -1;
     if (p1.LastUnchoked < p2.LastUnchoked)
         return 1;
     return 0;
 }
Exemplo n.º 21
0
 public LTMetadata(PeerId id, eMessageType type, int piece)
     : this(id, type, piece, null)
 {
 }
Exemplo n.º 22
0
        private static int CompareCandidatePeersWhileDownloading(PeerId p1, PeerId p2)
        {
            //Comparer for candidate peers for use when the torrent is downloading
            //First sort Am interested before !AmInterested
            if (p1.AmInterested && !p2.AmInterested)
                return -1;
            if (!p1.AmInterested && p2.AmInterested)
                return 1;

            //Both have the same AmInterested status, sort by download rate highest first
            return p2.LastReviewDownloadRate.CompareTo(p1.LastReviewDownloadRate);
        }
Exemplo n.º 23
0
 private static int CompareCandidatePeersWhileSeeding(PeerId p1, PeerId p2)
 {
     //Comparer for candidate peers for use when the torrent is seeding
     //Sort by upload rate, largest first
     return p2.LastReviewUploadRate.CompareTo(p1.LastReviewUploadRate);
 }
Exemplo n.º 24
0
 public bool Includes(PeerId peer)
 {
     //Return false if the supplied peer is null
     if (peer == null)
         return false;
     return _peers.Contains(peer);
 }
Exemplo n.º 25
0
		public override void HandlePeerConnected(PeerId id, Direction direction)
		{
			id.CloseConnection();
		}
Exemplo n.º 26
0
 public PeerEventArgs(PeerId peer)
     : base(peer.TorrentManager)
 {
     Peer = peer;
 }
Exemplo n.º 27
0
 public virtual void Choke(PeerId id)
 {
     id.AmChoking = true;
     id.TorrentManager.UploadingTo--;
     id.Enqueue(new ChokeMessage());
 }
Exemplo n.º 28
0
        private static int CompareOptimisticUnchokeCandidatesWhileSeeding(PeerId p1, PeerId p2)
        {
            //Comparer for optimistic unchoke candidates

            //Start by sorting peers that we have sent most data to before to the top
            if (p1.Monitor.DataBytesUploaded > p2.Monitor.DataBytesUploaded)
                return -1;
            if (p1.Monitor.DataBytesUploaded < p2.Monitor.DataBytesUploaded)
                return 1;

            //Amount of data sent is equal (and probably 0), sort untried before tried
            if (!p1.LastUnchoked.HasValue && p2.LastUnchoked.HasValue)
                return -1;
            if (p1.LastUnchoked.HasValue && !p2.LastUnchoked.HasValue)
                return 1;
            if (!p1.LastUnchoked.HasValue && p2.LastUnchoked.HasValue)
                //Both untried, nothing to choose between them
                return 0;

            //Both peers have been unchoked
            //Sort into descending order (most recent first)
            if (p1.LastUnchoked > p2.LastUnchoked)
                return -1;
            if (p1.LastUnchoked < p2.LastUnchoked)
                return 1;
            return 0;
        }
Exemplo n.º 29
0
 internal void Handle(PeerId id)
 {
     id.TorrentManager.Mode.HandleMessage(id, this);
 }
Exemplo n.º 30
0
 public LTMetadata(PeerId id, eMessageType type, int piece, byte[] metadata)
     : this(id.ExtensionSupports.MessageId(Support), type, piece, metadata)
 {
 }