Example #1
0
        public async Task <byte[]> SaveNodesAsync()
        {
            await MainLoop;

            var details = new BEncodedList();

            foreach (Bucket b in RoutingTable.Buckets)
            {
                foreach (Node n in b.Nodes)
                {
                    if (n.State != NodeState.Bad)
                    {
                        details.Add(n.CompactNode());
                    }
                }

                if (b.Replacement != null)
                {
                    if (b.Replacement.State != NodeState.Bad)
                    {
                        details.Add(b.Replacement.CompactNode());
                    }
                }
            }

            return(details.Encode());
        }
 public ErrorMessage(ErrorCode error, string message)
     : base(ErrorType)
 {
     var l = new BEncodedList();
     l.Add(new BEncodedNumber((int) error));
     l.Add(new BEncodedString(message));
     properties.Add(ErrorListKey, l);
 }
Example #3
0
        public ErrorMessage(ErrorCode error, string message)
            : base(ErrorType)
        {
            BEncodedList l = new BEncodedList();

            l.Add(new BEncodedNumber((int)error));
            l.Add(new BEncodedString(message));
            properties.Add(ErrorListKey, l);
        }
Example #4
0
        public void benListEncoding()
        {
            byte[]       data = System.Text.Encoding.UTF8.GetBytes("l4:test5:tests6:testede");
            BEncodedList list = new BEncodedList();

            list.Add(new BEncodedString("test"));
            list.Add(new BEncodedString("tests"));
            list.Add(new BEncodedString("tested"));

            Assert.IsTrue(Toolbox.ByteMatch(data, list.Encode()));
        }
        public ErrorMessage(BEncodedValue transactionId, ErrorCode error, string message)
            : base(ErrorType)
        {
            BEncodedList l = new BEncodedList();

            l.Add(new BEncodedNumber((int)error));
            l.Add(new BEncodedString(message));
            properties.Add(ErrorListKey, l);

            TransactionId = transactionId;
        }
Example #6
0
        public void benListEncodingBuffered()
        {
            byte[]       data = System.Text.Encoding.UTF8.GetBytes("l4:test5:tests6:testede");
            BEncodedList list = new BEncodedList();

            list.Add(new BEncodedString("test"));
            list.Add(new BEncodedString("tests"));
            list.Add(new BEncodedString("tested"));
            byte[] result = new byte[list.LengthInBytes()];
            list.Encode(result, 0);
            Assert.IsTrue(Toolbox.ByteMatch(data, result));
        }
Example #7
0
        public void benDictionaryEncoding()
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes("d4:spaml1:a1:bee");

            BEncodedDictionary dict = new BEncodedDictionary();
            BEncodedList list = new BEncodedList();
            list.Add(new BEncodedString("a"));
            list.Add(new BEncodedString("b"));
            dict.Add("spam", list);
            Assert.AreEqual(System.Text.Encoding.UTF8.GetString(data), System.Text.Encoding.UTF8.GetString(dict.Encode()));
            Assert.IsTrue(Toolbox.ByteMatch(data, dict.Encode()));
        }
        public void benDictionaryEncoding()
        {
            var data = Encoding.UTF8.GetBytes("d4:spaml1:a1:bee");

            var dict = new BEncodedDictionary();
            var list = new BEncodedList();
            list.Add(new BEncodedString("a"));
            list.Add(new BEncodedString("b"));
            dict.Add("spam", list);
            Assert.Equal(Encoding.UTF8.GetString(data), Encoding.UTF8.GetString(dict.Encode()));
            Assert.True(Toolbox.ByteMatch(data, dict.Encode()));
        }
 public void benDictionaryEncodingBuffered()
 {
     var data = Encoding.UTF8.GetBytes("d4:spaml1:a1:bee");
     var dict = new BEncodedDictionary();
     var list = new BEncodedList();
     list.Add(new BEncodedString("a"));
     list.Add(new BEncodedString("b"));
     dict.Add("spam", list);
     var result = new byte[dict.LengthInBytes()];
     dict.Encode(result, 0);
     Assert.True(Toolbox.ByteMatch(data, result));
 }
Example #10
0
        public void benDictionaryEncoding()
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes("d4:spaml1:a1:bee");

            BEncodedDictionary dict = new BEncodedDictionary();
            BEncodedList       list = new BEncodedList();

            list.Add(new BEncodedString("a"));
            list.Add(new BEncodedString("b"));
            dict.Add("spam", list);
            Assert.AreEqual(System.Text.Encoding.UTF8.GetString(data), System.Text.Encoding.UTF8.GetString(dict.Encode()));
            Assert.IsTrue(Toolbox.ByteMatch(data, dict.Encode()));
        }
