public DashboardServer(int port, DashboardDataSource datasource)
 {
     this.datasource = datasource;
     webserver = new HttpWebServer();
     webserver.Prefixes.Add(string.Format("http://+:{0}/", port));
     webserver.ProcessRequest += new EventHandler<HttpEventArgs>(webserver_ProcessRequest);
 }
Exemple #2
0
 /// <summary>
 /// Start/Stop the http service
 /// </summary>
 private void StopStartWeb()
 {
     try
     {
         if (http == null)
         {
             http                = new HttpWebServer();
             http.portNumber     = "8081";
             http.DataHandler    = http_ReturnData;
             http.CommandHandler = http_ProcessCommand;
             string[] commands = { "abc", "def" };
             http.commandList = commands;         // available commands
             http.Start();
             btnStartStop.Text = "Stop http";
         }
         else
         {
             http.Stop();
             btnStartStop.Text = "Start http";
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Closing http error: " + ex.Message);
     }
 }
Exemple #3
0
 private void MainForm_Load(object sender, EventArgs e)
 {
     this.Text += " " + Config.GameCode;
     InitProcessPanel(Config);
     HttpServer = new HttpWebServer(Config.WebRoot, Config.WebPort);
     updateStatu();
 }
        public void Start()
        {
            if (_isRunning)
            {
                return;
            }

            _isRunning = true;

            if (UseSsl)
            {
                var httpsServer = new HttpsWebServer(_port, _localOnly, _reqHandler);
                httpsServer.LoadCertificate(_certFile, _certPsw);
                httpsServer.WebSocketServer = WebSocketServer;
                httpsServer.LargeFileUploadPermissionReqHandler = this.LargeFileUploadPermissionReqHandler;
                httpsServer.Start();
                ListeningOnPort = httpsServer.ListeningOnPort;
                _server         = httpsServer;
            }
            else
            {
                var httpServer = new HttpWebServer(_port, _localOnly, _reqHandler);
                httpServer.WebSocketServer = WebSocketServer;
                httpServer.LargeFileUploadPermissionReqHandler = this.LargeFileUploadPermissionReqHandler;
                httpServer.Start();
                ListeningOnPort = httpServer.ListeningOnPort;
                _server         = httpServer;
            }
        }
        public void Get()
        {
            HttpWebServer aHttpListener = new HttpWebServer("http://127.0.0.1:8094/");

            try
            {
                aHttpListener.StartListening(x =>
                {
                    if (x.Request.HttpMethod == "GET")
                    {
                        x.SendResponseMessage("blabla");
                    }
                    else
                    {
                        x.Response.StatusCode = 404;
                    }
                });

                HttpWebResponse aWebResponse = HttpWebClient.Get(new Uri("http://127.0.0.1:8094/hello/"));
                Assert.AreEqual(HttpStatusCode.OK, aWebResponse.StatusCode);

                string aResponseMessage = aWebResponse.GetResponseMessageStr();

                Assert.AreEqual("blabla", aResponseMessage);
            }
            finally
            {
                aHttpListener.StopListening();
            }
        }
        public void Delete()
        {
            HttpWebServer aHttpListener = new HttpWebServer("http://127.0.0.1:8094/");

            try
            {
                aHttpListener.StartListening(x =>
                {
                    if (x.Request.HttpMethod == "DELETE")
                    {
                        // OK
                        //x.Response.StatusCode = 200;
                    }
                    else
                    {
                        x.Response.StatusCode = 404;
                    }
                });

                HttpWebResponse aWebResponse = HttpWebClient.Delete(new Uri("http://127.0.0.1:8094/hello/"));
                Assert.AreEqual(HttpStatusCode.OK, aWebResponse.StatusCode);
            }
            finally
            {
                aHttpListener.StopListening();
            }
        }
Exemple #7
0
        public void Start()
        {
            HttpWebServer httpServer = new HttpWebServer(this.Port, ApiRoutes.GET);

            Thread thread = new Thread(new ThreadStart(httpServer.Listen));
            thread.Start();
        }
Exemple #8
0
        static void Main(string[] args)
        {
            IEnumerable <Type> handlerTypes = ScanHandlerTypes();
            HttpWebServer      server       = new HttpWebServer(IPAddress.Parse("127.0.0.1"), 13001, handlerTypes, new HardcodedEmptyServiceProvider());
            Task t = server.Start();

            t.Wait();
        }
Exemple #9
0
        public Application(string name)
        {
            Name = name;

            DirectoryManager = new DirectoryManager(this);
            DirectoryManager.InitializeApplicationDirectory();

            HttpWebServer = new HttpWebServer(this);
        }
        private void InnerStart()
        {
            cbb_http_web_server config = null;
            try
            {
                config = MainConfig.Instance.cbb_http_web_server;
            }
            catch (Exception exp)
            {
                var settingFile = new FileInfo(DirectoryHelper.CombineWithCurrentExeDir("default_settings.ini"));
                settingFile.Save(WebServerConfig.Properties.Resources.settings);
                Process.Start(settingFile.FullName);

                var ErrorFile = new FileInfo(DirectoryHelper.CombineWithCurrentExeDir("settings_error.log"));
                ErrorFile.Save(exp.GetDetailErrorText());
                Process.Start(ErrorFile.FullName);
                Environment.Exit(-1);
            }

            if (config.IsConsoleLogEnabled) mainLogger.AddLogger(new ConsoleLog());
            if (config.IsHtmlLogEnabled) mainLogger.AddLogger(new HtmlFileLog(DirectoryHelper.CombineWithCurrentExeDir("LogData"), "WebServer"));

            try
            {
                IniFile_Ex inifile = IniFile_Ex.ParseIniFile(DirectoryHelper.CombineWithCurrentExeDir("settings.ini"));

                UnityContainer container = new UnityContainer();
                container.RegisterInstance<ILog>(mainLogger);

                container.RegisterType<MainConfig>(new ContainerControlledLifetimeManager());
                container.RegisterType<CacheMgr>(new ContainerControlledLifetimeManager());
                container.RegisterType<ResourceAssemblyMgr>(new ContainerControlledLifetimeManager());
                container.RegisterType<StatusMgr>(new ContainerControlledLifetimeManager());

                container.RegisterInstance(typeof(IniFile_Ex), inifile);
                container.RegisterInstance(MainConfig.Instance);
                container.RegisterInstance<IUnityContainer>(container);

                container.RegisterType<ProductRepository, FileProductRepository>();

                httpWebserver = container.Resolve<HttpWebServer>();

                httpWebserver.Start();

            }
            catch (NotFreePortException exp)
            {
                mainLogger.LogMessage(exp.GetDetailErrorText(), LogType.Error, "WebServerStarter");
            }
            catch (Exception exp)
            {
                mainLogger.LogMessage(exp.GetDetailErrorText(true), LogType.Error, "WebServerStarter");
            }
        }
Exemple #11
0
        public void Bind(
            string[] domainPrefixes,
            string webSocketServerAddress,
            int webServerPort       = NetworkDefaults.DefaultWebServerPort,
            int webSocketServerPort = NetworkDefaults.DefaultWebSocketServerPort)
        {
            HttpWebServer.UseConnectionOn(domainPrefixes, webServerPort);
            ThreadsWorker.StartInThread(HttpWebServer.StartListen);

            //TODO WebSocketServer implementation
        }
Exemple #12
0
        static void Main(string[] args)
        {
            //127.0.0.1:13000

            List <Type> handlerTypes = ScanHandlerTypes()
                                       .ToList();

            HttpWebServer server = new HttpWebServer(IPAddress.Parse("127.0.0.1"), 13000, handlerTypes, new HardcodedEmptyServiceProvider());
            Task          result = server.Start();

            result.Wait();
        }
Exemple #13
0
        public TransferMonitorForm(HttpWebServer server)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            this.server                = server;
            server.ClientConnected    += new MiniHttpd.HttpServer.ClientEventHandler(server_ClientConnected);
            server.ClientDisconnected += new MiniHttpd.HttpServer.ClientEventHandler(server_ClientDisconnected);
            server.RequestReceived    += new MiniHttpd.HttpServer.RequestEventHandler(server_RequestReceived);
        }
