コード例 #1
0
        void SetupEngine()
        {
            EngineSettings settings = new EngineSettings();

            settings.AllowedEncryption = EncryptionTypes.All;
            settings.PreferEncryption  = true;
            settings.SavePath          = RootFolder;

            engine = new ClientEngine(settings);
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, 6969));

            if (useDht)
            {
                byte[] nodes = null;
                try {
                    nodes = File.ReadAllBytes(DhtNodeFile);
                } catch {
                    Console.WriteLine("No existing dht nodes could be loaded");
                }

                DhtListener dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, 6970));
                DhtEngine   dht        = new DhtEngine(dhtListner);
                engine.RegisterDht(dht);
                dhtListner.Start();
                engine.DhtEngine.Start(nodes);
            }
        }
コード例 #2
0
        public TorrentExternal(EngineSettings settings, string node)
        {
            settings.PreferEncryption  = false;
            settings.AllowedEncryption = EncryptionTypes.All;

            Engine = new ClientEngine(settings);
            Engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, 12999));

            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(node);
            }
            catch
            {
                Console.WriteLine("No existing dht nodes could be loaded");
            }

            DhtListener = new DhtListener(new IPEndPoint(IPAddress.Any, 12999));
            Dht         = new DhtEngine(DhtListener);
            Engine.RegisterDht(Dht);
            DhtListener.Start();
            Engine.DhtEngine.Start(nodes);

            Listener = new Top10Listener(10);
        }
コード例 #3
0
 internal void Start()
 {
     if (listener.Status != ListenerStatus.Listening)
     {
         listener.Start();
     }
 }
コード例 #4
0
ファイル: MessageLoop.cs プロジェクト: tcz717/DhtWalker
 public void Start()
 {
     if (listener.Status != ListenerStatus.Listening)
     {
         listener.Start();
         handleThread.Start();
     }
 }
コード例 #5
0
        private void startDHT()
        {
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodesFile);
            }
            catch {}

            DhtListener dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, listenPort));
            DhtEngine   dht        = new DhtEngine(dhtListner);

            clientEngine.RegisterDht(dht);
            dhtListner.Start();
            clientEngine.DhtEngine.Start(nodes);
        }
コード例 #6
0
        private void InitBase(string DownloadDir)
        {
            if (!Directory.Exists(Environment.ExpandEnvironmentVariables(DownloadDir)))
            {
                Directory.CreateDirectory(Environment.ExpandEnvironmentVariables(DownloadDir));
            }
            if (!Directory.Exists(Environment.ExpandEnvironmentVariables(TORRENT_DIR)))
            {
                Directory.CreateDirectory(Environment.ExpandEnvironmentVariables(TORRENT_DIR));
            }

            //Initialize DHT engine for the first time
            lock ("DHT_Create")
            {
                if (DE == null)
                {
                    DL = new DhtListener(new IPEndPoint(IPAddress.Any, 54321));
                    DE = new DhtEngine(DL);
                    if (File.Exists(Environment.ExpandEnvironmentVariables(DHTFILE)))
                    {
                        DE.Start(File.ReadAllBytes(Environment.ExpandEnvironmentVariables(DHTFILE)));
                    }
                    else
                    {
                        DE.Start();
                    }
                    DL.Start();
                }
            }
            lock ("CE_Create")
            {
                if (ES == null)
                {
                    ES = new EngineSettings(Environment.ExpandEnvironmentVariables(DownloadDir), 54321, 500, 250, 0, 0, EncryptionTypes.All);
                }
                if (CE == null)
                {
                    CE = new ClientEngine(ES);
                    CE.RegisterDht(DE);
                }
            }
            TS = new TorrentSettings(10, 200, 0, 0);
        }
コード例 #7
0
        /// <summary>
        ///
        /// </summary>
        private void InitializeEngine()
        {
            int port = 60606;

            EngineSettings engineSettings = new EngineSettings(downloadDir, port)
            {
                PreferEncryption  = false,
                AllowedEncryption = MonoTorrent.Client.Encryption.EncryptionTypes.All
            };

            this.clientEngine = new ClientEngine(engineSettings);

            // Change to loopback, perhaps?
            this.clientEngine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));

            byte[] nodes = null;

            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch (Exception e)
            {
                Console.WriteLine("No existing DHT nodes could be loaded: {0}", e.Message);
            }

            DhtListener dhtListener = new DhtListener(new IPEndPoint(IPAddress.Any, port));
            DhtEngine   dhtEngine   = new DhtEngine(dhtListener);

            this.clientEngine.RegisterDht(dhtEngine);
            dhtListener.Start();
            this.clientEngine.DhtEngine.Start(nodes);

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(this.clientEngine.Settings.SavePath))
            {
                Directory.CreateDirectory(this.clientEngine.Settings.SavePath);
            }
        }
コード例 #8
0
ファイル: TorrentFile.cs プロジェクト: QstarLLC/FTorrent
        public TorrentFile(string pathToTorrent, string outPath, IPEndPoint endPoint, string dhtNodeFile = null, bool DHTenabled = true, bool preferEncryption = true, EncryptionTypes encryption = EncryptionTypes.All)
        {
            path     = pathToTorrent;
            savePath = outPath;

            settings = new EngineSettings();

            settings.AllowedEncryption = encryption;
            settings.PreferEncryption  = preferEncryption;
            settings.SavePath          = outPath;

            engine = new ClientEngine(settings);

            engine.ChangeListenEndpoint(endPoint);

            torrent = Torrent.Load(pathToTorrent);

            manager = new TorrentManager(torrent, outPath, new TorrentSettings());

            engine.Register(manager);

            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
            }

            if (DHTenabled)
            {
                dhtListener = new DhtListener(endPoint);
                dhtEngine   = new DhtEngine(dhtListener);
                engine.RegisterDht(dhtEngine);
                dhtListener.Start();
                engine.DhtEngine.Start(nodes);
            }
        }
コード例 #9
0
        public void Initialize(SettingsManager settingsManager)
        {
            SettingsManager             = settingsManager;
            Torrents                    = new ObservableCollection <PeriodicTorrent>();
            Torrents.CollectionChanged += Torrents_CollectionChanged;

            var port = SettingsManager.IncomingPort;

            if (SettingsManager.UseRandomPort)
            {
                port = new Random().Next(1, 65536);
            }
            if (SettingsManager.MapWithUPnP)
            {
                MapPort();
            }
            var settings = new EngineSettings(SettingsManager.DefaultDownloadLocation, port);

            settings.PreferEncryption  = SettingsManager.EncryptionSettings != EncryptionTypes.PlainText; // Always prefer encryption unless it's disabled
            settings.AllowedEncryption = SettingsManager.EncryptionSettings;
            Client = new ClientEngine(settings);
            Client.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));
            if (SettingsManager.EnableDHT)
            {
                var listener = new DhtListener(new IPEndPoint(IPAddress.Any, port));
                var dht      = new DhtEngine(listener);
                Client.RegisterDht(dht);
                listener.Start();
                if (File.Exists(SettingsManager.DhtCachePath))
                {
                    dht.Start(File.ReadAllBytes(SettingsManager.DhtCachePath));
                }
                else
                {
                    dht.Start();
                }
            }
            SettingsManager.PropertyChanged += SettingsManager_PropertyChanged;
        }
コード例 #10
0
        private static void Main()
        {
            var listener = new DhtListener(new IPEndPoint(IPAddress.Parse("192.168.0.6"), 15000));
            var engine   = new DhtEngine(listener);

            byte[] nodes = null;
            if (File.Exists("mynodes"))
            {
                nodes = File.ReadAllBytes("mynodes");
            }

            listener.Start();
            engine.PeersFound += (o, e) =>
            {
                Console.WriteLine("I FOUND PEERS: {0}", e.Peers.Count);
                engine.Start(nodes);

                var random = new Random(5);
                var bytes  = new byte[20];
                lock (random)
                    random.NextBytes(bytes);

                while (Console.ReadLine() != "q")
                {
                    for (var i = 0; i < 30; i++)
                    {
                        Console.WriteLine("Waiting: {0} seconds left", (30 - i));
                        System.Threading.Thread.Sleep(1000);
                    }

                    engine.GetPeers(bytes);
                    random.NextBytes(bytes);
                }

                File.WriteAllBytes("mynodes", engine.SaveNodes());
            };
        }
コード例 #11
0
        static void Main(string[] args)
        {
            DhtListener listener = new DhtListener(new IPEndPoint(IPAddress.Parse("192.168.0.6"), 15000));
            DhtEngine   engine   = new DhtEngine(listener);

            byte[] nodes = null;
            if (File.Exists("mynodes"))
            {
                nodes = File.ReadAllBytes("mynodes");
            }

            listener.Start();
            engine.PeersFound += delegate(object o, PeersFoundEventArgs e)
            {
                Console.WriteLine("I FOUND PEERS: {0}", e.Peers.Count);
                engine.Start(nodes);

                Random random = new Random(5);
                byte[] b      = new byte[20];
                lock (random)
                    random.NextBytes(b);

                while (Console.ReadLine() != "q")
                {
                    for (int i = 0; i < 30; i++)
                    {
                        Console.WriteLine("Waiting: {0} seconds left", (30 - i));
                        System.Threading.Thread.Sleep(1000);
                    }
                    // Get some peers for the torrent
                    engine.GetPeers(new InfoHash(b));
                    random.NextBytes(b);
                }
                File.WriteAllBytes("mynodes", engine.SaveNodes());
            };
        }
