예제 #1
0
        ///<summary>Start the Tracker. Start Watching the TORRENT_DIR Directory for new Torrents.</summary>
        public MySimpleTracker()
        {
            tracker = new TrackerServer();
            tracker.AllowUnregisteredTorrents = true;

            var httpEndpoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 10000);
            var udpEndpoint  = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 10001);

            Console.WriteLine("Listening for HTTP requests at: {0}", httpEndpoint);
            Console.WriteLine("Listening for UDP requests at: {0}", udpEndpoint);

            var listeners = new[] {
                TrackerListenerFactory.CreateHttp(httpEndpoint),
                TrackerListenerFactory.CreateUdp(udpEndpoint)
            };

            foreach (var listener in listeners)
            {
                tracker.RegisterListener(listener);
                listener.Start();
            }

            SetupTorrentWatcher();


            while (true)
            {
                System.Threading.Thread.Sleep(10000);
            }
        }
예제 #2
0
        public void Setup()
        {
            keys.Clear();

            listener.IncompleteAnnounce = listener.IncompleteScrape = false;

            server = new TrackerServer(trackerId)
            {
                AllowUnregisteredTorrents = true
            };
            server.RegisterListener(listener);

            tracker = (HTTPTracker)TrackerFactory.Create(AnnounceUrl);

            var infoHashBytes = new[] { ' ', '%', '&', '?', '&', '&', '?', '5', '1', '=' }
            .Select(t => (byte)t);

            infoHash       = new InfoHash(infoHashBytes.Concat(infoHashBytes).ToArray());
            announceParams = new AnnounceParameters()
                             .WithPort(5555)
                             .WithPeerId(peerId)
                             .WithInfoHash(infoHash);

            scrapeParams = new ScrapeParameters(new InfoHash(new byte[20]));
        }
예제 #3
0
        void cmdStartServers_Click(object sender, EventArgs e)
        {
            if (CheckServerFields() && _kClient == null && _kTracker == null)
            {
                var ipa = IPAddress.Parse(cboPossibleAddresses.Text);
                int trackerPort, kcPort;
                trackerPort = Convert.ToInt32(txtTrackerServerPort.Text);
                kcPort      = Convert.ToInt32(txtKClientPort.Text);
                _kTracker   = new TrackerServer(new IPEndPoint(ipa, trackerPort));
                _kClient    = new KClient(_kTracker, new IPEndPoint(ipa, kcPort));

                _kTracker.Logger = this;
                _kClient.Logger  = this;

                _kTracker.Listen();
                _kClient.Listen();

                Log("启动完成。本地参数: KClient=" + cboPossibleAddresses.Text + ":" + kcPort.ToString() + ", KTracker=" + cboPossibleAddresses.Text + ":" + trackerPort.ToString());

                txtTrackerURL.Text = "http://localhost:" + txtTrackerServerPort.Text + _kTracker.AnnouceUrl.TrimEnd('?');
                txtLocalKClientAddrAndPort.Text = cboPossibleAddresses.Text + ":" + txtKClientPort.Text;

                groupBox1.Enabled = false;
                groupBox2.Enabled = true;
                groupBox4.Enabled = true;
            }
            else
            {
                Log("本地服务器设置错误。");
            }
        }
예제 #4
0
 /// <summary>
 /// 使用指定的 <see cref="Kei.KTracker.TrackerServer"/> 和 <see cref="System.Net.IPEndPoint"/> 创建一个新的 <see cref="Kei.KNetwork.KClient"/> 实例。
 /// </summary>
 /// <param name="trackerServer">要用来处理 tracker 通信的 <see cref="Kei.KTracker.TrackerServer"/>。</param>
 /// <param name="localEndPoint">一个 <see cref="System.Net.IPEndPoint"/>,用来指示本地监听端点。注意应该使用本地局域网地址。</param>
 public KClient(TrackerServer trackerServer, IPEndPoint localEndPoint)
 {
     _trackerServer = trackerServer;
     SetLocalEndPoint(localEndPoint);
     _trackerServer.TrackerComm += TrackerServer_TrackerComm;
     _listener = new TcpListener(IPAddress.Any, LocalEndPoint.Port);
     FreeToGo  = false;
 }
예제 #5
0
        //-------------------------------------------------------------
        private Torrent()
        //-------------------------------------------------------------
        {
            TRACKERHTTP_PORT = Convert.ToInt32(ConfigurationManager.AppSettings.Get("Port:TorrentTrackerHTTP"));
            TRACKERUDP_PORT  = Convert.ToInt32(ConfigurationManager.AppSettings.Get("Port:TorrentTrackerUDP"));
            CLIENT_PORT      = Convert.ToInt32(ConfigurationManager.AppSettings.Get("Port:TorrentClient"));

            torrentManagers = new List <TorrentManager>();
            trackerServer   = null;
            engine          = null;
            settings        = null;
        }
예제 #6
0
        protected void Login()
        {
            this.TrackerServer = new TrackerServer(this.ToolKit);
            TrackerServer server1 = this.TrackerServer;

            server1.UserName      = this.ConnectionInformation.UserName;
            server1.UserPWD       = this.ConnectionInformation.UserPWD;
            server1.DBMSServer    = this.ConnectionInformation.DBMSServer;
            server1.DBMSType      = this.ConnectionInformation.DBMSType;
            server1.DBMSUserName  = this.ConnectionInformation.DBMSUserName;
            server1.DBMSPassword  = this.ConnectionInformation.DBMSPassword;
            server1.DBMSLoginMode = this.ConnectionInformation.DBMSLoginMode;
            server1.ProjectName   = this.ConnectionInformation.ProjectName;
            server1 = null;
            this.TrackerServer.Login();
        }
