コード例 #1
0
        private void ProcessExtended(IPeerWireClient client, int commandLength, byte[] payload)
        {
            Int32 msgId = payload[0];

            var buffer = payload.GetBytes(1, commandLength - 1);

            if (msgId == 0)
            {
                var extendedHandshake = (BDict)BencodingUtils.Decode(buffer);

                var mDict = (BDict)extendedHandshake["m"];
                foreach (KeyValuePair <string, IBencodingType> pair in mDict)
                {
                    var i = (BInt)pair.Value;
                    _extIncoming.Add(new ClientProtocolIDMap(client, pair.Key, (byte)i));

                    var ext = FindIBTExtensionByProtocol(pair.Key);
                    ext?.OnHandshake(client, buffer);
                }
            }
            else
            {
                var protocol = FindIBTProtocolByMessageID(msgId);
                var ext      = FindIBTExtensionByProtocol(protocol);
                ext?.OnExtendedMessage(client, buffer);
            }
        }
コード例 #2
0
        public void OnHandshake(IPeerWireClient peerWireClient, byte[] handshake)
        {
            var dict = (BDict)BencodingUtils.Decode(handshake);

            if (dict.ContainsKey(METADATA_SIZE_KEY))
            {
                var size = (BInt)dict[METADATA_SIZE_KEY];
                _metadataSize = size;
                _pieceCount   = (Int64)Math.Ceiling((double)_metadataSize / 16384);
            }

            RequestMetaData(peerWireClient);
        }
コード例 #3
0
        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);
        }
コード例 #4
0
        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());
                }
            }
        }
コード例 #5
0
        public void OnExtendedMessage(IPeerWireClient peerWireClient, byte[] bytes)
        {
            Int32 startAt = 0;

            BencodingUtils.Decode(bytes, ref startAt);
            _piecesReceived += 1;

            if (_pieceCount >= _piecesReceived)
            {
                _metadataBuffer = _metadataBuffer.Concat(bytes.Skip(startAt)).ToArray();
            }

            if (_pieceCount == _piecesReceived)
            {
                var metadata = (BDict)BencodingUtils.Decode(_metadataBuffer);

                MetaDataReceived?.Invoke(peerWireClient, this, metadata);
            }
        }
コード例 #6
0
        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);
                    }
                }
            }
        }
コード例 #7
0
        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));
        }
コード例 #8
0
        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);
                }
            }
        }
コード例 #9
0
        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);
                }
            }
        }
コード例 #10
0
ファイル: BaseAnalysis.cs プロジェクト: cl456852/videoFilter
        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);
        }
コード例 #11
0
        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);
        }
コード例 #12
0
        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);
        }
コード例 #13
0
        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);
        }
コード例 #14
0
        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);
        }