コード例 #12
0
        private static void StartEngine()
        {
            int     port    = 8589;
            Torrent torrent = null;



            // Create the settings which the engine will use
            // downloadsPath - this is the path where we will save all the files to
            // port - this is the port we listen for connections on
            EngineSettings engineSettings = new EngineSettings(downloadsPath, port);

            engineSettings.PreferEncryption  = false;
            engineSettings.AllowedEncryption = EncryptionTypes.All;

            //engineSettings.GlobalMaxUploadSpeed = 30 * 1024;
            //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024;
            //engineSettings.MaxReadRate = 1 * 1024 * 1024;


            // Create the default settings which a torrent will have.
            // 4 Upload slots - a good ratio is one slot per 5kB of upload speed
            // 50 open connections - should never really need to be changed
            // Unlimited download speed - valid range from 0 -> int.Max
            // Unlimited upload speed - valid range from 0 -> int.Max

            int yj  = 0;
            int yjv = 0;

            if (File.Exists("dwnspeed.tx"))
            {
                string hfg = File.ReadAllText("dwnspeed.tx");

                yjv = int.Parse(hfg);
            }
            if (File.Exists("uplspeed.tx"))
            {
                string hfg = File.ReadAllText("uplspeed.tx");

                yj = int.Parse(hfg);
            }

            TorrentSettings torrentDefaults = new TorrentSettings(100, 150, yjv, yj);

            // Create an instance of the engine.
            engine = new ClientEngine(engineSettings);
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
                Console.WriteLine("No existing dht nodes could be loaded");
            }

            DhtListener dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, port));
            DhtEngine   dht        = new DhtEngine(dhtListner);

            engine.RegisterDht(dht);
            dhtListner.Start();
            engine.DhtEngine.Start(nodes);

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(engine.Settings.SavePath))
            {
                Directory.CreateDirectory(engine.Settings.SavePath);
            }

            // If the torrentsPath does not exist, we want to create it
            if (!Directory.Exists(torrentsPath))
            {
                Directory.CreateDirectory(torrentsPath);
            }

            BEncodedDictionary fastResume;

            try
            {
                fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
            }
            catch
            {
                fastResume = new BEncodedDictionary();
            }

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            foreach (string file in Directory.GetFiles(torrentsPath))
            {
                if (file.EndsWith(".torrent"))
                {
                    try
                    {
                        // Load the .torrent from the file into a Torrent instance
                        // You can use this to do preprocessing should you need to
                        torrent = Torrent.Load(file);
                        Console.WriteLine(torrent.InfoHash.ToString());
                    }
                    catch (Exception e)
                    {
                        Console.Write("Couldn't decode {0}: ", file);
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    // When any preprocessing has been completed, you create a TorrentManager
                    // which you then register with the engine.
                    TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);
                    if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                    {
                        manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.infoHash.ToHex()]));
                    }
                    engine.Register(manager);

                    // Store the torrent manager in our list so we can access it later
                    torrents.Add(manager);
                    manager.PeersFound += new EventHandler <PeersAddedEventArgs>(manager_PeersFound);
                }
            }

            // If we loaded no torrents, just exist. The user can put files in the torrents directory and start
            // the client again
            if (torrents.Count == 0)
            {
                Console.WriteLine("No torrents found in the Torrents directory");
                Console.WriteLine("Exiting...");
                engine.Dispose();
                return;
            }

            // For each torrent manager we loaded and stored in our list, hook into the events
            // in the torrent manager and start the engine.
            foreach (TorrentManager manager in torrents)
            {
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) {
                    lock (listener)
                        listener.WriteLine(string.Format("Piece Hashed: {0} - {1}", e.PieceIndex, e.HashPassed ? "Pass" : "Fail"));
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) {
                    lock (listener)
                        listener.WriteLine("OldState: " + e.OldState.ToString() + " NewState: " + e.NewState.ToString());
                };

                // Every time the tracker's state changes, this is fired
                foreach (TrackerTier tier in manager.TrackerManager)
                {
                    foreach (MonoTorrent.Client.Tracker.Tracker t in tier.Trackers)
                    {
                        t.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e) {
                            listener.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString()));
                        };
                    }
                }
                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                manager.Start();
            }

            // While the torrents are still running, print out some stats to the screen.
            // Details for all the loaded torrent managers are shown.
            int           i       = 0;
            bool          running = true;
            StringBuilder sb      = new StringBuilder(1024);

            while (running)
            {
                if ((i++) % 10 == 0)
                {
                    sb.Remove(0, sb.Length);
                    running = torrents.Exists(delegate(TorrentManager m) { return(m.State != TorrentState.Stopped); });
                    foreach (TorrentManager manager in torrents)
                    {
                        AppendSeperator(sb);
                        AppendFormat(sb, "State:           {0}", manager.State);
                        AppendFormat(sb, "Name:            {0}", manager.Torrent == null ? "MetaDataMode" : manager.Torrent.Name);
                        AppendFormat(sb, "Progress:           {0:0.00}", manager.Progress);
                        AppendFormat(sb, "Download Speed:     {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0);
                        AppendFormat(sb, "Upload Speed:       {0:0.00} kB/s", manager.Monitor.UploadSpeed / 1024.0);
                        AppendFormat(sb, "Total Downloaded:   {0:0.00} MB", manager.Monitor.DataBytesDownloaded / (1024.0 * 1024.0));
                        AppendFormat(sb, "Total Uploaded:     {0:0.00} MB", manager.Monitor.DataBytesUploaded / (1024.0 * 1024.0));
                        MonoTorrent.Client.Tracker.Tracker tracker = manager.TrackerManager.CurrentTracker;
                        //AppendFormat(sb, "Tracker Status:     {0}", tracker == null ? "<no tracker>" : tracker.State.ToString());
                        AppendFormat(sb, "Warning Message:    {0}", tracker == null ? "<no tracker>" : tracker.WarningMessage);
                        AppendFormat(sb, "Failure Message:    {0}", tracker == null ? "<no tracker>" : tracker.FailureMessage);
                        if (manager.PieceManager != null)
                        {
                            AppendFormat(sb, "Current Requests:   {0}", manager.PieceManager.CurrentRequestCount());
                        }

                        foreach (PeerId p in manager.GetPeers())
                        {
                            AppendFormat(sb, "\t{2} - {1:0.00}/{3:0.00}kB/sec - {0}", p.Peer.ConnectionUri,
                                         p.Monitor.DownloadSpeed / 1024.0,
                                         p.AmRequestingPiecesCount,
                                         p.Monitor.UploadSpeed / 1024.0);
                        }

                        AppendFormat(sb, "", null);
                        if (manager.Torrent != null)
                        {
                            foreach (TorrentFile file in manager.Torrent.Files)
                            {
                                AppendFormat(sb, "{1:0.00}% - {0}", file.Path, file.BitField.PercentComplete);
                            }
                        }
                    }
                    AppendFormat(sb, "Total Download Rate: {0:0.00}kB/sec", engine.TotalDownloadSpeed / 1024.0);
                    AppendFormat(sb, "Total Upload Rate:   {0:0.00}kB/sec", engine.TotalUploadSpeed / 1024.0);
                    AppendFormat(sb, "Disk Read Rate:      {0:0.00} kB/s", engine.DiskManager.ReadRate / 1024.0);
                    AppendFormat(sb, "Disk Write Rate:     {0:0.00} kB/s", engine.DiskManager.WriteRate / 1024.0);
                    AppendFormat(sb, "Total Read:         {0:0.00} kB", engine.DiskManager.TotalRead / 1024.0);
                    AppendFormat(sb, "Total Written:      {0:0.00} kB", engine.DiskManager.TotalWritten / 1024.0);
                    AppendFormat(sb, "Open Connections:    {0}", engine.ConnectionManager.OpenConnections);


                    Console.Clear();
                    Console.WriteLine(sb.ToString());
                    listener.ExportTo(Console.Out);
                }

                System.Threading.Thread.Sleep(500);
            }
        }
