Example #1
0
        public static Torrent GetTorrentFromByte(byte[] bytes)
        {
            BEncodedDictionary bed = BEncodedDictionary.DecodeTorrent(bytes);
            Torrent            T   = Torrent.Load(bed);

            return(T);
        }
Example #2
0
        static void Main()
        {
#if WINDOWS
            string[]           commandLineArgs = null;
            BEncodedDictionary torrent         = null;
            string             filename        = null;

            List <Tuple <string, BEncodedDictionary> > torrentList = new List <Tuple <string, BEncodedDictionary> >();

            //MessageBox.Show(Environment.CommandLine);

            // 对于 Windows 系统,cmdline[0] => appname; cmdline[1] => ...
            // 对于 Linux……好像是 cmdline[0] => ... 吧……

            try
            {
                commandLineArgs = Environment.GetCommandLineArgs();
            }
            catch (Exception)
            {
            }
            bool shouldRunConsole = false;
            if (commandLineArgs != null && commandLineArgs.Length >= 2)
            {
                for (var i = 1; i < commandLineArgs.Length; i++)
                {
                    filename = commandLineArgs[i];
                    if (File.Exists(filename))
                    {
                        try
                        {
                            using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
                            {
                                torrent = BEncodedDictionary.DecodeTorrent(fs);
                                torrentList.Add(new Tuple <string, BEncodedDictionary>(filename, torrent));
                                shouldRunConsole = true;
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }

            if (shouldRunConsole)
            {
                RunConsole(torrentList);
            }
            else
            {
#endif
            RunGui();
#if WINDOWS
        }
#endif
        }
Example #3
0
        public void DecodeTorrentWithString()
        {
            var dict = new BEncodedDictionary {
                { "info", (BEncodedString)"value" }
            };

            var result = BEncodedDictionary.DecodeTorrent(dict.Encode());

            Assert.IsTrue(Toolbox.ByteMatch(dict.Encode(), result.Encode()));
        }
Example #4
0
        public void DecodeTorrentWithOutOfOrderKeys()
        {
            var good = "d4:infod5:key_a7:value_a5:key_b7:value_bee";
            var bad  = "d4:infod5:key_b7:value_b5:key_a7:value_aee";

            var good_result = BEncodedDictionary.DecodeTorrent(Encoding.UTF8.GetBytes(good));
            var bad_result  = BEncodedDictionary.DecodeTorrent(Encoding.UTF8.GetBytes(bad));

            Assert.IsTrue(Toolbox.ByteMatch(good_result.torrent.Encode(), bad_result.torrent.Encode()));
            Assert.AreNotEqual(good_result.infohash, bad_result.infohash);
        }
Example #5
0
        /// <summary>
        /// Called from either Load(stream) or Load(string).
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        static Torrent Load(Stream stream, string path)
        {
            Check.Stream(stream);
            Check.Path(path);

            try {
                var decoded = BEncodedDictionary.DecodeTorrent(stream);
                return(LoadCore(decoded.torrent, decoded.infohash));
            } catch (BEncodingException ex) {
                throw new TorrentException("Invalid torrent file specified", ex);
            }
        }
Example #6
0
        public void DecodeTorrentWithDict()
        {
            var dict = new BEncodedDictionary {
                { "other", new BEncodedDictionary   {
                      { "test", new BEncodedString("value") }
                  } }
            };

            var result = BEncodedDictionary.DecodeTorrent(dict.Encode());

            Assert.IsTrue(Toolbox.ByteMatch(dict.Encode(), result.Encode()));
        }
Example #7
0
        public void DecodeTorrentWithInfo()
        {
            var dict = new BEncodedDictionary();

            dict.Add("info", new BEncodedDictionary {
                { (BEncodedString)"test", (BEncodedString)"value" }
            });

            var result = BEncodedDictionary.DecodeTorrent(dict.Encode());

            Assert.IsTrue(Toolbox.ByteMatch(dict.Encode(), result.Encode()));
        }
Example #8
0
        public async Task <HttpResponseMessage> Download(string indexerID, string path, string apikey, string file)
        {
            try
            {
                var indexer = indexerService.GetIndexer(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));

                if (serverService.Config.APIKey != apikey)
                {
                    return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
                }

                var target = new Uri(path, UriKind.RelativeOrAbsolute);
                target = indexer.UncleanLink(target);

                var downloadBytes = await indexer.Download(target);

                // This will fix torrents where the keys are not sorted, and thereby not supported by Sonarr.
                var torrentDictionary = BEncodedDictionary.DecodeTorrent(downloadBytes);
                downloadBytes = torrentDictionary.Encode();

                char[] invalidChars = System.IO.Path.GetInvalidFileNameChars();
                for (int i = 0; i < file.Count(); i++)
                {
                    if (invalidChars.Contains(file[i]))
                    {
                        file = file.Remove(i, 1).Insert(i, " ");
                    }
                }

                var result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new ByteArrayContent(downloadBytes);
                result.Content.Headers.ContentType        = new MediaTypeHeaderValue("application/x-bittorrent");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = file
                };
                return(result);
            }
            catch (Exception e)
            {
                logger.Error(e, "Error downloading " + indexerID + " " + path);
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
        }
Example #9
0
 private static Torrent ParseBitTorrent(string file)
 {
     using (var stream = File.OpenRead(file))
     {
         var torrent = BEncodedDictionary.DecodeTorrent(stream);
         var it      = ParseBitTorrent((BEncodedDictionary)torrent["info"]);
         using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
         {
             var    rawBytes = ((BEncodedDictionary)torrent["info"]).Encode();
             byte[] infohash = sha1.ComputeHash(rawBytes);
             it.InfoHash = infohash.ToHex();
             return(it);
         }
     }
 }
Example #10
0
        /// <summary>
        /// Called from either Load(stream) or Load(string).
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        static Torrent Load(Stream stream, string path)
        {
            Check.Stream(stream);
            Check.Path(path);

            try
            {
                //Torrent t = Torrent.Load(BEncodedValue.Decode<BEncodedDictionary>(stream));
                var t = Torrent.Load(BEncodedDictionary.DecodeTorrent(stream));
                t.torrentPath = path;
                return(t);
            }
            catch (BEncodingException ex)
            {
                throw new TorrentException("Invalid torrent file specified", ex);
            }
        }
Example #11
0
 private void ReadTorrent(string filename)
 {
     using (var fs = new FileStream(filename, FileMode.Open))
     {
         try
         {
             torrent           = BEncodedDictionary.DecodeTorrent(fs);
             isHandlingTorrent = true;
             cmdGenerateNewTorrentFile.Enabled = true;
             ShowTorrentInformation();
         }
         catch (Exception ex)
         {
             isHandlingTorrent = false;
             cmdGenerateNewTorrentFile.Enabled = false;
             txtInfo.Text = ex.Message + Environment.NewLine + DROP_IN_HERE;
         }
     }
 }
Example #12
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 (serverService.Config.APIKey != jackett_apikey)
                {
                    return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
                }

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

                // This will fix torrents where the keys are not sorted, and thereby not supported by Sonarr.
                var torrentDictionary = BEncodedDictionary.DecodeTorrent(downloadBytes);
                downloadBytes = torrentDictionary.Encode();

                var result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new ByteArrayContent(downloadBytes);
                result.Content.Headers.ContentType        = new MediaTypeHeaderValue("application/x-bittorrent");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = StringUtil.MakeValidFileName(file, '_', false) // 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 #13
0
        public BEncodedDictionary GetMetaData(InfoHash hash, out bool netError)
        {
            netError = false;
            WireMessage  message;
            ExtHandShack exths;
            long         metadataSize;
            int          piecesNum;
            byte         ut_metadata;

            try
            {
                //连接
                if (!client.ConnectAsync(EndPoint.Address, EndPoint.Port).Wait(5000))
                {
                    netError = true;
                    Trace.WriteLine("Connect Timeout", "Socket");
                    return(null);
                }
                stream = client.GetStream();

                //发送握手
                message = new HandShack(hash);
                SendMessage(message);

                //接受握手
                message = ReceiveMessage <HandShack>(1);
                if (!message.Legal || !(message as HandShack).SupportExtend)
                {
                    netError = true;
                    Trace.WriteLine(EndPoint, "HandShack Fail");
                    return(null);
                }

                //发送拓展握手
                message = new ExtHandShack()
                {
                    SupportUtMetadata = true
                };
                SendMessage(message);

                //接受拓展
                exths = ReceiveMessage <ExtHandShack>();
                if (!exths.Legal || !exths.CanGetMetadate || exths.MetadataSize > MaxMetadataSize || exths.MetadataSize <= 0)
                {
                    netError = true;
                    Trace.WriteLine(EndPoint, "ExtendHandShack Fail");
                    return(null);
                }
                metadataSize = exths.MetadataSize;
                ut_metadata  = exths.UtMetadata;
                piecesNum    = (int)Math.Ceiling(metadataSize / (decimal)PieceLength);

                //开始接受pieces
                var rtask = ReceivePiecesAsync(metadataSize, piecesNum);
                //开始发送piece请求
                for (int i = 0; i < piecesNum; i++)
                {
                    message = new ExtQueryPiece(ut_metadata, i);
                    SendMessage(message);
                }
                //等待pieces接收完毕
                rtask.Wait();
                var rawBytes = rtask.Result;

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

                //检查hash值是否正确
                using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
                {
                    byte[] infohash = sha1.ComputeHash(rawBytes);
                    if (!infohash.SequenceEqual(hash.Hash))
                    {
                        Trace.WriteLine(EndPoint, "Hash Wrong");
                        return(null);
                    }
                }
                return(BEncodedDictionary.DecodeTorrent(rawBytes));
            }
            catch (AggregateException ex)
            {
                throw ex.InnerException;
            }
            finally
            {
                client?.Close();
            }
        }
Example #14
0
 public void NewDecode() => BEncodedDictionary.DecodeTorrent(Buffer);
Example #15
0
 public void OldDecode()
 {
     Stream.Position = 0;
     BEncodedDictionary.DecodeTorrent(Stream);
 }
Example #16
0
        public async Task <(BEncodedDictionary, bool)> GetMetaDataAsync(InfoHash hash)
        {
            try
            {
                //连接
                Task connectTask = client.ConnectAsync(EndPoint.Address, EndPoint.Port), waitTask = Task.Delay(5000);
                await Task.WhenAny(waitTask, connectTask);

                if (!connectTask.IsCompleted || connectTask.Status != TaskStatus.RanToCompletion)
                {
                    return(null, true);
                }
                stream = client.GetStream();
                //发送握手
                WireMessage message = new HandShack(hash);
                await SendMessageAsync(message);

                //接受握手
                message = await ReceiveMessageAsync <HandShack>(1);

                if (!message.Legal || !((HandShack)message).SupportExtend)
                {
                    return(null, true);
                }
                //发送拓展握手
                message = new ExtHandShack()
                {
                    SupportUtMetadata = true
                };
                await SendMessageAsync(message);

                //接受拓展
                var exths = await ReceiveMessageAsync <ExtHandShack>();

                if (!exths.Legal || !exths.CanGetMetadate || exths.MetadataSize > MaxMetadataSize || exths.MetadataSize <= 0)
                {
                    return(null, true);
                }
                var metadataSize = exths.MetadataSize;
                var utMetadata   = exths.UtMetadata;
                var piecesNum    = (int)Math.Ceiling(metadataSize / (decimal)PieceLength);
                var metaTask     = ReceivePiecesAsync(metadataSize, piecesNum);
                //开始发送piece请求
                for (int i = 0; i < piecesNum; i++)
                {
                    message = new ExtQueryPiece(utMetadata, i);
                    await SendMessageAsync(message);
                }
                //等待pieces接收完毕
                var metadata = await metaTask;
                if (metadata == null)
                {
                    return(null, false);
                }
                //检查hash值是否正确
                using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
                {
                    byte[] infohash = sha1.ComputeHash(metadata);
                    if (infohash.SequenceEqual(hash.Hash))
                    {
                        return(BEncodedDictionary.DecodeTorrent(metadata), false);
                    }
                    return(null, false);
                }
            }
            catch (AggregateException ex)
            {
                throw ex.InnerException;
            }
            finally
            {
                client?.Close();
            }
        }
Example #17
0
        public void DecodeTorrentNotDictionary()
        {
            string benString = "5:test";

            Assert.Throws <BEncodingException> (() => BEncodedDictionary.DecodeTorrent(Encoding.UTF8.GetBytes(benString)));
        }
Example #18
0
        public void DecodeTorrent_MissingTrailingE()
        {
            string benString = "d1:a1:b";

            Assert.Throws <BEncodingException> (() => BEncodedDictionary.DecodeTorrent(Encoding.UTF8.GetBytes(benString)));
        }