Example #11
0
        public void benDictionaryEncodingBuffered()
        {
            byte[]             data = System.Text.Encoding.UTF8.GetBytes("d4:spaml1:a1:bee");
            BEncodedDictionary dict = new BEncodedDictionary();
            BEncodedList       list = new BEncodedList();

            list.Add(new BEncodedString("a"));
            list.Add(new BEncodedString("b"));
            dict.Add("spam", list);
            byte[] result = new byte[dict.LengthInBytes()];
            dict.Encode(result, 0);
            Assert.IsTrue(Toolbox.ByteMatch(data, result));
        }
        public void CorruptList()
        {
            var list = new BEncodedList();
            for (var i = 0; i < peers.Count; i++)
                list.Add((BEncodedString) peers[i].CompactPeer());

            list.Insert(2, new BEncodedNumber(5));
            VerifyDecodedPeers(Peer.Decode(list));

            list.Clear();
            list.Add(new BEncodedString(new byte[3]));
            IList<Peer> decoded = Peer.Decode(list);
            Assert.Equal(0, decoded.Count);
        }
Example #13
0
        public void Stop()
        {
            if (torrentManager.State != TorrentState.Hashing)
            {
                torrentManager.Stop();

                while (torrentManager.State != TorrentState.Stopped)
                {
                    Thread.Sleep(250);
                }

                BEncodedList       bl   = new BEncodedList();
                FastResume         fr   = torrentManager.SaveFastResume();
                BEncodedDictionary item = fr.Encode();
                bl.Add(item);
                File.WriteAllBytes(fastResumeFile, bl.Encode());
            }
            else
            {
                torrentManager.Stop();
            }

            File.WriteAllBytes(dhtNodesFile, clientEngine.DhtEngine.SaveNodes());
            clientEngine.Dispose();
        }
Example #14
0
        void AddFiles(BEncodedDictionary dict, IEnumerable <TorrentFile> torrentFiles)
        {
            long totalSize = _piecelength - 1;
            var  bFiles    = new BEncodedList();

            foreach (var torrentFile in torrentFiles)
            {
                var path = new BEncodedList();
                foreach (var split in torrentFile.Path.Split('/'))
                {
                    path.Add((BEncodedString)split);
                }

                var dictionary = new BEncodedDictionary();
                dictionary["path"]   = path;
                dictionary["length"] = (BEncodedNumber)torrentFile.Length;
                bFiles.Add(dictionary);

                totalSize += torrentFile.Length;
            }

            dict[new BEncodedString("torrentFiles")] = bFiles;
            dict[new BEncodedString("name")]         = new BEncodedString("test.torrentFiles");
            dict[new BEncodedString("piece length")] = new BEncodedNumber(_piecelength);
            dict[new BEncodedString("pieces")]       = new BEncodedString(new byte[20 * (totalSize / _piecelength)]);
        }
Example #15
0
        ///<summary>
        ///this adds stuff common to single and multi file torrents
        ///</summary>
        void AddCommonStuff(BEncodedDictionary torrent)
        {
            if (announces.Count > 0 && announces[0].Count > 0)
            {
                torrent.Add("announce", new BEncodedString(announces[0][0]));
            }

            // If there is more than one tier or the first tier has more than 1 tracker
            if (announces.Count > 1 || (announces.Count > 0 && announces[0].Count > 1))
            {
                var announceList = new BEncodedList();
                for (var i = 0; i < announces.Count; i++)
                {
                    var tier = new BEncodedList();
                    for (var j = 0; j < announces[i].Count; j++)
                    {
                        tier.Add(new BEncodedString(announces[i][j]));
                    }

                    announceList.Add(tier);
                }

                torrent.Add("announce-list", announceList);
            }

            var epocheStart = new DateTime(1970, 1, 1);
            var span        = DateTime.Now - epocheStart;

            Logger.Log(null, "creation date: {0} - {1} = {2}:{3}", DateTime.Now, epocheStart, span, span.TotalSeconds);
            torrent.Add("creation date", new BEncodedNumber((long)span.TotalSeconds));
        }