예제 #7
0
        public StorageClient1 GetStorageClient(string groupName = "group1")
        {
            TrackerServer ts = _trackerClient.getTrackerServer();

            if (ts == null)
            {
                throw new Exception("getConnection return null");
            }
            else
            {
                StorageServer ss = _trackerClient.getStoreStorage(ts, groupName);
                if (ss == null)
                {
                    throw new Exception("getStoreStorage return null");
                }
                else
                {
                    StorageClient1 sc1 = new StorageClient1(ts, ss);
                    return(sc1);
                }
            }
        }
예제 #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Clear();

            if (Request.QueryString["accesstoken"] == null)
            {
                Response.Write("invalid access token");
            }
            else
            {
                using (var repositorio = new DataRepository <TokenRegistro>())
                {
                    try
                    {
                        var tokenGerado = repositorio.Single(t => t.Token == Request.QueryString["accesstoken"] && t.DataGeracao.AddMinutes(5) >= DateTime.Now);

                        // verificado que o token de fato existe, deleta-o e registra o torrent
                        repositorio.Delete(tokenGerado);
                        repositorio.SaveChanges();

                        lock (TrackerServer)
                        {
                            TrackerServer.Add(new CustomTrackable(Request.QueryString["name"], Request.QueryString["info"]));
                        }

                        Response.Write("torrent registered successfully");
                    }
                    catch (Exception ex)
                    {
                        Response.Write(ex.Message);
                    }
                }
            }

            Response.End();
        }
