Exemplo n.º 1
0
        public static Torrent LoadFromFile(string filePath, string downloadPath)
        {
            var obj  = BEncoding.DecodeFile(filePath);
            var name = Path.GetFileNameWithoutExtension(filePath);

            return(BEncodingObjectToTorrent(obj, name, downloadPath));
        }
Exemplo n.º 2
0
        public void DecodeExistingFile()
        {
            BEncoding          decoding = new BEncoding(Tools.GetTestDataFilePath("ubuntu-15.04-desktop-amd64.iso.torrent"));
            BEncodedDictionary values   = (BEncodedDictionary)decoding.Decode();

            Assert.AreEqual("http://torrent.ubuntu.com:6969/announce", values["announce"].ToString());
        }
Exemplo n.º 3
0
        private void DecodeByteArray_ReturnTrue()
        {
            var testcase      = "5:hello";
            var bytes         = GetBytes(testcase);
            var decodedResult = BEncoding.DecodeNextObject(GetIterator(bytes)) as byte[];
            var decodedStr    = GetString(decodedResult);

            Debug.Assert(decodedStr == "hello");
        }
Exemplo n.º 4
0
        /// <summary>
        /// Charge un torrent depuis un fichier
        /// </summary>
        /// <param name="path"></param>
        public Torrent(string path) : this()
        {
            BEncoding decoding = new BEncoding(path);

            _data = (BEncodedDictionary)decoding.Decode();

            //charge le torrent depuis les données récupérés
            LoadTorrent();
        }
Exemplo n.º 5
0
 private static CBORObject EncodingFromBytes(byte[] b)
 {
     try {
         using (var s = new MemoryStream(b)) {
             return(BEncoding.Read(s));
         }
     } catch (IOException ex) {
         throw new CBORException(String.Empty, ex);
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Saves this torrent information to a file on disk.
        /// </summary>
        /// <param name="filePath">The path to the file to create.</param>
        public void SaveToFile(string filePath)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }

            var torrentInfo = Save();

            BEncoding.EncodeToFile(torrentInfo, filePath);
        }
Exemplo n.º 7
0
 public void CheckFileTypeTorrent()
 {
     try {
         BEncoding encoding = new BEncoding("fichierquiexistepas.torrent");
         Assert.Fail("An exception should have been thrown");
     } catch (FileNotFoundException ex) {
         Assert.AreEqual("The given file was not found.", ex.Message);
     } catch (Exception ex) {
         Assert.Fail(string.Format("Unexpected exception of type {0} caught: {1}", ex.GetType(), ex.Message));
     }
 }
Exemplo n.º 8
0
        private void DecodeInt_ReturnTrue()
        {
            var testcase = 2331;
            var bytes    = GetBytes($"i{testcase}e");
            var resObj   = BEncoding.DecodeNextObject(GetIterator(bytes));

            Debug.Assert(resObj is long);
            var intVal = (long)resObj;

            Debug.Assert(intVal == 2331);
        }
Exemplo n.º 9
0
        private static InfoHash ComputeInfoHash(BEncoding.Dictionary info)
        {
            using (var stream = new MemoryStream())
            {
                BEncoding.Encode(info, stream);

                stream.Seek(0L, SeekOrigin.Begin);
                byte[] hash = HashHelper.ComputeSHA1(stream);
                return(new InfoHash(hash));
            }
        }