コード例 #13
0
        private void StartEngine(int port)
        {
            Torrent torrent = null;
            // Create the settings which the engine will use
            // downloadsPath - this is the path where we will save all the files to
            // port - this is the port we listen for connections on
            EngineSettings engineSettings = new EngineSettings(downloadsPath, port);

            engineSettings.PreferEncryption  = false;
            engineSettings.AllowedEncryption = EncryptionTypes.All;

            //engineSettings.GlobalMaxUploadSpeed = 30 * 1024;
            //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024;
            //engineSettings.MaxReadRate = 1 * 1024 * 1024;


            // Create the default settings which a torrent will have.
            // 4 Upload slots
            // 50 open connections
            // Unlimited download, upload speed
            TorrentSettings torrentDefaults = new TorrentSettings(4, 150, 0, 0);

            // Create an instance of the engine.
            engine = new ClientEngine(engineSettings);
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
                MessageBox.Show("No existing dht nodes could be loaded");
            }

            DhtListener dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, port));
            DhtEngine   dht        = new DhtEngine(dhtListner);

            engine.RegisterDht(dht);
            dhtListner.Start();
            engine.DhtEngine.Start(nodes);

            // If the torrentsPath does not exist, we want to create it
            if (!Directory.Exists(BasicTorrentsPath))
            {
                Directory.CreateDirectory(BasicTorrentsPath);
            }

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(engine.Settings.SavePath))
            {
                Directory.CreateDirectory(engine.Settings.SavePath);
            }

            BEncodedDictionary fastResume;

            try
            {
                fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
            }
            catch
            {
                fastResume = new BEncodedDictionary();
            }

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            foreach (string file in Directory.GetFiles(BasicTorrentsPath))
            {
                if (file.EndsWith(".torrent"))
                {
                    try
                    {
                        // Load the .torrent from the file into a Torrent instance
                        // You can use this to do preprocessing should you need to
                        torrent = Torrent.Load(file);

                        // Console.WriteLine(torrent.InfoHash.ToString());
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Couldn't decode {0}: " + e.Message, file);
                        //   continue;
                    }
                    // When any preprocessing has been completed, you create a TorrentManager
                    // which you then register with the engine.
                    TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);
                    if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                    {
                        manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                    }
                    engine.Register(manager);

                    // Store the torrent manager in our list so we can access it later
                    torrents.Add(manager);
                    manager.PeersFound += new EventHandler <PeersAddedEventArgs>(manager_PeersFound);
                }
            }

            // If we loaded no torrents, just exist. The user can put files in the torrents directory and start
            // the client again
            if (torrents.Count == 0)
            {
                MessageBox.Show("No torrents found in the Torrents directory");
                MessageBox.Show("Exiting...");
                engine.Dispose();
                return;
            }

            // For each torrent manager we loaded and stored in our list, hook into the events
            // in the torrent manager and start the engine.
            foreach (TorrentManager manager in torrents)
            {
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs e) {
                    lock (listener)
                        listener.WriteLine(string.Format("Piece Hashed: {0} - {1}", e.PieceIndex, e.HashPassed ? "Pass" : "Fail"));
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs e) {
                    lock (listener)
                        listener.WriteLine("OldState: " + e.OldState.ToString() + " NewState: " + e.NewState.ToString());
                };

                // Every time the tracker's state changes, this is fired
                foreach (TrackerTier tier in manager.TrackerManager)
                {
                    foreach (MonoTorrent.Client.Tracker.Tracker t in tier.GetTrackers())
                    {
                        t.AnnounceComplete += delegate(object sender, AnnounceResponseEventArgs e) {
                            listener.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString()));
                        };
                    }
                }
                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                manager.Start();
            }
        }
コード例 #14
0
        protected override async void OnNavigatedTo(NavigationEventArgs ee)
        {
            var port    = 6881;
            var dhtPort = 15000;

            // Use Universal.Nat to enable upnp port mapping

            /* var natManager = new NatManager(port);
             * natManager.Start();*/

            var picker = new FileOpenPicker();

            picker.FileTypeFilter.Add(".torrent");
            var file = await picker.PickSingleFileAsync();

            var stream = await file.OpenStreamForReadAsync();

            var torrent = Common.Torrent.Load(stream);

            if (torrent != null)
            {
                var engineSettings = new EngineSettings(ApplicationData.Current.LocalFolder.Path, port)
                {
                    PreferEncryption  = true,
                    AllowedEncryption = EncryptionTypes.All
                };

                // Create the default settings which a torrent will have.
                // 4 Upload slots - a good ratio is one slot per 5kB of upload speed
                // 50 open connections - should never really need to be changed
                // Unlimited download speed - valid range from 0 -> int.Max
                // Unlimited upload speed - valid range from 0 -> int.Max
                var torrentDefaults = new TorrentSettings(4, 150, 0, 0)
                {
                    UseDht             = true,
                    EnablePeerExchange = true
                };

                // Create an instance of the engine.
                var engine = new ClientEngine(engineSettings);
                //engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));

                var dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, dhtPort));
                var dht        = new DhtEngine(dhtListner);
                engine.RegisterDht(dht);
                dhtListner.Start();
                engine.DhtEngine.Start();

                // When any preprocessing has been completed, you create a TorrentManager
                // which you then register with the engine.
                var manager = new TorrentManager(torrent, ApplicationData.Current.LocalFolder, torrentDefaults);
                engine.Register(manager);

                // Every time a piece is hashed, this is fired.
                manager.PieceHashed +=
                    delegate(object o, PieceHashedEventArgs e)
                {
                    Debug.WriteLine("Piece Hashed: {0} - {1}", e.PieceIndex, e.HashPassed ? "Pass" : "Fail");
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged +=
                    delegate(object o, TorrentStateChangedEventArgs e)
                {
                    Debug.WriteLine("OldState: " + e.OldState + " NewState: " + e.NewState);
                };

                // Every time the tracker's state changes, this is fired
                foreach (var t in manager.TrackerManager.SelectMany(tier => tier.Trackers))
                {
                    t.AnnounceComplete +=
                        delegate(object sender, AnnounceResponseEventArgs e)
                    {
                        Debug.WriteLine("{0}: {1}", e.Successful, e.Tracker);
                    };
                }
                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                manager.Start();

                var dispatcher = Window.Current.Dispatcher;
                engine.StatsUpdate +=
                    async(sender, args) =>
                {
                    await
                    dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                        () =>
                    {
                        TextBlock.Text =
                            $"{manager.Peers.Seeds} seeds / {manager.Peers.Leechs} leechs / {manager.Progress} %";
                    });
                };
            }
        }
コード例 #15
0
        void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
            case "IncomingPort":
                Client.Listener.ChangeEndpoint(new IPEndPoint(IPAddress.Any, SettingsManager.IncomingPort));
                if (SettingsManager.MapWithUPnP)
                {
                    MapPort();
                }
                break;

            case "MapWithUPnP":
                if (SettingsManager.MapWithUPnP)
                {
                    MapPort();
                }
                break;

            case "MaxUploadSpeed":
                Client.Settings.GlobalMaxUploadSpeed = SettingsManager.MaxUploadSpeed * 1024;
                break;

            case "MaxDownloadSpeed":
                Client.Settings.GlobalMaxDownloadSpeed = SettingsManager.MaxDownloadSpeed * 1024;
                break;

            case "MaxConnections":
                Client.Settings.GlobalMaxConnections = SettingsManager.MaxConnections;
                break;

            case "EnableDHT":
                if (SettingsManager.EnableDHT)
                {
                    var port = SettingsManager.IncomingPort;
                    if (SettingsManager.UseRandomPort)
                    {
                        port = new Random().Next(1, 65536);
                    }
                    var listener = new DhtListener(new IPEndPoint(IPAddress.Any, port));
                    var dht      = new DhtEngine(listener);
                    Client.RegisterDht(dht);
                    listener.Start();
                    if (File.Exists(SettingsManager.DhtCachePath))
                    {
                        dht.Start(File.ReadAllBytes(SettingsManager.DhtCachePath));
                    }
                    else
                    {
                        dht.Start();
                    }
                }
                else
                {
                    Client.DhtEngine.Stop();
                }
                break;

            case "EncryptionSettings":
                Client.Settings.AllowedEncryption = SettingsManager.EncryptionSettings;
                break;

            case "ProxyAddress":
            case "EnableProxyAuthentication":
            case "ProxyUsername":
            case "ProxyPassword":
                if (string.IsNullOrEmpty(SettingsManager.ProxyAddress))
                {
                    ConnectionFactory.RegisterTypeForProtocol("tcp", typeof(IPV4Connection));
                }
                else
                {
                    ConnectionFactory.RegisterTypeForProtocol("tcp", typeof(ProxiedConnection));
                    ushort port    = 1080;
                    string address = SettingsManager.ProxyAddress;
                    if (SettingsManager.ProxyAddress.Contains(':'))
                    {
                        var parts = SettingsManager.ProxyAddress.Split(':');
                        address = parts[0];
                        port    = ushort.Parse(parts[1]);
                    }
                    if (!SettingsManager.EnableProxyAuthentication)
                    {
                        ProxiedConnection.SetProxyDetails(address, port);
                    }
                    else
                    {
                        ProxiedConnection.SetProxyDetails(address, port, SettingsManager.ProxyUsername, SettingsManager.ProxyPassword);
                    }
                }
                break;
            }
        }
