示例#1
0
文件: BEncodeTest.cs 项目: dhtweb/dht
        static void DecodeTorrentTest()
        {
            var path  = @"F:\迅雷下载\种子\00da1247df008e88f04a79af1816ea07.torrent";
            var bytes = File.ReadAllBytes(path);
            var dic   = (IDictionary <string, object>)BEncoder.Decode(bytes);
            var info  = (IDictionary <string, object>)dic["info"];
            var name  = (byte[])info["name"];

            Console.WriteLine(Encoding.UTF8.GetString(name));
            var files = (IList <object>)info["files"];

            foreach (IDictionary <string, object> file in files)
            {
                foreach (var kv in file)
                {
                    Console.WriteLine(kv.Key);
                    if (kv.Value is IList <object> list)
                    {
                        foreach (byte[] item in list)
                        {
                            Console.WriteLine(Encoding.UTF8.GetString(item));
                        }
                    }
                    else
                    {
                        Console.WriteLine(kv.Value);
                    }
                }
            }
            Console.WriteLine(info);;
        }
示例#2
0
文件: BEncodeTest.cs 项目: dhtweb/dht
        static void Test()
        {
            var lines = File.ReadAllLines(@"E:\Code\dotnetcore\dht\DhtCrawler\bin\Release\PublishOutput\torrent\B2960BC78CBBE627E43DCE0562C0DB6552F190A7");

            foreach (var line in lines)
            {
                if (!line.StartsWith("files"))
                {
                    continue;
                }
                var info = Encoding.UTF8.GetBytes(line.Split('\t')[1]);
                var list = (IList <object>)BEncoder.Decode(info);
                foreach (IDictionary <string, object> file in list)
                {
                    foreach (var kv in file)
                    {
                        Console.Write(kv.Key);
                        Console.Write('\t');
                        if (kv.Value is IList <object> paths)
                        {
                            Console.Write(string.Join("/", paths.Select(path => Encoding.UTF8.GetString((byte[])path))));
                        }
                        else
                        {
                            Console.Write(kv.Value);
                        }
                        Console.WriteLine();
                    }
                }
            }
            Assert.True(true);
        }
示例#3
0
        static void DecodeTorrentTest()
        {
            var path  = @"E:\Code\dotnetcore\dht\DhtCrawler.Test\xp1024.com_STP1179MP4.torrent";
            var bytes = File.ReadAllBytes(path);
            var dic   = (IDictionary <string, object>)BEncoder.Decode(bytes);
            var info  = (IDictionary <string, object>)dic["info"];
            var name  = (byte[])info["name"];

            Console.WriteLine(Encoding.UTF8.GetString(name));
            var files = (IList <object>)info["files"];

            foreach (IDictionary <string, object> file in files)
            {
                foreach (var kv in file)
                {
                    Console.WriteLine(kv.Key);
                    if (kv.Value is IList <object> list)
                    {
                        foreach (byte[] item in list)
                        {
                            Console.WriteLine(Encoding.UTF8.GetString(item));
                        }
                    }
                    else
                    {
                        Console.WriteLine(kv.Value);
                    }
                }
            }
            Console.WriteLine(info);
            ;
        }
