Beispiel #1
0
        public void TestDecodeByteArray1()
        {
            //Test1
            BytesNode bah1 = (BytesNode)BEncodingFactory.Decode("10:0123456789");

            Assert.AreEqual(bah1.ByteArray, _encoding.GetBytes("0123456789"));
            Assert.AreEqual(bah1.StringText, "0123456789");

            //Test2
            BytesNode bah2 = (BytesNode)BEncodingFactory.Decode("26:abcdefghijklmnopqrstuvwxyz");

            Assert.AreEqual(bah2.ByteArray, _encoding.GetBytes("abcdefghijklmnopqrstuvwxyz"));
            Assert.AreEqual(bah2.StringText, "abcdefghijklmnopqrstuvwxyz");

            //Test3
            BytesNode bah3 = (BytesNode)BEncodingFactory.Decode("186:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");

            Assert.AreEqual(bah3.ByteArray, _encoding.GetBytes("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"));
            Assert.AreEqual(bah3.StringText, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");

            //Test4
            BytesNode bah4 = (BytesNode)BEncodingFactory.Decode("0:");

            Assert.AreEqual(bah4.ByteArray, _encoding.GetBytes(string.Empty));
            Assert.AreEqual(bah4.StringText, string.Empty);
        }
Beispiel #2
0
        public void TestDecodeDictionary1()
        {
            //Test1整数
            DictNode dh1 = (DictNode)BEncodingFactory.Decode("d3:agei25ee");

            Assert.AreEqual(((IntNode)dh1["age"]).Value, 25);

            //Test2字节数组
            DictNode dh2 = (DictNode)BEncodingFactory.Decode("d3:agei25e5:color4:bluee");

            Assert.AreEqual(((IntNode)dh2["age"]).Value, 25);

            Assert.AreEqual((dh2["color"] as BytesNode).ByteArray, _encoding.GetBytes("blue"));
            Assert.AreEqual((dh2["color"] as BytesNode).StringText, "blue");

            //Test3字节数组与整数
            DictNode dh3        = (DictNode)BEncodingFactory.Decode("d8:spam.mp3d6:author5:Alice6:lengthi1048576eee");
            DictNode dHandler31 = (DictNode)dh3["spam.mp3"];

            Assert.AreEqual((dHandler31["author"] as BytesNode).ByteArray, _encoding.GetBytes("Alice"));
            Assert.AreEqual((dHandler31["author"] as BytesNode).StringText, "Alice");
            Assert.AreEqual(((IntNode)dHandler31["length"]).Value, 1048576);

            //Test4空字典
            DictNode dh4 = (DictNode)BEncodingFactory.Decode("de");

            Assert.AreEqual(dh4.Count, 0);
        }
Beispiel #3
0
        public void TestDecodeHandler1()
        {
            byte[]   source = File.ReadAllBytes(@"E:\Bittorrent\Torrents\winedt70.exe.torrent");
            DictNode dh     = (DictNode)BEncodingFactory.Decode(source);

            Assert.AreEqual("http://192.168.1.150:8080/announce", (dh["announce"] as BytesNode).StringText);
            Assert.AreEqual("http://192.168.1.150:8080/announce", _encoding.GetString((dh["announce"] as BytesNode).ByteArray));
        }
Beispiel #4
0
        public void TestDecodeList1()
        {
            //Test1整数
            ListNode lh1 = (ListNode)BEncodingFactory.Decode("li0ei1ei2ee");

            Assert.AreEqual(((IntNode)lh1[0]).Value, 0);
            Assert.AreEqual(((IntNode)lh1[1]).Value, 1);
            Assert.AreEqual(((IntNode)lh1[2]).Value, 2);

            //Test2字节数组
            ListNode lh2 = (ListNode)BEncodingFactory.Decode("l3:abc2:xye");

            Assert.AreEqual((lh2[0] as BytesNode).ByteArray, _encoding.GetBytes("abc"));
            Assert.AreEqual((lh2[0] as BytesNode).StringText, "abc");

            Assert.AreEqual((lh2[1] as BytesNode).ByteArray, _encoding.GetBytes("xy"));
            Assert.AreEqual((lh2[1] as BytesNode).StringText, "xy");

            //Test3空字节数组
            ListNode lh3 = (ListNode)BEncodingFactory.Decode("l0:0:0:e");

            Assert.AreEqual((lh3[0] as BytesNode).ByteArray, _encoding.GetBytes(string.Empty));
            Assert.AreEqual((lh3[0] as BytesNode).StringText, string.Empty);

            Assert.AreEqual((lh3[1] as BytesNode).ByteArray, _encoding.GetBytes(string.Empty));
            Assert.AreEqual((lh3[1] as BytesNode).StringText, string.Empty);

            Assert.AreEqual((lh3[2] as BytesNode).ByteArray, _encoding.GetBytes(string.Empty));
            Assert.AreEqual((lh3[2] as BytesNode).StringText, string.Empty);

            //Test4字节数组与整数
            ListNode lh4        = (ListNode)BEncodingFactory.Decode("ll5:Alice3:Bobeli2ei3eee");
            ListNode lHandler40 = (ListNode)lh4[0];
            ListNode lHandler41 = (ListNode)lh4[1];

            Assert.AreEqual((lHandler40[0] as BytesNode).ByteArray, _encoding.GetBytes("Alice"));
            Assert.AreEqual((lHandler40[0] as BytesNode).StringText, "Alice");

            Assert.AreEqual((lHandler40[1] as BytesNode).ByteArray, _encoding.GetBytes("Bob"));
            Assert.AreEqual((lHandler40[1] as BytesNode).StringText, "Bob");

            Assert.AreEqual(((IntNode)lHandler41[0]).Value, 2);

            Assert.AreEqual(((IntNode)lHandler41[1]).Value, 3);

            //Test5空列表
            ListNode lh5 = (ListNode)BEncodingFactory.Decode("le");

            Assert.AreEqual(lh5.Count, 0);
        }
Beispiel #5
0
        public void TestDecodeInteger1()
        {
            //Test1正整数
            IntNode ih1 = (IntNode)BEncodingFactory.Decode("i10e");

            Assert.AreEqual(ih1.Value, 10);

            //Test2零
            IntNode ih2 = (IntNode)BEncodingFactory.Decode("i0e");

            Assert.AreEqual(ih2.Value, 0);

            //Test3负整数
            IntNode ih3 = (IntNode)BEncodingFactory.Decode("i-55e");

            Assert.AreEqual(ih3.Value, -55);

            //Test4所有的数字
            IntNode ih4 = (IntNode)BEncodingFactory.Decode("i1234567890e");

            Assert.AreEqual(ih4.Value, 1234567890);
        }
Beispiel #6
0
        public void TestEncodeHandler1()
        {
            FileStream sourceFile = File.OpenRead(@"E:\Bittorrent\Torrents\winedt70.exe.torrent");

            byte[] source = new byte[sourceFile.Length];
            sourceFile.Read(source, 0, (int)sourceFile.Length);
            sourceFile.Close();
            DictNode dh = (DictNode)BEncodingFactory.Decode(source);

            byte[]     destion    = BEncodingFactory.ByteArrayEncode(dh);
            FileStream targetFile = File.OpenWrite(@"E:\Bittorrent\Torrents\test.torrent");

            targetFile.Write(destion, 0, destion.Length);

            int i;

            for (i = 0; i < source.Length; i++)
            {
                Assert.AreEqual(source[i], destion[i]);
            }

            targetFile.Close();
        }
Beispiel #7
0
 public void TestDecodeDictionary6()
 {
     BEncodingFactory.Decode("di1e0:e");
 }
Beispiel #8
0
 public void TestDecodeDictionary5()
 {
     BEncodingFactory.Decode("d3:fooe");
 }
Beispiel #9
0
 public void TestDecodeDictionary4()
 {
     BEncodingFactory.Decode("de0564adf");
 }
Beispiel #10
0
 public void TestDecodeDictionary2()
 {
     BEncodingFactory.Decode("d3:agei25e3:agei50ee");
 }
Beispiel #11
0
 public void TestDecodeHandler2()
 {
     BEncodingFactory.Decode("");
 }
Beispiel #12
0
 public void TestDecodeInteger5()
 {
     BEncodingFactory.Decode("i123");
 }
Beispiel #13
0
        public static void StartDownload(Parameters parameters, Flag doneFlag, StatusDelegate statusFunction, ErrorDelegate errorFunction, FinishedDelegate finishedFunction)
        {
            if (parameters.ResponseFile.Length == 0 && parameters.Url.Length == 0)
            {
                throw new BitTorrentException("需要Response file 或者 Url");
            }

            Parameters = parameters;
            Stream stream = null;

            byte[] response;
            long   length = 0;

            try
            {
                if (parameters.ResponseFile.Length != 0)
                {
                    stream = File.OpenRead(parameters.ResponseFile);
                    length = stream.Length;
                }

                else
                {
                    WebRequest  webRequest  = WebRequest.Create(parameters.Url);
                    WebResponse webResponse = webRequest.GetResponse();
                    stream = webResponse.GetResponseStream();
                    length = webResponse.ContentLength;
                }

                response = new byte[length];
                stream.Read(response, 0, (int)length);
            }

            catch
            {
                throw new BitTorrentException("Problem getting response info");
            }

            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }

            DictNode rootNode;

            try
            {
                rootNode = BEncodingFactory.Decode(response) as DictNode;
                //BTFormat.CheckMessage(rootNode);
            }
            catch
            {
                throw new BitTorrentException("got bad file");
            }

            DictNode       infoNode = rootNode["info"] as DictNode;
            List <BitFile> files    = new List <BitFile>();
            string         file;
            long           fileLength;

            try
            {
                if (infoNode.ContainsKey("length"))
                {
                    fileLength = (infoNode["length"] as IntNode).Value;
                    BytesNode nameNode = (infoNode["name"] as BytesNode);
                    if (nameNode == null)
                    {
                        return;
                    }
                    file = @"k:\torrent\" + nameNode.StringText;
                    Make(file, false);
                    files.Add(new BitFile(file, fileLength));
                }

                else
                {
                    fileLength = 0L;
                    ListNode filesNode = infoNode["files"] as ListNode;
                    foreach (BEncodedNode handler in filesNode)
                    {
                        DictNode fileNode = infoNode["files"] as DictNode;
                        fileLength += (fileNode["length"] as IntNode).Value;
                    }
                    //访问文件夹
                    BytesNode nameNode = infoNode["name"] as BytesNode;
                    if (nameNode == null)
                    {
                        return;
                    }
                    file = @"C:\torrent\" + nameNode.StringText;
                    // if this path exists, and no files from the info dict exist, we assume it's a new download and
                    // the user wants to create a new directory with the default name
                    bool existed = false;
                    if (Directory.Exists(file))
                    {
                        foreach (BEncodedNode handler in filesNode)
                        {
                            DictNode fileNode = handler as DictNode;
                            ListNode pathNode = fileNode["path"] as ListNode;
                            if (File.Exists(Path.Combine(file, (pathNode[0] as BytesNode).StringText)))
                            {
                                existed = true;
                                break;
                            }
                        }

                        if (!existed)
                        {
                            file = Path.Combine(file, (infoNode["name"] as BytesNode).StringText);
                        }
                    }
                    Make(file, true);

                    // alert the UI to any possible change in path
                    //TODO: if (pathFunc != null)
                    // pathFunc(file)

                    foreach (BEncodedNode handler in filesNode)
                    {
                        DictNode fileNode = handler as DictNode;
                        ListNode pathNode = fileNode["path"] as ListNode;
                        string   n        = file;
                        foreach (BEncodedNode stringHandler in pathNode)
                        {
                            n = Path.Combine(n, (stringHandler as BytesNode).StringText);
                        }
                        files.Add(new BitFile(n, (fileNode["length"] as IntNode).Value));
                        Make(n, false);
                    }
                }
            }
            catch
            {
                throw new BitTorrentException("Couldn't allocate directory...");
            }

            Flag           finishFlag     = new Flag();
            FinishedHelper finishedHelper = new FinishedHelper();

            finishedHelper.ErrorFunction    = errorFunction;
            finishedHelper.FinishedFunction = finishedFunction;
            finishedHelper.DoneFlag         = finishFlag;

            string sID = DateTime.Now.ToLongDateString() + "www.wallywood.co.uk";

            byte[] myID = Globals.GetSha1Hash(Encoding.ASCII.GetBytes(sID));//Globals.Sha1.ComputeHash(Encoding.Default.GetBytes(sID));

            byte[]        piece  = (infoNode["pieces"] as BytesNode).ByteArray;
            List <byte[]> pieces = new List <byte[]>();

            for (int i = 0; i < piece.Length; i += 20)
            {
                byte[] temp = new byte[20];
                Buffer.BlockCopy(piece, i, temp, 0, 20);
                pieces.Add(temp);
            }

            Storage _storage = null;

            try
            {
                try
                {
                    //_storage = new Storage(files, parameters.AllocatePause, statusFunction);
                    finishedHelper.Storage = _storage;
                }
                catch (Exception ex)
                {
                    errorFunction("trouble accessing files - " + ex.Message);
                }
                IntNode pieceLengthNode = infoNode["piece length"] as IntNode;
                StorageWrapper = new StorageWrapper(_storage, parameters.DownloadSliceSize, pieces, (int)pieceLengthNode.Value,
                                                    finishedHelper.Finished, finishedHelper.Failed, statusFunction, finishFlag, parameters.CheckHashes,
                                                    finishedHelper.DataFlunked);
            }
            // Catch ValueError
            // failed("bad data")
            // catch IO Error
            catch (Exception ex)
            {
                finishedHelper.Failed("Problem - " + ex.Message);
            }

            if (finishFlag.IsSet)
            {
                return;
            }

            RawServer rawServer = new RawServer(finishFlag, parameters.TimeoutCheckInterval, parameters.Timeout, false);

            if (parameters.MaxPort < parameters.MinPort)
            {
                int temp = parameters.MinPort;
                parameters.MinPort = parameters.MaxPort;
                parameters.MaxPort = parameters.MinPort;
            }

            ushort listenPort;

            for (listenPort = parameters.MinPort; listenPort <= parameters.MaxPort; listenPort++)
            {
                try
                {
                    rawServer.Bind(listenPort, parameters.Bind, false);
                    break;
                }
                catch (SocketException)
                {
                    //TODO: Error Code
                }
            }

            //TODO: Check whether nothing bound
            Choker = new Choker(parameters.MaxUploads, rawServer.AddTask, finishFlag);
            Measure     uploadMeasure   = new Measure(parameters.MaxRatePeriod, parameters.UploadRateFudge);
            Measure     downloadMeasure = new Measure(parameters.MaxRatePeriod);
            RateMeasure rateMeasure     = new RateMeasure(StorageWrapper.LeftLength);
            Downloader  downloader      =
                new NormalDownloader(StorageWrapper, new PiecePicker(pieces.Count), parameters.RequestBackLog,
                                     parameters.MaxRatePeriod, pieces.Count, downloadMeasure, parameters.SnubTime,
                                     rateMeasure.DataCameIn);

            Connecter connecter =
                new Connecter(downloader, Choker, pieces.Count, StorageWrapper.IsEverythingPending, uploadMeasure,
                              parameters.MaxUploadRate << 10, rawServer.AddTask);

            byte[] infoHash = Globals.GetSha1Hash(BEncodingFactory.ByteArrayEncode(infoNode));//Globals.Sha1.ComputeHash(BEncodingFactory.ByteArrayEncode(infoNode));

            Encrypter encrypter = new Encrypter(connecter, rawServer, myID, parameters.MaxMessageLength, rawServer.AddTask,
                                                parameters.KeepAliveInterval, infoHash, parameters.MaxInitiate);
            //ReRequester reRequester =
            //    new ReRequester((rootNode["announce"] as BytesNode).StringText, parameters.RerequestInterval,
            //                    rawServer.AddTask, connecter.GetConnectionsCount, parameters.MinPeers,
            //                    encrypter.StartConnect, rawServer.AddExternalTask,
            //                    StorageWrapper.GetLeftLength, uploadMeasure.GetTotalLength, downloadMeasure.GetTotalLength,
            //                    listenPort, parameters.IP,
            //                    myID, infoHash, parameters.HttpTimeout, null, parameters.MaxInitiate, finishFlag);

            DownloaderFeedback downloaderFeedback =
                new DownloaderFeedback(Choker, rawServer.AddTask, statusFunction, uploadMeasure.GetUpdatedRate,
                                       downloadMeasure.GetUpdatedRate, rateMeasure.GetTimeLeft, rateMeasure.GetLeftTime,
                                       fileLength, finishFlag, parameters.DisplayInterval,
                                       parameters.Spew);

            statusFunction("connection to peers", -1, -1, -1, -1);
            //TODO: finishedHelper.errorfunc

            finishedHelper.FinishFlag = finishFlag;
            //finishedHelper.ReRequester = reRequester;
            finishedHelper.RateMeasure = rateMeasure;

            //reRequester.d(0);
            rawServer.ListenForever(encrypter);
            //reRequester.Announce(2, null);
        }