コード例 #16
0
        private void DownloaderWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (e.Argument == null)
                {
                    return;
                }

                basePath       = Environment.CurrentDirectory;
                dhtNodeFile    = System.IO.Path.Combine(basePath, "DhtNodes");
                downloadsPath  = System.IO.Path.Combine(basePath, "Downloads");
                torrentsPath   = System.IO.Path.Combine(basePath, "Torrents");
                fastResumeFile = System.IO.Path.Combine(torrentsPath, "fastresume.data");
                torrents       = new List <TorrentManager>(); // The list where all the torrentManagers will be stored that the engine gives us
                listener       = new Top10Listener(10);

                string torrentpath = e.Argument.ToString();

                int     port    = 6969;
                Torrent torrent = null;

                // Create the settings which the engine will use
                // downloadsPath - this is the path where we will save all the files to
                // port - this is the port we listen for connections on
                EngineSettings engineSettings = new EngineSettings(downloadsPath, port);
                engineSettings.PreferEncryption  = false;
                engineSettings.AllowedEncryption = EncryptionTypes.All;

                //engineSettings.GlobalMaxUploadSpeed = 30 * 1024;
                //engineSettings.GlobalMaxDownloadSpeed = 100 * 1024;
                //engineSettings.MaxReadRate = 1 * 1024 * 1024;


                // Create the default settings which a torrent will have.
                // 4 Upload slots - a good ratio is one slot per 5kB of upload speed
                // 50 open connections - should never really need to be changed
                // Unlimited download speed - valid range from 0 -> int.Max
                // Unlimited upload speed - valid range from 0 -> int.Max
                TorrentSettings torrentDefaults = new TorrentSettings(4, 150, 0, 0);

                // Create an instance of the engine.
                engine = new ClientEngine(engineSettings);
                engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));
                byte[] nodes = null;
                try
                {
                    nodes = File.ReadAllBytes(dhtNodeFile);
                }
                catch
                {
                    Console.WriteLine("No existing dht nodes could be loaded");
                }

                DhtListener dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, port));
                DhtEngine   dht        = new DhtEngine(dhtListner);
                engine.RegisterDht(dht);
                dhtListner.Start();
                engine.DhtEngine.Start(nodes);

                // If the SavePath does not exist, we want to create it.
                if (!Directory.Exists(engine.Settings.SavePath))
                {
                    Directory.CreateDirectory(engine.Settings.SavePath);
                }

                // If the torrentsPath does not exist, we want to create it
                if (!Directory.Exists(torrentsPath))
                {
                    Directory.CreateDirectory(torrentsPath);
                }

                BEncodedDictionary fastResume;
                try
                {
                    fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
                }
                catch
                {
                    fastResume = new BEncodedDictionary();
                }


                // Load the .torrent from the file into a Torrent instance
                // You can use this to do preprocessing should you need to
                torrent = Torrent.Load(torrentpath);

                // When any preprocessing has been completed, you create a TorrentManager
                // which you then register with the engine.
                TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);
                //if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                //    manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.infoHash.ToHex()]));
                engine.Register(manager);

                // Store the torrent manager in our list so we can access it later
                torrents.Add(manager);
                manager.PeersFound += new EventHandler <PeersAddedEventArgs>(manager_PeersFound);


                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs ec)
                {
                    lock (listener)
                        listener.WriteLine(string.Format("Piece Hashed: {0} - {1}", ec.PieceIndex, ec.HashPassed ? "Pass" : "Fail"));
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += delegate(object o, TorrentStateChangedEventArgs ev)
                {
                    lock (listener)
                        listener.WriteLine("OldState: " + ev.OldState.ToString() + " NewState: " + ev.NewState.ToString());
                };

                // Every time the tracker's state changes, this is fired
                //foreach (TrackerTier tier in manager.TrackerManager)
                //{
                //    //foreach (MonoTorrent.Client.Tracker.Tracker t in tier.Trackers)
                //    //{
                //    //    t.AnnounceComplete += delegate (object sender, AnnounceResponseEventArgs e)
                //    //    {
                //    //        listener.WriteLine(string.Format("{0}: {1}", e.Successful, e.Tracker.ToString()));
                //    //    };
                //    //}
                //}
                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                manager.Start();


                // While the torrents are still running, print out some stats to the screen.
                // Details for all the loaded torrent managers are shown.
                bool          running = true;
                StringBuilder sb      = new StringBuilder(1024);
                while (running)
                {
                    //if ((i++) % 10 == 0)
                    //{
                    sb.Remove(0, sb.Length);
                    running = torrents.Exists(delegate(TorrentManager m) { return(m.State != TorrentState.Stopped); });

                    //AppendFormat(sb, "Total Download Rate: {0:0.00}kB/sec", engine.TotalDownloadSpeed / 1024.0);
                    downloadspeed = (engine.TotalDownloadSpeed / 1024.0).ToString();
                    //AppendFormat(sb, "Total Upload Rate:   {0:0.00}kB/sec", engine.TotalUploadSpeed / 1024.0);
                    //AppendFormat(sb, "Disk Read Rate:      {0:0.00} kB/s", engine.DiskManager.ReadRate / 1024.0);
                    //AppendFormat(sb, "Disk Write Rate:     {0:0.00} kB/s", engine.DiskManager.WriteRate / 1024.0);
                    //AppendFormat(sb, "Total Read:         {0:0.00} kB", engine.DiskManager.TotalRead / 1024.0);
                    //AppendFormat(sb, "Total Written:      {0:0.00} kB", engine.DiskManager.TotalWritten / 1024.0);
                    //AppendFormat(sb, "Open Connections:    {0}", engine.ConnectionManager.OpenConnections);


                    //AppendSeperator(sb);
                    //AppendFormat(sb, "State:           {0}", manager.State);
                    //AppendFormat(sb, "Name:            {0}", manager.Torrent == null ? "MetaDataMode" : manager.Torrent.Name);
                    //AppendFormat(sb, "Progress:           {0:0.00}", manager.Progress);
                    //progress = manager.Progress.ToString();
                    //AppendFormat(sb, "Download Speed:     {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0);
                    //AppendFormat(sb, "Upload Speed:       {0:0.00} kB/s", manager.Monitor.UploadSpeed / 1024.0);
                    //AppendFormat(sb, "Total Downloaded:   {0:0.00} MB", manager.Monitor.DataBytesDownloaded / (1024.0 * 1024.0));
                    //AppendFormat(sb, "Total Uploaded:     {0:0.00} MB", manager.Monitor.DataBytesUploaded / (1024.0 * 1024.0));
                    MonoTorrent.Client.Tracker.Tracker tracker = manager.TrackerManager.CurrentTracker;
                    //AppendFormat(sb, "Tracker Status:     {0}", tracker == null ? "<no tracker>" : tracker.State.ToString());
                    //AppendFormat(sb, "Warning Message:    {0}", tracker == null ? "<no tracker>" : tracker.WarningMessage);
                    //AppendFormat(sb, "Failure Message:    {0}", tracker == null ? "<no tracker>" : tracker.FailureMessage);
                    //if (manager.PieceManager != null)
                    //    AppendFormat(sb, "Current Requests:   {0}", manager.PieceManager.CurrentRequestCount());

                    //foreach (PeerId p in manager.GetPeers())
                    //    AppendFormat(sb, "\t{2} - {1:0.00}/{3:0.00}kB/sec - {0}", p.Peer.ConnectionUri,
                    //                                                              p.Monitor.DownloadSpeed / 1024.0,
                    //                                                              p.AmRequestingPiecesCount,
                    //                                                              p.Monitor.UploadSpeed / 1024.0);

                    //AppendFormat(sb, "", null);
                    //if (manager.Torrent != null)
                    //    foreach (TorrentFile file in manager.Torrent.Files)
                    //        AppendFormat(sb, "{1:0.00}% - {0}", file.Path, file.BitField.PercentComplete);

                    //Console.Clear();
                    //Console.WriteLine(sb.ToString());
                    //listener.ExportTo(Console.Out);
                    //}
                    DownloaderWorker.ReportProgress(Convert.ToInt32(manager.Progress), manager.State.ToString());
                    System.Threading.Thread.Sleep(500);
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: x27lu/NyaaDownloader
        public static void DownloadTorrent(string url, string downloadDirectory, int maxUploadSpeed)
        {
            var torrentFileName = string.Format("{0}.torrent", url.GetHashCode().ToString(CultureInfo.InvariantCulture));

            var torrentManager =
                new TorrentManager(
                    Torrent.Load(new Uri(url), torrentFileName),
                    downloadDirectory,
                    new TorrentSettings());

            // find an unused port
            var listener = new TcpListener(IPAddress.Any, 0);

            listener.Start();
            var port = ((IPEndPoint)listener.LocalEndpoint).Port;

            listener.Stop();

            var engineSettings = new EngineSettings(downloadDirectory, port)
            {
                PreferEncryption     = false,
                AllowedEncryption    = EncryptionTypes.All,
                GlobalMaxUploadSpeed = maxUploadSpeed
            };

            var dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, port));
            var dht        = new DhtEngine(dhtListner);

            var engine = new ClientEngine(engineSettings);

            engine.Register(torrentManager);
            engine.RegisterDht(dht);
            dhtListner.Start();
            engine.DhtEngine.Start();

            engine.StartAll();

            while (true)
            {
                var status = string.Format("{0:0.00}% - {1}\nDL:{2:0.00} kB/s    \nUL:{3:0.00} kB/s    ",
                                           torrentManager.Progress,
                                           torrentManager.Torrent.Name,
                                           torrentManager.Monitor.DownloadSpeed / 1024.0,
                                           torrentManager.Monitor.UploadSpeed / 1024.0);

                var cursorPosition = new Tuple <int, int>(Console.CursorLeft, Console.CursorTop);
                Console.WriteLine(status);

                if (torrentManager.State == TorrentState.Seeding)
                {
                    Console.WriteLine();
                    break;
                }

                Console.SetCursorPosition(cursorPosition.Item1, cursorPosition.Item2);

                Thread.Sleep(500);
            }

            dhtListner.Stop();
            engine.DhtEngine.Stop();
            engine.StopAll();
            engine.Dispose();

            File.Delete(torrentFileName);
        }
