Example #1
0
        private void ParseBEncodeDict(MemoryStream responseStream)
        {
            BencodeParser bParser = new BencodeParser(Encoding.GetEncoding(1252));

            if ((ContentEncoding == "gzip") || (ContentEncoding == "x-gzip"))
            {
                using (GZipStream stream = new GZipStream(responseStream, CompressionMode.Decompress))
                {
                    try
                    {
                        Dico = bParser.Parse <BDictionary>(stream);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            try
            {
                Dico = bParser.Parse <BDictionary>(responseStream);
            }
            catch (Exception exception1)
            {
                Console.Write(exception1.StackTrace);
            }
        }
        private bool RestoreSessionIfPresent()
        {
            byte[][] sessions = FileWorker.LoadMainSession(out string[] fileNames);
            if (fileNames != null)
            {
                string lostFiles = "";
                for (int i = 0; i < fileNames.Length; i++)
                {
                    if (sessions[i] == null)
                    {
                        lostFiles += fileNames[i] + Environment.NewLine;
                    }
                }
                if (lostFiles != "")
                {
                    MessageBox.Show(this, "The following session files: " + lostFiles + "has been lost or corrupted", "Warning",
                                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                if (sessions != null)
                {
                    filesList = new LinkedList <DownloadingFile>();
                    for (int i = 0; i < sessions.GetLength(0); i++)
                    {
                        if (sessions[i] != null)
                        {
                            try
                            {
                                var    dictionary      = standardParser.Parse <BDictionary>(sessions[i]);
                                string rootSessionPath = Path.GetDirectoryName(fileNames[i]) +
                                                         Path.DirectorySeparatorChar;
                                Torrent newTorrent = OpenAndParse(rootSessionPath + dictionary.First().Key.ToString());
                                if (newTorrent != null)
                                {
                                    ParseSession(dictionary, newTorrent, rootSessionPath);
                                }
                            }
                            catch
                            {
                                MessageBox.Show(this, "This session file is corrupted and cannot be read:\r\n" +
                                                fileNames[i], "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    return(true);
                }
            }
            // no session files found OR all of them were corrupted
            return(false);
        }
Example #3
0
        // Initiates an HTTP request for the torrent
        // returns a tracker response dictionary containg info on all the peers
        public Connection(Torrent torrent)
        {
            url.Append(torrent.Trackers[0][0].ToString() + "?");

            string hash = torrent.GetInfoHash();

            hash = Formatter.HashToPercentEncoding(hash);

            string peerid = GeneratePeerID();
            string port   = GeneratePort();
            string left   = torrent.File.FileSize.ToString();

            url.Append("info_hash=" + hash + "&");
            url.Append("peer_id=" + peerid + "&");
            url.Append("port=" + port + "&");
            url.Append("left=" + left + "&");
            url.Append("uploaded=0&downloaded=0&compact=0&no_peer_id=&event=started");

            string URL = url.ToString();

            WebClient client = new WebClient();

            byte[] databuffer = client.DownloadData(URL);

            var parser = new BencodeParser();

            trackerResponse = parser.Parse <BDictionary>(databuffer);

            GetPeers();
        }
Example #4
0
        public async Task <HttpResponseMessage> Download(string indexerID, string path, string jackett_apikey, string file)
        {
            try
            {
                var indexer = indexerService.GetWebIndexer(indexerID);

                if (!indexer.IsConfigured)
                {
                    logger.Warn(string.Format("Rejected a request to {0} which is unconfigured.", indexer.DisplayName));
                    return(Request.CreateResponse(HttpStatusCode.Forbidden, "This indexer is not configured."));
                }

                path = Encoding.UTF8.GetString(HttpServerUtility.UrlTokenDecode(path));
                path = protectionService.UnProtect(path);

                if (config.APIKey != jackett_apikey)
                {
                    return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
                }

                var target        = new Uri(path, UriKind.RelativeOrAbsolute);
                var downloadBytes = await indexer.Download(target);

                // handle magnet URLs
                if (downloadBytes.Length >= 7 &&
                    downloadBytes[0] == 0x6d && // m
                    downloadBytes[1] == 0x61 && // a
                    downloadBytes[2] == 0x67 && // g
                    downloadBytes[3] == 0x6e && // n
                    downloadBytes[4] == 0x65 && // e
                    downloadBytes[5] == 0x74 && // t
                    downloadBytes[6] == 0x3a    // :
                    )
                {
                    var magneturi = Encoding.UTF8.GetString(downloadBytes);
                    var response  = Request.CreateResponse(HttpStatusCode.Moved);
                    response.Headers.Location = new Uri(magneturi);
                    return(response);
                }

                // This will fix torrents where the keys are not sorted, and thereby not supported by Sonarr.
                var    parser              = new BencodeParser();
                var    torrentDictionary   = parser.Parse(downloadBytes);
                byte[] sortedDownloadBytes = torrentDictionary.EncodeAsBytes();

                var result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new ByteArrayContent(sortedDownloadBytes);
                result.Content.Headers.ContentType        = new MediaTypeHeaderValue("application/x-bittorrent");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = StringUtil.MakeValidFileName(file, '_', false) + ".torrent" // call MakeValidFileName again to avoid any kind of injection attack
                };
                return(result);
            }
            catch (Exception e)
            {
                logger.Error(e, "Error downloading " + indexerID + " " + path);
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
        }
Example #5
0
        public async Task <List <IPEndPoint> > RetrievePeersAsync(byte[] hashInfo, byte[] peerId, long size)
        {
            var peers = new List <IPEndPoint>();

            var trackerResponse = await _announce
                                  .SetQueryParam("info_hash", HttpUtility.UrlEncode(hashInfo), true)
                                  .SetQueryParam("peer_id", HttpUtility.UrlEncode(peerId), true)
                                  .SetQueryParam("port", 8861)
                                  .SetQueryParam("uploaded", "0")
                                  .SetQueryParam("downloaded", "0")
                                  .SetQueryParam("compact", "1")
                                  .SetQueryParam("left", size)
                                  .AllowHttpStatus("2xx")
                                  .GetAsync();

            var contentStream = await trackerResponse.Content.ReadAsStreamAsync();

            var peersArray = (
                _parser.Parse(contentStream)
                .ToKeyValuePairs().FirstOrDefault(r => r.Key == "peers")
                .Value as BString
                )?.Value ?? throw new InvalidOperationException("Could find peers array in tracker response");


            for (int i = 0; i < peersArray.Length; i += 6)
            {
                peers.Add(new IPEndPoint(new IPAddress(peersArray.Slice(i, 4).Span), BigEndian.ToUint16(peersArray.Slice(i + 4, 2).Span)));
            }

            return(peers);
        }
Example #6
0
        public TorrentParserTests()
        {
            BencodeParser = Substitute.For <IBencodeParser>();
            BencodeParser.Parse <BDictionary>(null).ReturnsForAnyArgs(x => ParsedData);

            ValidSingleFileTorrentData = new BDictionary
            {
                [TorrentFields.Info] = new BDictionary
                {
                    [TorrentInfoFields.Name]        = (BString)"",
                    [TorrentInfoFields.NameUtf8]    = (BString)"",
                    [TorrentInfoFields.Pieces]      = (BString)"",
                    [TorrentInfoFields.PieceLength] = (BNumber)0,
                    [TorrentInfoFields.Length]      = (BNumber)0
                },
            };

            ValidMultiFileTorrentData = new BDictionary
            {
                [TorrentFields.Info] = new BDictionary
                {
                    [TorrentInfoFields.Name]        = (BString)"",
                    [TorrentInfoFields.NameUtf8]    = (BString)"",
                    [TorrentInfoFields.Pieces]      = (BString)"",
                    [TorrentInfoFields.PieceLength] = (BNumber)0,
                    [TorrentInfoFields.Files]       = new BList()
                },
            };
        }
        private void AddTorrentFileButton_Click(object sender, EventArgs e)
        {
            var openfile = new OpenFileDialog
            {
                Filter = "Torrent Files|*.torrent",
                Title  = "Select Torrent File"
            };

            openfile.ShowDialog();

            var parser  = new BencodeParser();
            var torrent = parser.Parse <Torrent>(openfile.FileName);

            var addTorrent = new AddTorrentDialog();

            var drive = new DriveInfo("C");

            // Formatting Labels
            ((Label)addTorrent.Controls["TorrentSizeLabel"]).Text    = Formatter.BytesToEnglish(torrent.TotalSize) + " (Space Left on drive: " + Formatter.BytesToEnglish(drive.AvailableFreeSpace) + ")";
            ((Label)addTorrent.Controls["TorrentDateLabel"]).Text    = torrent.CreationDate.ToString();
            ((Label)addTorrent.Controls["TorrentHashLabel"]).Text    = Formatter.HashFormatter(torrent.GetInfoHash());
            ((Label)addTorrent.Controls["TorrentCommentLabel"]).Text = torrent.Comment;


            // Display Torrent Files in the AddTorrentMenu Window
            var listview = ((ListView)addTorrent.Controls["FilesList"]);
            var T        = torrent.File;

            // Only One File Exists
            if (torrent.Files == null)
            {
                var item = new ListViewItem(new string[] { T.FileName, Formatter.BytesToEnglish(T.FileSize), "Normal" });
                //var test = item.SubItems;
                listview.Items.Add(item);
                item.Checked = true;
            }

            // Multiple Files in the torrent
            else
            {
                MultiFileInfoList files = torrent.Files;

                foreach (MultiFileInfo f in files)
                {
                    listview.Items.Add(new ListViewItem(new string[] { f.FileName, Formatter.BytesToEnglish(f.FileSize), "Normal" }));
                }
            }

            ((ComboBox)addTorrent.Controls["TorrentDirectory"]).Text = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            DialogResult result = addTorrent.ShowDialog();

            if (result == DialogResult.OK)
            {
                var row = new ListViewItem(new string[] { (MainWindowListView.Items.Count + 1).ToString(), T.FileName, Formatter.BytesToEnglish(T.FileSize) });
                MainWindowListView.Items.Add(row);
                row.Selected = true;
                var test2 = new Connection(torrent);
            }
        }
Example #8
0
        static void Main(string[] args)
        {
            string torrentPath = AppDomain.CurrentDomain.BaseDirectory + "a.torrent";

            #region BencodeNET

            // Parse torrent by specifying the file path
            var parser = new BencodeParser(); // Default encoding is Encoding.UT8F, but you can specify another if you need to

            //非BT种子文件 会解析异常
            var torrent = parser.Parse <Torrent>(torrentPath);

            string MagnetLink = torrent.GetMagnetLink(MagnetLinkOptions.None);

            Console.WriteLine(MagnetLink);

            Console.WriteLine(torrent.CreationDate);

            #endregion

            MonoTorrent.Common.Torrent mtorrent = MonoTorrent.Common.Torrent.Load(torrentPath);

            string link1 = "magnet:?xt=urn:btih:5623641b93b175e9b2c8fb0466427ca59de25d32&dn=SAMA-327r-avi";

            string magnetLink = "magnet:?xt=urn:btih:" + BitConverter.ToString(mtorrent.InfoHash.ToArray()).Replace("-", "");

            Console.WriteLine(magnetLink);


            MonoTorrent.MagnetLink link = new MonoTorrent.MagnetLink(link1);

            Console.WriteLine(link.Name);
        }
Example #9
0
        /// <summary>
        /// Extracts the torrent properties, file/files, size and even the magnet link.
        /// </summary>
        /// <param name="torrentFile">The torrent file.</param>
        /// <returns></returns>
        public static Tuple <string, string, string> TorrentInfoExtractor(string torrentFile)
        {
            var parser = new BencodeParser();

            try
            {
                torrent = parser.Parse <Torrent>(torrentFile);
            }
            catch (Exception)
            {
                //add dialog
            }

            switch (torrent.FileMode)
            {
            case TorrentFileMode.Single:
                return(Tuple.Create(torrent.File.FileName, logic.TorrentHandler.SizeSuffix(torrent.File.FileSize), torrent.GetMagnetLink()));

            case TorrentFileMode.Multi:
                return(Tuple.Create(torrent.Files.DirectoryName, logic.TorrentHandler.SizeSuffix(torrent.TotalSize), torrent.GetMagnetLink()));

            default:
                return(Tuple.Create("Not recognized", "Not recognized", "Not recognized"));
            }
        }
 public static TorrentMetadata ReadTorrentFile(this Stream stream)
 {
     stream = stream ?? throw new ArgumentNullException(nameof(stream));
     try
     {
         var parser  = new BencodeParser();
         var dict    = parser.Parse <BDictionary>(stream);
         var torrent = new TorrentMetadata();
         foreach (var item in dict)
         {
             var readableKey = item.Key.ToString();
             if (Parsers.TryGetValue(readableKey, out Action <IBObject, TorrentMetadata> action))
             {
                 action(item.Value, torrent);
             }
             else
             {
                 torrent.Extensions.Add(readableKey, item.Value);
             }
         }
         return(torrent);
     }
     catch (Exception e)
     {
         throw new DataMisalignedException("Torrent was not recognized", e);
     }
 }
Example #11
0
        public Tuple <string, string> TorrentLoader(string torrent_file)
        {
            Debug.WriteLine(torrent_file);
            var parser = new BencodeParser();

            try
            {
                this.torrent = parser.Parse <Torrent>(torrent_file);
            }
            catch (Exception)
            {
                //ADD DIALOG
            }

            switch (torrent.FileMode)
            {
            case TorrentFileMode.Single:
                return(Tuple.Create(torrent.File.FileName, SizeSuffix(torrent.File.FileSize).ToString()));

            case TorrentFileMode.Multi:
                return(Tuple.Create(torrent.Files.DirectoryName, "N/A"));    ///FIX SIZE

            default:
                return(Tuple.Create("Not recognized", "Not recognized"));
            }
        }
        public ExtendedTorrent(string filePath)
        {
            var parser  = new BencodeParser();
            var torrent = parser.Parse <Torrent>(filePath);

            CopyFields(torrent);
        }
Example #13
0
        private BDictionary GetResponse(Node node)
        {
            try
            {
                byte[] recvBuff = null;

                if (Regex.IsMatch(node.host, @"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$"))
                {
                    IPEndPoint rEP = new IPEndPoint(IPAddress.Parse(node.host), node.port);
                    udpClient.Send(getPeersBytes, getPeersBytes.Length, rEP);
                    recvBuff = udpClient.Receive(ref rEP);
                }
                else
                {
                    udpClient.Send(getPeersBytes, getPeersBytes.Length, node.host, node.port);
                    recvBuff = udpClient.Receive(ref ipEP);
                }

                if (recvBuff == null || recvBuff.Length == 0)
                {
                    return(null);
                }

                return(bParser.Parse <BDictionary>(recvBuff));
            } catch (Exception) { return(null); }
        }
Example #14
0
        public bool AnnounceTCP(Int32 num_want = -1, Int64 downloaded = 0, Int64 left = 0, Int64 uploaded = 0)
        {
            if (!ConnectTCP())
            {
                return(false);
            }

            try
            {
                byte[] sendBuff = System.Text.Encoding.UTF8.GetBytes($"GET {uri.AbsolutePath}?info_hash={Utils.StringHexToUrlEncode(options.InfoHash)}&peer_id={Utils.StringHexToUrlEncode(BitConverter.ToString(options.PeerId).Replace("-",""))}&port=11111&left={left}&downloaded={downloaded}&uploaded={uploaded}&event=started&compact=1&numwant={num_want} HTTP/1.1\r\nHost: {host}:{port}\r\nConection: close\r\n\r\n");

                if (type == Type.HTTP)
                {
                    netStream.Write(sendBuff, 0, sendBuff.Length);
                }
                else
                {
                    sslStream.Write(sendBuff, 0, sendBuff.Length);
                }

                if (!ReceiveTCP())
                {
                    return(false);
                }

                BencodeParser parser = new BencodeParser();
                BDictionary   extDic = parser.Parse <BDictionary>(recvBuff);

                byte[] hashBytes = ((BString)extDic["peers"]).Value.ToArray();
                Dictionary <string, int> peers = new Dictionary <string, int>();

                for (int i = 0; i < hashBytes.Length; i += 6)
                {
                    IPAddress curIP   = new IPAddress(Utils.ArraySub(ref hashBytes, (uint)i, 4, false));
                    UInt16    curPort = (UInt16)BitConverter.ToInt16(Utils.ArraySub(ref hashBytes, (uint)i + 4, 2, true), 0);
                    if (curPort > 0)
                    {
                        peers[curIP.ToString()] = curPort;
                    }
                }

                if (options.Verbosity > 0)
                {
                    Log($"Success ({peers.Count} Peers)");
                }

                if (peers.Count > 0)
                {
                    Beggar.FillPeers(peers, BitSwarm.PeersStorage.TRACKER);
                }
            }
            catch (Exception e)
            {
                Log($"Failed {e.Message}\r\n{e.StackTrace}");
                return(false);
            }

            return(true);
        }
        private void BtnZipIt_Click(object sender, RoutedEventArgs e)
        {
            string[] torrentFiles = Directory.GetFiles(torrentFolder);

            var parser = new BencodeParser(); // Default encoding is Encoding.UTF8, but you can specify another if you need to

            ConcurrentBag <string> matchingTorrents = new ConcurrentBag <string>();

            //foreach (string torrentFile in torrentFiles)
            Parallel.ForEach(torrentFiles,
                             new ParallelOptions {
            }, (torrentFile, loopState) =>
                             // foreach (string srcFileName in filesInSourceFolder)
            {
                Torrent torrent;
                // Parse torrent by specifying the file path
                try
                {
                    torrent = parser.Parse <Torrent>(torrentFile);
                }
                catch (Exception)
                {
                    return;
                }

                // Calculate the info hash
                string infoHash = torrent.GetInfoHash();

                int index = Array.FindIndex(hashes, t => t.Trim().Equals(infoHash, StringComparison.InvariantCultureIgnoreCase));

                if (index != -1)
                {
                    matchingTorrents.Add(torrentFile);
                }
            });

            if (matchingTorrents.Count == 0)
            {
                MessageBox.Show("No matching torrents found.");
            }
            else
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Zip file (.zip)|*.zip";
                sfd.Title  = "Where to save .zip file of matching torrents?";
                if (sfd.ShowDialog() == true)
                {
                    using (ZipFile zip = new ZipFile())
                    {
                        foreach (string matchingTorrentFile in matchingTorrents)
                        {
                            zip.AddFile(matchingTorrentFile, "");
                        }
                        zip.Save(sfd.FileName);
                    }
                }
            }
        }
Example #16
0
        private void AddTorrent_Load(object sender, EventArgs e)
        {
            List <string> SavePathsList = WebWorker.GetSavePaths();

            foreach (string SavePath in SavePathsList)
            {
                SavePathComboBox.Items.Add(SavePath);
            }

            if (Properties.Settings.Default.DefaultSavePath == String.Empty)
            {
                SavePathComboBox.Text = SavePathsList[0];
            }
            else
            {
                SavePathComboBox.Text = Properties.Settings.Default.DefaultSavePath;
            }


            List <string> CategoriesList = WebWorker.GetCategories();

            foreach (string Category in CategoriesList)
            {
                CategoriesComboBox.Items.Add(Category);
            }

            if (Properties.Settings.Default.DefaultCategory != String.Empty)
            {
                CategoriesComboBox.Text = Properties.Settings.Default.DefaultCategory;
            }


            BencodeParser TorrentParser = new BencodeParser();
            Torrent       ParsedTorrent = TorrentParser.Parse <Torrent>(TorrentFilePath);

            this.Text = ParsedTorrent.DisplayName;

            Sizelbl.Text = "Size: " + SizeConverter.SizeSuffix(ParsedTorrent.TotalSize);
            Datelbl.Text = "Date: " + ParsedTorrent.CreationDate;
            Hashlbl.Text = "Hash: " + ParsedTorrent.OriginalInfoHash.ToLower();

            /*Uri uriResult;
             * if (Uri.TryCreate(ParsedTorrent.Comment, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps))
             *  Console.WriteLine("LINK");*/

            Commentlbl.Text = "Comment: " + ParsedTorrent.Comment;

            if (ParsedTorrent.File == null)
            {
                Console.WriteLine(ParsedTorrent.Files);
            }
            else if (ParsedTorrent.Files == null)
            {
                Console.WriteLine(ParsedTorrent.File);
            }
        }
Example #17
0
 public TorrentDownloader(string filePath)
 {
     if (!File.Exists(filePath))
     {
         throw new FileNotFoundException("File not found: " + filePath); //uh oh
     }
     this.BCodeParser    = new BencodeParser();
     this.TorrentFile    = BCodeParser.Parse <Torrent>(filePath);
     this.TrackerManager = new TrackerManager(this.TorrentFile);
 }
Example #18
0
        public TorrentFile(string fileName)
        {
            BencodeParser parser = new BencodeParser();

            Torrent = parser.Parse <Torrent>(fileName);
            if (Torrent.Trackers.Any())
            {
                Announce = Torrent.Trackers.First().FirstOrDefault();
            }
        }
Example #19
0
 public ActiveTorrent(string fileName)
 {
     parser            = new BencodeParser();
     torrent           = parser.Parse <Torrent>(fileName);
     currConnectionID  = initialConnectionID;
     numPieces         = torrent.NumberOfPieces;
     pieceSize         = torrent.PieceSize;
     peerID            = RandomID();
     connectionManager = new ConnectionManager(this);
     trackerManager    = new TrackerManager(this);
     port = 6881;
 }
        private string GetMagnetLink(string path)
        {
            var     parser  = new BencodeParser();
            Torrent torrent = parser.Parse <Torrent>(path);

            // Calculate the info hash
            //string infoHash = torrent.GetInfoHash();
            //byte[] infoHashBytes = torrent.GetInfoHashBytes();
            string magnetLink = torrent.GetMagnetLink();

            return(magnetLink);
        }
        public bool Prepare()
        {
            var query =
                from el in _context.SoftPosts
                where el.Id == 85 || el.Id == 132 || el.Id == 311
                select el;

            IList <SoftPost> lst = query.ToList();

            var     parser = new BencodeParser();
            Torrent file0  = parser.Parse <Torrent>(lst[0].TorrentFile);
            Torrent file1  = parser.Parse <Torrent>(lst[1].TorrentFile);
            Torrent file2  = parser.Parse <Torrent>(lst[2].TorrentFile);

            Torrent softFirefox  = parser.Parse <Torrent>(@"F:\VS Projects\[Torrent-Soft.Net]_Firefox Browser 81.0.1.torrent");
            Torrent nnmFirefox   = parser.Parse <Torrent>(@"F:\VS Projects\nnm club firefox.torrent");
            Torrent rutorFirefox = parser.Parse <Torrent>(@"F:\VS Projects\rutor firefox.torrent");

            var trackers = softFirefox.Trackers.Union(rutorFirefox.Trackers);

            softFirefox.Trackers = trackers.ToList();
            softFirefox.EncodeTo(@"F:\VS Projects\[Custom]rutor and soft firefox.torrent");

            return(true);
        }
Example #22
0
        public static bool IsDataValidTorrent(BlockData blockData)
        {
            try
            {
                var parser  = new BencodeParser();
                var torrent = parser.Parse <Torrent>(blockData.Data.ToArray());

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #23
0
        private void Start()
        {
            var parser    = new BencodeParser();
            var resumeDat = new ResumeDat(TorrentRoot, parser.Parse <BDictionary>(TorrentRoot));

            for (var i = 0; i < 100; i++)
            {
                if (startAsyncCommand.IsCancellationRequested)
                {
                    break;
                }
                Thread.Sleep(100);
            }
        }
Example #24
0
        public static Torrent GetTorrentInformation(Block block)
        {
            try
            {
                var parser  = new BencodeParser();
                var torrent = parser.Parse <Torrent>(block.BlockData.Data.ToArray());

                return(torrent);
            }
            catch
            {
                return(null);
            }
        }
Example #25
0
        static void Main(string[] args)
        {
            // Parse torrent by specifying the file path
            var parser  = new BencodeParser(); // Default encoding is Encoding.UT8F, but you can specify another if you need to
            var torrent = parser.Parse <Torrent>(fileLoc);

            /*
             * // Alternatively, handle the stream yourself
             * using (var stream = File.OpenRead(fileLoc))
             * {
             *  torrent = parser.Parse<Torrent>(stream);
             * }
             */

            // Calculate the info hash
            string infoHash = torrent.GetInfoHash();

            Console.WriteLine($"infoHash => {infoHash}");


            // or as bytes instead of a string
            byte[] infoHashBytes = torrent.GetInfoHashBytes();

            // Get Magnet link
            string magnetLink = torrent.GetMagnetLink();

            Console.WriteLine($"magnetLink => {magnetLink}");

            // create object to print th fields in the torrent file
            BencodePrinter Bprinter = new BencodePrinter();

            // Convert Torrent to its BDictionary representation
            BDictionary bencodeDict = torrent.ToBDictionary();

            Console.WriteLine(bencodeDict.Count);

            try
            {
                Bprinter.PrintBdict(bencodeDict);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


            Console.WriteLine("DONE!!!!!!!");
            Console.ReadKey();
        }
Example #26
0
        public BDictionary FillFromTorrentFile(string fileName)
        {
            BDictionary bdicTorrent = bParser.Parse <BDictionary>(fileName);
            BDictionary bInfo;

            if (bdicTorrent["info"] != null)
            {
                bInfo = (BDictionary)bdicTorrent["info"];
                FillTrackersFromInfo(bdicTorrent);
            }
            else if (bdicTorrent["name"] != null)
            {
                bInfo = bdicTorrent;
            }
            else
            {
                throw new Exception("Invalid torrent file");
            }

            file.infoHash = Utils.ArrayToStringHex(sha1.ComputeHash(bInfo.EncodeAsBytes()));
            file.name     = ((BString)bInfo["name"]).ToString();

            return(bInfo);
        }
        private async Task GetAndParseReannounceResponseAsync(string message, int numWant)
        {
            var trackerResponse = new TrackerResponse();
            await trackerResponse.GetTrackerResponse(this, ownerForm.myPeerID, 25000,
                                                     message, numWant).ConfigureAwait(false);

            var parser = new BencodeParser();

            foreach (var item in trackerResponse.response)
            {
                switch (item.Key.ToString())
                {
                case "interval":
                    trackerInterval = parser.Parse <BNumber>(item.Value.EncodeAsBytes()).Value;
                    if (trackerInterval >= 600)
                    {
                        trackerTimer.Change(trackerInterval * 1000, trackerInterval * 1000);
                    }
                    else
                    {
                        // if for some reason we didn't get the interval,
                        // or if it's too small, set it to 40 minutes
                        trackerTimer.Change(40 * 60 * 1000, 40 * 60 * 1000);
                    }
                    break;

                case "min interval":
                    trackerMinInterval = parser.Parse <BNumber>(item.Value.EncodeAsBytes()).Value;
                    break;

                case "tracker id":
                    trackerID = parser.Parse <BString>(item.Value.EncodeAsBytes()).ToString();
                    break;
                }
            }
        }
        public TorrentFileInfo(string path)
        {
            if (!File.Exists(path))
            {
                throw new ArgumentException($"{path} doesn't exist");
            }
            if (Path.GetExtension(path) != ".torrent")
            {
                throw new ArgumentException("provided file should have .torrent extension");
            }
            BencodeParser parser = new BencodeParser();

            _torrent    = parser.Parse <Torrent>(path);
            PieceHashes = SplitPieceHashes();
        }
Example #29
0
        private void lstTorrents_DragDrop(object sender, DragEventArgs e)
        {
            string[] files  = (string[])e.Data.GetData(DataFormats.FileDrop);
            var      parser = new BencodeParser(); //To extract torrent informations

            foreach (var file in files)
            {
                var torrent   = parser.Parse <Torrent>(file);
                var file_name = file.Substring(file.LastIndexOf('\\') + 1); //Extract torrent file name from it's full path
                var file_size = ByteSize.FromBytes(torrent.TotalSize);
                lstTorrents.Items.Add(new ListViewItem(new[] { file_name, file_size.ToString("0.000 GB") }, "torrent"));
                size = size + torrent.TotalSize;
            }
            lblFileCount.Text = lstTorrents.Items.Count.ToString();
            lblTotalSize.Text = ByteSize.FromBytes(size).ToString("0.000 GB");
        }
Example #30
0
        private AnnounceResult ProcessResponse(Stream response)
        {
            _logger.LogInformation($"Received response from {BaseUrl}");

            var resultPeers = new List <AnnounceResultPeer>();

            var parser = new BencodeParser();

            var dict = parser.Parse <BDictionary>(response);

            if (dict["peers"] is BList)
            {
                var peers = dict["peers"] as BList;
                foreach (BDictionary peer in peers)
                {
                    string ip   = (peer["ip"] as BString).ToString();
                    int    port = (int)(peer["port"] as BNumber).Value;

                    resultPeers.Add(new AnnounceResultPeer(IPAddress.Parse(ip), port));
                }
            }
            else
            {
                // Compact response
                var peersString = dict["peers"] as BString;
                using (var peersStream = new MemoryStream(peersString.Value.ToArray()))
                {
                    var reader = new BinaryReader(peersStream);
                    for (int i = 0; i < peersStream.Length; i += 6)
                    {
                        byte[] peerIp  = reader.ReadBytes(4);
                        byte   firstB  = reader.ReadByte();
                        byte   secondB = reader.ReadByte();

                        // TODO fix endian encoding (assumes host is little endian)
                        ushort port = BitConverter.ToUInt16(new[] { secondB, firstB }, 0);

                        string ip = $"{peerIp[0]}.{peerIp[1]}.{peerIp[2]}.{peerIp[3]}";
                        resultPeers.Add(new AnnounceResultPeer(IPAddress.Parse(ip), port));
                    }
                }
            }

            return(new AnnounceResult(resultPeers.Select(x => new TcpTransportStream(_tcpConnectionDetails.BindAddress, x.IPAddress, x.Port))));
        }