Example #16
0
        static void AddFiles(BEncodedDictionary dict, TorrentFile[] files, int pieceLength)
        {
            long totalSize = pieceLength - 1;
            var  bFiles    = new BEncodedList();

            for (int i = 0; i < files.Length; i++)
            {
                var path = new BEncodedList();
                foreach (string s in files[i].Path.Split('/'))
                {
                    path.Add((BEncodedString)s);
                }
                var d = new BEncodedDictionary {
                    ["path"]   = path,
                    ["length"] = (BEncodedNumber)files[i].Length
                };
                bFiles.Add(d);
                totalSize += files[i].Length;
            }

            dict[new BEncodedString("files")]        = bFiles;
            dict[new BEncodedString("name")]         = new BEncodedString("test.files");
            dict[new BEncodedString("piece length")] = new BEncodedNumber(pieceLength);
            dict[new BEncodedString("pieces")]       = new BEncodedString(new byte[20 * (totalSize / pieceLength)]);
        }
Example #17
0
        public override void Handle(IDhtEngine engine, Node node)
        {
            base.Handle(engine, node);

            BEncodedString   token    = engine.TokenManager.GenerateToken(node);
            GetPeersResponse response = new GetPeersResponse(engine.LocalId, TransactionId, token);

            var result = engine.QueryGetPeers(InfoHash);

            if (result.HasHash)
            {
                BEncodedList list = new BEncodedList();
                foreach (Node n in result.Values)
                {
                    list.Add(n.CompactPort());
                }
                response.Values = list;
            }
            else
            {
                // Is this right?
                response.Nodes = Node.CompactNode(result.Nodes);
            }

            if (Hook == null || Hook(response))
            {
                engine.Send(response, node.EndPoint);
            }
        }
Example #18
0
 internal static BEncodedList Encode(IEnumerable<Peer> peers)
 {
     BEncodedList list = new BEncodedList();
     foreach (Peer p in peers)
         list.Add((BEncodedString)p.CompactPeer());
     return list;
 }
 public void CorruptDictionary()
 {
     var l = new BEncodedList();
     var d = new BEncodedDictionary();
     l.Add(d);
     IList<Peer> decoded = Peer.Decode(l);
     Assert.Equal(0, decoded.Count);
 }
Example #20
0
 public void CorruptDictionary()
 {
     BEncodedList l = new BEncodedList();
     BEncodedDictionary d = new BEncodedDictionary();
     l.Add(d);
     IList<Peer> decoded = Peer.Decode(l);
     Assert.AreEqual(0, decoded.Count, "#1");
 }
        public void CorruptList()
        {
            BEncodedList list = new BEncodedList();

            for (int i = 0; i < peers.Count; i++)
            {
                list.Add((BEncodedString)peers[i].CompactPeer());
            }

            list.Insert(2, new BEncodedNumber(5));
            VerifyDecodedPeers(Peer.Decode(list));

            list.Clear();
            list.Add(new BEncodedString(new byte[3]));
            IList <Peer> decoded = Peer.Decode(list);

            Assert.AreEqual(0, decoded.Count, "#1");
        }
Example #22
0
        public void CorruptDictionary()
        {
            var list = new BEncodedList();
            var dictionary = new BEncodedDictionary();

            list.Add(dictionary);
            IList<Peer> decoded = Peer.Decode(list);
            Assert.AreEqual(0, decoded.Count, "#1");
        }
Example #23
0
        internal static BEncodedList Encode(IEnumerable <Peer> peers)
        {
            var list = new BEncodedList();

            foreach (Peer p in peers)
            {
                list.Add((BEncodedString)PeerInfo.CompactPeer(p.ConnectionUri));
            }
            return(list);
        }
Example #24
0
        public static BEncodedList Encode(IEnumerable <Peer> peers)
        {
            BEncodedList list = new BEncodedList();

            foreach (Peer p in peers)
            {
                list.Add((BEncodedString)p.CompactPeer());
            }
            return(list);
        }
Example #25
0
        internal static BEncodedList Encode(IEnumerable <Peer> peers)
        {
            var list = new BEncodedList();

            foreach (var p in peers)
            {
                list.Add((BEncodedString)p.CompactPeer());
            }
            return(list);
        }
Example #26
0
        public void CorruptDictionary()
        {
            var list       = new BEncodedList();
            var dictionary = new BEncodedDictionary();

            list.Add(dictionary);
            IList <Peer> decoded = Peer.Decode(list);

            Assert.AreEqual(0, decoded.Count, "#1");
        }
        public void CorruptDictionary()
        {
            BEncodedList       l = new BEncodedList();
            BEncodedDictionary d = new BEncodedDictionary();

            l.Add(d);
            IList <Peer> decoded = Peer.Decode(l);

            Assert.AreEqual(0, decoded.Count, "#1");
        }