コード例 #18
0
        public TorrentsManager()
        {
            // directories for torrent node
            string basePath = Environment.CurrentDirectory;

//            downloadsPath = Path.Combine(basePath, "Downloads");
            downloadsPath = "Q:\\fakedownloaddir";
            //fastResumeFile = Path.Combine(basePath, "fastresume.data"); // remove fast resume
            dhtNodeFile = Path.Combine(basePath, "DhtNodes");

            // Create the settings which the engine will use
            // downloadsPath - this is the path where we will save all the files to
            // port - this is the port we listen for connections on
            engineSettings = new EngineSettings(downloadsPath, port);
            engineSettings.PreferEncryption  = false;
            engineSettings.AllowedEncryption = EncryptionTypes.All;

            // Create an instance of the engine.
            engine = new ClientEngine(engineSettings);
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
                Debug.WriteLine("No existing dht nodes could be loaded");
            }

            DhtListener dhtListener = new DhtListener(new IPEndPoint(IPAddress.Any, port));
            DhtEngine   dht         = new DhtEngine(dhtListener);

            engine.RegisterDht(dht);
            dhtListener.Start();
            engine.DhtEngine.Start(nodes);

            workerTorrentsManage.DoWork                    += WorkerTorrentsManage_DoWork;
            workerTorrentsManage.ProgressChanged           += WorkerTorrentsManage_ProgressChanged;
            workerTorrentsManage.WorkerSupportsCancellation = true;
            workerTorrentsManage.WorkerReportsProgress      = true;
            workerTorrentsManage.RunWorkerAsync();

            // If the SavePath does not exist, we want to create it.
            //if (!Directory.Exists(engine.Settings.SavePath))
            //    Directory.CreateDirectory(engine.Settings.SavePath);

            try
            {
                //fastResume = BEncodedValue.Decode<BEncodedDictionary>(File.ReadAllBytes(fastResumeFile)); // remove fast resume
            }
            catch
            {
                //fastResume = new BEncodedDictionary(); // remove fast resume
            }

            // We need to cleanup correctly when the user closes the window
            // or an unhandled exception happens

            //AppDomain.CurrentDomain.ProcessExit += delegate { shutdown(); };
            //AppDomain.CurrentDomain.UnhandledException += delegate { shutdown(); };
            //Thread.GetDomain().UnhandledException += delegate { shutdown(); };
        }
コード例 #19
0
        void Start()
        {
            //Start Torrent Engine
            torrents = new List <TorrentManager>();
            messages = new List <SimpleMessage>();

            //Torrents to remove
            seedingLimitTorrents = new List <Tuple <DateTime, TorrentManager> >();

            Console.WriteLine("simpletorrent: version {0}", VERSION);
            Console.WriteLine("simpletorrent: Reading configuration file (simple.cfg)...");

            config = new SimpleConfiguration("simple.cfg");
            string basePath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

            Console.WriteLine("simpletorrent: ApplicationPath (derived) {0}", basePath);

            if (config.HasValue("Debug"))
            {
                debugWriter = new DebugWriter(true);
                Console.WriteLine("simpletorrent: Debugging Enabled!");
            }
            else
            {
                debugWriter = new DebugWriter(false);
            }

            PlatformID os = Environment.OSVersion.Platform;

            if (os == PlatformID.MacOSX)
            {
                Console.WriteLine("simpletorrent: We think we're on MacOSX");
                simpleOperatingSystem = SimpleTorrentOperatingMode.MacOSX;
            }
            else if (os == PlatformID.Unix)
            {
                Console.WriteLine("simpletorrent: We think we're on *nix");
                simpleOperatingSystem = SimpleTorrentOperatingMode.StarNix;
            }
            else
            {
                Console.WriteLine("simpletorrent: We think we're on Windows");
                simpleOperatingSystem = SimpleTorrentOperatingMode.Windows;
            }

            torrentsPath       = Path.GetFullPath(config.GetValue("TorrentPath", Path.Combine(basePath, "Torrents")));
            downloadsPath      = Path.GetFullPath(config.GetValue("DownloadPath", Path.Combine(basePath, "Downloads")));
            sslCertificatePath = Path.GetFullPath(config.GetValue("SslCertificatePath", Path.Combine(basePath, "simple.pfx")));
            useECDSA           = config.HasValue("SslCertificateECDSA");
            fastResumeFile     = Path.Combine(torrentsPath, "fastresume.data");
            dhtNodeFile        = Path.Combine(torrentsPath, "dht.data");

            requireProtocolEncryption = config.HasValue("RequireProtocolEncryption");

            sessionLimit = config.GetValueInt("SessionLimit", 20);
            seedingLimit = config.GetValueInt("SeedingLimit");

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(downloadsPath))
            {
                Directory.CreateDirectory(downloadsPath);
            }

            // If the torrentsPath does not exist, we want to create it
            if (!Directory.Exists(torrentsPath))
            {
                Directory.CreateDirectory(torrentsPath);
            }

            downloadsPathDrive = null;
            string myRootPath = Path.GetPathRoot(downloadsPath).ToLower();

            if (simpleOperatingSystem == SimpleTorrentOperatingMode.StarNix)
            {
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.EnableRaisingEvents              = false;
                proc.StartInfo.FileName               = "bash";
                proc.StartInfo.Arguments              = "-c \"df -h " + downloadsPath + " | awk '{print $6}' | tail -1\"";
                proc.StartInfo.UseShellExecute        = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.Start();
                string output = proc.StandardOutput.ReadToEnd().Trim().ToLower();
                proc.WaitForExit();

                if (proc.ExitCode == 0)
                {
                    myRootPath = output;
                    debugWriter.WriteLine("*nix override (bash -c 'df -h <path>') - \"" + output + "\"");
                }
            }
            else if (simpleOperatingSystem == SimpleTorrentOperatingMode.MacOSX)
            {
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.EnableRaisingEvents              = false;
                proc.StartInfo.FileName               = "bash";
                proc.StartInfo.Arguments              = "-c \"df -h " + downloadsPath + " | awk '{print $9}' | tail -1\"";
                proc.StartInfo.UseShellExecute        = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.Start();
                string output = proc.StandardOutput.ReadToEnd().Trim().ToLower();
                proc.WaitForExit();

                if (proc.ExitCode == 0)
                {
                    myRootPath = output;
                    debugWriter.WriteLine("*nix override (bash -c 'df -h <path>') - \"" + output + "\"");
                }
            }

            foreach (var drive in DriveInfo.GetDrives())
            {
                debugWriter.WriteLine("Enemerating Drives - " + drive.RootDirectory.FullName.ToString());

                if (drive.RootDirectory.FullName.ToLower()
                    == myRootPath)
                {
                    downloadsPathDrive = drive;
                    break;
                }
            }

            Console.WriteLine("simpletorrent: TorrentPath {0}", torrentsPath);
            Console.WriteLine("simpletorrent: DownloadPath {0}", downloadsPath);
            Console.WriteLine("simpletorrent: DownloadRootPath (derived) {0}", downloadsPathDrive);
            Console.WriteLine("simpletorrent: SslCertificatePath {0}", sslCertificatePath);
            Console.WriteLine("simpletorrent: SslCertificateECDSA {0}", useECDSA ? "Yes" : "No");
            Console.WriteLine("simpletorrent: RequireProtocolEncryption {0}", requireProtocolEncryption ? "Yes" : "No");
            Console.WriteLine("simpletorrent: SessionLimit {0}", sessionLimit);
            Console.WriteLine("simpletorrent: SeedingLimit {0}", seedingLimit.HasValue ? seedingLimit.Value.ToString() : "No");

            int?torrentListenPort = config.GetValueInt("TorrentListenPort");

            if (!torrentListenPort.HasValue)
            {
                throw new SimpleTorrentException("Configuration does not have a proper 'TorrentListenPort' value defined", null);
            }

            Console.WriteLine("simpletorrent: TorrentListenPort {0}", torrentListenPort);

            externalBanList  = new List <string>();
            externalBanLists = new Dictionary <string, BanList>();
            foreach (var i in config.GetValues("ExternalBanList"))
            {
                Console.WriteLine("simpletorrent: ExternalBanList {0}", i);
                externalBanList.Add(i);
            }

            externalBanListLimit = config.GetValueInt("ExternalBanListLimit");

            if (externalBanListLimit.HasValue)
            {
                Console.WriteLine("simpletorrent: ExternalBanListLimit {0}", externalBanListLimit.Value);
            }

            EngineSettings engineSettings = new EngineSettings(downloadsPath, torrentListenPort.Value);

            engineSettings.PreferEncryption     = true;
            engineSettings.AllowedEncryption    = requireProtocolEncryption ? EncryptionTypes.RC4Full : EncryptionTypes.All;
            engineSettings.GlobalMaxConnections = 500;

            torrentDefaults = new TorrentSettings(4, 500, 0, 0);
            engine          = new ClientEngine(engineSettings);
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, torrentListenPort.Value));

            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
                Console.WriteLine("simpletorrent: No existing DHT nodes could be loaded");
            }

            dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, torrentListenPort.Value));
            DhtEngine dht = new DhtEngine(dhtListner);

            engine.RegisterDht(dht);
            dhtListner.Start();
            engine.DhtEngine.Start(nodes);

            foreach (var torrent in Directory.GetFiles(torrentsPath, "*.torrent"))
            {
                Torrent t = Torrent.Load(torrent);

                if (engine.Torrents.Where(i => i.InfoHash == t.InfoHash).Count() == 0)
                {
                    TorrentManager tm = new TorrentManager(t, downloadsPath, torrentDefaults);
                    engine.Register(tm);
                }
            }

            BEncodedDictionary fastResume;

            try
            {
                fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
            }
            catch
            {
                fastResume = new BEncodedDictionary();
            }

            if (seedingLimit.HasValue)
            {
                Console.WriteLine("simpletorrent: Starting seeding limits watchdog timer...");
                seedingLimitTimer           = new System.Timers.Timer();
                seedingLimitTimer.AutoReset = true;
                seedingLimitTimer.Interval  = 60 * 1000;
                seedingLimitTimer.Elapsed  += (s, e) =>
                {
                    lock (seedingLimitTorrents)
                    {
                        var torrentsToRemove = seedingLimitTorrents.Where(a => (DateTime.Now - a.Item1).TotalSeconds >= seedingLimit).ToArray();
                        foreach (var i in torrentsToRemove)
                        {
                            try
                            {
                                seedingLimitTorrents.Remove(i);

                                if (i != null && i.Item2.State == TorrentState.Seeding)
                                {
                                    Console.WriteLine("simpletorrent: Automatically removing \"{0}\"...",
                                                      i.Item2.Torrent.Name);
                                    torrentInformation[i.Item2.InfoHash.ToHex()].ToRemove = "delete-torrent";
                                    i.Item2.Stop();
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                };
                seedingLimitTimer.Start();
            }

            //Ban List System
            UpdateBanLists();

            engine.ConnectionManager.BanPeer += (s, e) =>
            {
                bool ban = false;

                lock (externalBanLists)
                {
                    foreach (var i in externalBanLists)
                    {
                        ban |= i.Value.IsBanned(IPAddress.Parse(e.Peer.ConnectionUri.Host));
                    }
                }

                e.BanPeer = ban;

                if (e.BanPeer)
                {
                    debugWriter.WriteLine(string.Format("Connection from {0} denied.", e.Peer.ConnectionUri.Host));
                }
                else
                {
                    debugWriter.WriteLine(string.Format("Connection from {0} allowed.", e.Peer.ConnectionUri.Host));
                }
            };

            if (externalBanListLimit.HasValue)
            {
                Console.WriteLine("simpletorrent: Starting external ban list update timer...");
                externalBanListLimitTimer           = new System.Timers.Timer();
                externalBanListLimitTimer.AutoReset = true;
                externalBanListLimitTimer.Interval  = 1000 * externalBanListLimit.Value;
                externalBanListLimitTimer.Elapsed  += (s, e) =>
                {
                    UpdateBanLists();
                };

                externalBanListLimitTimer.Start();
            }

            using (var httpServer = new HttpServer(new HttpRequestProvider()))
            {
                Console.WriteLine("simpletorrent: Starting HTTP(S) server...");
                bool listeningOne = false;

                Console.WriteLine("simpletorrent: Creating session manager...");
                httpServer.Use(new SessionHandler <SimpleTorrentSession>(() =>
                                                                         new SimpleTorrentSession(), sessionLimit));

                foreach (var ip in config.GetValues("Listen"))
                {
                    try
                    {
                        TcpListener tl = getTcpListener(ip);
                        httpServer.Use(new TcpListenerAdapter(tl));
                        Console.WriteLine("simpletorrent: Listening for HTTP on {0}...", tl.LocalEndpoint);
                        listeningOne = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("simpletorrent: ({0}) " + ex.Message, ip);
                    }
                }


                System.Security.Cryptography.X509Certificates.X509Certificate2 cert = null;
                if (config.HasValue("ListenSsl"))
                {
                    cert = SSLSelfSigned.GetCertOrGenerate(sslCertificatePath, useECDSA);
                }

                foreach (var ip in config.GetValues("ListenSsl"))
                {
                    try
                    {
                        TcpListener tl = getTcpListener(ip);

                        //Mono does not support TLS 1.1 or 1.2 -->
#if MONO
                        httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(tl), cert, System.Security.Authentication.SslProtocols.Ssl3 |
                                                                System.Security.Authentication.SslProtocols.Tls));
#else
                        //Force new systems to use TLS 1.1 or 1.2
                        httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(tl), cert, System.Security.Authentication.SslProtocols.Tls11
                                                                | System.Security.Authentication.SslProtocols.Tls12));
#endif

                        Console.WriteLine("simpletorrent: Listening for HTTPS on {0}...", tl.LocalEndpoint);
                        listeningOne = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("simpletorrent: ({0}) " + ex.Message, ip);
                    }
                }

                if (!listeningOne)
                {
                    throw new SimpleTorrentException("simpletorrent was unable to bind to a single port.");
                }

                Console.WriteLine("simpletorrent: Running...");

                httpServer.Use((context, next) =>
                {
                    context.Response = ProcessRequest(context);

                    return(Task.Factory.GetCompleted());
                });

                foreach (var tm in engine.Torrents)
                {
                    SetupTorrent(tm);
                }

                httpServer.Start();

                Console.ReadLine();
            }
        }