示例#4
0
        private async Task ProcessMsgData()
        {
            while (running)
            {
                if (!_recvMessageQueue.TryTake(out DhtData dhtData))
                {
                    await Task.Delay(1000);

                    continue;
                }
                try
                {
                    var dic = (Dictionary <string, object>)BEncoder.Decode(dhtData.Data);
                    var msg = new DhtMessage(dic);
                    switch (msg.MesageType)
                    {
                    case MessageType.Request:
                        var item = new Tuple <DhtMessage, IPEndPoint>(msg, dhtData.RemoteEndPoint);
                        _requestQueue.TryAdd(item);
                        break;

                    case MessageType.Response:
                        if (msg.MessageId.Length != 2)
                        {
                            continue;
                        }
                        var remotePoint  = dhtData.RemoteEndPoint;
                        var responseNode = new DhtNode()
                        {
                            NodeId = (byte[])msg.Data["id"], Host = remotePoint.Address, Port = (ushort)remotePoint.Port
                        };
                        var flag = await MessageMap.RequireRegisteredInfoAsync(msg, responseNode);

                        if (!flag)
                        {
                            continue;
                        }
                        _responseQueue.TryAdd(new Tuple <DhtMessage, DhtNode>(msg, responseNode), 10);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    if (ex is DecodeException)
                    {
                        filterPeers.Add(dhtData.RemoteEndPoint.ToInt64());
                        continue;
                    }
                    _logger.Error($"ErrorData:{BitConverter.ToString(dhtData.Data)}", ex);
                    var response = new DhtMessage
                    {
                        MesageType = MessageType.Exception,
                        MessageId  = new byte[] { 0, 0 }
                    };
                    response.Errors.Add(202);
                    response.Errors.Add("Server Error:" + ex.Message);
                    _sendMessageQueue.TryAdd(new Tuple <DhtMessage, DhtNode>(response, new DhtNode(dhtData.RemoteEndPoint)));
                }
            }
        }
示例#5
0
        public static ExtHandHackMessage Decode(byte[] bytes)
        {
            var msgId = bytes[0]; //读取消息Id
            var extId = bytes[1]; //读取扩展Id
            var data  = (IDictionary <string, object>)BEncoder.Decode(bytes.Skip(2).ToArray());
            var msg   = new ExtHandHackMessage(data);

            return(msg);
        }
示例#6
0
文件: BEncodeTest.cs 项目: dhtweb/dht
        static void TempTest()
        {
            var dir   = @"F:\迅雷下载\种子\";
            var paths = Directory.GetFiles(dir, "*.torrent");
            var list  = new List <KeyValuePair <string, long> >();

            foreach (var path in paths)
            {
                long length = 0;
                try
                {
                    var bytes = File.ReadAllBytes(path);
                    var dic   = (IDictionary <string, object>)BEncoder.Decode(bytes);
                    var info  = (IDictionary <string, object>)dic["info"];
                    var name  = (byte[])info["name"];
                    Console.WriteLine(Encoding.UTF8.GetString(name));
                    if (info.ContainsKey("files"))
                    {
                        var files = (IList <object>)info["files"];
                        foreach (IDictionary <string, object> file in files)
                        {
                            foreach (var kv in file)
                            {
                                if (kv.Key == "length")
                                {
                                    length += Convert.ToInt64(kv.Value);
                                    break;
                                }
                            }
                        }
                    }
                    else if (info.ContainsKey("length"))
                    {
                        length = Convert.ToInt64(info["length"]);
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine(path);
                }
                list.Add(new KeyValuePair <string, long>(path, length));
            }
            list.Sort((kv1, kv2) => (int)(kv1.Value - kv2.Value));
            var step = list.Count / 10;

            for (int j = 0; j < 10; j++)
            {
                var target = $@"F:\迅雷下载\种子\{j}";
                Directory.CreateDirectory(target);
                for (var i = step * j; i < list.Count; i++)
                {
                    var item = list[i];
                    File.Move(item.Key, $@"{target}\\{item.Value}_{Path.GetFileName(item.Key)}");
                }
            }
        }
示例#7
0
        static ExtHandHackMessage()
        {
            var headerAttribute = new Dictionary <string, object>(1)
            {
                { UtMetadataKey, 1 }
            };
            var header = new Dictionary <string, object>(1)
            {
                { MethodKey, headerAttribute }
            };

            ExtendHeader = BEncoder.EncodeObject(header);
        }
示例#8
0
文件: BEncodeTest.cs 项目: dhtweb/dht
        static void EncodeTest()
        {
            var str =
                "64-31-3A-65-6C-69-32-30-33-65-31-34-3A-45-72-72-6F-72-20-50-72-6F-74-6F-63-6F-6C-65-31-3A-74".Split('-');
            var bytes = new List <byte>();

            foreach (var s in str)
            {
                bytes.Add(Convert.ToByte(s, 16));
            }
            var dic = BEncoder.Decode(bytes.ToArray());

            Console.WriteLine(dic);
            Assert.True(true);
        }
示例#9
0
 public override byte[] Encode()
 {
     //1.写入包长度
     //2.写入msgId
     //3.写入extTypeId
     //4.写入字典
     using (var stream = new MemoryStream())
     {
         stream.Write(BitConverter.IsLittleEndian ? BitConverter.GetBytes(Length).Reverse().ToArray() : BitConverter.GetBytes(Length), 0, 4);
         stream.WriteByte(20);
         stream.WriteByte(ExtTypeID);
         BEncoder.EncodeObject(Parameters, stream);
         return(stream.ToArray());
     }
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var res = new Dictionary <string, object>
            {
                {
                    "failure reason",
                    Message
                }
            };

            var response = context.HttpContext.Response;

            response.Write(BEncoder.BEncodeDictionary(res));
        }
示例#11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var res = new Dictionary <string, object>
            {
                {
                    "interval",
                    Interval
                },
                {
                    "peers",
                    Peers
                }
            };
            var response = context.HttpContext.Response;

            response.Write(BEncoder.BEncodeDictionary(res));
            response.End();
        }
示例#12
0
        //
        // GET: /Announce/Announce/
        // GET: /announce/123af0c917876f6d4711654b2293895f
        public ActionResult Announce(AnnounceModel announceModel)
        {
            if (!announceModel.IsValidRequest())
            {
                return(new BTErrorResult("Invalid request (see specification: http://bit.ly/bcYmSu)"));
            }

            if (!Regex.IsMatch(announceModel.Passkey, "[0-9a-fA-F]{32}"))
            {
                return(new BTErrorResult("Invalid passkey."));
            }

            if (BLACKLIST_PORTS && IsPortBlackListed(Convert.ToInt32(announceModel.port)))
            {
                return(new BTErrorResult(string.Format("Port {0} is blacklisted", announceModel.port)));
            }

            try
            {
                using (var context = new OpenTrackerDbContext())
                {
                    var crntUser = (from u in context.users
                                    where u.passkey == announceModel.Passkey
                                    select u).Take(1).FirstOrDefault();
                    if (crntUser == null)
                    {
                        return(new BTErrorResult(string.Format("Unknown passkey. Please re-download the torrent from {0}.",
                                                               TrackerSettings.BASE_URL)));
                    }

                    if (crntUser.activated == 0)
                    {
                        return(new BTErrorResult("Permission denied, you\'re not activated."));
                    }

                    var seeder = false;
                    if (announceModel.left == 0)
                    {
                        seeder = true;
                    }

                    // Entity Framework does not support BINARY keys
                    var EncodedPeerId   = Convert.ToBase64String(Encoding.ASCII.GetBytes(announceModel.peer_id));
                    var EncodedInfoHash = BEncoder.FormatUrlInfoHash();

                    var torrentExist = (from t in context.torrents
                                        where t.info_hash == EncodedInfoHash
                                        select t).Take(1).FirstOrDefault();
                    if (torrentExist == null)
                    {
                        return(new BTErrorResult("Torrent not registered with this tracker."));
                    }

                    var peerAlreadyExist = (from t in context.peers
                                            where t.torrentid == torrentExist.id &&
                                            t.peer_id == EncodedPeerId &&
                                            t.passkey == announceModel.Passkey
                                            select t).Take(1);
                    var   existingPeerCount = peerAlreadyExist.Count();
                    peers p;
                    if (existingPeerCount == 1)
                    {
                        p = peerAlreadyExist.First();
                    }
                    else
                    {
                        var connectionLimit = (from t in context.peers
                                               where t.torrentid == torrentExist.id &&
                                               t.passkey == announceModel.Passkey
                                               select t).Count();
                        if (connectionLimit >= 1 && !seeder)
                        {
                            return(new BTErrorResult("Connection limit exceeded! " +
                                                     "You may only leech from one location at a time."));
                        }
                        if (connectionLimit >= 3 && seeder)
                        {
                            return(new BTErrorResult("Connection limit exceeded."));
                        }


                        if (announceModel.left > 0 && crntUser.@class < (decimal)AccountValidation.Class.Administrator)
                        {
                            var epoch   = Unix.ConvertToUnixTimestamp(DateTime.UtcNow);
                            var elapsed = Math.Floor((epoch - torrentExist.added) / 3600);

                            var uploadedGigs = crntUser.uploaded / (1024 * 1024 * 1024);
                            var ratio        = ((crntUser.downloaded > 0) ? (crntUser.uploaded / crntUser.downloaded) : 1);

                            int wait;
                            if (ratio < (decimal)0.5 || uploadedGigs < 5)
                            {
                                wait = 48;
                            }
                            else if (ratio < (decimal)0.65 || uploadedGigs < (decimal)6.5)
                            {
                                wait = 24;
                            }
                            else if (ratio < (decimal)0.8 || uploadedGigs < 8)
                            {
                                wait = 12;
                            }
                            else if (ratio < (decimal)0.95 || uploadedGigs < (decimal)9.5)
                            {
                                wait = 6;
                            }
                            else
                            {
                                wait = 0;
                            }

                            if (elapsed < wait)
                            {
                                return(new BTErrorResult(string.Format("Not authorized (wait {0}h) - READ THE FAQ!",
                                                                       (wait - elapsed))));
                            }
                        }

                        p = new peers
                        {
                            torrentid = torrentExist.id,
                            peer_id   = EncodedPeerId,
                            userid    = crntUser.id,
                            passkey   = announceModel.Passkey,
                            useragent = Request.UserAgent
                        };
                    }

                    var remoteHost = Request.ServerVariables["REMOTE_HOST"];
                    var ip         = !string.IsNullOrEmpty(announceModel.ip) ? announceModel.ip : remoteHost;

                    if (CHECK_CONNECTABLE)
                    {
                        p.connectable = IsConnectable(ip, Convert.ToInt32(announceModel.port)) ? 1 : 0;
                    }
                    if (announceModel.left != null)
                    {
                        p.left = (decimal)announceModel.left;
                    }
                    p.port = Convert.ToInt32(announceModel.port);
                    p.ip   = ip;

                    p.seeding = seeder ? 1 : 0;

                    if (existingPeerCount == 0)
                    {
                        context.AddTopeers(p);
                    }
                    else
                    {
                        if (crntUser.@class < (decimal)AccountValidation.Class.Administrator)
                        {
                            var nonUpdatedPeer = peerAlreadyExist.First();
                            var thisUploaded   = (announceModel.uploaded - nonUpdatedPeer.uploaded);
                            var thisDownloaded = (announceModel.downloaded - nonUpdatedPeer.downloaded);

                            p.uploaded   += (decimal)thisUploaded;
                            p.downloaded += (decimal)thisDownloaded;

                            if (thisUploaded > 0)
                            {
                                crntUser.uploaded = (crntUser.uploaded + Convert.ToInt64(thisUploaded));
                            }
                            if (thisDownloaded > 0)
                            {
                                crntUser.downloaded = (crntUser.downloaded + Convert.ToInt64(thisDownloaded));
                            }
                        }

                        if (announceModel.Event == "completed")
                        {
                            torrentExist.snatches = torrentExist.snatches + 1;                             // torrentExist.snatches++;
                        }
                    }
                    context.SaveChanges();

                    if (announceModel.Event == "stopped")
                    {
                        var removePeer = (from pr in context.peers
                                          where pr.torrentid == torrentExist.id &&
                                          pr.peer_id == EncodedPeerId
                                          select pr).Take(1).FirstOrDefault();
                        context.peers.DeleteObject(removePeer);
                        context.SaveChanges();

                        var announceResultStop = new AnnounceResult
                        {
                            Interval = ANNOUNCE_INTERVAL
                        };
                        return(announceResultStop);
                    }

                    var announceResult = new AnnounceResult
                    {
                        Interval = ANNOUNCE_INTERVAL
                    };

                    var existingPeers = (from t in context.peers
                                         where t.torrentid == torrentExist.id
                                         select t).ToList();

                    foreach (var peer in existingPeers)
                    {
                        announceResult.AddPeer(peer.peer_id, peer.ip, peer.port);
                    }

                    return(announceResult);
                }
            }
            catch (Exception)
            {
                return(new BTErrorResult("Database unavailable"));
            }
        }
示例#13
0
 public byte[] BEncodeBytes()
 {
     return(BEncoder.EncodeObject(_message));
 }