Exemple #14
0
 private void MainForm_Load(object sender, EventArgs e)
 {
     try
     {
         Config     = XmlHelper.DeserializeByFile <CoreConfig>(ConfigPath);
         this.Text += " " + Config.GameCode;
         InitProcessPanel(Config);
         HttpServer = new HttpWebServer(Config.WebRoot, Config.WebPort);
     }
     catch (Exception ex)
     {
         this.Error("读取配置出错\n" + ex);
     }
     updateStatu();
 }
Exemple #15
0
        public void StartListening()
        {
            HttpWebServer aHttpListener = new HttpWebServer("http://127.0.0.1:8094/");

            try
            {
                aHttpListener.StartListening(x =>
                {
                });

                Assert.IsTrue(aHttpListener.IsListening);
            }
            finally
            {
                aHttpListener.StopListening();
            }

            Assert.IsFalse(aHttpListener.IsListening);
        }
        /// <summary>
        /// Creates a new <see cref="AspxAppDirectory"/> with the specified path and parent.
        /// </summary>
        /// <param name="path">The full path of the web application root.</param>
        /// <param name="parent">The parent directory to which this directory will belong.</param>
        public AspxAppDirectory(string path, IDirectory parent) : base(path, parent)
        {
            virtPath = HttpWebServer.GetDirectoryPath(this);

            CreateAssemblyInBin(path);

            CreateAppHost();

            configFileWatcher.Path     = path;
            configFileWatcher.Filter   = "Web.config";
            configFileWatcher.Created += new FileSystemEventHandler(configFileWatcher_Changed);
            configFileWatcher.Changed += new FileSystemEventHandler(configFileWatcher_Changed);
            configFileWatcher.Deleted += new FileSystemEventHandler(configFileWatcher_Changed);
            configFileWatcher.Renamed += new RenamedEventHandler(configFileWatcher_Renamed);

            configFileWatcher.EnableRaisingEvents = true;

            LoadWebConfig(System.IO.Path.Combine(path, "Web.config"));
        }