Example #28
0
        public void GetPeersResponseDecode()
        {
            GetPeersEncode();
            MessageFactory.RegisterSend(message);

            string           text = "d1:rd2:id20:abcdefghij01234567895:token8:aoeusnth6:valuesl6:axje.u6:idhtnmee1:t2:aa1:y1:re";
            GetPeersResponse m    = (GetPeersResponse)Decode(text);

            Assert.AreEqual(token, m.Token, "#1");
            Assert.AreEqual(id, m.Id, "#2");

            BEncodedList l = new BEncodedList();

            l.Add((BEncodedString)"axje.u");
            l.Add((BEncodedString)"idhtnm");
            Assert.AreEqual(l, m.Values, "#3");

            Compare(m, text);
        }
        private static BEncodedDictionary CreateTorrent(int pieceLength)
        {
            var infoDict = new BEncodedDictionary();
            infoDict[new BEncodedString("piece length")] = new BEncodedNumber(pieceLength);
            infoDict[new BEncodedString("pieces")] = new BEncodedString(new byte[20*15]);
            infoDict[new BEncodedString("length")] = new BEncodedNumber(15*256*1024 - 1);
            infoDict[new BEncodedString("name")] = new BEncodedString("test.files");

            var dict = new BEncodedDictionary();
            dict[new BEncodedString("info")] = infoDict;

            var announceTier = new BEncodedList();
            announceTier.Add(new BEncodedString("custom://transfers1/announce"));
            announceTier.Add(new BEncodedString("custom://transfers2/announce"));
            announceTier.Add(new BEncodedString("http://transfers3/announce"));
            var announceList = new BEncodedList();
            announceList.Add(announceTier);
            dict[new BEncodedString("announce-list")] = announceList;
            return dict;
        }
        public void DecodeList()
        {
            // List of String
            BEncodedList list = new BEncodedList();

            foreach (Peer p in peers)
            {
                list.Add((BEncodedString)p.CompactPeer());
            }

            VerifyDecodedPeers(Peer.Decode(list));
        }
        private void SaveFastResume(TorrentManager[] managers)
        {
            BEncodedList list = new BEncodedList();

            foreach (TorrentManager manager in managers)
            {
                FastResume         data       = manager.SaveFastResume();
                BEncodedDictionary fastResume = data.Encode();
                list.Add(fastResume);
            }

            File.WriteAllBytes(pathToFolderApplicationData + "\\FastResume.dat", list.Encode());
        }
Example #32
0
        public void DecodeDictionary()
        {
            BEncodedList list = new BEncodedList();

            foreach (Peer p in peers)
            {
                BEncodedDictionary dict = new BEncodedDictionary();
                dict.Add("ip", (BEncodedString)p.ConnectionUri.Host);
                dict.Add("port", (BEncodedNumber)p.ConnectionUri.Port);
                dict.Add("peer id", (BEncodedString)p.PeerId);
                list.Add(dict);
            }

            VerifyDecodedPeers(Peer.Decode(list));
        }
        private static BEncodedDictionary CreateTorrent(int pieceLength)
        {
            BEncodedDictionary infoDict = new BEncodedDictionary();

            infoDict[new BEncodedString("piece length")] = new BEncodedNumber(pieceLength);
            infoDict[new BEncodedString("pieces")]       = new BEncodedString(new byte[20 * 15]);
            infoDict[new BEncodedString("length")]       = new BEncodedNumber(15 * 256 * 1024 - 1);
            infoDict[new BEncodedString("name")]         = new BEncodedString("test.files");

            BEncodedDictionary dict = new BEncodedDictionary();

            dict[new BEncodedString("info")] = infoDict;

            BEncodedList announceTier = new BEncodedList();

            announceTier.Add(new BEncodedString("custom://transfers1/announce"));
            announceTier.Add(new BEncodedString("custom://transfers2/announce"));
            announceTier.Add(new BEncodedString("http://transfers3/announce"));
            BEncodedList announceList = new BEncodedList();

            announceList.Add(announceTier);
            dict[new BEncodedString("announce-list")] = announceList;
            return(dict);
        }
Example #34
0
        private static void AddAnnounces(BEncodedDictionary dict, string[][] tiers)
        {
            BEncodedList announces = new BEncodedList();

            foreach (string[] tier in tiers)
            {
                BEncodedList bTier = new BEncodedList();
                announces.Add(bTier);
                foreach (string s in tier)
                {
                    bTier.Add((BEncodedString)s);
                }
            }
            dict["announce"]      = (BEncodedString)tiers[0][0];
            dict["announce-list"] = announces;
        }