コード例 #20
0
        private void StartEngine(int maxUpload)
        {
            int     port    = 54321;
            Torrent torrent = null;
            // Create the settings which the engine will use
            // downloadsPath - this is the path where we will save all the files to
            // port - this is the port we listen for connections on
            EngineSettings engineSettings = new EngineSettings(downloadsPath, port);

            engineSettings.PreferEncryption  = true;
            engineSettings.AllowedEncryption = EncryptionTypes.RC4Full | EncryptionTypes.RC4Header;

            // Create the default settings which a torrent will have.
            // 4 Upload slots - a good ratio is one slot per 5kB of upload speed
            // 50 open connections - should never really need to be changed
            // Unlimited download speed - valid range from 0 -> int.Max
            // Unlimited upload speed - valid range from 0 -> int.Max
            TorrentSettings torrentDefaults = new TorrentSettings(100, 150, 0, maxUpload);

            // Create an instance of the engine.
            engine = new ClientEngine(engineSettings);
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, port));
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(dhtNodeFile);
            }
            catch
            {
                Console.WriteLine("No existing dht nodes could be loaded");
            }

            DhtListener dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, port));
            DhtEngine   dht        = new DhtEngine(dhtListner);

            engine.RegisterDht(dht);
            dhtListner.Start();
            engine.DhtEngine.Start(nodes);

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(engine.Settings.SavePath))
            {
                Directory.CreateDirectory(engine.Settings.SavePath);
            }

            // If the torrentsPath does not exist, we want to create it
            if (!Directory.Exists(torrentsPath))
            {
                Directory.CreateDirectory(torrentsPath);
            }

            BEncodedDictionary fastResume;

            try
            {
                fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(fastResumeFile));
            }
            catch
            {
                fastResume = new BEncodedDictionary();
            }

            // For each file in the torrents path that is a .torrent file, load it into the engine.
            foreach (string file in Directory.GetFiles(torrentsPath))
            {
                if (file.EndsWith(".torrent"))
                {
                    try
                    {
                        // Load the .torrent from the file into a Torrent instance
                        // You can use this to do preprocessing should you need to
                        torrent = Torrent.Load(file);
                        RemoveReadOnly(torrent);
                    }
                    catch (Exception e)
                    {
                        Console.Write("Couldn't decode {0}: ", file);
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    // When any preprocessing has been completed, you create a TorrentManager
                    // which you then register with the engine.
                    TorrentManager manager = new TorrentManager(torrent, downloadsPath, torrentDefaults);
                    //if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                    //    manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                    engine.Register(manager);

                    // Store the torrent manager in our list so we can access it later
                    torrents.Add(manager);
                    manager.PeersFound += new EventHandler <PeersAddedEventArgs>(manager_PeersFound);
                }
            }

            // If we loaded no torrents, just exist. The user can put files in the torrents directory and start
            // the client again
            if (torrents.Count == 0)
            {
                Console.WriteLine("No torrents found in the Torrents directory");
                Console.WriteLine("Exiting...");
                engine.Dispose();
                return;
            }

            // For each torrent manager we loaded and stored in our list, hook into the events
            // in the torrent manager and start the engine.
            foreach (TorrentManager manager in torrents)
            {
                // Every time a piece is hashed, this is fired.
                manager.PieceHashed += delegate(object o, PieceHashedEventArgs e)
                {
                };

                // Every time the state changes (Stopped -> Seeding -> Downloading -> Hashing) this is fired
                manager.TorrentStateChanged += OnTorrentStateChanged;

                // Every time the tracker's state changes, this is fired
                foreach (TrackerTier tier in manager.TrackerManager)
                {
                }
                // Start the torrentmanager. The file will then hash (if required) and begin downloading/seeding
                manager.Start();
            }

            // While the torrents are still running, print out some stats to the screen.
            // Details for all the loaded torrent managers are shown.
            int           i            = 0;
            bool          running      = true;
            StringBuilder sb           = new StringBuilder(1024);
            DateTime      lastAnnounce = DateTime.Now;
            bool          firstRun     = true;

            while (running)
            {
                if (firstRun || lastAnnounce < DateTime.Now.AddMinutes(-1))
                {
                    foreach (TorrentManager tm in torrents)
                    {
                        tm.TrackerManager.Announce();
                    }
                    lastAnnounce = DateTime.Now;
                    firstRun     = false;
                }
                if ((i++) % 10 == 0)
                {
                    sb.Remove(0, sb.Length);
                    running = torrents.Exists(delegate(TorrentManager m) { return(m.State != TorrentState.Stopped); });

                    TorrentState totalState = torrents.Exists(m => m.State == TorrentState.Hashing) ? TorrentState.Hashing : torrents.Exists(m => m.State == TorrentState.Downloading) ? TorrentState.Downloading : TorrentState.Seeding;

                    string status = "";
                    switch (totalState)
                    {
                    case TorrentState.Hashing:
                        double totalHashProgress = 0;
                        foreach (TorrentManager m in torrents)
                        {
                            totalHashProgress += (m.State == TorrentState.Hashing) ? m.Progress : 100;
                        }
                        totalHashProgress = totalHashProgress / torrents.Count;
                        status            = String.Format("Checking files ({0:0.00}%)", totalHashProgress);
                        break;

                    case TorrentState.Seeding:
                        status = "";
                        break;

                    default:
                        double totalDownloadProgress = 0;
                        double totalDownloaded       = 0;
                        double totalToDownload       = 0;
                        double totalDownloadSpeed    = 0;
                        long   totalDownloadSize     = 0;
                        foreach (TorrentManager m in torrents)
                        {
                            totalDownloadSize += m.Torrent.Size;
                        }

                        foreach (TorrentManager m in torrents)
                        {
                            totalDownloaded    += m.Torrent.Size / 1024 * (m.Progress / 100);
                            totalToDownload    += m.Torrent.Size / 1024;
                            totalDownloadSpeed += m.Monitor.DownloadSpeed;
                        }
                        totalDownloadProgress = (totalDownloaded / totalToDownload) * 100;
                        status  = "Status: " + (torrents.Exists(m => m.State == TorrentState.Downloading && m.GetPeers().Count > 0) ? "Downloading" : "Finding peers");
                        status += "\n" + String.Format("Progress: {0:0.00}%", totalDownloadProgress);
                        status += "\n" + String.Format("D/L Speed: {0:0.00} kB/s", totalDownloadSpeed / 1024.0);
                        break;
                    }
                    if (installer != null)
                    {
                        installer.Status = status;
                    }

                    #region OLDPROGRESS
                    //foreach (TorrentManager manager in torrents)
                    //{
                    //    AppendSeperator(sb);
                    //    AppendFormat(sb, "State:           {0}", manager.State);
                    //    AppendFormat(sb, "Name:            {0}", manager.Torrent == null ? "MetaDataMode" : manager.Torrent.Name);
                    //    AppendFormat(sb, "Progress:           {0:0.00}", manager.Progress);
                    //    string status = "";
                    //    switch (manager.State)
                    //    {
                    //        case TorrentState.Hashing:
                    //            status = String.Format("Checking files ({0:0.00}%)", manager.Progress);
                    //            break;
                    //        case TorrentState.Seeding: status = ""; break;
                    //        default:
                    //            status = "Status: " + (manager.GetPeers().Count == 0 ? "Finding Peers" : "Downloading");
                    //            status += "\n" + String.Format("Progress: {0:0.00}%", manager.Progress);
                    //            status += "\n" + String.Format("D/L Speed: {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0);
                    //            break;
                    //    }
                    //    if (installer != null)
                    //        installer.Status = status;
                    //    AppendFormat(sb, "Download Speed:     {0:0.00} kB/s", manager.Monitor.DownloadSpeed / 1024.0);
                    //    AppendFormat(sb, "Upload Speed:       {0:0.00} kB/s", manager.Monitor.UploadSpeed / 1024.0);
                    //    AppendFormat(sb, "Total Downloaded:   {0:0.00} MB", manager.Monitor.DataBytesDownloaded / (1024.0 * 1024.0));
                    //    AppendFormat(sb, "Total Uploaded:     {0:0.00} MB", manager.Monitor.DataBytesUploaded / (1024.0 * 1024.0));
                    //    MonoTorrent.Client.Tracker.Tracker tracker = manager.TrackerManager.CurrentTracker;
                    //    AppendFormat(sb, "Tracker Status:     {0}", tracker == null ? "<no tracker>" : tracker.Status.ToString());
                    //    AppendFormat(sb, "Warning Message:    {0}", tracker == null ? "<no tracker>" : tracker.WarningMessage);
                    //    AppendFormat(sb, "Failure Message:    {0}", tracker == null ? "<no tracker>" : tracker.FailureMessage);
                    //}
                    ////Console.Clear();
                    //Console.WriteLine(sb.ToString());
                    #endregion
                }

                System.Threading.Thread.Sleep(500);
            }
        }