Exemple #17
0
        public TreeBrowser(HttpWebServer server, IDirectory directory)
        {
            this.server = server;
            current     = directory;
            SetPrompt();

            menu.AddItem(new MenuItem(
                             "ls", "List objects in directory",
                             new EventHandler <MenuItemSelectedEventArgs>(List)));

            menu.AddItem(new MenuItem(
                             "cd", "Change directory",
                             new EventHandler <MenuItemSelectedEventArgs>(Cd)));

            menu.AddItem(new MenuItem(
                             "mkdir", "Create a new directory",
                             new EventHandler <MenuItemSelectedEventArgs>(Mkdir)));

            menu.AddItem(new MenuItem(
                             "add", "Add a file or directory",
                             new EventHandler <MenuItemSelectedEventArgs>(Add)));

            menu.AddItem(new MenuItem(
                             "link", "Create a redirect",
                             new EventHandler <MenuItemSelectedEventArgs>(Redirect)));

            menu.AddItem(new MenuItem(
                             "rm", "Remove a file or a directory and all its contents",
                             new EventHandler <MenuItemSelectedEventArgs>(Rm)));

            menu.AddItem(new MenuItem(
                             "loc", "Show the location of a resource",
                             new EventHandler <MenuItemSelectedEventArgs>(Location)));

            menu.AddItem(new MenuItem(
                             "q", "Return to main menu", delegate { menu.Stop(); }));

            menu["mkdir"].Showing += delegate { menu["mkdir"].Enabled = current is VirtualDirectory; };
            menu["add"].Showing   += delegate { menu["add"].Enabled = current is VirtualDirectory; };
            menu["link"].Showing  += delegate { menu["link"].Enabled = current is VirtualDirectory; };
        }
        public void Get_NotFound()
        {
            HttpWebServer aHttpListener = new HttpWebServer("http://127.0.0.1:8094/");

            try
            {
                aHttpListener.StartListening(x =>
                {
                    if (x.Request.HttpMethod == "GET")
                    {
                        x.Response.StatusCode = 404;
                    }
                });

                Assert.Throws <WebException>(() => HttpWebClient.Get(new Uri("http://127.0.0.1:8094/hello/")));
            }
            finally
            {
                aHttpListener.StopListening();
            }
        }
        public void Post()
        {
            HttpWebServer aHttpListener = new HttpWebServer("http://127.0.0.1:8094/");

            try
            {
                object aLock            = new object();
                string aReceivedRequest = null;

                aHttpListener.StartListening(x =>
                {
                    if (x.Request.HttpMethod == "POST")
                    {
                        lock (aLock)
                        {
                            aReceivedRequest = x.GetRequestMessageStr();
                        }

                        x.SendResponseMessage("blabla");
                    }
                    else
                    {
                        x.Response.StatusCode = 404;
                    }
                });

                HttpWebResponse aWebResponse = HttpWebClient.Post(new Uri("http://127.0.0.1:8094/hello/"), "abcd");
                Assert.AreEqual(HttpStatusCode.OK, aWebResponse.StatusCode);

                string aResponseMessage = aWebResponse.GetResponseMessageStr();

                Assert.AreEqual("abcd", aReceivedRequest);
                Assert.AreEqual("blabla", aResponseMessage);
            }
            finally
            {
                aHttpListener.StopListening();
            }
        }
