public BroadcastEventArgs(Node sender, int ttl, string cmd, BDict message) { Sender = sender; TTL = ttl; Command = cmd; Message = message; }
public void BDictSetNullValue() { BDict dict = new BDict(); dict.Add("a", new BInt(0)); dict["a"] = null; }
private void ProcessExtended(IPeerWireClient client, int commandLength, byte[] payload) { Int32 msgId = payload[0]; byte[] buffer = payload.GetBytes(1, commandLength - 1); if (msgId == 0) { BDict extendedHandshake = (BDict)BencodingUtils.Decode(buffer); BDict mDict = (BDict)extendedHandshake["m"]; foreach (KeyValuePair <string, IBencodingType> pair in mDict) { BInt i = (BInt)pair.Value; this._extIncoming.Add(new ClientProtocolIDMap(client, pair.Key, (byte)i)); IBTExtension ext = this.FindIBTExtensionByProtocol(pair.Key); if (ext != null) { ext.OnHandshake(client, buffer); } } } else { string protocol = this.FindIBTProtocolByMessageID(msgId); IBTExtension ext = this.FindIBTExtensionByProtocol(protocol); if (ext != null) { ext.OnExtendedMessage(client, buffer); } } }
public void SendMessage(IPeerWireClient peerWireClient, IPEndPoint[] addedEndPoints, byte[] flags, IPEndPoint[] droppedEndPoints) { if (addedEndPoints == null && droppedEndPoints == null) return; BDict d = new BDict(); if (addedEndPoints != null) { byte[] added = new byte[addedEndPoints.Length * 6]; for (int x = 0; x < addedEndPoints.Length; x++) { addedEndPoints[x].Address.GetAddressBytes().CopyTo(added, x * 6); BitConverter.GetBytes((ushort)addedEndPoints[x].Port).CopyTo(added, (x * 6)+4); } d.Add("added", new BString { ByteValue = added }); } if (droppedEndPoints != null) { byte[] dropped = new byte[droppedEndPoints.Length * 6]; for (int x = 0; x < droppedEndPoints.Length; x++) { droppedEndPoints[x].Address.GetAddressBytes().CopyTo(dropped, x * 6); dropped.SetValue((ushort)droppedEndPoints[x].Port, (x * 6) + 2); } d.Add("dropped", new BString { ByteValue = dropped }); } _parent.SendExtended(peerWireClient, _parent.GetOutgoingMessageID(peerWireClient, this), BencodingUtils.EncodeBytes(d)); }
private BDict ParseDict() { var dict = new BDict(); var largest = (BString)null; do { var key = ParseString(); if (dict.Value.ContainsKey(key)) { var msg = $"Key '{key}' is already present in the dictionary."; throw new BParserException(msg); } if (dict.Value.Comparer.Compare(largest, key) > 0) { var msg = $"Key '{key}' is not lexicographically larger than preceding keys."; throw new BParserException(msg); } largest = key; dict.Value.Add(key, ParseAnyType()); }while (!IsAtEnd() && !Match(BLiteral.End)); return(dict); }
public LocalRequest(ulong index, BDict request, TimeSpan time) { Response = new TaskCompletionSource <RemoteResponse>(); Index = index; Request = request; Time = time; }
/// <summary> /// Calculates the InfoHash from a torrent. You must supply the "info" dictionary from the torrent. /// </summary> /// <param name="torrentInfoDict">The "info" dictionary.</param> /// <example> /// This example, will load a torrent, take the "info" dictionary out of the root dictionary and hash this. /// <code> /// BDict torrent = BencodingUtils.DecodeFile(@"torrentFile.torrent") as BDict; /// byte[] infoHash = BencodingUtils.CalculateTorrentInfoHash(torrent["info"] as BDict); /// </code> /// /// The "infoHash" byte array now contains 20 bytes with the SHA-1 infoHash. /// </example> /// <returns></returns> public static byte[] CalculateTorrentInfoHash(BDict torrentInfoDict) { // Take the "info" dictionary provided, and encode it byte[] infoBytes = EncodeBytes(torrentInfoDict); // Hash the encoded dictionary return new SHA1CryptoServiceProvider().ComputeHash(infoBytes); }
public void BDictSetValue() { BDict dict = new BDict(); dict.Add("a", new BInt(0)); BInt newInt = new BInt(1); dict["a"] = newInt; Assert.AreEqual(newInt, dict["a"]); }
public void DecodeDict_Empty() { const string testString = "de"; BDict testExpected = new BDict(); IBencodingType testResult = BencodingUtils.Decode(testString); Assert.AreEqual(testExpected, testResult); }
public void DecodeDict() { const string testString = "d1:a11:Hello Worlde"; BDict testExpected = new BDict(); testExpected.Add("a", new BString("Hello World")); IBencodingType testResult = BencodingUtils.Decode(testString); Assert.AreEqual(testExpected, testResult); }
public void OnHandshake(IPeerWireClient peerWireClient, byte[] handshake) { BDict dict = (BDict)BencodingUtils.Decode(handshake); if (dict.ContainsKey("metadata_size")) { BInt size = (BInt)dict["metadata_size"]; this._metadataSize = size; this._pieceCount = (Int64)Math.Ceiling((double)this._metadataSize / 16384); } this.RequestMetaData(peerWireClient); }
public void EncodeDictionary() { BDict testDict = new BDict(); BString testString = new BString("Hello World"); BInt testInt = new BInt(5); testDict.Add("a", testString); testDict.Add("b", testInt); string test = BencodingUtils.EncodeString(testDict); Assert.AreEqual("d1:a11:Hello World1:bi5ee", test); }
public object VisitBDict(BDict node) { _bytes.Add((byte)BLiteral.StartDict); foreach (var pair in node.Value) { pair.Key.Accept(this); pair.Value.Accept(this); } _bytes.Add((byte)BLiteral.End); return(null); }
public LocalRequest NewRequest(BDict dict, CancellationToken cancellationToken = default) { LocalRequest result; lock (requests) { result = new LocalRequest(autoIndex++, dict, requestTimeout, cancellationToken); requests.Add(result); } result.CancellationTokenSource.Token.Register(() => { Pop(result.Index); result.Response.TrySetCanceled(result.CancellationTokenSource.Token); }); return(result); }
public void OnExtendedMessage(IPeerWireClient peerWireClient, byte[] bytes) { BDict dict = (BDict)BencodingUtils.Decode(bytes); if (dict.ContainsKey("added")) { var trackerList = (BList)dict["added"]; foreach (var tracker in trackerList) { TrackerAdded?.Invoke(peerWireClient, this, tracker.ToString()); } } }
public LocalRequest(ulong index, BDict request, TimeSpan timeout, CancellationToken cancellationToken) { Index = index; DateTime = DateTime.Now; Request = request; if (cancellationToken.CanBeCanceled) { CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(new CancellationTokenSource(timeout).Token, cancellationToken); } else { CancellationTokenSource = new CancellationTokenSource(timeout); } }
private async void HandleClient(Socket client) { try { using var stream = new NetworkStream(client, ownsSocket: true) { ReadTimeout = 5000, WriteTimeout = 5000, }; BDict dict = (BDict)await Bencode.DecodeAsync(stream, this.client.NetworkPrefix); await this.client.P2P.TcpServer_GetValue(stream, dict); } catch { } }
public static Torrent ReadTorrent(string filename) { // Читаем файл торрента и берем необходимый словарь info List <LostFile> files = new List <LostFile>(); BDict torrent = (BDict)BencodingUtils.DecodeFile(filename, Encoding.UTF8); BDict fileInfo = (BDict)torrent["info"]; string name = ((BString)fileInfo["name"]).Value; int pieceLength = (int)((BInt)fileInfo["piece length"]).Value; // Перечитываем торрент еще раз, чтобы взять хеш в нужном виде torrent = (BDict)BencodingUtils.DecodeFile(filename, Encoding.GetEncoding(437)); char[] pieces = ((BString)((BDict)torrent["info"])["pieces"]).Value.ToCharArray(); if (fileInfo.ContainsKey("files")) // Multifile torrent { BList filesData = (BList)fileInfo["files"]; long begin = 0; foreach (BDict file in filesData) { BList filePaths = (BList)file["path"]; long length = ((BInt)file["length"]).Value; string fullPath = name; foreach (BString partOfPath in filePaths) { fullPath += @"\" + partOfPath.Value; } files.Add(new LostFile(fullPath, length, begin)); begin += length; } } else // Singlefile torrent { long Length = ((BInt)fileInfo["length"]).Value; files.Add(new LostFile(name, Length, 0)); } return(new Torrent(name, files, pieceLength, pieces, filename)); }
public void OnExtendedMessage(IPeerWireClient peerWireClient, byte[] bytes) { BDict d = (BDict)BencodingUtils.Decode(bytes); if (d.ContainsKey("added") && d.ContainsKey("added.f")) { BString pexList = (BString)d["added"]; BString pexFlags = (BString)d["added.f"]; for (int i = 0; i < pexList.ByteValue.Length / 6; i++) { UInt32 ip = Unpack.UInt32(pexList.ByteValue, i * 6, Unpack.Endianness.Little); UInt16 port = Unpack.UInt16(pexList.ByteValue, (i * 6) + 4, Unpack.Endianness.Big); byte flags = pexFlags.ByteValue[i]; IPEndPoint ipAddr = new IPEndPoint(ip, port); if (Added != null) { Added(peerWireClient, this, ipAddr, flags); } } } if (d.ContainsKey("dropped")) { BString pexList = (BString)d["dropped"]; for (int i = 0; i < pexList.ByteValue.Length / 6; i++) { UInt32 ip = Unpack.UInt32(pexList.ByteValue, i * 6, Unpack.Endianness.Little); UInt16 port = Unpack.UInt16(pexList.ByteValue, (i * 6) + 4, Unpack.Endianness.Big); IPEndPoint ipAddr = new IPEndPoint(ip, port); if (Dropped != null) { Dropped(peerWireClient, this, ipAddr); } } } }
static Torrent Parse(BDict dict) { var info = dict["info"] as BDict; var torrent = new Torrent(); if(info.ContainsKey("files")) { var files = info["files"] as BList; torrent.Files.AddRange(files.Cast<BDict>().Select(f => new TorrentInfoFile { Path = ((f["path"] as BList).First() as BString).Value, Length = (f["length"] as BInt).Value })); } else { torrent.Files.Add(new TorrentInfoFile { Path = (info["name"] as BString).Value, Length = (info["length"] as BInt).Value }); } return torrent; }
public void OnExtendedMessage(IPeerWireClient peerWireClient, byte[] bytes) { BDict dictionary = (BDict)BencodingUtils.Decode(bytes); if (!dictionary.ContainsKey(ADDED_KEY) && !dictionary.ContainsKey(ADDED_FLAGS_KEY) && !dictionary.ContainsKey(DROPPED_KEY)) { return; } if (dictionary.ContainsKey(ADDED_KEY) && dictionary.ContainsKey(ADDED_FLAGS_KEY)) { var pexList = (BString)dictionary[ADDED_KEY]; var pexFlags = (BString)dictionary[ADDED_FLAGS_KEY]; for (int i = 0; i < pexList.ByteValue.Length / 6; i++) { var ip = Unpack.UInt32(pexList.ByteValue, i * 6, Unpack.Endianness.Little); var port = Unpack.UInt16(pexList.ByteValue, (i * 6) + 4, Unpack.Endianness.Big); var flags = pexFlags.ByteValue[i]; var ipAddr = new IPEndPoint(ip, port); Added?.Invoke(peerWireClient, this, ipAddr, flags); } } else //if (d.ContainsKey(DROPPED_KEY)) { BString pexList = (BString)dictionary[DROPPED_KEY]; for (int i = 0; i < pexList.ByteValue.Length / 6; i++) { var ip = Unpack.UInt32(pexList.ByteValue, i * 6, Unpack.Endianness.Little); var port = Unpack.UInt16(pexList.ByteValue, (i * 6) + 4, Unpack.Endianness.Big); var ipAddr = new IPEndPoint(ip, port); Dropped?.Invoke(peerWireClient, this, ipAddr); } } }
public void SendMessage(IPeerWireClient peerWireClient, IPEndPoint[] addedEndPoints, byte[] flags, IPEndPoint[] droppedEndPoints) { if (addedEndPoints == null && droppedEndPoints == null) { return; } BDict d = new BDict(); if (addedEndPoints != null) { byte[] added = new byte[addedEndPoints.Length * 6]; for (int x = 0; x < addedEndPoints.Length; x++) { addedEndPoints[x].Address.GetAddressBytes().CopyTo(added, x * 6); BitConverter.GetBytes((ushort)addedEndPoints[x].Port).CopyTo(added, (x * 6) + 4); } d.Add("added", new BString { ByteValue = added }); } if (droppedEndPoints != null) { byte[] dropped = new byte[droppedEndPoints.Length * 6]; for (int x = 0; x < droppedEndPoints.Length; x++) { droppedEndPoints[x].Address.GetAddressBytes().CopyTo(dropped, x * 6); dropped.SetValue((ushort)droppedEndPoints[x].Port, (x * 6) + 2); } d.Add("dropped", new BString { ByteValue = dropped }); } _parent.SendExtended(peerWireClient, _parent.GetOutgoingMessageID(peerWireClient, this), BencodingUtils.EncodeBytes(d)); }
public bool OnHandshake(IPeerWireClient client) { BDict handshakeDict = new BDict(); BDict mDict = new BDict(); byte i = 1; foreach (IBTExtension extension in _protocolExtensions) { _extOutgoing.Add(new ClientProtocolIDMap(client, extension.Protocol, i)); mDict.Add(extension.Protocol, new BInt(i)); i++; } handshakeDict.Add("m", mDict); String handshakeEncoded = BencodingUtils.EncodeString(handshakeDict); byte[] handshakeBytes = Encoding.ASCII.GetBytes(handshakeEncoded); Int32 length = 2 + handshakeBytes.Length; client.SendBytes((new byte[0]).Cat(Pack.Int32(length, Pack.Endianness.Big).Cat(new[] { (byte)20 }).Cat(new[] { (byte)0 }).Cat(handshakeBytes))); return true; }
public void OnExtendedMessage(IPeerWireClient peerWireClient, byte[] bytes) { Int32 startAt = 0; BencodingUtils.Decode(bytes, ref startAt); this._piecesReceived += 1; if (this._pieceCount >= this._piecesReceived) { this._metadataBuffer = this._metadataBuffer.Concat(bytes.Skip(startAt)).ToArray(); } if (this._pieceCount == this._piecesReceived) { BDict metadata = (BDict)BencodingUtils.Decode(this._metadataBuffer); if (MetaDataReceived != null) { MetaDataReceived(peerWireClient, this, metadata); } } }
public void EqualityDict() { // Make initial dict BDict testDict = new BDict(); BString testString = new BString("Hello World"); BInt testInt = new BInt(5); testDict.Add("a", testString); testDict.Add("b", testInt); // Make test dict BDict testDict2 = new BDict(); BString testString2 = new BString("Hello World"); BInt testInt2 = new BInt(5); testDict2.Add("a", testString2); testDict2.Add("b", testInt2); // Test equality recursive Assert.AreEqual(testDict, testDict2); // Test null dict BDict nullDict = null; Assert.IsFalse(testDict.Equals(nullDict)); // Test different counts testDict2.Add("c", new BInt(10)); Assert.IsFalse(testDict.Equals(testDict2)); // Test different values testDict.Add("c", new BInt(9)); Assert.IsFalse(testDict.Equals(testDict2)); // Test missing keys testDict2.Remove("c"); testDict2.Add("d", new BInt(9)); Assert.IsFalse(testDict.Equals(testDict2)); }
public float GetTorrentSize(string p) { long length = 0; BDict torrentFile = null; BList b; try { torrentFile = BencodingUtils.DecodeFile(p) as BDict; } catch (Exception e) { Tool.MoveFile("decodeErr", p); return(0); } if (torrentFile == null) { Tool.MoveFile("decodeErr", p); return(0); } if ((torrentFile["info"] as BDict).ContainsKey("files")) { b = (BList)(torrentFile["info"] as BDict)["files"]; for (int i = 0; i < b.Count; i++) { BDict bd = (BDict)b[i]; length = length + ((BInt)bd["length"]).Value; } } else { length = ((BInt)(torrentFile["info"] as BDict)["length"]).Value; } return(length / 1024 / 1024); }
public bool OnHandshake(IPeerWireClient client) { var handshakeDict = new BDict(); var mDict = new BDict(); byte i = 1; foreach (var extension in _protocolExtensions) { _extOutgoing.Add(new ClientProtocolIDMap(client, extension.Protocol, i)); mDict.Add(extension.Protocol, new BInt(i)); i++; } handshakeDict.Add("m", mDict); var handshakeEncoded = BencodingUtils.EncodeString(handshakeDict); var handshakeBytes = Encoding.ASCII.GetBytes(handshakeEncoded); var length = 2 + handshakeBytes.Length; client.SendBytes((new byte[0]).Cat(Pack.Int32(length, Pack.Endianness.Big).Cat(new[] { (byte)20 }).Cat(new[] { (byte)0 }).Cat(handshakeBytes))); return(true); }
public bool OnHandshake(IPeerWireClient client) { BDict handshakeDict = new BDict(); BDict mDict = new BDict(); byte i = 1; foreach (IBTExtension extension in this._protocolExtensions) { this._extOutgoing.Add(new ClientProtocolIDMap(client, extension.Protocol, i)); mDict.Add(extension.Protocol, new BInt(i)); i++; } handshakeDict.Add("m", mDict); string handshakeEncoded = BencodingUtils.EncodeString(handshakeDict); byte[] handshakeBytes = Encoding.ASCII.GetBytes(handshakeEncoded); Int32 length = 2 + handshakeBytes.Length; client.SendBytes((new byte[0]).Cat(PackHelper.Int32(length).Cat(new[] { (byte)20 }).Cat(new[] { (byte)0 }).Cat(handshakeBytes))); return(true); }
public void RequestMetaData(IPeerWireClient peerWireClient) { byte[] sendBuffer = new byte[0]; for (Int32 i = 0; i < _pieceCount; i++) { BDict masterBDict = new BDict { {"msg_type", (BInt) 0}, {"piece", (BInt) i} }; String encoded = BencodingUtils.EncodeString(masterBDict); byte[] buffer = Pack.Int32(2 + encoded.Length, Pack.Endianness.Big); buffer = buffer.Concat(new byte[] {20}).ToArray(); buffer = buffer.Concat(new[] { _parent.GetOutgoingMessageID(peerWireClient, this) }).ToArray(); buffer = buffer.Concat(Encoding.GetEncoding(1252).GetBytes(encoded)).ToArray(); sendBuffer = sendBuffer.Concat(buffer).ToArray(); } peerWireClient.SendBytes(sendBuffer); }
public void RequestMetaData(IPeerWireClient peerWireClient) { byte[] sendBuffer = new byte[0]; for (Int32 i = 0; i < this._pieceCount; i++) { BDict masterBDict = new BDict { { "msg_type", (BInt)0 }, { "piece", (BInt)i } }; string encoded = BencodingUtils.EncodeString(masterBDict); byte[] buffer = PackHelper.Int32(2 + encoded.Length); buffer = buffer.Concat(new byte[] { 20 }).ToArray(); buffer = buffer.Concat(new[] { this._parent.GetOutgoingMessageID(peerWireClient, this) }).ToArray(); buffer = buffer.Concat(Encoding.GetEncoding(1252).GetBytes(encoded)).ToArray(); sendBuffer = sendBuffer.Concat(buffer).ToArray(); } peerWireClient.SendBytes(sendBuffer); }
public void RequestMetaData(IPeerWireClient peerWireClient) { var sendBuffer = new byte[0]; for (Int32 i = 0; i < _pieceCount; i++) { var masterBDict = new BDict { { MESSAGE_TYPE_KEY, (BInt)0 }, { PIECE_KEY, (BInt)i } }; var encoded = BencodingUtils.EncodeString(masterBDict); var buffer = Pack.Int32(2 + encoded.Length, Pack.Endianness.Big); buffer = buffer.Concat(new byte[] { 20 }).ToArray(); buffer = buffer.Concat(new[] { _parent.GetOutgoingMessageID(peerWireClient, this) }).ToArray(); buffer = buffer.Concat(Encoding.GetEncoding(1252).GetBytes(encoded)).ToArray(); sendBuffer = sendBuffer.Concat(buffer).ToArray(); } peerWireClient.SendBytes(sendBuffer); }
public bool Load(Stream stream) { _root = BencodingUtils.Decode(stream); if (_root == null) { return(false); } BDict dictRoot = (_root as BDict); if (dictRoot == null) { return(false); } if (dictRoot.ContainsKey("announce")) { Announce = (BString)dictRoot["announce"]; } if (dictRoot.ContainsKey("announce-list")) { BList announceList = (BList)dictRoot["announce-list"]; foreach (IBencodingType type in announceList) { if (type is BString) { AnnounceList.Add(type as BString); } else { BList list = type as BList; if (list == null) { continue; } BList listType = list; foreach (IBencodingType bencodingType in listType) { BString s = (BString)bencodingType; AnnounceList.Add(s); } } } } if (dictRoot.ContainsKey("comment")) { Comment = (BString)dictRoot["comment"]; } if (dictRoot.ContainsKey("created by")) { CreatedBy = (BString)dictRoot["created by"]; } if (dictRoot.ContainsKey("creation date")) { long ts = (BInt)dictRoot["creation date"]; CreationDate = new DateTime(1970, 1, 1).AddSeconds(ts); } if (dictRoot.ContainsKey("info")) { BDict infoDict = (BDict)dictRoot["info"]; using (SHA1Managed sha1 = new SHA1Managed()) { byte[] str = BencodingUtils.EncodeBytes(infoDict); Hash = sha1.ComputeHash(str); } if (infoDict.ContainsKey("files")) { //multi file mode BList fileList = (BList)infoDict["files"]; foreach (IBencodingType bencodingType in fileList) { BDict fileDict = (BDict)bencodingType; String filename = string.Empty; Int64 filesize = default(Int64); if (fileDict.ContainsKey("path")) { BList filenameList = (BList)fileDict["path"]; foreach (IBencodingType type in filenameList) { filename += (BString)type; filename += "\\"; } filename = filename.Trim('\\'); } if (fileDict.ContainsKey("length")) { filesize = (BInt)fileDict["length"]; } Files.Add(filename, filesize); } } if (infoDict.ContainsKey("name")) { Name = (BString)infoDict["name"]; if (Files.Count == 0 && infoDict.ContainsKey("length")) { Files.Add(Name, (BInt)infoDict["length"]); } } if (infoDict.ContainsKey("private")) { BInt isPrivate = (BInt)infoDict["private"]; Private = isPrivate != 0; } if (infoDict.ContainsKey("pieces")) { BString pieces = (BString)infoDict["pieces"]; for (int x = 0; x < pieces.ByteValue.Length; x += 20) { byte[] hash = pieces.ByteValue.GetBytes(x, 20); PieceHashes.Add(hash); } } if (infoDict.ContainsKey("piece length")) { PieceSize = (BInt)infoDict["piece length"]; } } return(true); }
private string getName(string torrentPath) { BDict torrentFile = BencodingUtils.DecodeFile(torrentPath) as BDict; return(((BString)((torrentFile["info"] as BDict)["name"])).Value); }
internal RemoteRequest(BDict request, IPEndPoint remote, in Bytes <Address> senderAddress)
internal RemoteRequest(BDict request, IPEndPoint remote, in Address senderAddress)
public static IBencodingType Decode(BinaryReader inputStream, ref int bytesConsumed) { IBencodingType returnValue = null; char next = (char)inputStream.PeekChar(); switch (next) { case 'i': // Integer returnValue = new BInt(0); break; case 'l': // List returnValue = new BList(); break; case 'd': // Dictionary returnValue = new BDict(); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // String returnValue = new BString(); break; } return returnValue.Decode(inputStream, ref bytesConsumed); }
public IDictionary <string, ScrapeInfo> Scrape(string url, string[] hashes) { Dictionary <String, ScrapeInfo> returnVal = new Dictionary <string, ScrapeInfo>(); String realUrl = url.Replace("announce", "scrape") + "?"; String hashEncoded = ""; foreach (String hash in hashes) { byte[] hashBytes = Pack.Hex(hash); hashEncoded = hashBytes.Aggregate(hashEncoded, (current, b) => current + String.Format("%{0:X2}", b)); realUrl += "info_hash=" + hashEncoded + "&"; } HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(realUrl); webRequest.Accept = "*/*"; webRequest.UserAgent = "System.Net.Torrent"; webRequest.Timeout = this.Timeout * 1000; HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); Stream stream = webResponse.GetResponseStream(); if (stream == null) { return(null); } BinaryReader binaryReader = new BinaryReader(stream); byte[] bytes = new byte[0]; while (true) { try { byte[] b = new byte[1]; b[0] = binaryReader.ReadByte(); bytes = bytes.Concat(b).ToArray(); } catch (Exception) { break; } } BDict decoded = (BDict)BencodingUtils.Decode(bytes); if (decoded.Count == 0) { return(null); } if (!decoded.ContainsKey("files")) { return(null); } BDict bDecoded = (BDict)decoded["files"]; foreach (String k in bDecoded.Keys) { BDict d = (BDict)bDecoded[k]; if (d.ContainsKey("complete") && d.ContainsKey("downloaded") && d.ContainsKey("incomplete")) { String rk = Unpack.Hex(BencodingUtils.ExtendedASCIIEncoding.GetBytes(k)); returnVal.Add(rk, new ScrapeInfo((uint)((BInt)d["complete"]).Value, (uint)((BInt)d["downloaded"]).Value, (uint)((BInt)d["incomplete"]).Value, ScraperType.HTTP)); } } return(returnVal); }
public SuperEventArgs(NetworkStream stream, BDict dict, SuperNode node) { Stream = stream; Dict = dict; Node = node; }
public GetValueEventArgs(BDict dict, NetworkStream?stream) { Dict = dict; Stream = stream; }
public void BDictAddNullKey() { BDict dict = new BDict(); dict.Add(null, new BInt(0)); }
public void BDictAddNullValue() { BDict dict = new BDict(); dict.Add("a", null); }
/// <summary> /// Background thread handling all incoming traffic /// </summary> private void ReceivePackets() { while (true) { try { // Get a datagram receiveFrom = new IPEndPoint(IPAddress.Any, localPort); // Stopwatch sw = new Stopwatch(); // sw.Start(); byte[] data = udpClientReceive.Receive(ref receiveFrom); //if (sw.ElapsedMilliseconds > 10) { Console.WriteLine(sw.ElapsedMilliseconds); } //sw.Stop(); // Decode the message Stream stream = new MemoryStream(data); IBencodingType receivedMsg = BencodingUtils.Decode(stream); string decoded = BencodingUtils.ExtendedASCIIEncoding.GetString(data.ToArray()); //Log("Received message!"); // t is transaction id // y is e for error, r for reply, q for query if (receivedMsg is BDict) // throws error.. todo: fix { BDict dictMsg = (BDict)receivedMsg; if (dictMsg.ContainsKey("y")) { if (dictMsg["y"].Equals(new BString("e"))) { //Log("Received error! (ignored)"); } else if (dictMsg["y"].Equals(new BString("r"))) { // received reply if (dictMsg.ContainsKey("r")) { if (dictMsg["r"] is BDict) { BDict dictMsg2 = (BDict)dictMsg["r"]; if (dictMsg2.ContainsKey("values")) { //Log("Received list of peers for torrent!"); countRecvPeerPackets++; } else if (dictMsg2.ContainsKey("nodes")) { // could be an answer to find node or get peers //Log("Received list of nodeID & IP & port!"); countRecvNodePackets++; BString nodeIDString = (BString)dictMsg2["nodes"]; UpdateContactList(nodeIDString); } else { // no values and no nodes, assuming its a ping, // at least some form of response } } else { } } } else if (dictMsg["y"].Equals(new BString("q"))) { // received query countRecvQuery++; //Log("Received query! (ignored)"); } } } } catch (Exception ex) { //Log("Error receiving data: " + ex.ToString()); } } }
/// <summary> /// Background thread handling all incoming traffic /// </summary> private void ReceivePackets() { while (true) { try { // Get a datagram receiveFrom = new IPEndPoint(IPAddress.Any, localPort); byte[] data = udpClient.Receive(ref receiveFrom); // Decode the message Stream stream = new MemoryStream(data); IBencodingType receivedMsg = BencodingUtils.Decode(stream); string decoded = BencodingUtils.ExtendedASCIIEncoding.GetString(data.ToArray()); Log("Received message!"); //Log(decoded); // t is transaction id : todo: check, since ports are reused // y is e for error, r for reply, q for query if (receivedMsg is BDict) // throws error.. todo: fix { BDict dictMsg = (BDict)receivedMsg; if (dictMsg.ContainsKey("y")) { if (dictMsg["y"].Equals(new BString("e"))) { // received error Log("Received error! (ignored)"); } else if (dictMsg["y"].Equals(new BString("r"))) { // received reply if (dictMsg.ContainsKey("r")) { if (dictMsg["r"] is BDict) { BDict dictMsg2 = (BDict)dictMsg["r"]; if (dictMsg2.ContainsKey("values") && dictMsg.ContainsKey("t")) { Log("Received list of peers for torrent!"); countRecvPeerPackets++; BList peerAdrs = (BList)dictMsg2["values"]; UpdateTorrentPeerList(peerAdrs, (BString)dictMsg["t"]); } else if (dictMsg2.ContainsKey("nodes") && dictMsg.ContainsKey("t")) { // could be an answer to find node or get peers Log("Received list of nodeID & IP & port!"); countRecvNodePackets++; BString nodeIDString = (BString)dictMsg2["nodes"]; UpdateContactList(nodeIDString, (BString)dictMsg["t"]); } else { } } else { } } } else if (dictMsg["y"].Equals(new BString("q"))) { // received query Log("Received query! (ignored)"); } } } } catch (Exception ex) { Log("Error receiving data: " + ex.ToString()); } } }
public AnnounceInfo Announce(string url, string hash, string peerId, long bytesDownloaded, long bytesLeft, long bytesUploaded, int eventTypeFilter, int ipAddress, int numWant, int listenPort, int extensions) { byte[] hashBytes = Pack.Hex(hash); byte[] peerIdBytes = Encoding.ASCII.GetBytes(peerId); String realUrl = url.Replace("scrape", "announce") + "?"; String hashEncoded = ""; foreach (byte b in hashBytes) { hashEncoded += String.Format("%{0:X2}", b); } String peerIdEncoded = ""; foreach (byte b in peerIdBytes) { peerIdEncoded += String.Format("%{0:X2}", b); } realUrl += "info_hash=" + hashEncoded; realUrl += "&peer_id=" + peerIdEncoded; realUrl += "&port=" + listenPort; realUrl += "&uploaded=" + bytesUploaded; realUrl += "&downloaded=" + bytesDownloaded; realUrl += "&left=" + bytesLeft; realUrl += "&event=started"; realUrl += "&compact=1"; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(realUrl); webRequest.Accept = "*/*"; webRequest.UserAgent = "System.Net.Torrent"; HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); Stream stream = webResponse.GetResponseStream(); if (stream == null) { return(null); } BinaryReader binaryReader = new BinaryReader(stream); byte[] bytes = new byte[0]; while (true) { try { byte[] b = new byte[1]; b[0] = binaryReader.ReadByte(); bytes = bytes.Concat(b).ToArray(); } catch (Exception) { break; } } BDict decoded = (BDict)BencodingUtils.Decode(bytes); if (decoded.Count == 0) { return(null); } if (!decoded.ContainsKey("peers")) { return(null); } if (!(decoded["peers"] is BString)) { throw new NotSupportedException("Dictionary based peers not supported"); } Int32 waitTime = 0; Int32 seeders = 0; Int32 leachers = 0; if (decoded.ContainsKey("interval")) { waitTime = (BInt)decoded["interval"]; } if (decoded.ContainsKey("complete")) { seeders = (BInt)decoded["complete"]; } if (decoded.ContainsKey("incomplete")) { leachers = (BInt)decoded["incomplete"]; } BString peerBinary = (BString)decoded["peers"]; return(new AnnounceInfo(GetPeers(peerBinary.ByteValue), waitTime, seeders, leachers)); }