Example #35
0
        public void SaveState()
        {
            BEncodedList list = new BEncodedList();

            foreach (TorrentManagerAdapter adapter in this.downloaders.Values)
            {
                TorrentData d = new TorrentData();
                d.FastResume  = adapter.Manager.SaveFastResume();
                d.SavePath    = adapter.Manager.SavePath;
                d.Settings    = adapter.Manager.Settings;
                d.TorrentPath = adapter.Manager.Torrent.TorrentPath;
                list.Add(d.Serialize());
            }

            System.IO.File.WriteAllBytes(System.IO.Path.Combine(StoragePath, SettingsFile), list.Encode());
        }
Example #36
0
 public void StoreFastResume()
 {
     try
     {
         logger.Info("storing fast resume");
         BEncodedList list = new BEncodedList();
         foreach (Download t in Torrents)
         {
             list.Add(t.SaveFastResume().Encode());
         }
         File.WriteAllBytes(Defines.SerializedFastResume, list.Encode());
     }
     catch (Exception ex)
     {
         logger.Warn(string.Format("Couldn't store fast resume: {0}", ex));
     }
 }
Example #37
0
        ///<summary>
        ///used for creating multi file mode torrents.
        ///</summary>
        ///<returns>the dictionary representing which is stored in the torrent file</returns>
        protected void CreateMultiFileTorrent(BEncodedDictionary dictionary, TorrentFile[] files, PieceWriter writer, string name)
        {
            AddCommonStuff(dictionary);
            var info = (BEncodedDictionary)dictionary["info"];

            var torrentFiles = new BEncodedList();             //the dict which hold the file infos

            for (var i = 0; i < files.Length; i++)
            {
                torrentFiles.Add(GetFileInfoDict(files[i]));
            }

            info.Add("files", torrentFiles);

            Logger.Log(null, "Topmost directory: {0}", name);
            info.Add("name", new BEncodedString(name));

            info.Add("pieces", new BEncodedString(CalcPiecesHash(Path, files, writer)));
        }
Example #38
0
        public void SaveFastResume()
        {
            if (string.IsNullOrWhiteSpace(settings.FastResumePath))
            {
                return;
            }

            var encodedList    = new BEncodedList();
            var fastResumeData = torrentsReadonly
                                 .Where(x => x.HashChecked)
                                 .Select(tm => tm.SaveFastResume().Encode());

            foreach (var data in fastResumeData)
            {
                encodedList.Add(data);
            }

            File.WriteAllBytes(settings.FastResumePath, encodedList.Encode());
        }
Example #39
0
		public override void Handle(DhtEngine engine, Node node)
		{
			base.Handle(engine, node);

			BEncodedString token = engine.TokenManager.GenerateToken(node);
			var response = new GetPeersResponse(engine.RoutingTable.LocalNode.Id, TransactionId, token);
			if (engine.Torrents.ContainsKey(InfoHash))
			{
				var list = new BEncodedList();
				foreach (Node n in engine.Torrents[InfoHash])
					list.Add(n.CompactPort());
				response.Values = list;
			}
			else
			{
				// Is this right?
				response.Nodes = Node.CompactNode(engine.RoutingTable.GetClosest(InfoHash));
			}

			engine.MessageLoop.EnqueueSend(response, node.EndPoint);
		}
Example #40
0
        BEncodedValue ToFileInfoDict(TorrentFile file)
        {
            BEncodedDictionary fileDict = new BEncodedDictionary();

            BEncodedList filePath = new BEncodedList();

            string [] splittetPath = file.Path.Split(new char [] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string s in splittetPath)
            {
                filePath.Add(new BEncodedString(s));
            }

            fileDict ["length"] = new BEncodedNumber(file.Length);
            fileDict ["path"]   = filePath;
            if (file.MD5 != null)
            {
                fileDict ["md5sum"] = (BEncodedString)file.MD5;
            }

            return(fileDict);
        }
		///<summary>
		///this adds stuff common to single and multi file torrents
		///</summary>
		void AddCommonStuff(BEncodedDictionary torrent)
		{
			if (announces.Count > 0 && announces[0].Count > 0) torrent.Add("announce", new BEncodedString(announces[0][0]));

			// If there is more than one tier or the first tier has more than 1 tracker
			if (announces.Count > 1 || (announces.Count > 0 && announces[0].Count > 1))
			{
				var announceList = new BEncodedList();
				for (var i = 0; i < announces.Count; i++)
				{
					var tier = new BEncodedList();
					for (var j = 0; j < announces[i].Count; j++) tier.Add(new BEncodedString(announces[i][j]));

					announceList.Add(tier);
				}

				torrent.Add("announce-list", announceList);
			}

			var epocheStart = new DateTime(1970, 1, 1);
			var span = DateTime.Now - epocheStart;
			Logger.Log(null, "creation date: {0} - {1} = {2}:{3}", DateTime.Now, epocheStart, span, span.TotalSeconds);
			torrent.Add("creation date", new BEncodedNumber((long)span.TotalSeconds));
		}