コード例 #15
0
        public void process(string directoryStr, bool ifCheckHis)
        {
            string md5;

            if (md5Set.Count == 0)
            {
                getList();
            }
            startTime = DateTime.Now;
            String[] path = Directory.GetFiles(directoryStr, "*", SearchOption.TopDirectoryOnly);
            foreach (String p in path)
            {
                if (p.EndsWith(".torrent"))
                {
                    if (Path.GetFileNameWithoutExtension(p).ToLower().Contains(".sd."))
                    {
                        Tool.moveFile("SD", p);
                        continue;
                    }
                    md5 = GetMd5(p);
                    if (md5Set.Contains(md5))
                    {
                        Tool.moveFile("Md5Duplicate", p);
                        continue;
                    }
                    if (!Path.GetFileNameWithoutExtension(p).Replace("rarbg.to", "").Contains("."))
                    {
                        Tool.moveFile("invalid", p);
                    }
                    BDict torrentFile = null;
                    bool  hasBigFile  = false;
                    try
                    {
                        torrentFile = BencodingUtils.DecodeFile(p) as BDict;
                    }
                    catch (Exception e)
                    {
                        Tool.moveFile("decodeErr", p);
                    }
                    if (torrentFile != null)
                    {
                        bool              flag = true;
                        BList             b;
                        List <HisTorrent> listTorrent = new List <HisTorrent>();
                        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];
                                long  length = ((BInt)bd["length"]).Value;
                                if (length > 25 * 1024 * 1024)
                                {
                                    hasBigFile = true;
                                }
                                BList      list = (BList)bd["path"];
                                string     s    = ((BString)list[list.Count - 1]).Value;
                                HisTorrent trt  = new HisTorrent();
                                trt.CreateTime = DateTime.Now;
                                trt.Path       = p;
                                trt.Size       = length;
                                if (s.LastIndexOf('.') > 0)
                                {
                                    trt.File = s.Substring(0, s.LastIndexOf('.'));
                                    trt.Ext  = s.Substring(s.LastIndexOf('.'));
                                }
                                else
                                {
                                    trt.File = s;
                                }
                                listTorrent.Add(trt);
                                if (!check(trt, ifCheckHis))
                                {
                                    flag = false;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            hasBigFile = true;
                            HisTorrent trt = new HisTorrent();
                            trt.CreateTime = DateTime.Now;
                            trt.Path       = p;
                            trt.Size       = ((BInt)(torrentFile["info"] as BDict)["length"]).Value;
                            string name = ((BString)(torrentFile["info"] as BDict)["name"]).Value;
                            if (name.LastIndexOf('.') > 0)
                            {
                                trt.File = name.Substring(0, name.LastIndexOf('.'));
                                trt.Ext  = name.Substring(name.LastIndexOf('.'));
                            }
                            else
                            {
                                trt.File = name;
                            }
                            listTorrent.Add(trt);
                            if (!check(trt, ifCheckHis))
                            {
                                flag = false;
                            }
                        }
                        if (!hasBigFile)
                        {
                            Tool.moveFile("noBigFile", p);
                        }
                        if (flag && hasBigFile)
                        {
                            foreach (HisTorrent his in listTorrent)
                            {
                                if (his.Size > 60 * 1024 * 1024)
                                {
                                    if (ifCheckHis)
                                    {
                                        his.Md5 = md5;
                                        DBHelper.insertTorrent(his);
                                    }
                                    try
                                    {
                                        md5Set.Add(md5);
                                        dic.Add(Tool.filterName(his.File), his);
                                        torrentNameDic.Add(his.FilteredFileName, his);
                                    }catch (ArgumentException e)
                                    {
                                        dic.Remove(Tool.filterName(his.File));
                                        dic.Add(Tool.filterName(his.File), his);
                                        torrentNameDic.Remove(his.FilteredFileName);
                                        torrentNameDic.Add(his.FilteredFileName, his);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        Tool.moveFile("decodeErr", p);
                    }
                }
            }
        }
コード例 #16
0
 public void OnHandshake(IPeerWireClient peerWireClient, byte[] handshake)
 {
     var dictionary = (BDict)BencodingUtils.Decode(handshake);
 }
コード例 #17
0
        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));
        }
コード例 #18
0
        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));
        }
コード例 #19
0
        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);
        }
コード例 #20
0
        /// <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());
                }
            }
        }