Exemplo n.º 10
0
 private static byte[] EncodingToBytes(CBORObject b)
 {
     try {
         using (var ms = new MemoryStream()) {
             BEncoding.Write(b, ms);
             return(ms.ToArray());
         }
     } catch (IOException ex) {
         throw new CBORException(String.Empty, ex);
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Makes an announce request to this tracker.
        /// </summary>
        /// <param name="request">The announce request object.</param>
        /// <returns>The announce response.</returns>
        public override async Task <AnnounceResponse> Announce(AnnounceRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            // Check if announces are allowed
            if (announceUri == null)
            {
                return(null);
            }

            try
            {
                Uri    uri           = request.GetUri(announceUri, key, trackerID);
                byte[] responseBytes = await client.GetByteArrayAsync(uri).ConfigureAwait(false);

                Stats.IncreaseDownloadedBytes(responseBytes.Length);
                var info = BEncoding.Decode(responseBytes) as BEncoding.Dictionary;
                if (info == null)
                {
                    status         = TrackerStatus.InvalidResponse;
                    failureMessage = "The tracker returned an invalid announce response.";
                    return(null);
                }

                var announceResponse = HandleAnnounceResponse(info);
                if (announceResponse == null)
                {
                    status         = TrackerStatus.InvalidResponse;
                    failureMessage = "The tracker returned an invalid announce response.";
                    return(null);
                }

                failureMessage = announceResponse.FailureReason;
                warningMessage = announceResponse.WarningMessage;
                status         = TrackerStatus.OK;
                return(announceResponse);
            }
            catch (HttpRequestException ex)
            {
                status         = TrackerStatus.Offline;
                failureMessage = string.Format("Failed to perform announce request: {0}", ex.Message);
                return(null);
            }
            catch (Exception ex)
            {
                status         = TrackerStatus.InvalidResponse;
                failureMessage = string.Format("Exception performing announce request: {0}", ex.Message);
                return(null);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Makes a scrape request to this tracker.
        /// </summary>
        /// <param name="infoHashes">The optional array of info hashes. Can be null or empty.</param>
        /// <returns>The announce response.</returns>
        public override async Task <ScrapeResponse> Scrape(InfoHash[] infoHashes)
        {
            if (infoHashes == null)
            {
                throw new ArgumentNullException("infoHashes");
            }

            // Check if scrapes are allowed
            if (scrapeUri == null)
            {
                return(null);
            }

            try
            {
                var queryParameters = new KeyValuePair <string, object> [infoHashes.Length];
                for (int i = 0; i < infoHashes.Length; i++)
                {
                    queryParameters[i] = new KeyValuePair <string, object>("info_hash", infoHashes[i].ToUrlEncodedString());
                }

                var    uri           = UriHelper.AppendQueryString(scrapeUri, queryParameters);
                byte[] responseBytes = await client.GetByteArrayAsync(uri).ConfigureAwait(false);

                Stats.IncreaseDownloadedBytes(responseBytes.Length);
                var info = BEncoding.Decode(responseBytes) as BEncoding.Dictionary;
                if (info == null)
                {
                    failureMessage = "The tracker returned an invalid scrape response.";
                    return(null);
                }

                var scrapeResponse = HandleScrapeResponse(info);
                if (scrapeResponse == null)
                {
                    failureMessage = "The tracker returned an invalid scrape response.";
                    return(null);
                }

                return(scrapeResponse);
            }
            catch (HttpRequestException ex)
            {
                failureMessage = string.Format("Failed to perform scrape request: {0}", ex.Message);
                return(null);
            }
            catch (Exception ex)
            {
                failureMessage = string.Format("Exception performing scrape request: {0}", ex.Message);
                return(null);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Saves this torrent information to a stream.
        /// </summary>
        /// <param name="stream">The stream to save to.</param>
        public void SaveToStream(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            else if (!stream.CanWrite)
            {
                throw new ArgumentException("The stream cannot be written to.", "stream");
            }

            var torrentInfo = Save();

            BEncoding.Encode(torrentInfo, stream);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Loads torrent information from a torrent file on disk.
        /// </summary>
        /// <param name="filePath">The path to the torrent file.</param>
        public void LoadFromFile(string filePath)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }

            var torrentInfo = BEncoding.DecodeFromFile(filePath) as BEncoding.Dictionary;

            if (torrentInfo == null)
            {
                throw new InvalidDataException("The specified file does not appear to include torrent information.");
            }

            Load(torrentInfo);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Loads torrent information from a stream.
        /// </summary>
        /// <param name="stream">The stream to load the torrent from.</param>
        public void LoadFromStream(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            else if (!stream.CanRead)
            {
                throw new ArgumentException("The stream cannot be read from.", "stream");
            }

            var torrentInfo = BEncoding.Decode(stream) as BEncoding.Dictionary;

            if (torrentInfo == null)
            {
                throw new InvalidDataException("The specified file does not appear to include torrent information.");
            }

            Load(torrentInfo);
        }
Exemplo n.º 16
0
        private void DecodeDictionary_ReturnTrue()
        {
            var authorInfo = "i'am";
            var infoVal    = 331;
            var testcase   = $"d4:infoi{infoVal}e6:author{authorInfo.Length}:{authorInfo}";
            var bytes      = GetBytes(testcase);
            var result     = BEncoding.DecodeNextObject(GetIterator(bytes));

            Debug.Assert(result is IDictionary <string, object>);

            var dict = result as IDictionary <string, object>;

            Debug.Assert(dict.Keys.Contains("info"));
            Debug.Assert(dict.Keys.Contains("author"));
            Debug.Assert((long)dict["info"] == 331);

            var authorBytes  = GetBytes(authorInfo);
            var resultAuthor = (byte[])dict["author"];

            Debug.Assert(resultAuthor.Length == authorBytes.Length);
            Debug.Assert(authorBytes.SequenceEqual(resultAuthor));
        }
Exemplo n.º 17
0
 public void CheckFileTypeNotTorrent()
 {
     BEncoding encoding = new BEncoding("fichierquiexistepas.extension");
 }
Exemplo n.º 18
0
 public void CheckFileExists()
 {
     BEncoding encoding = new BEncoding("fichierquiexistepas.torrent");
 }
Exemplo n.º 19
0
        public static void SafeToFile(Torrent torrent)
        {
            var obj = TorrentToBEncodingObject(torrent);

            BEncoding.EncodeToFile(obj, $"{torrent.Name}.{TORRENT_EXTENSION_FILE}");
        }
Exemplo n.º 20
0
        /// <summary>
        ///
        /// </summary>
        public void Request()
        {
            string encoded_hash = Torrent.GetEncodedInfoHash();

            //construction de la requête vers le tracker
            StringBuilder builder = new StringBuilder(Tracker.Url);

            builder.AppendFormat("?info_hash={0}", encoded_hash);
            builder.Append("&peer_id=adkiepeycosozpsngtoi");
            builder.Append("&uploaded=0");
            builder.Append("&downloaded=0");
            builder.AppendFormat("&compact={0}", Compact ? 1 : 0);
            builder.Append("&left=120000");
            builder.Append("&event=started");
            builder.Append("&port=6881");

            //création de la requête GET
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(builder.ToString());

            request.Method = "GET";

            //envoi de la requête
            using (WebResponse response = request.GetResponse()) {
                //récupération de la réponse
                using (Stream stream = response.GetResponseStream()) {
                    using (var reader = new StreamReader(stream, Encoding.Default)) {
                        string responseText = reader.ReadToEnd();

                        byte[] data = Encoding.Default.GetBytes(responseText);

                        BEncoding          encoding   = new BEncoding(data);
                        BEncodedDictionary dictionary = (BEncodedDictionary)encoding.Decode();

                        Complete   = (BEncodedInteger)dictionary["complete"];
                        Incomplete = (BEncodedInteger)dictionary["incomplete"];
                        Interval   = (BEncodedInteger)dictionary["interval"];

                        // la liste des peers peut être soit une liste, soit une chaine simplifiée en big endian
                        if (dictionary["peers"] is BEncodedList)
                        {
                            BEncodedList peers = (BEncodedList)dictionary["peers"];
                        }
                        else if (dictionary["peers"] is BEncodedString)
                        {
                            byte[] peers = Encoding.Default.GetBytes((BEncodedString)dictionary["peers"]);

                            for (int i = 0; i < peers.Length; i = i + 6)
                            {
                                byte[] ip   = new byte[4];
                                byte[] port = new byte[2];

                                Array.Copy(peers, i, ip, 0, 4);
                                Array.Copy(peers, i + 4, port, 0, 2);
                                Array.Reverse(port);

                                IPEndPoint ipEndPoint = new IPEndPoint(new IPAddress(ip), BitConverter.ToUInt16(port, 0));

                                Peer peer = new Peer(ipEndPoint);
                                Peers.Add(peer);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 21
0
 public void CheckFilePathEmpty()
 {
     BEncoding encoding = new BEncoding(string.Empty);
 }
Exemplo n.º 22
0
 public void CheckDataEmpty()
 {
     BEncoding encoding = new BEncoding(new byte[0]);
 }
Exemplo n.º 23
0
        public Torrent(string name,
                       string downloadDir,
                       List <FileItem> files,
                       List <string> trackers,
                       int pieceSize,
                       byte[] pieceHashes = null,
                       int blockSize      = 16384,
                       bool?isPrivate     = false)
        {
            Name = name;
            DownloadDirectory = downloadDir;
            Files             = files;

            PieceSize = pieceSize;
            BlockSize = blockSize;
            IsPrivate = isPrivate;

            fileWriteLocks = new object[Files.Count];
            for (var i = 0; i < Files.Count; ++i)
            {
                fileWriteLocks[i] = new object();
            }

            if (trackers != null)
            {
                foreach (var url in trackers)
                {
                    var tracker = new Tracker(url);
                    Trackers.Add(tracker);
                    tracker.PeerListUpdated += HandlePeerListUpdated;
                }
            }

            var piecesCount = Convert.ToInt32(Math.Ceiling(TotalSize / Convert.ToDouble(PieceSize)));

            PieceHashes     = new byte[piecesCount][];
            IsPieceVerified = new bool[piecesCount];
            IsBlockAcquired = new bool[piecesCount][];

            for (var i = 0; i < PieceCount; ++i)
            {
                IsBlockAcquired[i] = new bool[GetBlockCount(i)];
            }

            if (pieceHashes != null)
            {
                for (var i = 0; i < PieceCount; ++i)
                {
                    PieceHashes[i] = GetHash(i);
                }
            }
            else
            {
                for (var i = 0; i < PieceCount; ++i)
                {
                    PieceHashes[i] = new byte[20];
                    Buffer.BlockCopy(pieceHashes, i * 20, PieceHashes[i], 0, 20);
                }
            }

            object info = TorrentInfoToBEncodingObject(this);

            byte[] bytes = BEncoding.Encode(info);
            InfoHash = SHA1.Create().ComputeHash(bytes);

            for (var i = 0; i < PieceCount; ++i)
            {
                CheckIntegrityOfPiece(i);
            }
        }