예제 #9
0
        public static void Run(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Error: Must have 2 parameters, one is config filename, "
                                  + "the other is the local filename to upload");
                return;
            }

            string conf_filename  = args[0];
            string local_filename = args[1];

            try
            {
                ClientGlobal.init(conf_filename);

                long          startTime;
                ServerInfo[]  servers;
                TrackerClient tracker       = new TrackerClient();
                TrackerServer trackerServer = tracker.getConnection();

                StorageServer storageServer = null;

                StorageClientEx client = new StorageClientEx(trackerServer, storageServer);
                byte[]          file_buff;
                NameValuePair[] meta_list;
                string          group_name;
                string          appender_file_id;
                string          file_ext_name;
                int             errno;

                meta_list    = new NameValuePair[4];
                meta_list[0] = new NameValuePair("width", "800");
                meta_list[1] = new NameValuePair("heigth", "600");
                meta_list[2] = new NameValuePair("bgcolor", "#FFFFFF");
                meta_list[3] = new NameValuePair("author", "Mike");

                file_buff = Encoding.GetEncoding(ClientGlobal.g_charset).GetBytes("this is a test");
                Console.WriteLine("file length: " + file_buff.Length);

                group_name = null;
                StorageServer[] storageServers = tracker.getStoreStorages(trackerServer, group_name);
                if (storageServers == null)
                {
                    Console.WriteLine("get store storage servers fail, error code: " + tracker.ErrorCode);
                }
                else
                {
                    Console.WriteLine("store storage servers count: " + storageServers.Length);
                    for (int k = 0; k < storageServers.Length; k++)
                    {
                        Console.WriteLine((k + 1) + ". " + storageServers[k].InetSockAddr.Address + ":" + storageServers[k].InetSockAddr.Port);
                    }
                    Console.WriteLine("");
                }

                Stopwatch sw = new Stopwatch();
                sw.Start();
                appender_file_id = client.upload_appender_file1(file_buff, "txt", meta_list);
                sw.Stop();
                Console.WriteLine("upload_appender_file1 time used: " + sw.ElapsedMilliseconds + " ms");

                /*
                 * group_name = "";
                 * appender_file_id = client.upload_appender_file1(group_name, file_buff, "txt", meta_list);
                 */
                if (appender_file_id == null)
                {
                    Console.WriteLine("upload file fail, error code: " + client.ErrorCode);
                    return;
                }
                else
                {
                    Console.WriteLine(client.get_file_info1(appender_file_id));

                    servers = tracker.getFetchStorages1(trackerServer, appender_file_id);
                    if (servers == null)
                    {
                        Console.WriteLine("get storage servers fail, error code: " + tracker.ErrorCode);
                    }
                    else
                    {
                        Console.WriteLine("storage servers count: " + servers.Length);
                        for (int k = 0; k < servers.Length; k++)
                        {
                            Console.WriteLine((k + 1) + ". " + servers[k].Ip_Addr + ":" + servers[k].Port);
                        }
                        Console.WriteLine("");
                    }

                    meta_list    = new NameValuePair[4];
                    meta_list[0] = new NameValuePair("width", "1024");
                    meta_list[1] = new NameValuePair("heigth", "768");
                    meta_list[2] = new NameValuePair("bgcolor", "#000000");
                    meta_list[3] = new NameValuePair("title", "Untitle");

                    sw.Restart();
                    errno = client.set_metadata1(appender_file_id, meta_list, ProtoCommon.STORAGE_SET_METADATA_FLAG_MERGE);
                    sw.Stop();
                    Console.WriteLine("set_metadata time used: " + sw.ElapsedMilliseconds + " ms");
                    if (errno == 0)
                    {
                        Console.WriteLine("set_metadata success");
                    }
                    else
                    {
                        Console.WriteLine("set_metadata fail, error no: " + errno);
                    }

                    meta_list = client.get_metadata1(appender_file_id);
                    if (meta_list != null)
                    {
                        for (int i = 0; i < meta_list.Length; i++)
                        {
                            Console.WriteLine(meta_list[i]._Name + " " + meta_list[i]._Value);
                        }
                    }

                    sw.Restart();
                    file_buff = client.download_file1(appender_file_id);
                    sw.Stop();
                    Console.WriteLine("download_file time used: " + sw.ElapsedMilliseconds + " ms");

                    if (file_buff != null)
                    {
                        Console.WriteLine("file length:" + file_buff.Length);
                        Console.WriteLine(Encoding.GetEncoding(ClientGlobal.g_charset).GetString(file_buff));
                    }

                    file_buff     = Encoding.GetEncoding(ClientGlobal.g_charset).GetBytes("this is a slave buff");
                    file_ext_name = "txt";
                    sw.Restart();
                    errno = client.append_file1(appender_file_id, file_buff);
                    sw.Stop();
                    Console.WriteLine("append_file time used: " + sw.ElapsedMilliseconds + " ms");
                    if (errno == 0)
                    {
                        Console.WriteLine(client.get_file_info1(appender_file_id));
                    }
                    else
                    {
                        Console.WriteLine("append file fail, error no: " + errno);
                    }

                    sw.Restart();
                    errno = client.delete_file1(appender_file_id);
                    sw.Stop();
                    Console.WriteLine("delete_file time used: " + sw.ElapsedMilliseconds + " ms");
                    if (errno == 0)
                    {
                        Console.WriteLine("Delete file success");
                    }
                    else
                    {
                        Console.WriteLine("Delete file fail, error no: " + errno);
                    }
                }

                appender_file_id = client.upload_appender_file1(local_filename, null, meta_list);
                if (appender_file_id != null)
                {
                    int        ts;
                    string     token;
                    string     file_url;
                    IPEndPoint inetSockAddr;

                    inetSockAddr = trackerServer.InetSockAddr;
                    file_url     = "http://" + inetSockAddr.Address;
                    if (ClientGlobal.g_tracker_http_port != 80)
                    {
                        file_url += ":" + ClientGlobal.g_tracker_http_port;
                    }
                    file_url += "/" + appender_file_id;
                    if (ClientGlobal.g_anti_steal_token)
                    {
                        ts        = (int)ProtoCommon.DateTimeToUnixTimestamp(DateTime.Now);
                        token     = ProtoCommon.getToken(appender_file_id, ts, ClientGlobal.g_secret_key);
                        file_url += "?token=" + token + "&ts=" + ts;
                    }

                    Console.WriteLine(client.get_file_info1(appender_file_id));
                    Console.WriteLine("file url: " + file_url);

                    errno = client.download_file1(appender_file_id, 0, 0, "c:\\" + appender_file_id.Replace("/", "_"));
                    if (errno == 0)
                    {
                        Console.WriteLine("Download file success");
                    }
                    else
                    {
                        Console.WriteLine("Download file fail, error no: " + errno);
                    }

                    errno = client.download_file1(appender_file_id, 0, 0, new DownloadFileWriter("c:\\" + appender_file_id.Replace("/", "-")));
                    if (errno == 0)
                    {
                        Console.WriteLine("Download file success");
                    }
                    else
                    {
                        Console.WriteLine("Download file fail, error no: " + errno);
                    }

                    file_ext_name = null;
                    sw.Restart();
                    errno = client.append_file1(appender_file_id, local_filename);
                    sw.Stop();
                    Console.WriteLine("append_file time used: " + sw.ElapsedMilliseconds + " ms");
                    if (errno == 0)
                    {
                        Console.WriteLine(client.get_file_info1(appender_file_id));
                    }
                    else
                    {
                        Console.WriteLine("append file fail, error no: " + errno);
                    }
                }

                System.IO.FileInfo f;
                f             = new System.IO.FileInfo(local_filename);
                file_ext_name = Path.GetExtension(local_filename).Trim('.');

                appender_file_id = client.upload_appender_file1(null, f.Length,
                                                                new UploadLocalFileSender(local_filename), file_ext_name, meta_list);
                if (appender_file_id != null)
                {
                    Console.WriteLine(client.get_file_info1(appender_file_id));

                    sw.Restart();
                    errno = client.append_file1(appender_file_id, f.Length, new UploadLocalFileSender(local_filename));
                    sw.Stop();
                    Console.WriteLine("append_file time used: " + sw.ElapsedMilliseconds + " ms");
                    if (errno == 0)
                    {
                        Console.WriteLine(client.get_file_info1(appender_file_id));
                    }
                    else
                    {
                        Console.WriteLine("append file fail, error no: " + errno);
                    }

                    sw.Restart();
                    errno = client.modify_file1(appender_file_id, 0, f.Length, new UploadLocalFileSender(local_filename));
                    sw.Stop();
                    Console.WriteLine("modify_file time used: " + sw.ElapsedMilliseconds + " ms");
                    if (errno == 0)
                    {
                        Console.WriteLine(client.get_file_info1(appender_file_id));
                    }
                    else
                    {
                        Console.WriteLine("modify file fail, error no: " + errno);
                    }

                    sw.Restart();
                    errno = client.truncate_file1(appender_file_id, 0);
                    sw.Stop();
                    Console.WriteLine("truncate_file time used: " + sw.ElapsedMilliseconds + " ms");
                    if (errno == 0)
                    {
                        Console.WriteLine(client.get_file_info1(appender_file_id));
                    }
                    else
                    {
                        Console.WriteLine("truncate file fail, error no: " + errno);
                    }
                }
                else
                {
                    Console.WriteLine("Upload file fail, error no: " + errno);
                }

                storageServer = tracker.getFetchStorage1(trackerServer, appender_file_id);
                if (storageServer == null)
                {
                    Console.WriteLine("getFetchStorage fail, errno code: " + tracker.ErrorCode);
                    return;
                }
                /* for test only */
                Console.WriteLine("active test to storage server: " + ProtoCommon.activeTest(storageServer.getSocket()));

                storageServer.close();

                /* for test only */
                Console.WriteLine("active test to tracker server: " + ProtoCommon.activeTest(trackerServer.getSocket()));

                trackerServer.close();
            }
            catch (Exception ex)
            {
            }
        }
