public MetadataMode(TorrentManager manager, string savePath)
     : base(manager)
 {
     this.savePath = savePath;
 }
 protected virtual void RaiseConnectionReceived(Peer peer, IConnection connection, TorrentManager manager)
 {
     if (ConnectionReceived != null)
     {
         Toolbox.RaiseAsyncEvent <NewConnectionEventArgs>(ConnectionReceived, this, new NewConnectionEventArgs(peer, connection, manager));
     }
 }
Example #3
0
 /// <summary>
 /// Creates a new TorrentStateChangedEventArgs
 /// </summary>
 /// <param name="oldState">The old state of the Torrent</param>
 /// <param name="newState">The new state of the Torrent</param>
 public TorrentStateChangedEventArgs(TorrentManager manager, TorrentState oldState, TorrentState newState)
     : base(manager)
 {
     this.oldState = oldState;
     this.newState = newState;
 }
        public static void EnqueueReceiveMessage(IConnection connection, IEncryption decryptor, IRateLimiter rateLimiter, ConnectionMonitor monitor, TorrentManager manager, AsyncMessageReceivedCallback callback, object state)
        {
            // FIXME: Hardcoded number
            int count  = 4;
            var buffer = ClientEngine.BufferManager.GetBuffer(count);
            var data   = receiveCache.Dequeue().Initialise(connection, decryptor, rateLimiter, monitor, manager, buffer, callback, state);

            NetworkIO.EnqueueReceive(connection, buffer, 0, count, rateLimiter, monitor, data.ManagerMonitor, MessageLengthReceivedCallback, data);
        }
Example #5
0
 public DownloadMode(TorrentManager manager)
     : base(manager)
 {
     state = manager.Complete ? TorrentState.Seeding : TorrentState.Downloading;
 }
 /// <summary>
 /// Creates a new PieceHashedEventArgs
 /// </summary>
 /// <param name="pieceIndex">The index of the piece that was hashed</param>
 /// <param name="hashPassed">True if the piece passed the hashcheck, false otherwise</param>
 public PieceHashedEventArgs(TorrentManager manager, int pieceIndex, bool hashPassed)
     : base(manager)
 {
     this.pieceIndex = pieceIndex;
     this.hashPassed = hashPassed;
 }
Example #7
0
 protected Mode(TorrentManager manager)
 {
     CanAcceptConnections  = true;
     this.manager          = manager;
     manager.chokeUnchoker = new ChokeUnchokeManager(manager, manager.Settings.MinimumTimeBetweenReviews, manager.Settings.PercentOfMaxRateToSkipReview);
 }
Example #8
0
 public ReceiveMessageState Initialise(IConnection connection, IEncryption decryptor, IRateLimiter limiter, ConnectionMonitor peerMonitor, TorrentManager manager, byte[] buffer, AsyncMessageReceivedCallback callback, object state)
 {
     Connection     = connection;
     Decryptor      = decryptor;
     Manager        = manager;
     Buffer         = buffer;
     PeerMonitor    = peerMonitor;
     RateLimiter    = limiter;
     ManagerMonitor = manager == null ? null : manager.Monitor;
     Callback       = callback;
     State          = state;
     return(this);
 }
Example #9
0
 public ErrorMode(TorrentManager manager)
     : base(manager)
 {
     CanAcceptConnections = false;
     CloseConnections();
 }
        public static PeerMessage ReceiveMessage(CustomConnection connection, IEncryption decryptor, TorrentManager manager)
        {
            byte[] buffer = new byte[4];
            Receive(connection, buffer, 0, buffer.Length);
            decryptor.Decrypt(buffer);

            int count = IPAddress.HostToNetworkOrder(BitConverter.ToInt32(buffer, 0));

            byte[] message = new byte[count + 4];
            Buffer.BlockCopy(buffer, 0, message, 0, 4);

            Receive(connection, message, 4, count);
            decryptor.Decrypt(message, 4, count);

            return(PeerMessage.DecodeMessage(message, 0, message.Length, manager));
        }
 public StoppedMode(TorrentManager manager)
     : base(manager)
 {
     CanAcceptConnections = false;
 }
Example #12
0
 public AsyncConnectState(TorrentManager manager, Peer peer, IConnection connection)
 {
     Manager    = manager;
     Peer       = peer;
     Connection = connection;
 }