コード例 #21
0
        async Task UpdateSettingsAsync(EngineSettings oldSettings, EngineSettings newSettings)
        {
            await DiskManager.UpdateSettingsAsync(newSettings);

            if (newSettings.DiskCacheBytes != oldSettings.DiskCacheBytes)
            {
                await Task.WhenAll(Torrents.Select(t => DiskManager.FlushAsync(t)));
            }

            ConnectionManager.Settings = newSettings;

            if (oldSettings.UsePartialFiles != newSettings.UsePartialFiles)
            {
                foreach (var manager in Torrents)
                {
                    await manager.UpdateUsePartialFiles(newSettings.UsePartialFiles);
                }
            }
            if (oldSettings.AllowPortForwarding != newSettings.AllowPortForwarding)
            {
                if (newSettings.AllowPortForwarding)
                {
                    await PortForwarder.StartAsync(CancellationToken.None);
                }
                else
                {
                    await PortForwarder.StopAsync(removeExistingMappings : true, CancellationToken.None);
                }
            }

            if (oldSettings.DhtEndPoint != newSettings.DhtEndPoint)
            {
                if (DhtListener.LocalEndPoint != null)
                {
                    await PortForwarder.UnregisterMappingAsync(new Mapping (Protocol.Udp, DhtListener.LocalEndPoint.Port), CancellationToken.None);
                }
                DhtListener.Stop();

                if (newSettings.DhtEndPoint == null)
                {
                    DhtListener = new NullDhtListener();
                    await RegisterDht(new NullDhtEngine());
                }
                else
                {
                    DhtListener = Factories.CreateDhtListener(Settings.DhtEndPoint) ?? new NullDhtListener();
                    if (IsRunning)
                    {
                        DhtListener.Start();
                    }

                    if (oldSettings.DhtEndPoint == null)
                    {
                        var dht = Factories.CreateDht();
                        await dht.SetListenerAsync(DhtListener);
                        await RegisterDht(dht);
                    }
                    else
                    {
                        await DhtEngine.SetListenerAsync(DhtListener);
                    }
                }

                if (DhtListener.LocalEndPoint != null)
                {
                    await PortForwarder.RegisterMappingAsync(new Mapping (Protocol.Udp, DhtListener.LocalEndPoint.Port));
                }
            }

            if (!Equals(oldSettings.ListenEndPoint, newSettings.ListenEndPoint))
            {
                if (PeerListener.LocalEndPoint != null)
                {
                    await PortForwarder.UnregisterMappingAsync(new Mapping (Protocol.Tcp, PeerListener.LocalEndPoint.Port), CancellationToken.None);
                }

                PeerListener.Stop();
                PeerListener = (newSettings.ListenEndPoint == null ? null : Factories.CreatePeerConnectionListener(newSettings.ListenEndPoint)) ?? new NullPeerListener();
                listenManager.SetListener(PeerListener);

                if (IsRunning)
                {
                    PeerListener.Start();
                    // The settings could say to listen at port 0, which means 'choose one dynamically'
                    if (PeerListener.LocalEndPoint != null)
                    {
                        await PortForwarder.RegisterMappingAsync(new Mapping (Protocol.Tcp, PeerListener.LocalEndPoint.Port));
                    }
                }
            }

            if (oldSettings.AllowLocalPeerDiscovery != newSettings.AllowLocalPeerDiscovery)
            {
                RegisterLocalPeerDiscovery(!newSettings.AllowLocalPeerDiscovery ? null : Factories.CreateLocalPeerDiscovery());
            }
        }