コード例 #21
0
        public bool Load(Stream stream)
        {
            _root = BencodingUtils.Decode(stream);
            if (_root == null)
            {
                return(false);
            }

            var dictRoot = (_root as BDict);

            if (dictRoot == null)
            {
                return(false);
            }

            if (dictRoot.ContainsKey(ANNOUNCE_KEY))
            {
                Announce = (BString)dictRoot[ANNOUNCE_KEY];
            }

            if (dictRoot.ContainsKey(ANNOUNCE_LIST_KEY))
            {
                var announceList = (BList)dictRoot[ANNOUNCE_LIST_KEY];
                foreach (IBencodingType type in announceList)
                {
                    if (type is BString)
                    {
                        AnnounceList.Add(type as BString);
                    }
                    else
                    {
                        var list = type as BList;
                        if (list == null)
                        {
                            continue;
                        }

                        var listType = list;
                        foreach (IBencodingType bencodingType in listType)
                        {
                            var s = (BString)bencodingType;
                            AnnounceList.Add(s);
                        }
                    }
                }
            }

            if (dictRoot.ContainsKey(COMMENT_KEY))
            {
                Comment = (BString)dictRoot[COMMENT_KEY];
            }

            if (dictRoot.ContainsKey(CREATED_BY_KEY))
            {
                CreatedBy = (BString)dictRoot[CREATED_BY_KEY];
            }

            if (dictRoot.ContainsKey(CREATION_DATE_KEY))
            {
                long ts = (BInt)dictRoot[CREATION_DATE_KEY];
                CreationDate = new DateTime(1970, 1, 1).AddSeconds(ts);
            }

            if (dictRoot.ContainsKey(INFO_KEY))
            {
                var infoDict = (BDict)dictRoot[INFO_KEY];

                using (SHA1Managed sha1 = new SHA1Managed())
                {
                    var str = BencodingUtils.EncodeBytes(infoDict);
                    Hash = sha1.ComputeHash(str);
                }

                if (infoDict.ContainsKey(FILES_KEY))
                {
                    //multi file mode
                    var fileList = (BList)infoDict[FILES_KEY];
                    foreach (IBencodingType bencodingType in fileList)
                    {
                        var fileDict = (BDict)bencodingType;

                        var filename = string.Empty;
                        var filesize = default(Int64);

                        if (fileDict.ContainsKey(PATH_KEY))
                        {
                            var filenameList = (BList)fileDict[PATH_KEY];
                            foreach (IBencodingType type in filenameList)
                            {
                                filename += (BString)type;
                                filename += "\\";
                            }
                            filename = filename.Trim('\\');
                        }

                        if (fileDict.ContainsKey(LENGTH_KEY))
                        {
                            filesize = (BInt)fileDict[LENGTH_KEY];
                        }

                        Files.Add(filename, filesize);
                    }
                }

                if (infoDict.ContainsKey(NAME_KEY))
                {
                    Name = (BString)infoDict[NAME_KEY];
                    if (Files.Count == 0 && infoDict.ContainsKey(LENGTH_KEY))
                    {
                        Files.Add(Name, (BInt)infoDict[LENGTH_KEY]);
                    }
                }

                if (infoDict.ContainsKey(PRIVATE_KEY))
                {
                    var isPrivate = (BInt)infoDict[PRIVATE_KEY];
                    Private = isPrivate != 0;
                }

                if (infoDict.ContainsKey(PIECES_KEY))
                {
                    var pieces = (BString)infoDict[PIECES_KEY];
                    for (var x = 0; x < pieces.ByteValue.Length; x += 20)
                    {
                        var hash = pieces.ByteValue.GetBytes(x, 20);
                        PieceHashes.Add(hash);
                    }
                }

                if (infoDict.ContainsKey(PIECE_LENGTH_KEY))
                {
                    PieceSize = (BInt)infoDict[PIECE_LENGTH_KEY];
                }
            }

            return(true);
        }
