Esempio n. 1
0
 protected ResponseMessage(NodeId id, BEncodedValue transactionId)
     : base(ResponseType)
 {
     properties.Add(ReturnValuesKey, new BEncodedDictionary());
     Parameters.Add(IdKey, BEncodedString.FromMemory(id.AsMemory()));
     TransactionId = transactionId;
 }
 public AnnouncePeer(NodeId id, NodeId infoHash, BEncodedNumber port, BEncodedValue token)
     : base(id, QueryName)
 {
     Parameters.Add(InfoHashKey, BEncodedString.FromMemory(infoHash.AsMemory()));
     Parameters.Add(PortKey, port);
     Parameters.Add(TokenKey, token);
 }
Esempio n. 3
0
        protected virtual async void HandlePeerExchangeMessage(PeerId id, PeerExchangeMessage message)
        {
            // Ignore peer exchange messages on private toirrents
            if ((Manager.Torrent != null && Manager.Torrent.IsPrivate) || !Manager.Settings.AllowPeerExchange)
            {
                Manager.RaisePeersFound(new PeerExchangePeersAdded(Manager, 0, 0, id));
            }
            else
            {
                // If we already have lots of peers, don't process the messages anymore.
                if ((Manager.Peers.Available + Manager.OpenConnections) >= Manager.Settings.MaximumConnections)
                {
                    return;
                }

                IList <Peer> newPeers = Peer.Decode(BEncodedString.FromMemory(message.Added));
                for (int i = 0; i < newPeers.Count && i < message.AddedDotF.Length; i++)
                {
                    newPeers[i].IsSeeder = (message.AddedDotF.Span[i] & 0x2) == 0x2;
                }
                int count = await Manager.AddPeersAsync(newPeers);

                Manager.RaisePeersFound(new PeerExchangePeersAdded(Manager, count, newPeers.Count, id));
            }
        }
Esempio n. 4
0
        public static BEncodedString NextId()
        {
            int value = Interlocked.Increment(ref current);

            byte[] data = new[] { (byte)(value >> 8), (byte)value };
            return(BEncodedString.FromMemory(data));
        }
Esempio n. 5
0
        public async Task StartAsync(ReadOnlyMemory <byte> initialNodes)
        {
            CheckDisposed();

            await MainLoop;

            MessageLoop.Start();
            if (RoutingTable.NeedsBootstrap)
            {
                RaiseStateChanged(DhtState.Initialising);
                // HACK: We want to disambiguate between 'decode one' and 'decode many' when using a Span<byte>
                InitializeAsync(Node.FromCompactNode(BEncodedString.FromMemory(initialNodes)));
            }
            else
            {
                RaiseStateChanged(DhtState.Ready);
            }

            MainLoop.QueueTimeout(TimeSpan.FromSeconds(30), delegate {
                if (!Disposed)
                {
                    _ = RefreshBuckets();
                }
                return(!Disposed);
            });
        }
        protected QueryMessage(NodeId id, BEncodedString queryName, BEncodedDictionary queryArguments)
            : base(QueryType)
        {
            properties.Add(QueryNameKey, queryName);
            properties.Add(QueryArgumentsKey, queryArguments);

            Parameters.Add(IdKey, BEncodedString.FromMemory(id.AsMemory()));
        }
Esempio n. 7
0
        Uri CreateAnnounceString(AnnounceRequest parameters)
        {
            var b = new UriQueryBuilder(Uri);

            b.Add("info_hash", parameters.InfoHash.UrlEncode())
            .Add("peer_id", BEncodedString.FromMemory(parameters.PeerId).UrlEncode())
            .Add("port", parameters.Port)
            .Add("uploaded", parameters.BytesUploaded)
            .Add("downloaded", parameters.BytesDownloaded)
            .Add("left", parameters.BytesLeft)
            .Add("compact", 1)
            .Add("numwant", 100);

            if (parameters.SupportsEncryption)
            {
                b.Add("supportcrypto", 1);
            }
            if (parameters.RequireEncryption)
            {
                b.Add("requirecrypto", 1);
            }
            if (!b.Contains("key") && Key != null)
            {
                b.Add("key", Key.UrlEncode());
            }
            if (!string.IsNullOrEmpty(parameters.IPAddress))
            {
                b.Add("ip", parameters.IPAddress !);
            }

            // If we have not successfully sent the started event to this tier, override the passed in started event
            // Otherwise append the event if it is not "none"
            //if (!parameters.Id.Tracker.Tier.SentStartedEvent)
            //{
            //    sb.Append("&event=started");
            //    parameters.Id.Tracker.Tier.SendingStartedEvent = true;
            //}
            if (parameters.ClientEvent != TorrentEvent.None)
            {
                b.Add("event", parameters.ClientEvent.ToString().ToLower());
            }

            if (!BEncodedString.IsNullOrEmpty(TrackerId))
            {
                b.Add("trackerid", TrackerId !.UrlEncode());
            }

            return(b.ToUri());
        }