Example #42
0
        private BEncodedList CreateFiles()
        {
            BEncodedList files = new BEncodedList();
            BEncodedDictionary file;
            BEncodedList path;

            path = new BEncodedList();
            path.Add(new BEncodedString("file1.txt"));

            file = new BEncodedDictionary();
            file.Add("sha1", new BEncodedString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("file1 hash1"))));
            file.Add("ed2k", new BEncodedString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("file1 hash2"))));
            file.Add("length", new BEncodedNumber(50000));
            file.Add("md5sum", new BEncodedString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("file1 hash3"))));
            file.Add("path.utf-8", path);
            file.Add("path", path);

            files.Add(file);


            path = new BEncodedList();
            path.Add(new BEncodedString("subfolder1"));
            path.Add(new BEncodedString("file2.txt"));

            file = new BEncodedDictionary();
            file.Add("sha1", new BEncodedString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("file1 hash1"))));
            file.Add("ed2k", new BEncodedString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("file1 hash2"))));
            file.Add("length", new BEncodedNumber(60000));
            file.Add("md5sum", new BEncodedString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("file1 hash3"))));
            file.Add("path.utf-8", path);
            file.Add("path", path);

            files.Add(file);


            path = new BEncodedList();
            path.Add(new BEncodedString("subfolder1"));
            path.Add(new BEncodedString("subfolder2"));
            path.Add(new BEncodedString("file3.txt"));

            file = new BEncodedDictionary();
            file.Add("sha1", new BEncodedString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("file1 hash1"))));
            file.Add("ed2k", new BEncodedString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("file1 hash2"))));
            file.Add("length", new BEncodedNumber(70000));
            file.Add("md5sum", new BEncodedString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("file1 hash3"))));
            file.Add("path.utf-8", path);
            file.Add("path", path);

            files.Add(file);


            path = new BEncodedList();
            path.Add(new BEncodedString("subfolder1"));
            path.Add(new BEncodedString("subfolder2"));
            path.Add(new BEncodedString("file4.txt"));

            file = new BEncodedDictionary();
            file.Add("sha1", new BEncodedString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("file1 hash1"))));
            file.Add("ed2k", new BEncodedString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("file1 hash2"))));
            file.Add("length", new BEncodedNumber(80000));
            file.Add("md5sum", new BEncodedString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("file1 hash3"))));
            file.Add("path.utf-8", path);
            file.Add("path", path);

            files.Add(file);

            return files;
        }
Example #43
0
        public byte[] SaveNodes()
        {
            var details = new BEncodedList();

            MainLoop.QueueWait(delegate
            {
                foreach (var b in RoutingTable.Buckets)
                {
                    foreach (var n in b.Nodes.Where(n => n.State != NodeState.Bad))
                        details.Add(n.CompactNode());

                    if (b.Replacement != null)
                        if (b.Replacement.State != NodeState.Bad)
                            details.Add(b.Replacement.CompactNode());
                }
            });

            return details.Encode();
        }
Example #44
0
 public void benListEncodingBuffered()
 {
     byte[] data = System.Text.Encoding.UTF8.GetBytes("l4:test5:tests6:testede");
     BEncodedList list = new BEncodedList();
     list.Add(new BEncodedString("test"));
     list.Add(new BEncodedString("tests"));
     list.Add(new BEncodedString("tested"));
     byte[] result = new byte[list.LengthInBytes()];
     list.Encode(result, 0);
     Assert.IsTrue(Toolbox.ByteMatch(data, result));
 }
        public void benListEncoding()
        {
            var data = Encoding.UTF8.GetBytes("l4:test5:tests6:testede");
            var list = new BEncodedList();
            list.Add(new BEncodedString("test"));
            list.Add(new BEncodedString("tests"));
            list.Add(new BEncodedString("tested"));

            Assert.True(Toolbox.ByteMatch(data, list.Encode()));
        }
Example #46
0
 private static void AddAnnounces(BEncodedDictionary dict, string[][] tiers)
 {
     var announces = new BEncodedList();
     foreach (var tier in tiers)
     {
         var bTier = new BEncodedList();
         announces.Add(bTier);
         foreach (var s in tier)
             bTier.Add((BEncodedString) s);
     }
     dict["announce"] = (BEncodedString) tiers[0][0];
     dict["announce-list"] = announces;
 }