Beispiel #14
0
 public void TestDecodeInteger2()
 {
     BEncodingFactory.Decode("ie");
 }
Beispiel #15
0
 public void TestDecodeDictionary7()
 {
     BEncodingFactory.Decode("d0:1:ae");
 }
Beispiel #16
0
 public void TestDecodeDictionary9()
 {
     BEncodingFactory.Decode("d01:x0:e");
 }
Beispiel #17
0
 public void TestDecodeByteArray5()
 {
     BEncodingFactory.Decode("9:abc");
 }
Beispiel #18
0
 public void TestDecodeByteArray4()
 {
     BEncodingFactory.Decode("0:0:");
 }
Beispiel #19
0
 public void TestDecodeInteger6()
 {
     BEncodingFactory.Decode("i0345e");
 }
Beispiel #20
0
 public void TestDecodeByteArray3()
 {
     BEncodingFactory.Decode("02:ab");
 }
Beispiel #21
0
 public void TestDecodeByteArray2()
 {
     BEncodingFactory.Decode("2:abcedefg");
 }
Beispiel #22
0
 public void TestDecodeDictionary8()
 {
     BEncodingFactory.Decode("d0:");
 }
Beispiel #23
0
 public void TestDecodeList2()
 {
     BEncodingFactory.Decode("lezeral");
 }
