protected Message(BEncodedString messageType) { properties.Add(TransactionIdKey, null); properties.Add(MessageTypeKey, messageType); if (UseVersionKey) properties.Add(VersionKey, DhtVersion); }
public AnnouncePeer(NodeId id, NodeId infoHash, BEncodedNumber port, BEncodedString token) : base(id, QueryName, responseCreator) { Parameters.Add(InfoHashKey, infoHash.BencodedString()); Parameters.Add(PortKey, port); Parameters.Add(TokenKey, token); }
private void CheckContent(BEncodedDictionary dict, BEncodedString key, BEncodedNumber value) { CheckContent(dict, key); if (!dict[key].Equals(value)) throw new TorrentException( string.Format("Invalid FastResume data. The value of '{0}' was '{1}' instead of '{2}'", key, dict[key], value)); }
protected QueryMessage(NodeId id, BEncodedString queryName, BEncodedDictionary queryArguments, ResponseCreator responseCreator) : base(QueryType) { Properties.Add(QueryNameKey, queryName); Properties.Add(QueryArgumentsKey, queryArguments); Parameters.Add(IdKey, id.BencodedString()); ResponseCreator = responseCreator; }
public static BEncodedString NextId() { lock (Current) { var result = new BEncodedString((byte[]) Current.Clone()); if (Current[0]++ == 255) Current[1]++; return result; } }
private static BEncodedDictionary CreateTorrent(int pieceLength) { var infoDict = new BEncodedDictionary(); infoDict[new BEncodedString("piece length")] = new BEncodedNumber(pieceLength); infoDict[new BEncodedString("pieces")] = new BEncodedString(new byte[20*15]); infoDict[new BEncodedString("length")] = new BEncodedNumber(15*256*1024 - 1); infoDict[new BEncodedString("name")] = new BEncodedString("test.files"); var dict = new BEncodedDictionary(); dict[new BEncodedString("info")] = infoDict; var announceTier = new BEncodedList(); announceTier.Add(new BEncodedString("custom://transfers1/announce")); announceTier.Add(new BEncodedString("custom://transfers2/announce")); announceTier.Add(new BEncodedString("http://transfers3/announce")); var announceList = new BEncodedList(); announceList.Add(announceTier); dict[new BEncodedString("announce-list")] = announceList; return dict; }
public void Save(IList<ResumeItem> resumeItems) { foreach (var keypair in this._originalDictionary) { if (keypair.Value is BEncodedDictionary) { var dic = (BEncodedDictionary)keypair.Value; var item = resumeItems.FirstOrDefault(c => c.TorrentName == keypair.Key.Text); if (item != null) { if (dic.ContainsKey("label")) { dic["label"] = new BEncodedString(item.Label); } else { dic.Add("label", new BEncodedString(item.Label)); } } } } File.WriteAllBytes(this._resumePath, this._originalDictionary.Encode()); }
protected void SetDictionary(BEncodedDictionary dictionary, BEncodedString key, BEncodedDictionary value) { if (dictionary == InfoDict) CheckCanEditSecure(); dictionary[key] = value; }
public static MonoTorrentCollection<Peer> Decode(BEncodedString peers) { // "Compact Response" peers are encoded in network byte order. // IP's are the first four bytes // Ports are the following 2 bytes byte[] byteOrderedData = peers.TextBytes; int i = 0; UInt16 port; StringBuilder sb = new StringBuilder(27); MonoTorrentCollection<Peer> list = new MonoTorrentCollection<Peer>((byteOrderedData.Length / 6) + 1); while ((i + 5) < byteOrderedData.Length) { sb.Remove(0, sb.Length); sb.Append("tcp://"); sb.Append(byteOrderedData[i++]); sb.Append('.'); sb.Append(byteOrderedData[i++]); sb.Append('.'); sb.Append(byteOrderedData[i++]); sb.Append('.'); sb.Append(byteOrderedData[i++]); port = (UInt16)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(byteOrderedData, i)); i += 2; sb.Append(':'); sb.Append(port); Uri uri = new Uri(sb.ToString()); list.Add(new Peer("", uri, EncryptionTypes.All)); } return list; }
public void RemoveCustomSecure(BEncodedString key) { CheckCanEditSecure(); Check.Key(key); InfoDict.Remove(key); }
protected long GetLong(BEncodedDictionary dictionary, BEncodedString key) { BEncodedValue value; if (dictionary.TryGetValue(key, out value)) return ((BEncodedNumber) value).Number; throw new ArgumentException(string.Format("The value for key {0} was not a BEncodedNumber", key)); }
protected QueryMessage(NodeId id, BEncodedString queryName, ResponseCreator responseCreator) : this(id, queryName, new BEncodedDictionary(), responseCreator) { }
public string this[int index] { get { return(((BEncodedString)Tier [index]).Text); } set { Tier [index] = new BEncodedString(value); } }
public HandshakeMessage(InfoHash infoHash, BEncodedString peerId, string protocolString, bool enableFastPeer) : this(infoHash, peerId, protocolString, enableFastPeer, ClientEngine.SupportsExtended) { }
private void AddFiles(BEncodedDictionary dict, TorrentFile[] files) { long totalSize = piecelength - 1; var bFiles = new BEncodedList(); for (var i = 0; i < files.Length; i++) { var path = new BEncodedList(); foreach (var s in files[i].Path.Split('/')) path.Add((BEncodedString) s); var d = new BEncodedDictionary(); d["path"] = path; d["length"] = (BEncodedNumber) files[i].Length; bFiles.Add(d); totalSize += files[i].Length; } dict[new BEncodedString("files")] = bFiles; dict[new BEncodedString("name")] = new BEncodedString("test.files"); dict[new BEncodedString("piece length")] = new BEncodedNumber(piecelength); dict[new BEncodedString("pieces")] = new BEncodedString(new byte[20*(totalSize/piecelength)]); }
public AnnounceParameters WithPeerId(BEncodedString peerId) { return(peerId == PeerId ? this : new AnnounceParameters(BytesDownloaded, BytesUploaded, BytesLeft, ClientEvent, InfoHash, RequireEncryption, peerId, IPAddress, Port, SupportsEncryption)); }
internal NodeId(BEncodedString value) : this(new BigInteger(value.TextBytes)) { Bytes = value.TextBytes; }
public VoteResponse(NodeId id, BEncodedValue transactionId, BEncodedString token) : base(id, transactionId) { ReturnValues.Add(_tokenKey, token); }
protected QueryMessage(NodeId id, BEncodedString queryName) : this(id, queryName, new BEncodedDictionary()) { }
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); }
public void benStringEncoding() { var data = Encoding.UTF8.GetBytes("22:this is my test string"); var benString = new BEncodedString("this is my test string"); Assert.True(Toolbox.ByteMatch(data, benString.Encode())); }
public void NodesIsNotAList() { torrentInfo["nodes"] = new BEncodedString("192.168.0.1:12345"); torrent = Torrent.Load(torrentInfo); Assert.IsNull(torrent.Nodes, "#1"); }
public void benStringEncodingBuffered() { var data = Encoding.UTF8.GetBytes("22:this is my test string"); var benString = new BEncodedString("this is my test string"); var result = new byte[benString.LengthInBytes()]; benString.Encode(result, 0); Assert.True(Toolbox.ByteMatch(data, result)); }
protected void LoadInternal(BEncodedDictionary torrentInformation) { Check.TorrentInformation(torrentInformation); originalDictionary = torrentInformation; torrentPath = ""; try { foreach (KeyValuePair <BEncodedString, BEncodedValue> keypair in torrentInformation) { switch (keypair.Key.Text) { case ("announce"): // Ignore this if we have an announce-list if (torrentInformation.ContainsKey("announce-list")) { break; } announceUrls.Add(new RawTrackerTier()); announceUrls[0].Add(keypair.Value.ToString()); break; case ("creation date"): try { try { creationDate = creationDate.AddSeconds(long.Parse(keypair.Value.ToString())); } catch (Exception e) { if (e is ArgumentOutOfRangeException) { creationDate = creationDate.AddMilliseconds(long.Parse(keypair.Value.ToString())); } else { throw; } } } catch (Exception e) { if (e is ArgumentOutOfRangeException) { throw new BEncodingException("Argument out of range exception when adding seconds to creation date.", e); } else if (e is FormatException) { throw new BEncodingException(String.Format("Could not parse {0} into a number", keypair.Value), e); } else { throw; } } break; case ("nodes"): nodes = (BEncodedList)keypair.Value; break; case ("comment.utf-8"): if (keypair.Value.ToString().Length != 0) { comment = keypair.Value.ToString(); // Always take the UTF-8 version } break; // even if there's an existing value case ("comment"): if (String.IsNullOrEmpty(comment)) { comment = keypair.Value.ToString(); } break; case ("publisher-url.utf-8"): // Always take the UTF-8 version publisherUrl = keypair.Value.ToString(); // even if there's an existing value break; case ("publisher-url"): if (String.IsNullOrEmpty(publisherUrl)) { publisherUrl = keypair.Value.ToString(); } break; case ("azureus_properties"): azureusProperties = keypair.Value; break; case ("created by"): createdBy = keypair.Value.ToString(); break; case ("encoding"): encoding = keypair.Value.ToString(); break; case ("info"): using (SHA1 s = HashAlgoFactory.Create <SHA1>()) infoHash = new InfoHash(s.ComputeHash(keypair.Value.Encode())); ProcessInfo(((BEncodedDictionary)keypair.Value)); break; case ("name"): // Handled elsewhere break; case ("announce-list"): if (keypair.Value is BEncodedString) { break; } BEncodedList announces = (BEncodedList)keypair.Value; for (int j = 0; j < announces.Count; j++) { if (announces[j] is BEncodedList) { BEncodedList bencodedTier = (BEncodedList)announces[j]; List <string> tier = new List <string>(bencodedTier.Count); for (int k = 0; k < bencodedTier.Count; k++) { tier.Add(bencodedTier[k].ToString()); } Toolbox.Randomize <string>(tier); RawTrackerTier collection = new RawTrackerTier(); for (int k = 0; k < tier.Count; k++) { collection.Add(tier[k]); } if (collection.Count != 0) { announceUrls.Add(collection); } } else if (announces[j] is BEncodedString) { BEncodedString tier = (BEncodedString)announces[j]; announceUrls.Add(new RawTrackerTier { tier.Text }); } else { throw new BEncodingException(String.Format("Non-BEncodedList found in announce-list (found {0})", announces[j].GetType())); } } break; case ("httpseeds"): // This form of web-seeding is not supported. break; case ("url-list"): if (keypair.Value is BEncodedString) { getRightHttpSeeds.Add(((BEncodedString)keypair.Value).Text); } else if (keypair.Value is BEncodedList) { foreach (BEncodedString str in (BEncodedList)keypair.Value) { GetRightHttpSeeds.Add(str.Text); } } break; default: break; } } } catch (Exception e) { if (e is BEncodingException) { throw; } else { throw new BEncodingException("", e); } } }
public void benStringEncoding2() { byte[] data = System.Text.Encoding.UTF8.GetBytes("0:"); BEncodedString benString = new BEncodedString(""); Assert.IsTrue(Toolbox.ByteMatch(data, benString.Encode())); }
public void SetCustomSecure(BEncodedString key, BEncodedValue value) { CheckCanEditSecure(); Check.Key(key); Check.Value(value); InfoDict[key] = value; }
/// <summary> /// Initializes a new instance of the <see cref="Software"/> class. /// </summary> /// <param name="peerId">The peer id.</param> internal Software(BEncodedString peerId) { Match m; PeerId = peerId; string idAsText = peerId.Text; if (idAsText.StartsWith("-WebSeed-", System.StringComparison.Ordinal)) { ShortId = "WebSeed"; Client = ClientApp.WebSeed; return; } #region Standard style peers if ((m = standard.Match(idAsText)).Success) { ShortId = m.Groups[1].Value; switch (m.Groups[2].Value) { case ("AG"): case ("A~"): Client = ClientApp.Ares; break; case ("AR"): Client = ClientApp.Artic; break; case ("AT"): Client = ClientApp.Artemis; break; case ("AX"): Client = ClientApp.BitPump; break; case ("AV"): Client = ClientApp.Avicora; break; case ("AZ"): Client = ClientApp.Azureus; break; case ("BB"): Client = ClientApp.BitBuddy; break; case ("BC"): Client = ClientApp.BitComet; break; case ("BF"): Client = ClientApp.Bitflu; break; case ("BS"): Client = ClientApp.BTSlave; break; case ("BX"): Client = ClientApp.BitTorrentX; break; case ("CD"): Client = ClientApp.EnhancedCTorrent; break; case ("CT"): Client = ClientApp.CTorrent; break; case ("DE"): Client = ClientApp.DelugeTorrent; break; case ("EB"): Client = ClientApp.EBit; break; case ("ES"): Client = ClientApp.ElectricSheep; break; case ("KT"): Client = ClientApp.KTorrent; break; case ("LP"): Client = ClientApp.Lphant; break; case ("lt"): case ("LT"): Client = ClientApp.LibTorrent; break; case ("MP"): Client = ClientApp.MooPolice; break; case ("MO"): Client = ClientApp.MonoTorrent; break; case ("MT"): Client = ClientApp.MoonlightTorrent; break; case ("qB"): Client = ClientApp.qBittorrent; break; case ("QT"): Client = ClientApp.Qt4Torrent; break; case ("RT"): Client = ClientApp.Retriever; break; case ("SB"): Client = ClientApp.Swiftbit; break; case ("SS"): Client = ClientApp.SwarmScope; break; case ("SZ"): Client = ClientApp.Shareaza; break; case ("TN"): Client = ClientApp.TorrentDotNET; break; case ("TR"): Client = ClientApp.Transmission; break; case ("TS"): Client = ClientApp.Torrentstorm; break; case ("UL"): Client = ClientApp.uLeecher; break; case ("UT"): Client = ClientApp.uTorrent; break; case "UW": Client = ClientApp.uTorrentWeb; break; case ("XT"): Client = ClientApp.XanTorrent; break; case ("ZT"): Client = ClientApp.ZipTorrent; break; default: System.Diagnostics.Trace.WriteLine($"Unsupported standard style: {m.Groups[2].Value}"); Client = ClientApp.Unknown; break; } return; } #endregion #region Shadows Style if ((m = shadows.Match(idAsText)).Success) { ShortId = m.Groups[1].Value; switch (m.Groups[2].Value) { case ("A"): Client = ClientApp.ABC; break; case ("O"): Client = ClientApp.OspreyPermaseed; break; case ("R"): Client = ClientApp.Tribler; break; case ("S"): Client = ClientApp.ShadowsClient; break; case ("T"): Client = ClientApp.BitTornado; break; case ("U"): Client = ClientApp.UPnPNatBitTorrent; break; default: Client = ClientApp.Unknown; break; } return; } #endregion #region Brams Client if ((m = brahms.Match(idAsText)).Success) { ShortId = "M"; Client = ClientApp.BitTorrent; return; } #endregion #region BitLord if ((m = bitlord.Match(idAsText)).Success) { Client = ClientApp.BitLord; ShortId = "lord"; return; } #endregion #region BitComet if ((m = bitcomet.Match(idAsText)).Success) { Client = ClientApp.BitComet; ShortId = "BC"; return; } #endregion #region XBT if ((m = xbt.Match(idAsText)).Success) { Client = ClientApp.XBTClient; ShortId = "XBT"; return; } #endregion #region Opera if ((m = opera.Match(idAsText)).Success) { Client = ClientApp.Opera; ShortId = "OP"; } #endregion #region MLDonkey if ((m = mldonkey.Match(idAsText)).Success) { Client = ClientApp.MLDonkey; ShortId = "ML"; return; } #endregion #region Bits on wheels if ((m = bow.Match(idAsText)).Success) { Client = ClientApp.BitsOnWheels; ShortId = "BOW"; return; } #endregion #region Queen Bee if ((m = queenbee.Match(idAsText)).Success) { Client = ClientApp.QueenBee; ShortId = "Q"; return; } #endregion #region BitTornado special style if ((m = bittornado.Match(idAsText)).Success) { ShortId = m.Groups[1].Value; Client = ClientApp.BitTornado; return; } #endregion Client = ClientApp.Unknown; ShortId = idAsText; }
/// <summary> /// Initializes a new instance of the <see cref="Software"/> class. /// </summary> /// <param name="peerId">The peer id.</param> internal Software(BEncodedString peerId) { Match m; PeerId = peerId; string idAsText = peerId.Text; if (idAsText.StartsWith("-WebSeed-", System.StringComparison.Ordinal)) { ShortId = "WebSeed"; Client = ClientApp.WebSeed; return; } #region Standard style peers if ((m = standard.Match(idAsText)).Success) { ShortId = m.Groups[1].Value; switch (m.Groups[2].Value) { case ("AG"): case ("A~"): Client = ClientApp.Ares; break; case ("AR"): Client = ClientApp.Artic; break; case ("AT"): Client = ClientApp.Artemis; break; case ("AX"): Client = ClientApp.BitPump; break; case ("AV"): Client = ClientApp.Avicora; break; case ("AZ"): Client = ClientApp.Azureus; break; case ("BB"): Client = ClientApp.BitBuddy; break; case ("BC"): Client = ClientApp.BitComet; break; case ("BF"): Client = ClientApp.Bitflu; break; case ("BS"): Client = ClientApp.BTSlave; break; case ("BX"): Client = ClientApp.BitTorrentX; break; case ("CD"): Client = ClientApp.EnhancedCTorrent; break; case ("CT"): Client = ClientApp.CTorrent; break; case ("DE"): Client = ClientApp.DelugeTorrent; break; case ("EB"): Client = ClientApp.EBit; break; case ("ES"): Client = ClientApp.ElectricSheep; break; case ("KT"): Client = ClientApp.KTorrent; break; case ("LP"): Client = ClientApp.Lphant; break; case ("lt"): case ("LT"): Client = ClientApp.LibTorrent; break; case ("MP"): Client = ClientApp.MooPolice; break; case ("MO"): Client = ClientApp.MonoTorrent; break; case ("MT"): Client = ClientApp.MoonlightTorrent; break; case ("qB"): Client = ClientApp.qBittorrent; break; case ("QT"): Client = ClientApp.Qt4Torrent; break; case ("RT"): Client = ClientApp.Retriever; break; case ("SB"): Client = ClientApp.Swiftbit; break; case ("SS"): Client = ClientApp.SwarmScope; break; case ("SZ"): Client = ClientApp.Shareaza; break; case ("TN"): Client = ClientApp.TorrentDotNET; break; case ("TR"): Client = ClientApp.Transmission; break; case ("TS"): Client = ClientApp.Torrentstorm; break; case ("UL"): Client = ClientApp.uLeecher; break; case ("UT"): Client = ClientApp.uTorrent; break; case "UW": Client = ClientApp.uTorrentWeb; break; case ("XT"): Client = ClientApp.XanTorrent; break; case ("ZT"): Client = ClientApp.ZipTorrent; break; default: System.Diagnostics.Trace.WriteLine($"Unsupported standard style: {m.Groups[2].Value}"); Client = ClientApp.Unknown; break; } return; } #endregion #region Shadows Style if ((m = shadows.Match(idAsText)).Success) { ShortId = m.Groups[1].Value; Client = m.Groups[2].Value switch { ("A") => ClientApp.ABC, ("O") => ClientApp.OspreyPermaseed, ("R") => ClientApp.Tribler, ("S") => ClientApp.ShadowsClient, ("T") => ClientApp.BitTornado, ("U") => ClientApp.UPnPNatBitTorrent, _ => ClientApp.Unknown, }; return; }
public bool VerifyToken(Node node, BEncodedString token) { return(token.Equals(GetToken(node, secret)) || token.Equals(GetToken(node, previousSecret))); }
public void RemoveCustom(BEncodedString key) { Check.Key(key); Metadata.Remove(key); }
public Peer(BEncodedString peerId, Uri connectionUri) : this(peerId, connectionUri, EncryptionTypes.All) { }
protected BEncodedDictionary GetDictionary(BEncodedDictionary dictionary, BEncodedString key) { // // Required? Probably. // if (dictionary == InfoDict) // CheckCanEditSecure (); BEncodedValue value; if (dictionary.TryGetValue(key, out value)) return (BEncodedDictionary) value; return null; }
public Peer(BEncodedString peerId, Uri connectionUri, IList <EncryptionType> allowedEncryption) { PeerId = peerId ?? throw new ArgumentNullException(nameof(peerId)); ConnectionUri = connectionUri ?? throw new ArgumentNullException(nameof(connectionUri)); AllowedEncryption = allowedEncryption; }
protected string GetString(BEncodedDictionary dictionary, BEncodedString key) { BEncodedValue value; if (dictionary.TryGetValue(key, out value)) return value.ToString(); return ""; }
internal static IList <Peer> Decode(BEncodedList l) => PeerDecoder.Decode(l).Select(t => new Peer(BEncodedString.FromMemory(t.PeerId), t.Uri)).ToArray();
protected void SetString(BEncodedDictionary dictionary, BEncodedString key, string value) { if (dictionary == InfoDict) CheckCanEditSecure(); dictionary[key] = new BEncodedString(value); }
public BEncodedString GenerateToken(Node node) { BEncodedString token = getToken(node); return(token); }
public bool VerifyToken(Node node, BEncodedString token) { return (token.Equals(GetToken(node, secret)) || token.Equals(GetToken(node, previousSecret))); }
public bool VerifyToken(Node node, BEncodedString token) { return(getToken(node).Equals(token)); }
public void benStringEncoding2() { var data = Encoding.UTF8.GetBytes("0:"); var benString = new BEncodedString(""); Assert.True(Toolbox.ByteMatch(data, benString.Encode())); }
public bool VerifyToken(Node node, BEncodedString token) { return(token.Equals(GenerateToken(node, currentSecret)) || token.Equals(GenerateToken(node, previousSecret))); }
public void Setup() { manager = new TokenManager(); node = new Node(NodeId.Create(), new IPEndPoint(IPAddress.Parse("127.0.0.1"), 25)); token = manager.GenerateToken(node); }
public GetPeersResponse(NodeId id, BEncodedValue transactionId, BEncodedString token) : base(id, transactionId) { Parameters.Add(TokenKey, token); }
private void CheckContent(BEncodedDictionary dict, BEncodedString key) { if (dict == null) throw new ArgumentNullException(nameof(dict)); if (!dict.ContainsKey(key)) throw new TorrentException(string.Format("Invalid FastResume data. Key '{0}' was not present", key)); }
public void benStringEncodingBuffered() { byte[] data = System.Text.Encoding.UTF8.GetBytes("22:this is my test string"); BEncodedString benString = new BEncodedString("this is my test string"); byte[] result = new byte[benString.LengthInBytes()]; benString.Encode(result, 0); Assert.IsTrue(Toolbox.ByteMatch(data, result)); }
/// <summary> /// Adds a custom value to the main bencoded dictionary /// </summary> public void AddCustom(BEncodedString key, BEncodedValue value) { dict.Add(key, value); }
static BEncodedValue Get(BEncodedDictionary dictionary, BEncodedString key) { return dictionary.ContainsKey(key) ? dictionary[key] : null; }
public static IList <PeerInfo> Decode(BEncodedString peers) => PeerInfo.FromCompact(peers.Span);
internal static IEnumerable <Node> FromCompactNode(BEncodedString nodes) { return(FromCompactNode(nodes.TextBytes)); }
/// <summary> /// Removes a custom value from the main bencoded dictionary. /// </summary> public void RemoveCustom(BEncodedString key) { dict.Remove(key); }
static void Set(BEncodedDictionary dictionary, BEncodedString key, BEncodedValue value) { if (dictionary.ContainsKey(key)) dictionary[key] = value; else dictionary.Add(key, value); }
public GetPeers(NodeId id, NodeId infohash) : base(id, QueryName) { Parameters.Add(InfoHashKey, BEncodedString.FromMemory(infohash.AsMemory())); }