Example #47
0
        private void AddFiles(BEncodedDictionary dict, TorrentFile[] files)
        {
            long totalSize = piecelength - 1;
            var bFiles = new BEncodedList();
            for (var i = 0; i < files.Length; i++)
            {
                var path = new BEncodedList();
                foreach (var s in files[i].Path.Split('/'))
                    path.Add((BEncodedString) s);
                var d = new BEncodedDictionary();
                d["path"] = path;
                d["length"] = (BEncodedNumber) files[i].Length;
                bFiles.Add(d);
                totalSize += files[i].Length;
            }

            dict[new BEncodedString("files")] = bFiles;
            dict[new BEncodedString("name")] = new BEncodedString("test.files");
            dict[new BEncodedString("piece length")] = new BEncodedNumber(piecelength);
            dict[new BEncodedString("pieces")] = new BEncodedString(new byte[20*(totalSize/piecelength)]);
        }
        public void DecodeDictionary()
        {
            var list = new BEncodedList();
            foreach (var p in peers)
            {
                var dict = new BEncodedDictionary();
                dict.Add("ip", (BEncodedString) p.ConnectionUri.Host);
                dict.Add("port", (BEncodedNumber) p.ConnectionUri.Port);
                dict.Add("peer id", (BEncodedString) p.PeerId);
                list.Add(dict);
            }

            VerifyDecodedPeers(Peer.Decode(list));
        }
Example #49
0
 internal static BEncodedList Encode(IEnumerable<Peer> peers)
 {
     BEncodedList list = new BEncodedList();
     foreach (Peer p in peers)
         list.Add((BEncodedString)p.CompactPeer());
     return list;
 }
Example #50
0
        public void SaveFastResume()
        {
            if (string.IsNullOrWhiteSpace(settings.FastResumePath))
                return;

            var encodedList = new BEncodedList();
            var fastResumeData = torrentsReadonly
                .Where(x => x.HashChecked)
                .Select(tm => tm.SaveFastResume().Encode());
            foreach (var data in fastResumeData)
                encodedList.Add(data);

            File.WriteAllBytes(settings.FastResumePath, encodedList.Encode());
        }
		///<summary>
		///used for creating multi file mode torrents.
		///</summary>
		///<returns>the dictionary representing which is stored in the torrent file</returns>
		protected void CreateMultiFileTorrent(BEncodedDictionary dictionary, TorrentFile[] files, PieceWriter writer, string name)
		{
			AddCommonStuff(dictionary);
			var info = (BEncodedDictionary)dictionary["info"];

			var torrentFiles = new BEncodedList(); //the dict which hold the file infos

			for (var i = 0; i < files.Length; i++) torrentFiles.Add(GetFileInfoDict(files[i]));

			info.Add("files", torrentFiles);

			Logger.Log(null, "Topmost directory: {0}", name);
			info.Add("name", new BEncodedString(name));

			info.Add("pieces", new BEncodedString(CalcPiecesHash(Path, files, writer)));
		}
Example #52
0
        public void GetPeersResponseDecode()
        {
            GetPeersEncode();
            MessageFactory.RegisterSend(message);

            string text = "d1:rd2:id20:abcdefghij01234567895:token8:aoeusnth6:valuesl6:axje.u6:idhtnmee1:t2:aa1:y1:re";
            GetPeersResponse m = (GetPeersResponse)Decode(text);

            Assert.AreEqual(token, m.Token, "#1");
            Assert.AreEqual(id, m.Id, "#2");

            BEncodedList l = new BEncodedList();
            l.Add((BEncodedString)"axje.u");
            l.Add((BEncodedString)"idhtnm");
            Assert.AreEqual(l, m.Values, "#3");

            Compare(m, text);
        }
		///<summary>
		///this method is used for multi file mode torrents to return a dictionary with
		///file relevant informations. 
		///<param name="file">the file to report the informations for</param>
		///<param name="basePath">used to subtract the absolut path information</param>
		///</summary>
		BEncodedDictionary GetFileInfoDict(TorrentFile file)
		{
			var fileDict = new BEncodedDictionary();

			fileDict.Add("length", new BEncodedNumber(file.Length));

			var filePath = new BEncodedList();
			var splittetPath = file.Path.Split(System.IO.Path.DirectorySeparatorChar);

			foreach (var s in splittetPath)
			{
				if (s.Length > 0) //exclude empties
					filePath.Add(new BEncodedString(s));
			}

			fileDict.Add("path", filePath);

			return fileDict;
		}
        private BEncodedValue ToFileInfoDict(TorrentFile file)
        {
            var fileDict = new BEncodedDictionary();

            var filePath = new BEncodedList();
            var splittetPath = file.Path.Split(new[] {Path.DirectorySeparatorChar},
                StringSplitOptions.RemoveEmptyEntries);
            foreach (var s in splittetPath)
                filePath.Add(new BEncodedString(s));

            fileDict["length"] = new BEncodedNumber(file.Length);
            fileDict["path"] = filePath;
            if (file.MD5 != null)
                fileDict["md5sum"] = (BEncodedString) file.MD5;

            return fileDict;
        }