コード例 #22
0
        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)
        {
            var hashBytes   = Pack.Hex(hash);
            var peerIdBytes = Encoding.ASCII.GetBytes(peerId);

            var realUrl = url.Replace("scrape", "announce") + "?";

            var hashEncoded = string.Empty;

            foreach (byte b in hashBytes)
            {
                hashEncoded += string.Format("%{0:X2}", b);
            }

            var peerIdEncoded = string.Empty;

            foreach (byte b in peerIdBytes)
            {
                peerIdEncoded += string.Format("%{0:X2}", b);
            }

            realUrl = BuildUrl(hashEncoded, peerIdEncoded, listenPort, bytesUploaded, bytesDownloaded, bytesLeft);

            var webRequest = (HttpWebRequest)WebRequest.Create(realUrl);

            webRequest.Accept    = "*/*";
            webRequest.UserAgent = $"{nameof(System)}.{nameof(Net)}.{nameof(Torrent)}";
            var webResponse = (HttpWebResponse)webRequest.GetResponse();

            var stream = webResponse.GetResponseStream();

            if (stream == null)
            {
                return(null);
            }

            var binaryReader = new BinaryReader(stream);

            var bytes = new byte[0];

            while (true)
            {
                try
                {
                    var b = new byte[1];
                    b[0]  = binaryReader.ReadByte();
                    bytes = bytes.Concat(b).ToArray();
                }
                catch (Exception)
                {
                    break;
                }
            }

            var decoded = (BDict)BencodingUtils.Decode(bytes);

            if (decoded.Count == 0)
            {
                return(null);
            }

            if (!decoded.ContainsKey(PEERS_KEY))
            {
                return(null);
            }

            if (!(decoded[PEERS_KEY] is BString))
            {
                throw new NotSupportedException("Dictionary based peers not supported");
            }

            var waitTime = 0;
            var seeders  = 0;
            var leachers = 0;

            if (decoded.ContainsKey(INTERVAL_KEY))
            {
                waitTime = (BInt)decoded[INTERVAL_KEY];
            }

            if (decoded.ContainsKey(COMPLETE_KEY))
            {
                seeders = (BInt)decoded[COMPLETE_KEY];
            }

            if (decoded.ContainsKey(INCOMPLETE_KEY))
            {
                leachers = (BInt)decoded[INCOMPLETE_KEY];
            }

            var peerBinary = (BString)decoded[PEERS_KEY];

            return(new AnnounceInfo(GetPeers(peerBinary.ByteValue), waitTime, seeders, leachers));
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: cl456852/torrentFilter
 void BencodeTest()
 {
     BDict torrentFile = BencodingUtils.DecodeFile(@"E:\Program Files (x86)\BitSpirit\Torrent - 副本\51C2F0FB04B2EFD2.torrent") as BDict;
 }
コード例 #24
0
        public IDictionary <string, ScrapeInfo> Scrape(string url, string[] hashes)
        {
            var returnVal = new Dictionary <string, ScrapeInfo>();

            var realUrl = url.Replace("announce", "scrape") + "?";

            var hashEncoded = string.Empty;

            foreach (string hash in hashes)
            {
                var hashBytes = Pack.Hex(hash);

                hashEncoded = hashBytes.Aggregate(hashEncoded, (current, b) => current + string.Format("%{0:X2}", b));

                realUrl += $"info_hash={hashEncoded}&";
            }

            var webRequest = (HttpWebRequest)WebRequest.Create(realUrl);

            webRequest.Accept    = "*/*";
            webRequest.UserAgent = $"{nameof(System)}.{nameof(Net)}.{nameof(Torrent)}";
            var webResponse = (HttpWebResponse)webRequest.GetResponse();

            var stream = webResponse.GetResponseStream();

            if (stream == null)
            {
                return(null);
            }

            var binaryReader = new BinaryReader(stream);

            var bytes = new byte[0];

            while (true)
            {
                try
                {
                    var b = new byte[1];
                    b[0]  = binaryReader.ReadByte();
                    bytes = bytes.Concat(b).ToArray();
                }
                catch (Exception)
                {
                    break;
                }
            }

            var decoded = (BDict)BencodingUtils.Decode(bytes);

            if (decoded.Count == 0)
            {
                return(null);
            }

            if (!decoded.ContainsKey(FILES_KEY))
            {
                return(null);
            }

            var bDecoded = (BDict)decoded[FILES_KEY];

            foreach (var k in bDecoded.Keys)
            {
                var dictionary = (BDict)bDecoded[k];

                if (dictionary.ContainsKey(COMPLETE_KEY) && dictionary.ContainsKey(DOWNLOADED_KEY) && dictionary.ContainsKey(INCOMPLETE_KEY))
                {
                    var rk = Unpack.Hex(BencodingUtils.ExtendedASCIIEncoding.GetBytes(k));
                    returnVal.Add(rk, new ScrapeInfo((uint)((BInt)dictionary[COMPLETE_KEY]).Value, (uint)((BInt)dictionary[DOWNLOADED_KEY]).Value, (uint)((BInt)dictionary[INCOMPLETE_KEY]).Value, ScraperType.HTTP));
                }
            }

            return(returnVal);
        }
コード例 #25
0
        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);
        }
コード例 #26
0
ファイル: Form1.cs プロジェクト: cl456852/MoveFile
        private string getName(string torrentPath)
        {
            BDict torrentFile = BencodingUtils.DecodeFile(torrentPath) as BDict;

            return(((BString)((torrentFile["info"] as BDict)["name"])).Value);
        }
コード例 #27
0
        /// <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());
                }
            }
        }