Beispiel #24
0
 public void TestDecodeHandler3()
 {
     BEncodingFactory.Decode("35208734823ljdahflajhdf");
 }
Beispiel #25
0
 public void TestDecodeList3()
 {
     BEncodingFactory.Decode("l");
 }
Beispiel #26
0
 public void TestDecodeList4()
 {
     BEncodingFactory.Decode("l0:");
 }
Beispiel #27
0
 public void TestDecodeList5()
 {
     BEncodingFactory.Decode("l01:xe");
 }
Beispiel #28
0
 public void TestDecodeInteger3()
 {
     BEncodingFactory.Decode("i341foo382e");
 }
Beispiel #29
0
        /// <summary>
        /// Announce the tracker server
        /// </summary>
        /// <returns>Return the response of announce information</returns>
        public async void Announce()
        {
            try
            {
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(Uri);
                try
                {
                    BEncodedNode node;
                    using (WebResponse webResponse = await httpRequest.GetResponseAsync())
                    {
                        Stream stream = webResponse.GetResponseStream();
                        Debug.Assert(stream != null);

                        int count = Setting.TrackerBufferLength;

                        byte[] rcvBuf = new byte[Setting.TrackerBufferLength];
                        using (MemoryStream ms = new MemoryStream(Setting.TrackerBufferLength))
                        {
                            int readLength;
                            do
                            {
                                readLength = await stream.ReadAsync(rcvBuf, 0, count);

                                ms.Write(rcvBuf, 0, readLength);
                            } while (readLength != 0);
                            node = BEncodingFactory.Decode(ms.ToArray());
                        }
                    }

                    DictNode responseNode = node as DictNode;
                    if (responseNode != null)
                    {
                        AnnounceResponse response = Parse(responseNode);
                        if (response != null)
                        {
                            _timer.Interval = response.Interval * 1000;
                            GotAnnounceResponse(this, response);
                        }
                        else
                        {
                            _timer.Interval = Setting.TrackerFailInterval;
                            BitTorrentException exception = new BitTorrentException("Tracker returns fail message.");
                            ReturnMessageFail(this, exception);
                        }
                    }
                    else
                    {
                        _timer.Interval = Setting.TrackerFailInterval;
                        BitTorrentException exception = new BitTorrentException("Tracker returns fail message.");
                        ReturnMessageFail(this, exception);
                    }
                }
                catch (WebException e)
                {
                    _timer.Interval = Setting.TrackerFailInterval;
                    Debug.Assert(ConnectFail != null);
                    ConnectFail(this, e);
                }
                finally
                {
                    _timer.Start();
                }
            }
            catch (NullReferenceException)
            {
                //Nothing to be done.
            }
        }