Example #13
0
 /// <summary>
 /// Creates a new PeersAddedEventArgs
 /// </summary>
 /// <param name="peersAdded">The number of peers just added</param>
 public PeerAddedEventArgs(TorrentManager manager, Peer peerAdded)
     : base(manager)
 {
     this.peer = peerAdded;
 }
 public PauseLimiter(TorrentManager manager)
 {
     this.manager = manager;
 }
 /// <summary>
 /// Creates a new PeersAddedEventArgs
 /// </summary>
 /// <param name="peersAdded">The number of peers just added</param>
 protected PeersAddedEventArgs(TorrentManager manager, int peersAdded, int total)
     : base(manager)
 {
     this.count = peersAdded;
     this.total = total;
 }
 /// <summary>
 /// Creates a new choke/unchoke manager for a torrent manager
 /// </summeary>
 /// <param name="TorrentManager">The torrent manager this choke/unchoke manager belongs to</param>
 public ChokeUnchokeManager(TorrentManager TorrentManager, int MinimumTimeBetweenReviews, int PercentOfMaxRateToSkipReview)
 {
     owningTorrent                = TorrentManager;
     minimumTimeBetweenReviews    = MinimumTimeBetweenReviews;
     percentOfMaxRateToSkipReview = PercentOfMaxRateToSkipReview;
 }
Example #17
0
 public LocalPeersAdded(TorrentManager manager, int peersAdded, int total)
     : base(manager, peersAdded, total)
 {
 }
 public void Add(TorrentManager manager, IConnection connection)
 {
     System.Net.BitTorrent.Client.Peer p = new System.Net.BitTorrent.Client.Peer("", new Uri("tcp://12.123.123.1:2342"), EncryptionTypes.All);
     base.RaiseConnectionReceived(p, connection, manager);
 }
        private void OnReceiveCallBack(IAsyncResult ar)
        {
            UdpClient  u = (UdpClient)ar.AsyncState;
            IPEndPoint e = new IPEndPoint(IPAddress.Any, 0);

            try
            {
                byte[] receiveBytes  = u.EndReceive(ar, ref e);
                string receiveString = Encoding.ASCII.GetString(receiveBytes);

                Regex 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");
                Match match = exp.Match(receiveString);

                if (!match.Success)
                {
                    return;
                }

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

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

                if (manager == null)
                {
                    return;
                }

                Uri  uri  = new Uri("tcp://" + e.Address.ToString() + ':' + match.Groups["port"].Value);
                Peer peer = new Peer("", uri, EncryptionTypes.All);

                // Add new peer to matched Torrent
                if (!manager.HasMetadata || !manager.Torrent.IsPrivate)
                {
                    ClientEngine.MainLoop.Queue(delegate {
                        int count = manager.AddPeersCore(peer);
                        manager.RaisePeersFound(new LocalPeersAdded(manager, count, 1));
                    });
                }
            }
            catch
            {
                // Failed to receive data, ignore
            }
            finally
            {
                try
                {
                    u.BeginReceive(OnReceiveCallBack, ar.AsyncState);
                }
                catch
                {
                    // It's closed
                }
            }
        }