コード例 #22
0
ファイル: MonoTorrentClient.cs プロジェクト: kl4w/BTDeploy
        public void Start()
        {
            // Create an instance of the engine.
            Engine = new ClientEngine(new EngineSettings
            {
                PreferEncryption  = false,
                AllowedEncryption = EncryptionTypes.All
            });
            Engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, Port));

            // Setup DHT listener.
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(DHTNodeFile);
            }
            catch
            {
            }
            var dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, Port));

            Engine.RegisterDht(new DhtEngine(dhtListner));
            dhtListner.Start();
            Engine.DhtEngine.Start(nodes);

            // Fast resume.
            try
            {
                FastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(FastResumeFile));
            }
            catch
            {
                FastResume = new BEncodedDictionary();
            }

            // Try load the cache file.
            try
            {
                TorrentMappingsCache.Load();
            }
            catch
            {
            }

            // Cross reference torrent files against cache entries (sync).
            var torrents = Directory.GetFiles(TorrentFileDirectory, "*.torrent").Select(Torrent.Load).ToList();

            TorrentMappingsCache.RemoveAll(tmc => !torrents.Any(t => t.InfoHash.ToString() == tmc.InfoHash));
            TorrentMappingsCache.Save();
            torrents.Where(t => !TorrentMappingsCache.Any(tmc => tmc.InfoHash == t.InfoHash.ToString()))
            .ToList().ForEach(t => File.Delete(t.TorrentPath));

            // Reload the torrents and add them.
            Directory.GetFiles(TorrentFileDirectory, "*.torrent").ToList().ForEach(torrentFile =>
            {
                var torrent             = Torrent.Load(torrentFile);
                var outputDirectoryPath = TorrentMappingsCache.First(tmc => tmc.InfoHash == torrent.InfoHash.ToString()).OutputDirectoryPath;
                try
                {
                    Add(torrent, outputDirectoryPath);
                }
                catch
                {
                    var brokenTorrentFileName = Path.GetFileName(torrentFile);
                    var brokenTorrentFilePath = System.IO.Path.Combine(BrokenTorrentFileDirectory, brokenTorrentFileName);
                    File.Copy(torrentFile, brokenTorrentFilePath, true);
                    Remove(torrent.InfoHash.ToString());
                }
            });
        }
コード例 #23
0
        async Task UpdateSettingsAsync(EngineSettings oldSettings, EngineSettings newSettings)
        {
            await DiskManager.UpdateSettingsAsync(newSettings);

            if (newSettings.DiskCacheBytes != oldSettings.DiskCacheBytes)
            {
                await Task.WhenAll(Torrents.Select(t => DiskManager.FlushAsync(t)));
            }

            ConnectionManager.Settings = newSettings;

            if (oldSettings.AllowPortForwarding != newSettings.AllowPortForwarding)
            {
                if (newSettings.AllowPortForwarding)
                {
                    await PortForwarder.StartAsync(CancellationToken.None);
                }
                else
                {
                    await PortForwarder.StopAsync(removeExistingMappings : true, CancellationToken.None);
                }
            }

            if (oldSettings.DhtPort != newSettings.DhtPort)
            {
                if (DhtListener.EndPoint != null)
                {
                    await PortForwarder.UnregisterMappingAsync(new Mapping (Protocol.Udp, DhtListener.EndPoint.Port), CancellationToken.None);
                }
                else if (oldSettings.DhtPort > 0)
                {
                    await PortForwarder.UnregisterMappingAsync(new Mapping (Protocol.Udp, oldSettings.DhtPort), CancellationToken.None);
                }

                DhtListener = DhtListenerFactory.CreateUdp(newSettings.DhtPort);

                if (oldSettings.DhtPort == -1)
                {
                    await RegisterDht(DhtEngineFactory.Create(DhtListener));
                }
                else if (newSettings.DhtPort == -1)
                {
                    await RegisterDht(new NullDhtEngine());
                }

                DhtEngine.SetListener(DhtListener);

                if (IsRunning)
                {
                    DhtListener.Start();
                    if (Listener is ISocketListener newDhtListener)
                    {
                        await PortForwarder.RegisterMappingAsync(new Mapping (Protocol.Udp, newDhtListener.EndPoint.Port));
                    }
                    else
                    {
                        await PortForwarder.RegisterMappingAsync(new Mapping (Protocol.Udp, newSettings.DhtPort));
                    }
                }
            }

            if (oldSettings.ListenPort != newSettings.ListenPort)
            {
                if (Listener is ISocketListener oldListener)
                {
                    await PortForwarder.UnregisterMappingAsync(new Mapping (Protocol.Tcp, oldListener.EndPoint.Port), CancellationToken.None);
                }
                else if (oldSettings.ListenPort > 0)
                {
                    await PortForwarder.UnregisterMappingAsync(new Mapping (Protocol.Tcp, oldSettings.ListenPort), CancellationToken.None);
                }

                Listener.Stop();
                Listener = PeerListenerFactory.CreateTcp(newSettings.ListenPort);
                listenManager.SetListener(Listener);

                if (IsRunning)
                {
                    Listener.Start();
                    // The settings could say to listen at port 0, which means 'choose one dynamically'
                    if (Listener is ISocketListener peerListener)
                    {
                        await PortForwarder.RegisterMappingAsync(new Mapping (Protocol.Tcp, peerListener.EndPoint.Port));
                    }
                    else
                    {
                        await PortForwarder.RegisterMappingAsync(new Mapping (Protocol.Tcp, newSettings.ListenPort));
                    }
                }
            }

            // This depends on the Listener binding to it's local port.
            var localPort = newSettings.ListenPort;

            if (Listener is ISocketListener newListener)
            {
                localPort = newListener.EndPoint.Port;
            }

            if ((oldSettings.AllowLocalPeerDiscovery != newSettings.AllowLocalPeerDiscovery) ||
                (oldSettings.ListenPort != newSettings.ListenPort))
            {
                RegisterLocalPeerDiscovery(newSettings.AllowLocalPeerDiscovery && localPort > 0 ? new LocalPeerDiscovery(localPort) : null);
            }
        }
コード例 #24
0
        public void Initialize()
        {
            string downloadsPath = Client.Settings.StorageAutoSelect ? StorageHelper.GetBestSaveDirectory() : Client.Settings.StoragePath;

            if (Client.Settings.TorrentTcpPort == 0)
            {
                var r = new Random();
                int port;
                while (!TcpConnectionListener.IsPortFree(port = r.Next(6881, 7000)))
                {
                }
                logger.Info("Auto selected torrent port: {0}", port);
                Client.Settings.TorrentTcpPort = port;
            }

            var engineSettings = new EngineSettings(downloadsPath, Client.Settings.TorrentTcpPort)
            {
                PreferEncryption  = false,
                AllowedEncryption = EncryptionTypes.All
            };

            _torrentDefaults = new TorrentSettings(4, 50, 0, 0);

            _engine = new ClientEngine(engineSettings);
            _engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, Client.Settings.TorrentTcpPort));
            byte[] nodes = null;
            try
            {
                nodes = File.ReadAllBytes(TorrentDhtNodesPath);
            }
            catch
            {
                logger.Info("No existing dht nodes could be loaded");
            }

            var dhtListner = new DhtListener(new IPEndPoint(IPAddress.Any, Client.Settings.TorrentTcpPort));
            var dht        = new DhtEngine(dhtListner);

            _engine.RegisterDht(dht);
            dhtListner.Start();
            _engine.DhtEngine.Start(nodes);

            // If the SavePath does not exist, we want to create it.
            if (!Directory.Exists(_engine.Settings.SavePath))
            {
                Directory.CreateDirectory(_engine.Settings.SavePath);
            }

            // If the torrentsPath does not exist, we want to create it
            if (!Directory.Exists(TorrentsFolder))
            {
                Directory.CreateDirectory(TorrentsFolder);
            }

            BEncodedDictionary fastResume;

            try
            {
                if (File.Exists(TorrentFastResumePath))
                {
                    fastResume = BEncodedValue.Decode <BEncodedDictionary>(File.ReadAllBytes(TorrentFastResumePath));
                }
                else
                {
                    fastResume = new BEncodedDictionary();
                }
            }
            catch
            {
                fastResume = new BEncodedDictionary();
            }

            var knownTorrentsPaths = Directory.GetFiles(TorrentsFolder, "*.torrent");

            logger.Info("Loading {0} saved torrents", knownTorrentsPaths.Length);

            foreach (var file in knownTorrentsPaths)
            {
                Torrent torrent;
                try
                {
                    torrent = Torrent.Load(file);
                }
                catch (Exception e)
                {
                    logger.Error("Couldn't decode {0}: ", file);
                    logger.Error(e.Message);
                    continue;
                }

                var manager = new TorrentManager(torrent, downloadsPath, TorrentDefaults);
                if (fastResume.ContainsKey(torrent.InfoHash.ToHex()))
                {
                    manager.LoadFastResume(new FastResume((BEncodedDictionary)fastResume[torrent.InfoHash.ToHex()]));
                }
                RegisterTorrent(manager);

                manager.Start();
            }

#if DEBUG
            FrmDebug       = new FrmDownloadDebug();
            FrmDebug.Width = Screen.PrimaryScreen.WorkingArea.Width;
            FrmDebug.Show();
#endif
        }