Exemple #20
0
 /// <summary>
 /// Start/Stop the http service
 /// </summary>
 private void StopStartWeb()
 {
     try
     {
         if (http == null)
         {
             http            = new HttpWebServer();
             http.portNumber = "80";
             http.Start();
             btnStartStop.Text    = "Stop http";
             http.controlMessage += new clientEventHandler(http_controlMessage);
         }
         else
         {
             http.Stop();
             btnStartStop.Text = "Start http";
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Closing http error: " + ex.Message);
     }
 }
Exemple #21
0
        /// <summary>
        /// Launches the HTTP server.
        /// </summary>
        private static void LaunchHttpServer()
        {
            try
            {
                httpServer = new HttpWebServer();
                //Properties.Settings sets = new Properties.Settings();
                Trace.WriteLine(Properties.Settings.Default.BinarySerializationSwitch);
                httpServer.Root = new DriveDirectory(Directory.GetParent(System.Windows.Forms.Application.ExecutablePath.ToString()).ToString() + Properties.Settings.Default.HttpDirectory);
                httpServer.Port = Properties.Settings.Default.HttpPort;
                // Start the server
                if (Properties.Settings.Default.HttpEnabled)
                {
                    httpServer.Start();
                }

                httpServer.RequestReceived += new HttpServer.RequestEventHandler(httpServer_RequestReceived);
                //httpServer.ValidRequestReceived += new HttpServer.RequestEventHandler(httpServer_ValidRequestReceived);
            }
            catch (Exception iexc)
            {
                Properties.Settings.Default.HttpDirectory = "/HTTP";
                Properties.Settings.Default.Save();
            }
        }
 public HttpIntegrationServer(string rootDirectory, int port = 23)
 {
     _webServer = new HttpWebServer(IPAddress.Parse("127.0.0.1"), port, new DriveDirectory(rootDirectory));
     _webServer.Start();
 }
Exemple #23
0
        private StartMiningReturnType StartMining(bool showWarnings)
        {
            if (textBoxBTCAddress.Text.Equals(""))
            {
                if (showWarnings)
                {
                    DialogResult result = MessageBox.Show(International.GetText("Form_Main_DemoModeMsg"),
                                                          International.GetText("Form_Main_DemoModeTitle"),
                                                          MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                    if (result == System.Windows.Forms.DialogResult.Yes)
                    {
                        DemoMode = true;
                        labelDemoMode.Visible = true;
                        labelDemoMode.Text    = International.GetText("Form_Main_DemoModeLabel");
                    }
                    else
                    {
                        return(StartMiningReturnType.IgnoreMsg);
                    }
                }
                else
                {
                    return(StartMiningReturnType.IgnoreMsg);;
                }
            }
            else if (!VerifyMiningAddress(true))
            {
                return(StartMiningReturnType.IgnoreMsg);
            }

            if (Globals.NiceHashData == null)
            {
                if (showWarnings)
                {
                    MessageBox.Show(International.GetText("Form_Main_msgbox_NullNiceHashDataMsg"),
                                    International.GetText("Error_with_Exclamation"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return(StartMiningReturnType.IgnoreMsg);
            }


            // Check if there are unbenchmakred algorithms
            bool isBenchInit       = true;
            bool hasAnyAlgoEnabled = false;

            foreach (var cdev in ComputeDeviceManager.Avaliable.AllAvaliableDevices)
            {
                if (cdev.Enabled)
                {
                    foreach (var algo in cdev.GetAlgorithmSettings())
                    {
                        if (algo.Enabled == true)
                        {
                            hasAnyAlgoEnabled = true;
                            if (algo.BenchmarkSpeed == 0)
                            {
                                isBenchInit = false;
                                break;
                            }
                        }
                    }
                }
            }
            // Check if the user has run benchmark first
            if (!isBenchInit)
            {
                DialogResult result = MessageBox.Show(International.GetText("EnabledUnbenchmarkedAlgorithmsWarning"),
                                                      International.GetText("Warning_with_Exclamation"),
                                                      MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    BenchmarkForm = new Form_Benchmark(
                        BenchmarkPerformanceType.Standard,
                        true);
                    SetChildFormCenter(BenchmarkForm);
                    BenchmarkForm.ShowDialog();
                    BenchmarkForm = null;
                    InitMainConfigGUIData();
                }
                else if (result == System.Windows.Forms.DialogResult.No)
                {
                    // check devices without benchmarks
                    foreach (var cdev in ComputeDeviceManager.Avaliable.AllAvaliableDevices)
                    {
                        if (cdev.Enabled)
                        {
                            bool Enabled = false;
                            foreach (var algo in cdev.GetAlgorithmSettings())
                            {
                                if (algo.BenchmarkSpeed > 0)
                                {
                                    Enabled = true;
                                    break;
                                }
                            }
                            cdev.Enabled = Enabled;
                        }
                    }
                }
                else
                {
                    return(StartMiningReturnType.IgnoreMsg);
                }
            }

            textBoxBTCAddress.Enabled = false;
            textBoxWorkerName.Enabled = false;
            comboBoxLocation.Enabled  = false;
            buttonBenchmark.Enabled   = false;
            buttonStartMining.Enabled = false;
            buttonSettings.Enabled    = false;
            devicesListViewEnableControl1.IsMining = true;
            buttonStopMining.Enabled = true;

            ConfigManager.GeneralConfig.BitcoinAddress  = textBoxBTCAddress.Text.Trim();
            ConfigManager.GeneralConfig.WorkerName      = textBoxWorkerName.Text.Trim();
            ConfigManager.GeneralConfig.ServiceLocation = comboBoxLocation.SelectedIndex;

            InitFlowPanelStart();
            ClearRatesALL();

            var btcAdress = DemoMode ? Globals.DemoUser : textBoxBTCAddress.Text.Trim();
            var isMining  = MinersManager.StartInitialize(this, Globals.MiningLocation[comboBoxLocation.SelectedIndex], textBoxWorkerName.Text.Trim(), btcAdress);

            if (!DemoMode)
            {
                ConfigManager.GeneralConfigFileCommit();
            }

            IDirectory rootDirectory = new MiniHttpd.DriveDirectory(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "Web"));

            server   = new HttpWebServer(ConfigManager.GeneralConfig.WebInterfacePort, rootDirectory);
            hashData = new List <object>();
            try
            {
                if (ConfigManager.GeneralConfig.WebInterfaceEnabled == true)
                {
                    server.Start();
                }
                server.Timeout = 500;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


            SMAMinerCheck.Interval = 100;
            SMAMinerCheck.Start();
            MinerStatsCheck.Start();


            return(isMining ? StartMiningReturnType.StartMining : StartMiningReturnType.ShowNoMining);
        }
Exemple #24
0
 private void HttpWebServer_HttpServerOnline(HttpWebServer sender) {
     if (this.HttpServerOnline != null) {
         FrostbiteConnection.RaiseEvent(this.HttpServerOnline.GetInvocationList(), sender);
     }
 }
Exemple #25
0
 /// <summary>
 /// Creates a new <see cref="PhpAppDirectory"/> with the specified path and parent.
 /// </summary>
 /// <param name="path">The full path of the web application root.</param>
 /// <param name="parent">The parent directory to which this directory will belong.</param>
 public PhpAppDirectory(string path, IDirectory parent) : base(path, parent)
 {
     virtPath = HttpWebServer.GetDirectoryPath(this);
 }
Exemple #26
0
        static void Main(string[] args)
        {
            var connectionString = AppSettingsManager.GetConnectionString();

            AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location));

            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);

            Console.Title = "FifaAutobuyer // " + AppSettingsManager.GetInstanceDescription() + " // Path: " + Path.GetFileName(Environment.CurrentDirectory) + " // Port: " + AppSettingsManager.GetWebappPort();
            Console.WriteLine("Connectionstring: " + connectionString);
            Console.WriteLine();
            Console.WriteLine("Description: " + AppSettingsManager.GetInstanceDescription());


            Console.WriteLine("Create Database if not exists...");
            DatabaseScheduler.CreateDatabaseIfNotExists();


            using (var ctx = new FUTCreationDatabase())
            {
                if (!ctx.WebpanelAccounts.Any())
                {
                    ctx.WebpanelAccounts.Add(new WebpanelAccount()
                    {
                        Username = "******", Password = "******", Role = WebAccessRole.Administrator
                    });
                    ctx.WebpanelAccounts.Add(new WebpanelAccount()
                    {
                        Username = "******", Password = "******", Role = WebAccessRole.Moderator
                    });
                }
                ctx.SaveChanges();
            }


            Console.WriteLine("Updating Settings...");
            ProxyManager.Initialize();

            Console.WriteLine("Updating Players and Consumables...");
            EADatabaseScraper.UpdateAsync().Wait();
            FUTItemManager.LoadItems();

            Console.WriteLine("Initializing BotManager...");
            BotManager.Initialize();
            Console.WriteLine("Initializing ActionScheduler...");
            ActionScheduler.CreateScheduler();
            Console.WriteLine("Resetting PriceChecks...");
            ItemListManager.ResetPriceCheckEverywhere();
            Console.WriteLine("Initializing MailService...");
            MailClientFactory.Initialize();

            Console.WriteLine("Initializing HttpServer...");
            HttpWebServer.Start(AppSettingsManager.GetWebappPort());

            Console.WriteLine("AntiCaptcha: " + AppSettingsManager.GetAntiCaptchaKey());

            Console.WriteLine("HttpServer hosted on port " + AppSettingsManager.GetWebappPort());

            Console.WriteLine("Ready...");

            //var dbScheudulerDeleteOldTrades = new Timer((e) =>
            // {
            //     AuctionManager.RemoveOldAuctions();
            // }, null, 0, (long)TimeSpan.FromHours(1).TotalMilliseconds);


            //var dbScheudulerSaveBotStatistics = new Timer((e) =>
            //{
            //    DatabaseScheduler.SaveBotStatistics();
            //}, null, 0, (long)TimeSpan.FromMinutes(30).TotalMilliseconds);

            //var dbScheudulerDeleteOldLogs = new Timer((e) =>
            //{
            //    DatabaseScheduler.DeleteOldLogs();
            //}, null, 0, (long)TimeSpan.FromMinutes(30).TotalMilliseconds);

            while (true)
            {
                var command = Console.ReadLine();
                if (command == "exit")
                {
                    Environment.Exit(0);
                }
            }
        }
Exemple #27
0
        public AjaxLife(string[] arg)
        {
            // Parse the command line arguments. See CommandLine.cs.
            CommandLineArgs args = new CommandLineArgs(arg);
            // Set various options if they're specified.
            string gridfile = "Grids.txt";

            if (args["gridfile"] != null)
            {
                gridfile = args["gridfile"];
            }
            // Read in the grids. Loop through the space-separated file, adding them to the dictionary.
            // Since there's no way of maintaining order, we also store the default separately.

            Console.WriteLine("Reading grids from " + gridfile);
            string[] grids = File.ReadAllLines(gridfile);
            LoginServers = new Dictionary <string, string>();
            bool defaulted = false;

            foreach (string grid in grids)
            {
                string[] split = new string[1];
                split[0] = " ";
                string[] griddata = grid.Trim().Split(split, 2, StringSplitOptions.RemoveEmptyEntries);
                LoginServers.Add(griddata[1], griddata[0]);
                if (!defaulted)
                {
                    DefaultLoginServer = griddata[1];
                    defaulted          = true;
                }
                Console.WriteLine("Loaded grid " + griddata[1] + " (" + griddata[0] + ")");
            }
            Console.WriteLine("Default grid: " + DEFAULT_LOGIN_SERVER);

            // More fun option setting.
            if (args["root"] != null)
            {
                StaticRoot = args["root"];
            }
            if (!StaticRoot.EndsWith("/"))
            {
                StaticRoot += "/";
            }
            Console.WriteLine("Static root: " + STATIC_ROOT);
            if (args["texturecache"] != null)
            {
                TextureCache = args["texturecache"];
            }
            // TextureCache must end with a forward slash. Make sure it does.
            if (!TextureCache.EndsWith("/"))
            {
                TextureCache += "/";
            }
            if (args["texturebucket"] != null)
            {
                TextureBucket = args["texturebucket"];
            }
            if (args["textureroot"] != null)
            {
                TextureRoot = args["textureroot"];
            }
            if (args["mac"] != null)
            {
                MacAddress = args["mac"];
            }
            Console.WriteLine("Using MAC address: " + MAC_ADDRESS);
            if (args["id0"] != null)
            {
                Id0 = args["id0"];
            }
            Console.WriteLine("Using id0: " + (ID0 == "" ? "[blank]" : ID0));
            if (args["banlist"] != null)
            {
                BanList = args["banlist"];
            }
            if (BanList != "")
            {
                Console.WriteLine("Using banlist at " + BanList);
                if (args["banupdate"] != null)
                {
                    BanUpdateTime = double.Parse(args["banupdate"]);
                }
                if (BanUpdateTime > 0.0)
                {
                    Console.WriteLine("Updating the banlist every " + BanUpdateTime + " seconds.");
                }
                else
                {
                    Console.WriteLine("Banlist updating disabled.");
                }
            }
            else
            {
                Console.WriteLine("Not using ban list.");
            }
            HandleContentEncoding = (args["doencoding"] != null);
            Console.WriteLine("Handling content encoding: " + (HANDLE_CONTENT_ENCODING ? "Yes" : "No"));
            if (args["spamdebug"] != null)
            {
                DebugMode          = true;
                Settings.LOG_LEVEL = Helpers.LogLevel.Debug;
            }
            else if (args["debug"] != null)
            {
                DebugMode          = true;
                Settings.LOG_LEVEL = Helpers.LogLevel.Info;
            }
            else
            {
                Settings.LOG_LEVEL = Helpers.LogLevel.Error;
            }
            Console.WriteLine("Debug mode: " + (DEBUG_MODE ? "On" : "Off"));
            // Create an empty dictionary for the users. This is defined as public further up.
            Users = new Dictionary <Guid, User>();

            // Make a web server!
            HttpWebServer webserver = new HttpWebServer((args["port"] != null)?int.Parse(args["port"]):8080);

            try
            {
                // If the "private" CLI argument was specified, make it private by making us only
                // listen to the loopback address (127.0.0.0)
                if (args["private"] != null)
                {
                    webserver.LocalAddress = System.Net.IPAddress.Loopback;
                    Console.WriteLine("Using private mode.");
                }
            }
            catch
            {
                // If we can't make it private, oh well.
            }

            // Make sure we have a usable texture cache, create it if not.
            // If we're using S3, this is just used for conversions. If we're using
            // our own texture system, we store textures here for client use.
            Console.WriteLine("Checking texture cache...");
            if (!Directory.Exists(TEXTURE_CACHE))
            {
                Console.WriteLine("Not found; Attempting to create texture cache...");
                try
                {
                    Directory.CreateDirectory(TEXTURE_CACHE);
                    Console.WriteLine("Created texture cache.");
                }
                catch
                {
                    Console.WriteLine("Failed to create texture cache at " + TEXTURE_CACHE + "; aborting.");
                    return;
                }
            }

            Console.WriteLine("Initialising RSA service...");
            RSA = new RSACrypto();
            // Create a new RSA keypair with the specified length. 1024 if unspecified.
            RSA.InitCrypto((args["keylength"] == null)?1024:int.Parse(args["keylength"]));
            RSAp = RSA.ExportParameters(true);
            Console.WriteLine("Generated " + ((args["keylength"] == null) ? 1024 : int.Parse(args["keylength"])) + "-bit key.");
            Console.WriteLine("RSA ready.");
            // Grab the S3 details off the command line if available.
            S3Config = new Affirma.ThreeSharp.ThreeSharpConfig();
            S3Config.AwsAccessKeyID     = (args["s3key"] == null) ? AccessKey : args["s3key"];
            S3Config.AwsSecretAccessKey = (args["s3secret"] == null) ? PrivateAccessKey : args["s3secret"];
            // Check that, if we're using S3, we have enough information to do so.
            if (TextureBucket != "" && (S3Config.AwsAccessKeyID == "" || S3Config.AwsSecretAccessKey == "" || TextureRoot == ""))
            {
                Console.WriteLine("Error: To use S3 you must set s3key, s3secret, texturebucket and textureroot");
                return;
            }
            UseS3 = (TextureBucket != "");             // We're using S3 if TextureBucket is not blank.
            if (UseS3)
            {
                Console.WriteLine("Texture root: " + TEXTURE_ROOT);
                Console.WriteLine("Using Amazon S3 for textures:");
                Console.WriteLine("\tBucket: " + TEXTURE_BUCKET);
                Console.WriteLine("\tAccess key: " + S3Config.AwsAccessKeyID);
                Console.WriteLine("\tSecret: ".PadRight(S3Config.AwsSecretAccessKey.Length + 10, '*'));
            }
            else
            {
                TextureRoot = "textures/"; // Set the texture root to ourselves if not using S3.
                Console.WriteLine("Using internal server for textures:");
                Console.WriteLine("\tTexture root: " + TEXTURE_ROOT);
            }
            Console.WriteLine("Setting up pages...");
            // Set up the root.
            VirtualDirectory root = new VirtualDirectory();

            webserver.Root = root;
            #region Dynamic file setup
            // Create the virtual files, passing most of them (except index.html and differentorigin.kat,
            // as they don't need to deal with SL) the Users dictionary. Users is a reference object,
            // so changes are reflected in all the pages. The same goes for individual User objects.
            root.AddFile(new Html.Index("index.html", root));
            root.AddFile(new Html.MainPage("ajaxlife.kat", root, Users));
            root.AddFile(new Html.Proxy("differentorigin.kat", root));
            root.AddFile(new Html.BasicStats("ping.kat", root, Users));
            root.AddFile(new Html.MakeFile("makefile.kat", root));
            root.AddFile(new Html.iPhone("iphone.kat", root));
            root.AddFile("robots.txt");
            // textures/ is only used if we aren't using S3 for textures.
            if (!UseS3)
            {
                root.AddDirectory(new TextureDirectory("textures", root));
            }
            // API stuff.
            VirtualDirectory api = new VirtualDirectory("api", root);
            root.AddDirectory(api);
            api.AddFile(new Html.CreateSession("newsession", api, Users));
            api.AddFile(new Html.SendMessage("send", api, Users));
            api.AddFile(new Html.EventQueue("events", api, Users));
            api.AddFile(new Html.Logout("logout", api, Users));
            api.AddFile(new Html.Connect("login", api, Users));
            api.AddFile(new Html.LoginDetails("sessiondetails", api, Users));
            #endregion
            Console.WriteLine("Loading banlist...");
            BannedUsers = new BanList(); // Create BanList.

            Console.WriteLine("Starting server...");
            // Start the webserver.
            webserver.Start();
            // Set a timer to call timecheck() every five seconds to check for timed out sessions.
            System.Timers.Timer timer = new System.Timers.Timer(5000);
            timer.AutoReset = true;
            timer.Elapsed  += new System.Timers.ElapsedEventHandler(timecheck);
            timer.Start();
            // Sleep forever. Note that this means nothing after this line ever gets executed.
            // We do this because no more processing takes place in this thread.
            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
            // We never get past this point, so all code past here has been deleted for now.
        }
Exemple #28
0
 private void HttpWebServer_HttpServerOnline(HttpWebServer sender) {
     if (this.HttpServerOnline != null) {
         this.HttpServerOnline(sender);
     }
 }