Example #55
0
        private static void AddSingleFile(BEncodedDictionary dict, int pieceLength)
        {
            BEncodedNumber[] sizes = new BEncodedNumber[] { (int)(pieceLength * 0.44) +
                                                            (int)(pieceLength * 13.25)+
                                                            (int)(pieceLength * 23.68)+
                                                            (int)(pieceLength * 2.05) };

            List<BEncodedList> paths = new List<BEncodedList>();
            paths.Add(new BEncodedList(new BEncodedString[] { "Dir1", "File1" }));

            BEncodedList files = new BEncodedList();
            for (int i = 0; i < paths.Count; i++)
            {
                BEncodedDictionary d = new BEncodedDictionary();
                d["path"] = paths[i];
                d["length"] = sizes[i];
                files.Add(d);
            }

            dict[new BEncodedString("files")] = files;
            dict[new BEncodedString("name")] = new BEncodedString("test.files");
            dict[new BEncodedString("piece length")] = new BEncodedNumber(pieceLength);
            dict[new BEncodedString("pieces")] = new BEncodedString(new byte[20 * 40]);
            dict["url-list"] = (BEncodedString)"http://127.0.0.1:120/announce/File1.exe";
        }
Example #56
0
        public byte[] SaveNodes()
        {
            BEncodedList details = new BEncodedList();

            MainLoop.QueueWait((MainLoopTask)delegate {
                foreach (Bucket b in RoutingTable.Buckets)
                {
                    foreach (Node n in b.Nodes)
                        if (n.State != NodeState.Bad)
                            details.Add(n.CompactNode());

                    if (b.Replacement != null)
                        if (b.Replacement.State != NodeState.Bad)
                            details.Add(b.Replacement.CompactNode());
                }
            });

            return details.Encode();
        }
        public void DecodeList()
        {
            // List of String
            var list = new BEncodedList();
            foreach (var p in peers)
                list.Add((BEncodedString) p.CompactPeer());

            VerifyDecodedPeers(Peer.Decode(list));
        }
Example #58
0
        public void benListEncoding()
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes("l4:test5:tests6:testede");
            BEncodedList list = new BEncodedList();
            list.Add(new BEncodedString("test"));
            list.Add(new BEncodedString("tests"));
            list.Add(new BEncodedString("tested"));

            Assert.IsTrue(Toolbox.ByteMatch(data, list.Encode()));
        }
Example #59
0
        ///<summary>
        ///this method is used for multi file mode torrents to return a dictionary with
        ///file relevant informations. 
        ///<param name="file">the file to report the informations for</param>
        ///<param name="basePath">used to subtract the absolut path information</param>
        ///</summary>
        private BEncodedDictionary GetFileInfoDict(TorrentFile file)
        {
            BEncodedDictionary fileDict = new BEncodedDictionary();

            fileDict.Add("length", new BEncodedNumber(file.Length));

            #warning Implement this again
            //if (StoreMD5)
                //AddMD5(fileDict, file);

            Logger.Log(null, "Without base: {0}", file.Path);
            BEncodedList filePath = new BEncodedList();
            string[] splittetPath = file.Path.Split(System.IO.Path.DirectorySeparatorChar);

            foreach (string s in splittetPath)
            {
                if (s.Length > 0)//exclude empties
                    filePath.Add(new BEncodedString(s));
            }

            fileDict.Add("path", filePath);

            return fileDict;
        }
Example #60
0
        public byte[] SaveNodes()
        {
            var details = new BEncodedList();

            MainLoop.QueueWait(() =>
                                   {
                                       foreach (var bucket in RoutingTable.Buckets)
                                       {
                                           foreach (var node in bucket.Nodes)
                                               if (node.State != NodeState.Bad)
                                                   details.Add(node.CompactNode());

                                           if (bucket.Replacement != null)
                                               if (bucket.Replacement.State != NodeState.Bad)
                                                   details.Add(bucket.Replacement.CompactNode());
                                       }
                                   });

            return details.Encode();
        }