Esempio n. 8
0
        public override void Decode(ReadOnlySpan <byte> buffer)
        {
            ProtocolStringLength = ReadByte(ref buffer);                   // First byte is length

            // #warning Fix this hack - is there a better way of verifying the protocol string? Hack
            if (ProtocolStringLength != Constants.ProtocolStringV100.Length)
            {
                ProtocolStringLength = Constants.ProtocolStringV100.Length;
            }

            ProtocolString = ReadString(ref buffer, ProtocolStringLength);
            CheckForSupports(ref buffer);
            InfoHash = InfoHash.FromMemory(ReadBytes(ref buffer, 20));
            PeerId   = BEncodedString.FromMemory(ReadBytes(ref buffer, 20));
        }
Esempio n. 9
0
        public async Task Announce_ValidateParams()
        {
            var argsTask = new TaskCompletionSource <AnnounceRequest> ();

            listener.AnnounceReceived += (o, e) => argsTask.TrySetResult(e);

            await tracker.AnnounceAsync(announceParams, CancellationToken.None);

            Assert.IsTrue(argsTask.Task.Wait(5000), "#1");

            var args = argsTask.Task.Result;

            Assert.AreEqual(peerId, BEncodedString.FromMemory(announceParams.PeerId), "#1");
            Assert.AreEqual(BEncodedString.FromMemory(announceParams.PeerId), args.PeerId, "#2");

            Assert.AreEqual(infoHash, args.InfoHash, "#3");
            Assert.IsTrue(announceParams.InfoHash == args.InfoHash, "#3");
        }
Esempio n. 10
0
 public override void Decode(ReadOnlySpan <byte> buffer)
 {
     ConnectionId = ReadLong(ref buffer);
     if (Action != ReadInt(ref buffer))
     {
         ThrowInvalidActionException();
     }
     TransactionId = ReadInt(ref buffer);
     InfoHash      = InfoHash.FromMemory(ReadBytes(ref buffer, 20));
     PeerId        = BEncodedString.FromMemory(ReadBytes(ref buffer, 20));
     Downloaded    = ReadLong(ref buffer);
     Left          = ReadLong(ref buffer);
     Uploaded      = ReadLong(ref buffer);
     TorrentEvent  = (TorrentEvent)ReadInt(ref buffer);
     IP            = ReadUInt(ref buffer);
     Key           = ReadUInt(ref buffer);
     NumWanted     = ReadInt(ref buffer);
     Port          = ReadUShort(ref buffer);
 }
Esempio n. 11
0
 public FindNode(NodeId id, NodeId target)
     : base(id, QueryName)
 {
     Parameters.Add(TargetKey, BEncodedString.FromMemory(target.AsMemory()));
 }
Esempio n. 12
0
        async void DhtEnginePeersFound(object o, PeersFoundEventArgs e)
        {
            await MainLoop;

            TorrentManager manager = allTorrents.FirstOrDefault(t => t.InfoHash == e.InfoHash);

            if (manager == null)
            {
                return;
            }

            if (manager.CanUseDht)
            {
                int successfullyAdded = await manager.AddPeersAsync(e.Peers.Select(p => new Peer(BEncodedString.FromMemory(p.PeerId), p.Uri)));

                manager.RaisePeersFound(new DhtPeersAdded(manager, successfullyAdded, e.Peers.Count));
            }
            else
            {
                // This is only used for unit testing to validate that even if the DHT engine
                // finds peers for a private torrent, we will not add them to the manager.
                manager.RaisePeersFound(new DhtPeersAdded(manager, 0, 0));
            }
        }
Esempio n. 13
0
 public GetPeers(NodeId id, NodeId infohash)
     : base(id, QueryName)
 {
     Parameters.Add(InfoHashKey, BEncodedString.FromMemory(infohash.AsMemory()));
 }
Esempio n. 14
0
 internal static IList <Peer> Decode(BEncodedList l)
 => PeerDecoder.Decode(l).Select(t => new Peer(BEncodedString.FromMemory(t.PeerId), t.Uri)).ToArray();
Esempio n. 15
0
 void Initialize(ReadOnlyMemory <byte> added, ReadOnlyMemory <byte> addedDotF, ReadOnlyMemory <byte> dropped)
 {
     peerDict[AddedKey]     = BEncodedString.FromMemory(added);
     peerDict[AddedDotFKey] = BEncodedString.FromMemory(addedDotF);
     peerDict[DroppedKey]   = BEncodedString.FromMemory(dropped);
 }