예제 #10
0
        public static void Run(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Error: Must have 1 parameter: config filename");
                return;
            }

            try
            {
                ClientGlobal.init(args[0]);
                TrackerClient tc      = new TrackerClient();
                TrackerServer tracker = tc.getConnection();
                if (tracker == null)
                {
                    return;
                }

                int count = 0;
                StructGroupStat[] groupStats = tc.listGroups(tracker);
                if (groupStats == null)
                {
                    Console.WriteLine("");
                    Console.WriteLine("ERROR! list groups error, error no: " + tc.ErrorCode);
                    Console.WriteLine("");
                    return;
                }
                Console.WriteLine("group count: " + groupStats.Length);

                foreach (StructGroupStat groupStat in groupStats)
                {
                    count++;
                    Console.WriteLine("Group " + count + ":");
                    Console.WriteLine("group name = " + groupStat.GroupName);
                    Console.WriteLine("disk total space = " + groupStat.TotalMB + "MB");
                    Console.WriteLine("disk free space = " + groupStat.FreeMB + " MB");
                    Console.WriteLine("trunk free space = " + groupStat.TrunkFreeMB + " MB");
                    Console.WriteLine("storage server count = " + groupStat.StorageCount);
                    Console.WriteLine("active server count = " + groupStat.ActiveCount);
                    Console.WriteLine("storage server port = " + groupStat.StoragePort);
                    Console.WriteLine("storage HTTP port = " + groupStat.StorageHttpPort);
                    Console.WriteLine("store path count = " + groupStat.StorePathCount);
                    Console.WriteLine("subdir count per path = " + groupStat.SubdirCountPerPath);
                    Console.WriteLine("current write server index = " + groupStat.CurrentWriteServer);
                    Console.WriteLine("current trunk file id = " + groupStat.CurrentTrunkFileId);

                    StructStorageStat[] storageStats = tc.listStorages(tracker, groupStat.GroupName);
                    if (storageStats == null)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("ERROR! list storage error, error no: " + tc.ErrorCode);
                        Console.WriteLine("");
                        break;
                    }

                    int stroageCount = 0;
                    foreach (StructStorageStat storageStat in storageStats)
                    {
                        stroageCount++;
                        Console.WriteLine("\tStorage " + stroageCount + ":");
                        Console.WriteLine("\t\tstorage id = " + storageStat.Id);
                        Console.WriteLine("\t\tip_addr = " + storageStat.IpAddr + "  " + ProtoCommon.getStorageStatusCaption(storageStat.Status));
                        Console.WriteLine("\t\thttp domain = " + storageStat.DomainName);
                        Console.WriteLine("\t\tversion = " + storageStat.Version);
                        Console.WriteLine("\t\tjoin time = " + storageStat.JoinTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        Console.WriteLine("\t\tup time = " + storageStat.UpTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        Console.WriteLine("\t\ttotal storage = " + storageStat.TotalMB + "MB");
                        Console.WriteLine("\t\tfree storage = " + storageStat.FreeMB + "MB");
                        Console.WriteLine("\t\tupload priority = " + storageStat.UploadPriority);
                        Console.WriteLine("\t\tstore_path_count = " + storageStat.StorePathCount);
                        Console.WriteLine("\t\tsubdir_count_per_path = " + storageStat.SubdirCountPerPath);
                        Console.WriteLine("\t\tstorage_port = " + storageStat.StoragePort);
                        Console.WriteLine("\t\tstorage_http_port = " + storageStat.StorageHttpPort);
                        Console.WriteLine("\t\tcurrent_write_path = " + storageStat.CurrentWritePath);
                        Console.WriteLine("\t\tsource ip_addr = " + storageStat.SrcIpAddr);
                        Console.WriteLine("\t\tif_trunk_server = " + storageStat.IfTrunkServer);
                        Console.WriteLine("\t\tconntion.alloc_count  = " + storageStat.ConnectionAllocCount);
                        Console.WriteLine("\t\tconntion.current_count  = " + storageStat.ConnectionCurrentCount);
                        Console.WriteLine("\t\tconntion.max_count  = " + storageStat.ConnectionMaxCount);
                        Console.WriteLine("\t\ttotal_upload_count = " + storageStat.TotalUploadCount);
                        Console.WriteLine("\t\tsuccess_upload_count = " + storageStat.SuccessUploadCount);
                        Console.WriteLine("\t\ttotal_append_count = " + storageStat.TotalAppendCount);
                        Console.WriteLine("\t\tsuccess_append_count = " + storageStat.SuccessAppendCount);
                        Console.WriteLine("\t\ttotal_modify_count = " + storageStat.TotalModifyCount);
                        Console.WriteLine("\t\tsuccess_modify_count = " + storageStat.SuccessModifyCount);
                        Console.WriteLine("\t\ttotal_truncate_count = " + storageStat.TotalTruncateCount);
                        Console.WriteLine("\t\tsuccess_truncate_count = " + storageStat.SuccessTruncateCount);
                        Console.WriteLine("\t\ttotal_set_meta_count = " + storageStat.TotalSetMetaCount);
                        Console.WriteLine("\t\tsuccess_set_meta_count = " + storageStat.SuccessSetMetaCount);
                        Console.WriteLine("\t\ttotal_delete_count = " + storageStat.TotalDeleteCount);
                        Console.WriteLine("\t\tsuccess_delete_count = " + storageStat.SuccessDeleteCount);
                        Console.WriteLine("\t\ttotal_download_count = " + storageStat.TotalDownloadCount);
                        Console.WriteLine("\t\tsuccess_download_count = " + storageStat.SuccessDownloadCount);
                        Console.WriteLine("\t\ttotal_get_meta_count = " + storageStat.TotalGetMetaCount);
                        Console.WriteLine("\t\tsuccess_get_meta_count = " + storageStat.SuccessGetMetaCount);
                        Console.WriteLine("\t\ttotal_create_link_count = " + storageStat.TotalCreateLinkCount);
                        Console.WriteLine("\t\tsuccess_create_link_count = " + storageStat.SuccessCreateLinkCount);
                        Console.WriteLine("\t\ttotal_delete_link_count = " + storageStat.TotalDeleteLinkCount);
                        Console.WriteLine("\t\tsuccess_delete_link_count = " + storageStat.SuccessDeleteLinkCount);
                        Console.WriteLine("\t\ttotal_upload_bytes = " + storageStat.TotalUploadBytes);
                        Console.WriteLine("\t\tsuccess_upload_bytes = " + storageStat.SuccessUploadBytes);
                        Console.WriteLine("\t\ttotal_append_bytes = " + storageStat.TotalAppendBytes);
                        Console.WriteLine("\t\tsuccess_append_bytes = " + storageStat.SuccessAppendBytes);
                        Console.WriteLine("\t\ttotal_modify_bytes = " + storageStat.TotalModifyBytes);
                        Console.WriteLine("\t\tsuccess_modify_bytes = " + storageStat.SuccessModifyBytes);
                        Console.WriteLine("\t\ttotal_download_bytes = " + storageStat.TotalDownloadloadBytes);
                        Console.WriteLine("\t\tsuccess_download_bytes = " + storageStat.SuccessDownloadloadBytes);
                        Console.WriteLine("\t\ttotal_sync_in_bytes = " + storageStat.TotalSyncInBytes);
                        Console.WriteLine("\t\tsuccess_sync_in_bytes = " + storageStat.SuccessSyncInBytes);
                        Console.WriteLine("\t\ttotal_sync_out_bytes = " + storageStat.TotalSyncOutBytes);
                        Console.WriteLine("\t\tsuccess_sync_out_bytes = " + storageStat.SuccessSyncOutBytes);
                        Console.WriteLine("\t\ttotal_file_open_count = " + storageStat.TotalFileOpenCount);
                        Console.WriteLine("\t\tsuccess_file_open_count = " + storageStat.SuccessFileOpenCount);
                        Console.WriteLine("\t\ttotal_file_read_count = " + storageStat.TotalFileReadCount);
                        Console.WriteLine("\t\tsuccess_file_read_count = " + storageStat.SuccessFileReadCount);
                        Console.WriteLine("\t\ttotal_file_write_count = " + storageStat.TotalFileWriteCount);
                        Console.WriteLine("\t\tsuccess_file_write_count = " + storageStat.SuccessFileWriteCount);
                        Console.WriteLine("\t\tlast_heart_beat_time = " + storageStat.LastHeartBeatTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        Console.WriteLine("\t\tlast_source_update = " + storageStat.LastSourceUpdate.ToString("yyyy-MM-dd HH:mm:ss"));
                        Console.WriteLine("\t\tlast_sync_update = " + storageStat.LastSyncUpdate.ToString("yyyy-MM-dd HH:mm:ss"));
                        //Console.WriteLine("\t\tlast_synced_timestamp = " + storageStat.LastSyncedTimestamp.ToString("yyyy-MM-dd HH:mm:ss") + getSyncedDelayString(storageStats, storageStat));
                    }
                }
                tracker.close();

                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
예제 #11
0
파일: fMain.cs 프로젝트: radtek/KeiSystem
        void cmdStartServers_Click(object sender, EventArgs e)
        {
            if (_kClient == null || _kTracker == null)
            {
                if (CheckServerFields())
                {
                    IPAddress ipa;
                    _wasStartedAsPI = KeiGuiOptions.Current.IsPointInsertion;
                    if (KeiGuiOptions.Current.IsPointInsertion || (false && KeiGuiOptions.Current.UsePortMapping))
                    {
                        // 作为接入点或者启用了 UPnP 的普通用户启动
                        ipa = IPAddress.Parse(cboPossibleAddresses.Text.Split(' ')[0]);
                    }
                    else
                    {
                        // 作为普通用户启动
                        ipa = IPAddress.Loopback;
                    }
                    var nTracker        = Convert.ToInt32(txtLocalTrackerServerPort.Text);
                    var nKClient        = Convert.ToInt32(txtLocalKClientPort.Text);
                    var trackerEndPoint = new IPEndPoint(ipa, nTracker);
                    var kcEndPoint      = new IPEndPoint(ipa, nKClient);

                    if (_kTracker == null)
                    {
                        _kTracker = new TrackerServer(trackerEndPoint);
                    }
                    if (_kClient == null)
                    {
                        _kClient = new KClient(_kTracker, kcEndPoint);
                        _kClient.ConnectionListChanged += _kClient_ConnectionListChanged;
                    }

                    //if (!_kTracker.IsBound)
                    //{
                    //    if (!_kTracker.TestBind(trackerEndPoint))
                    //    {
                    //        MessageBox.Show("Tracker 服务器端口不可用,请设置一个新的端口。", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    //        _kTracker = null;
                    //        return;
                    //    }
                    //}
                    //txtLocalTrackerServerPort.Enabled = false;
                    //if (!_kClient.IsBound)
                    //{
                    //    if (!_kClient.TestBind(kcEndPoint))
                    //    {
                    //        MessageBox.Show("K客户端服务器端口不可用,请设置一个新的端口。", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    //        _kClient = null;
                    //        return;
                    //    }
                    //}
                    //txtLocalKClientPort.Enabled = false;

                    if (KeiGuiOptions.Current.EnableLogging)
                    {
                        _kTracker.Logger = Program.Logger;
                        _kClient.Logger  = Program.Logger;
                    }

                    if (KeiGuiOptions.Current.IsPointInsertion)
                    {
                        _kClient.FreeToGo  = true;
                        _kTracker.FreeToGo = true;
                    }

                    _kTracker.Listen();
                    if (KeiGuiOptions.Current.IsPointInsertion)
                    {
                        // 接入点立即启动,普通用户要连接到接入点后才能启动
                        _kClient.Listen();
                    }

                    groupBox1.Enabled = false;
                    groupBox2.Enabled = true;

                    txtLocalKClientEndPoint.Text = _kClient.LocalKEndPoint.ToString();
                    txtLocalTrackerAddress.Text  = "http://localhost:" + _kTracker.LocalEndPoint.Port.ToString() + _kTracker.AnnouceUrl.TrimEnd('?');

                    SetStatusText("服务器已启动");
                    KGState = KeiGuiState.ServersStarted;
                }
            }
        }
예제 #12
0
 public void TearDown()
 {
     this.TrackerServer = null;
     this.ToolKit = null;
 }
예제 #13
0
        public static void Process(string inputFilename, BEncodedDictionary torrent)
        {
            bool successful               = false;
            bool isFgbtTorrent            = false;
            BEncodedDictionary newTorrent = new BEncodedDictionary();

            TryReadKeiGuiConfig();

            if (true && !string.IsNullOrEmpty(inputFilename) && torrent != null)
            {
                FileInfo fi = new FileInfo(inputFilename);
                // 先判断是否是未来花园的种子
                if (fi.Name.StartsWith("[FGBT]."))
                {
                    try
                    {
                        var sourceString = ((torrent["info"] as BEncodedDictionary)["source"] as BEncodedString).Text;
                        if (sourceString.StartsWith("FGBT-"))
                        {
                            // 是原来的未来花园的种子
                            isFgbtTorrent = true;
                        }
                    }
                    catch (Exception)
                    {
                    }
                }

                var kt             = new TrackerServer(new IPEndPoint(IPAddress.Loopback, 10000));
                var announceString = "http://localhost:" + kgOptions.LocalTrackerServerPort.ToString() + kt.AnnouceUrl.TrimEnd('?');

                try
                {
                    newTorrent.Add("announce", announceString);
                    newTorrent.Add("announce-list", new BEncodedList()
                    {
                        new BEncodedList()
                        {
                            announceString,
                        }
                    });
                    newTorrent.Add("created by", (torrent["created by"] as BEncodedString).Text);
                    newTorrent.Add("creation date", (torrent["creation date"] as BEncodedNumber).Number);
                    // 遵循花园的原则,不转码,直接设置编码为 UTF-8
                    newTorrent.Add("encoding", "UTF-8");

                    var info = new BEncodedDictionary();
                    if (isFgbtTorrent)
                    {
                        foreach (var item in (torrent["info"] as BEncodedDictionary))
                        {
                            info.Add(item);
                        }
                    }
                    else
                    {
                        if ((torrent["info"] as BEncodedDictionary).ContainsKey("files"))
                        {
                            // 单文件的种子是没有 files 项的
                            info.Add("files", (torrent["info"] as BEncodedDictionary)["files"]);
                        }
                        else
                        {
                            // 单文件的种子有 length 项
                            info.Add("length", (torrent["info"] as BEncodedDictionary)["length"]);
                        }
                        info.Add("name", (torrent["info"] as BEncodedDictionary)["name"]);
                        info.Add("piece length", (torrent["info"] as BEncodedDictionary)["piece length"]);
                        info.Add("pieces", (torrent["info"] as BEncodedDictionary)["pieces"]);
                        info.Add("private", 1);

                        // 至于 source 呢,要经过编码……
                        var origInfo     = torrent["info"].Encode();
                        var sha1         = SHA1.Create();
                        var origInfoHash = sha1.ComputeHash(origInfo);
                        sha1.Dispose();
                        var origInfoHashString = BitConverter.ToString(origInfoHash);
                        origInfoHashString = new string(origInfoHashString.Where((c) => c != '-').ToArray());
                        info.Add("source", "KS-" + origInfoHashString);
                    }

                    newTorrent.Add("info", info);
                    successful = true;
                }
                catch (Exception)
                {
                    successful = false;
                }
                kt = null;
            }

            if (successful)
            {
                var fi      = new FileInfo(inputFilename);
                var newName = Path.Combine(fi.DirectoryName, "[KS]." + fi.Name);
                // 命令行状态下不提示
                //if (File.Exists(newName))
                //{
                //    var dresult = MessageBox.Show("已存在 " + newName + ",是否覆盖?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                //    if (dresult == DialogResult.No)
                //    {
                //        return;
                //    }
                //}
                try
                {
                    using (var fs = new FileStream(newName, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        var buf = newTorrent.Encode();
                        fs.Write(buf, 0, buf.Length);
                    }
                    Console.WriteLine("成功保存到 " + newName + "。");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("无法写入 " + newName + ": " + ex.Message);
                }
            }
            else
            {
                Console.WriteLine("尝试生成并保存种子失败。");
            }
        }
예제 #14
0
        /// <summary>
        /// 解码连接到接入点时收到的字节数组,并应用这些信息。
        /// </summary>
        /// <param name="data">收到的数据。</param>
        ///// <param name="sendPeerEnter">解码过程中是否应该广播 PeerEnterNetwork 消息。</param>
        /// <exception cref="System.FormatException">解码失败时发生。</exception>
        /// <remarks>
        /// 需要发送 PeerEnterNetwork 消息的情况会发生于:A开启客户端和μT,B开启客户端和μT,A(用户列表非空)再尝试连接B,此时如果B并没有保存全网的用户列表,那么A就要广播 PeerEnterNetwork。
        /// </remarks>
        private void DecodeTargetInformation(byte[] data)
        {
            // 如果对方发过来的是空,那么就肯定不会有数据啦
            if (data.Length > 0)
            {
                BEncodedDictionary dictionary = BEncodedDictionary.Decode(data) as BEncodedDictionary;
                if (dictionary == null)
                {
                    throw new FormatException("无法解码。");
                }
                BEncodedList       connList  = dictionary["connections"] as BEncodedList;
                BEncodedDictionary peersDict = dictionary["peers"] as BEncodedDictionary;

                // 规范 v1.2
                // 先确认自己,同时 if ... 是兼容老版的通信
                if (dictionary.ContainsKey("your endpoint"))
                {
                    BEncodedDictionary yourEndPoint = dictionary["your endpoint"] as BEncodedDictionary;
                    var ip   = new IPAddress((yourEndPoint["ip"] as BEncodedString).TextBytes);
                    var port = BitConverter.ToUInt16((yourEndPoint["port"] as BEncodedString).TextBytes, 0);
                    // 分别设置 KClient、TrackerServer 和 BT 客户端的自己
                    SetLocalEndPoint(new IPEndPoint(ip, port));
                    TrackerServer.SetLocalEndPoint(new IPEndPoint(ip, TrackerServer.LocalEndPoint.Port));
                    TrackerServer.SetMyself(new IPEndPoint(ip, TrackerServer.Myself.EndPoint.GetPortNumber()));

                    this.FreeToGo          = true;
                    TrackerServer.FreeToGo = true;
                }

                // ...
                lock (ConnectionList)
                {
                    foreach (var item in connList)
                    {
                        var       d   = item as BEncodedDictionary;
                        KEndPoint kep = KEndPoint.Empty;
                        kep.SetAddress((d["ip"] as BEncodedString).TextBytes);
                        kep.SetPort((int)BitConverter.ToUInt16((d["port"] as BEncodedString).TextBytes, 0));
                        try
                        {
                            AddToConnectionList(kep);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }

                // 如果已经有用户登记了,那么应该广播
                if (TrackerServer.Seeds.Count > 0)
                {
                    lock (TrackerServer.Seeds)
                    {
                        foreach (var kv in TrackerServer.Seeds)
                        {
                            // 广播消息
                            BroadcastMyselfAddAsPeer(kv.Key);
                        }
                    }
                }
                lock (TrackerServer.Seeds)
                {
                    foreach (var kv in peersDict)
                    {
                        InfoHash    infoHash = InfoHash.FromByteArray(kv.Key.TextBytes);
                        List <Peer> peers    = new List <Peer>((kv.Value as BEncodedList).Count);
                        foreach (var item in (kv.Value as BEncodedList))
                        {
                            var       d   = item as BEncodedDictionary;
                            KEndPoint kep = KEndPoint.Empty;
                            kep.SetAddress((d["ip"] as BEncodedString).TextBytes);
                            kep.SetPort((int)BitConverter.ToUInt16((d["port"] as BEncodedString).TextBytes, 0));
                            Peer peer = Peer.Create(kep);
                            peers.Add(peer);
                        }
                        try
                        {
                            TrackerServer.Seeds.Add(infoHash, peers);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
            else
            {
                Logger.Log("待解码的数据为空,这意味着对方客户端目前持有的连接列表和用户列表为空。");
            }
        }
예제 #15
0
 public void TearDown()
 {
     this.TrackerServer = null;
     this.ToolKit       = null;
 }
예제 #16
0
        //-------------------------------------------------------------
        public void StartTracker(byte[] torrentData)
        //-------------------------------------------------------------
        {
            Log.Get().Write("Starting torrent tracker server, http on port: " + TRACKERHTTP_PORT + " udp on port: " + TRACKERUDP_PORT);
            if (!Helper.IsPortAvailable(TRACKERHTTP_PORT))
            {
                Log.Get().Write("Failed starting torrent tracker server on http port: " + TRACKERHTTP_PORT + " Port in use", Log.LogType.Error);
            }
            if (!Helper.IsPortAvailable(TRACKERUDP_PORT))
            {
                Log.Get().Write("Failed starting torrent tracker server on UDP port: " + TRACKERUDP_PORT + " Port in use", Log.LogType.Error);
            }

            //-------------------------------------------------------------
            //Create tracker server
            //-------------------------------------------------------------
            if (trackerServer == null)
            {
                trackerServer = new TrackerServer();
                listenerHttp  = TrackerListenerFactory.CreateHttp(IPAddress.Any, TRACKERHTTP_PORT); // http://localhost:{TRACKER_PORT}/announce
                listenerUdp   = TrackerListenerFactory.CreateUdp(IPAddress.Any, TRACKERUDP_PORT);   // http://localhost:{TRACKER_PORT}/announce

                //Add logning
                trackerServer.PeerAnnounced   += delegate(object o, AnnounceEventArgs e) { Log.Get().Write("TrackerServer PeerAnnounced"); };
                trackerServer.PeerScraped     += delegate(object o, ScrapeEventArgs e) { Log.Get().Write("TrackerServer PeerScrape"); };
                trackerServer.PeerTimedOut    += delegate(object o, TimedOutEventArgs e) { Log.Get().Write("TrackerServer Peer timeout"); };
                listenerHttp.AnnounceReceived += delegate(object o, AnnounceRequest e) { Log.Get().Write("TrackerListenerHTTP Announce received"); };
                listenerHttp.ScrapeReceived   += delegate(object o, TrackerScrapeRequest e) { Log.Get().Write("TrackerListenerHTTP Scrape received"); };
                listenerHttp.StatusChanged    += delegate(object o, EventArgs e)
                {
                    Log.Get().Write("TrackerListenerHttp Status changed: " + listenerHttp.Status);  //Typecast not working here, protectionlevel error. :( /*((MonoTorrent.Tracker.Listeners.HttpTrackerListener)o)*/
                };
                listenerUdp.AnnounceReceived += delegate(object o, AnnounceRequest e) { Log.Get().Write("TrackerListenerUDP Announce received"); };
                listenerUdp.ScrapeReceived   += delegate(object o, TrackerScrapeRequest e) { Log.Get().Write("TrackerListenerUDP Scrape received"); };
                listenerUdp.StatusChanged    += delegate(object o, EventArgs e)
                {
                    Log.Get().Write("TrackerListenerUdp Status changed: " + listenerUdp.Status);
                };

                //Start tracking server
                trackerServer.RegisterListener(listenerHttp);
                trackerServer.RegisterListener(listenerUdp);
                listenerUdp.Start();
                listenerHttp.Start();
                trackerServer.AllowUnregisteredTorrents = false; // If an announce request is received for a torrent which is not registered with the tracker an error will be returned.
                Log.Get().Write("TrackerListener listener status http:" + listenerHttp.Status + " udp status: " + listenerUdp.Status);
            }

            //-------------------------------------------------------------
            //Add new torrent to tracker
            //-------------------------------------------------------------
            MonoTorrent.Torrent torrent   = MonoTorrent.Torrent.Load(torrentData);
            InfoHashTrackable   trackable = new InfoHashTrackable(torrent);

            trackerServer.Add(trackable);
            Log.Get().Write("Adding torrent to tracker server, torrent size: " + torrentData.Length);

            //-------------------------------------------------------------
            //Seed file
            //-------------------------------------------------------------
            Log.Get().Write("Prepare to seed file");
            DownloadTorrent(torrent);
        }
예제 #17
0
        public async Task RunAsync()
        {
            //LoggerFactory.Creator = className => new TextLogger (Console.Out, className);

            int port   = 37827;
            var seeder = new ClientEngine(
                new EngineSettingsBuilder {
                AllowedEncryption = new[] { EncryptionType.PlainText },
                DiskCacheBytes    = DataSize,
                ListenEndPoint    = new IPEndPoint(IPAddress.Any, port++)
            }.ToSettings(),
                Factories.Default.WithPieceWriterCreator(maxOpenFiles => new NullWriter())
                );

            var downloaders = Enumerable.Range(port, 16).Select(p => {
                return(new ClientEngine(
                           new EngineSettingsBuilder {
                    AllowedEncryption = new[] { EncryptionType.PlainText },
                    DiskCacheBytes = DataSize,
                    ListenEndPoint = new IPEndPoint(IPAddress.Any, p),
                }.ToSettings(),
                           Factories.Default.WithPieceWriterCreator(maxOpenFiles => new NullWriter())
                           ));
            }).ToArray();

            Directory.CreateDirectory(DataDir);
            // Generate some fake data on-disk
            var buffer = Enumerable.Range(0, 16 * 1024).Select(s => (byte)s).ToArray();

            using (var fileStream = File.OpenWrite(Path.Combine(DataDir, "file.data"))) {
                for (int i = 0; i < DataSize / buffer.Length; i++)
                {
                    fileStream.Write(buffer, 0, buffer.Length);
                }
                fileStream.SetLength(DataSize);
            }

            var trackerListener = TrackerListenerFactory.CreateHttp(IPAddress.Parse("127.0.0.1"), 25611);
            var tracker         = new TrackerServer {
                AllowUnregisteredTorrents = true
            };

            tracker.RegisterListener(trackerListener);
            trackerListener.Start();

            // Create the torrent file for the fake data
            var creator = new TorrentCreator();

            creator.Announces.Add(new List <string> ());
            creator.Announces[0].Add("http://127.0.0.1:25611/announce");

            var metadata = await creator.CreateAsync(new TorrentFileSource (DataDir));

            // Set up the seeder
            await seeder.AddAsync(Torrent.Load(metadata), DataDir, new TorrentSettingsBuilder { UploadSlots = 20 }.ToSettings());

            using (var fileStream = File.OpenRead(Path.Combine(DataDir, "file.data"))) {
                while (fileStream.Position < fileStream.Length)
                {
                    var dataRead = new byte[16 * 1024];
                    int offset   = (int)fileStream.Position;
                    int read     = fileStream.Read(dataRead, 0, dataRead.Length);
                    // FIXME: Implement a custom IPieceWriter to handle this.
                    // The internal MemoryWriter is limited and isn't a general purpose read/write API
                    // await seederWriter.WriteAsync (seeder.Torrents[0].Files[0], offset, dataRead, 0, read, false);
                }
            }

            await seeder.StartAllAsync();

            List <Task> tasks = new List <Task> ();

            for (int i = 0; i < downloaders.Length; i++)
            {
                await downloaders[i].AddAsync(
                    Torrent.Load(metadata),
                    Path.Combine(DataDir, "Downloader" + i)
                    );

                tasks.Add(RepeatDownload(downloaders[i]));
            }

            while (true)
            {
                long downTotal        = seeder.TotalDownloadRate;
                long upTotal          = seeder.TotalUploadRate;
                long totalConnections = 0;
                long dataDown         = seeder.Torrents[0].Monitor.DataBytesReceived + seeder.Torrents[0].Monitor.ProtocolBytesReceived;
                long dataUp           = seeder.Torrents[0].Monitor.DataBytesSent + seeder.Torrents[0].Monitor.ProtocolBytesSent;
                foreach (var engine in downloaders)
                {
                    downTotal += engine.TotalDownloadRate;
                    upTotal   += engine.TotalUploadRate;

                    dataDown         += engine.Torrents[0].Monitor.DataBytesReceived + engine.Torrents[0].Monitor.ProtocolBytesReceived;
                    dataUp           += engine.Torrents[0].Monitor.DataBytesSent + engine.Torrents[0].Monitor.ProtocolBytesSent;
                    totalConnections += engine.ConnectionManager.OpenConnections;
                }
                Console.Clear();
                Console.WriteLine($"Speed Down:        {downTotal / 1024 / 1024}MB.");
                Console.WriteLine($"Speed Up:          {upTotal / 1024 / 1024}MB.");
                Console.WriteLine($"Data Down:          {dataDown / 1024 / 1024}MB.");
                Console.WriteLine($"Data Up:            {dataUp / 1024 / 1024}MB.");

                Console.WriteLine($"Total Connections: {totalConnections}");
                await Task.Delay(3000);
            }
        }