Example #20
0
 public EndGameSwitcher(StandardPicker standard, EndGamePicker endgame, int blocksPerPiece, TorrentManager torrentManager)
     : base(null)
 {
     this.standard       = standard;
     this.endgame        = endgame;
     this.blocksPerPiece = blocksPerPiece;
     this.torrentManager = torrentManager;
 }
        private void handleHandshake(PeerId id, HandshakeMessage message)
        {
            TorrentManager man = null;

            try
            {
                if (message.ProtocolString != VersionInfo.ProtocolStringV100)
                {
                    throw new ProtocolException("Invalid protocol string in handshake");
                }
            }
            catch (Exception ex)
            {
                Logger.Log(id.Connection, ex.Message);
                id.Connection.Dispose();
                return;
            }

            ClientEngine.MainLoop.QueueWait((MainLoopTask) delegate {
                for (int i = 0; i < engine.Torrents.Count; i++)
                {
                    if (message.infoHash == engine.Torrents[i].InfoHash)
                    {
                        man = engine.Torrents[i];
                    }
                }
            });

            //FIXME: #warning FIXME: Don't stop the message loop until Dispose() and track all incoming connections
            if (man == null)        // We're not hosting that torrent
            {
                Logger.Log(id.Connection, "ListenManager - Handshake requested nonexistant torrent");
                id.Connection.Dispose();
                return;
            }
            if (man.State == TorrentState.Stopped)
            {
                Logger.Log(id.Connection, "ListenManager - Handshake requested for torrent which is not running");
                id.Connection.Dispose();
                return;
            }
            if (!man.Mode.CanAcceptConnections)
            {
                Logger.Log(id.Connection, "ListenManager - Current mode does not support connections");
                id.Connection.Dispose();
                return;
            }

            id.Peer.PeerId    = message.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.Encryptor is PlainTextEncryption && !Toolbox.HasEncryption(engine.Settings.AllowedEncryption, EncryptionTypes.PlainText)) && ClientEngine.SupportsEncryption)
            {
                Logger.Log(id.Connection, "ListenManager - Encryption is required but was not active");
                id.Connection.Dispose();
                return;
            }

            message.Handle(id);
            Logger.Log(id.Connection, "ListenManager - Handshake successful handled");

            id.ClientApp = new Software(message.PeerId);

            message = new HandshakeMessage(id.TorrentManager.InfoHash, engine.PeerId, VersionInfo.ProtocolStringV100);
            var callback = engine.ConnectionManager.incomingConnectionAcceptedCallback;

            PeerIO.EnqueueSendMessage(id.Connection, id.Encryptor, message, id.TorrentManager.UploadLimiter,
                                      id.Monitor, id.TorrentManager.Monitor, callback, id);
        }
        public void PieceDataReceived(PeerId peer, PieceMessage message)
        {
            Piece piece;

            if (picker.ValidatePiece(peer, message.PieceIndex, message.StartOffset, message.RequestLength, out piece))
            {
                PeerId         id      = peer;
                TorrentManager manager = id.TorrentManager;
                Block          block   = piece.Blocks [message.StartOffset / Piece.BlockSize];
                long           offset  = (long)message.PieceIndex * id.TorrentManager.Torrent.PieceLength + message.StartOffset;

                id.LastBlockReceived = DateTime.Now;
                id.TorrentManager.PieceManager.RaiseBlockReceived(new BlockEventArgs(manager, block, piece, id));
                id.TorrentManager.Engine.DiskManager.QueueWrite(manager, offset, message.Data, message.RequestLength, delegate {
                    piece.Blocks[message.StartOffset / Piece.BlockSize].Written = true;
                    ClientEngine.BufferManager.FreeBuffer(ref message.Data);
                    // If we haven't written all the pieces to disk, there's no point in hash checking
                    if (!piece.AllBlocksWritten)
                    {
                        return;
                    }

                    // Hashcheck the piece as we now have all the blocks.
                    id.Engine.DiskManager.BeginGetHash(id.TorrentManager, piece.Index, delegate(object o) {
                        byte[] hash = (byte[])o;
                        bool result = hash == null ? false : id.TorrentManager.Torrent.Pieces.IsValid(hash, piece.Index);
                        id.TorrentManager.Bitfield[message.PieceIndex] = result;

                        ClientEngine.MainLoop.Queue(delegate
                        {
                            id.TorrentManager.PieceManager.UnhashedPieces[piece.Index] = false;

                            id.TorrentManager.HashedPiece(new PieceHashedEventArgs(id.TorrentManager, piece.Index, result));
                            List <PeerId> peers = new List <PeerId>(piece.Blocks.Length);
                            for (int i = 0; i < piece.Blocks.Length; i++)
                            {
                                if (piece.Blocks[i].RequestedOff != null && !peers.Contains(piece.Blocks[i].RequestedOff))
                                {
                                    peers.Add(piece.Blocks[i].RequestedOff);
                                }
                            }

                            for (int i = 0; i < peers.Count; i++)
                            {
                                if (peers[i].Connection != null)
                                {
                                    peers[i].Peer.HashedPiece(result);
                                    if (peers [i].Peer.TotalHashFails == 5)
                                    {
                                        peers[i].ConnectionManager.CleanupSocket(id, "Too many hash fails");
                                    }
                                }
                            }

                            // If the piece was successfully hashed, enqueue a new "have" message to be sent out
                            if (result)
                            {
                                id.TorrentManager.finishedPieces.Enqueue(piece.Index);
                            }
                        });
                    });
                });

                if (piece.AllBlocksReceived)
                {
                    this.unhashedPieces[message.PieceIndex] = true;
                }
            }
            else
            {
            }
        }
 /// <summary>
 /// Creates a new PeerMessageEventArgs
 /// </summary>
 /// <param name="message">The peer message involved</param>
 /// <param name="direction">The direction of the message</param>
 internal BlockEventArgs(TorrentManager manager, Block block, Piece piece, PeerId id)
     : base(manager)
 {
     Init(block, piece, id);
 }
 public TorrentEventArgs(TorrentManager manager)
 {
     torrentManager = manager;
 }
 /// <summary>
 /// Creates a new inactive peer manager for a torrent manager
 /// </summary>
 /// <param name="TorrentManager">The torrent manager this choke/unchoke manager belongs to</param>
 /// <param name="TimeToWaitBeforeIdle">Number of seconds to protect a peer from being marked as inactive</param>
 public InactivePeerManager(TorrentManager TorrentManager)
 {
     owningTorrent = TorrentManager;
 }