Example #1
0
        private async void Btn_start_httpserver_ClickAsync(object sender, EventArgs e)
        {
            string input = Frm.txt_httpserver_port.Text.Trim();

            if (string.IsNullOrEmpty(input) || !int.TryParse(input, out int port))
            {
                Toast.Warn("端口号格式不正确");
                return;
            }
            if (port < 0 || port <= 1024)
            {
                Toast.Warn("端口号应大于0且不小于1024");
                return;
            }
            try
            {
                if (HttpServer == null || HttpServer.SocketChannel.Open == false)
                {
                    HttpServer = new HttpServer.HttpServer()
                    {
                        Port = port
                    };
                    HttpServer.SocketChannel = await HttpServer.StartAsync();

                    HttpServerLog("HTTP服务器启动成功");
                }
            }
            catch (Exception ex)
            {
                HttpServerLog("HTTP服务器启动失败 失败原因: {0}", ex.Message);
            }
        }
Example #2
0
        public async Task Test1(int maxServer, int maxRequests)
        {
            var server       = new HttpServer.HttpServer(1234, maxServer);
            var serverThread = new Thread(async() => await server.StartAsync());

            serverThread.Start();
            var client = new HttpClient()
            {
                BaseAddress = new Uri("http://localhost:1234/")
            };

            var requests = Enumerable.Repeat <Func <Task <HttpResponseMessage> > >(() => client.GetAsync("/"), maxRequests).Select(x => x.Invoke()).ToList();
            await Task.WhenAll(requests);

            Dictionary <int, List <int> > requestsByThread = new Dictionary <int, List <int> >();

            foreach (var r in requests.Select(x => x.Result.Content.ReadAsStringAsync()))
            {
                var str   = await r;;
                var match = _regex.Match(str);
                Assert.True(match.Success);
                ParseAndAddToDict(match, requestsByThread);
            }

            // проверка счетчика
            foreach (var thread in requestsByThread.Keys)
            {
                var max      = requestsByThread[thread].Max();
                var actual   = requestsByThread[thread].OrderBy(x => x);
                var expected = Enumerable.Range(1, max);
                Assert.Equal(expected, actual);
            }
        }
Example #3
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // Start the in-app HTTP server
            httpServer = HttpServer.HttpServer.Instance;

            // Copy the PDF viewer contents file to the application local data folder.
            await PrepareContentsAsync();

            // Allow "window.external.notify()" in this webview.
            MyWebView.ScriptNotify += MyWebView_ScriptNotify;
            MyWebView.AllowedScriptNotifyUris = WebView.AnyScriptNotifyUri;

            string parameter = e.Parameter.ToString();
            string path = "";
            if (parameter != null)
            {
                path = "/" + parameter.Replace("\\", "/");
            }

            var port = httpServer.Port;

            // Open the pdf viewer in In-app HTTP server. (Set the PDF file name to "file" parameter.)
            if (path != "")
            {
                MyWebView.Navigate(new Uri("http://localhost:" + port + "/" + LOCAL_CONTENTS_FOLDER + "/viewer.html?file=" + path));
            }
            else
            {
                MyWebView.Navigate(new Uri("http://localhost:" + port + "/" + LOCAL_CONTENTS_FOLDER + "/viewer.html"));
            }
        }
Example #4
0
        public void Start(IPEndPoint ipEndPoint)
        {
            httpServer = new HttpServer.HttpServer();
            httpServer.Start(ipEndPoint.Address, ipEndPoint.Port);

            httpModules.ForEach(module => { module.Start(); httpServer.Add(module); });

            Console.WriteLine("HTTP server STARTED listening @ " + ipEndPoint);
        }
Example #5
0
        public void Start()
        {
            Console.WriteLine("Manager: start listening for connections on " + Config.Hostname + " port " + Config.Port);

            _server = new HttpServer.HttpServer();
            _server.Add(new ManagerRequestHandler(this));
            _server.Start(Dns.GetHostEntry(Config.Hostname).AddressList[0], Config.Port);

            Thread.Sleep(10);
        }
Example #6
0
        public void Start()
        {
            _server = new HttpServer.HttpServer();
            _server.Add(new WorkerRequestHandler(this));
            _server.Start(Dns.GetHostEntry(Config.Hostname).AddressList[0], Config.Port);

            _keepalive = new KeepaliveThread(this);
            _keepalive.Start();

            Thread.Sleep(10);
        }
Example #7
0
        static void Main(string[] args)
        {
            HttpServer.HttpServer test = new HttpServer.HttpServer(80, IPAddress.Any);
            HttpServer.HttpServer.SITE_PATH        = @"C:\Users\xwh16\Desktop\WebSever\HttpServer\Resources";
            HttpServer.HttpServer.PROTOCOL_VERSION = "HTTP/1.1";

            System.Console.WriteLine(
                "Web Server 工作在 本地: {0}端口",
                HttpServer.HttpServer.SERVER_PORT);

            test.Start();
        }
Example #8
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var httpServer = new HttpServer.HttpServer(64000, new HttpServer.NetCore.Platform.SocketListener(64000));

            httpServer.Start();

            while (Console.ReadKey().Key != ConsoleKey.Escape)
            {
            }

            httpServer.Stop();
            httpServer.Dispose();
        }
Example #9
0
        public static void StartServers()
        {
            if (_running)
                return;

            _server = new HttpServer.HttpServer();
            _server.Add(new FileReaderModule());
            _server.Start(IPAddress.Any, 9100);

            _selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://localhost:9100");
            _selenium.Start();
            _selenium.SetContext("NET Selenium DSL Tests");

            _running = true;
        }
Example #10
0
 private void OnConnect(object sender, EventArgs e)
 {
     mConnectTool.Checked = !mConnectTool.Checked;
     if (mConnectTool.Checked)
     {
         mServer = new HttpServer.HttpServer();
         mServer.Add(mModulePlugIns);
         mServer.Start(IPAddress.Any, int.Parse(mPort.Text));
         mLogger.WriteLine("Server online on port {0}", mPort.Text);
     }
     else
     {
         mServer.Stop();
         mServer = null;
     }
 }
Example #11
0
        public void StartTutorial()
        {
            Console.WriteLine("Welcome to Tutorial #3 - Building a own HTTP Module");
            Console.WriteLine("");
            Console.WriteLine("A http module do not handle a spefic url, instead all modules");
            Console.WriteLine("are asked by the server until one tells it that it have handled the url.");
            Console.WriteLine("");
            Console.WriteLine("In this way you can even let multiple modules handle the same, but handle");
            Console.WriteLine("different content types.");
            Console.WriteLine("");
            Console.WriteLine("Browse to http://localhost:8081/anything/you/want");

            _server = new HttpServer.HttpServer();

            // MyModule does currently handle all urls with the same message.
            _server.Add(new MyModule());

            _server.Start(IPAddress.Any, 8081);
        }
        public void StartTutorial()
        {
            Console.WriteLine("Welcome to Tutorial #3 - Building a own HTTP Module");
            Console.WriteLine("");
            Console.WriteLine("A http module do not handle a spefic url, instead all modules");
            Console.WriteLine("are asked by the server until one tells it that it have handled the url.");
            Console.WriteLine("");
            Console.WriteLine("In this way you can even let multiple modules handle the same, but handle");
            Console.WriteLine("different content types.");
            Console.WriteLine("");
            Console.WriteLine("Browse to http://localhost:8081/anything/you/want");

            _server = new HttpServer.HttpServer();

            // MyModule does currently handle all urls with the same message.
            _server.Add(new MyModule());

            _server.Start(IPAddress.Any, 8081);
        }
Example #13
0
        private void OnConnect(object sender, EventArgs e)
        {
            mConnectTool.Checked = !mConnectTool.Checked;
            if (mConnectTool.Checked)
            {
                Server = new HttpServer.HttpServer();
                Server.Add(ModulePugIns);
                Server.Start(IPAddress.Any, int.Parse(mPort.Text));
                Logger.WriteLine("Server online on port {0}", mPort.Text);

                mConnectTool.Image = Properties.Resources.connect;
            }
            else
            {
                Server.Stop();
                Server = null;

                mConnectTool.Image = Properties.Resources.disconnect;
            }
        }
Example #14
0
        static void Main()
        {
            var routes = new List <Route>()
            {
                new Route()
                {
                    Name     = "Hello Handler",
                    UrlRegex = @"^/hello$",
                    Method   = RequestMethod.GET,
                    Callable = (HttpRequest request) =>
                    {
                        return(new HttpResponse()
                        {
                            ContentAsUTF8 = "<h3>Hello from HttpServer :)</h3>",
                            StatusCode = ResponceStatusCode.OK
                        });
                    }
                }
            };

            HttpServer.HttpServer httpServer = new HttpServer.HttpServer(8081, routes);
            httpServer.Listen();
        }
Example #15
0
        /// <summary>
        /// Sets up the webserver and starts it
        /// </summary>
        /// <param name="options">A set of options</param>
        public Server(IDictionary <string, string> options)
        {
            int               port;
            string            portstring;
            IEnumerable <int> ports = null;

            options.TryGetValue(OPTION_PORT, out portstring);
            if (!string.IsNullOrEmpty(portstring))
            {
                ports =
                    from n in portstring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    where int.TryParse(n, out port)
                    select int.Parse(n);
            }

            if (ports == null || !ports.Any())
            {
                ports = new int[] { DEFAULT_OPTION_PORT }
            }
            ;

            string interfacestring;

            System.Net.IPAddress listenInterface;
            options.TryGetValue(OPTION_INTERFACE, out interfacestring);

            if (string.IsNullOrWhiteSpace(interfacestring))
            {
                interfacestring = Program.DataConnection.ApplicationSettings.ServerListenInterface;
            }
            if (string.IsNullOrWhiteSpace(interfacestring))
            {
                interfacestring = DEFAULT_OPTION_INTERFACE;
            }

            if (interfacestring.Trim() == "*" || interfacestring.Trim().Equals("any", StringComparison.InvariantCultureIgnoreCase))
            {
                listenInterface = System.Net.IPAddress.Any;
            }
            else if (interfacestring.Trim() == "loopback")
            {
                listenInterface = System.Net.IPAddress.Loopback;
            }
            else
            {
                listenInterface = System.Net.IPAddress.Parse(interfacestring);
            }

            string certificateFile;

            options.TryGetValue(OPTION_SSLCERTIFICATEFILE, out certificateFile);

            string certificateFilePassword;

            options.TryGetValue(OPTION_SSLCERTIFICATEFILEPASSWORD, out certificateFilePassword);

            X509Certificate2 cert      = null;
            bool             certValid = false;

            if (certificateFile == null)
            {
                try
                {
                    cert = Program.DataConnection.ApplicationSettings.ServerSSLCertificate;

                    if (cert != null)
                    {
                        certValid = cert.HasPrivateKey;
                    }
                }
                catch (Exception ex)
                {
                    Library.Logging.Log.WriteMessage("Unable to create SSL certificate using data from database. Starting without SSL.", Duplicati.Library.Logging.LogMessageType.Warning, ex);
                }
            }
            else if (certificateFile.Length == 0)
            {
                Program.DataConnection.ApplicationSettings.ServerSSLCertificate = null;
            }
            else
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(certificateFilePassword))
                    {
                        cert = new X509Certificate2(certificateFile, "", X509KeyStorageFlags.Exportable);
                    }
                    else
                    {
                        cert = new X509Certificate2(certificateFile, certificateFilePassword, X509KeyStorageFlags.Exportable);
                    }

                    certValid = cert.HasPrivateKey;
                }
                catch (Exception ex)
                {
                    throw new Exception("Unable to create SSL certificate using provided parameters. Exception detail: " + ex.Message);
                }
            }

            // If we are in hosted mode with no specified port,
            // then try different ports
            foreach (var p in ports)
            {
                try
                {
                    // Due to the way the server is initialized,
                    // we cannot try to start it again on another port,
                    // so we create a new server for each attempt

                    var server = CreateServer(options);

                    if (!certValid)
                    {
                        server.Start(listenInterface, p);
                    }
                    else
                    {
                        server.Start(listenInterface, p, cert, System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12, null, false);
                    }

                    m_server            = server;
                    m_server.ServerName = "Duplicati v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                    this.Port           = p;

                    if (interfacestring != Program.DataConnection.ApplicationSettings.ServerListenInterface)
                    {
                        Program.DataConnection.ApplicationSettings.ServerListenInterface = interfacestring;
                    }

                    if (certValid && !cert.Equals(Program.DataConnection.ApplicationSettings.ServerSSLCertificate))
                    {
                        Program.DataConnection.ApplicationSettings.ServerSSLCertificate = cert;
                    }

                    return;
                }
                catch (System.Net.Sockets.SocketException)
                {
                }
            }

            throw new Exception("Unable to open a socket for listening, tried ports: " + string.Join(",", from n in ports select n.ToString()));
        }
Example #16
0
        /// <summary>
        /// Sets up the webserver and starts it
        /// </summary>
        /// <param name="options">A set of options</param>
        public Server(IDictionary<string, string> options)
        {
            int port;
            string portstring;
            IEnumerable<int> ports = null;
            options.TryGetValue(OPTION_PORT, out portstring);
            if (!string.IsNullOrEmpty(portstring))
                ports = 
                    from n in portstring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                where int.TryParse(n, out port)
                                select int.Parse(n);

            if (ports == null || !ports.Any())
                ports = new int[] { DEFAULT_OPTION_PORT };

            string interfacestring;
            System.Net.IPAddress listenInterface;
            options.TryGetValue(OPTION_INTERFACE, out interfacestring);

            if (string.IsNullOrWhiteSpace(interfacestring))
                interfacestring = Program.DataConnection.ApplicationSettings.ServerListenInterface;
            if (string.IsNullOrWhiteSpace(interfacestring))
                interfacestring = DEFAULT_OPTION_INTERFACE;

            if (interfacestring.Trim() == "*" || interfacestring.Trim().Equals("any", StringComparison.InvariantCultureIgnoreCase))
                listenInterface = System.Net.IPAddress.Any;
            else if (interfacestring.Trim() == "loopback")
                listenInterface = System.Net.IPAddress.Loopback;
            else
                listenInterface = System.Net.IPAddress.Parse(interfacestring);


            // If we are in hosted mode with no specified port, 
            // then try different ports
            foreach(var p in ports)
                try
                {
                    // Due to the way the server is initialized, 
                    // we cannot try to start it again on another port, 
                    // so we create a new server for each attempt
                
                    var server = CreateServer(options);
                    server.Start(listenInterface, p);
                    m_server = server;
                    m_server.ServerName = "Duplicati v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                    this.Port = p;

                    if (interfacestring !=  Program.DataConnection.ApplicationSettings.ServerListenInterface)
                        Program.DataConnection.ApplicationSettings.ServerListenInterface = interfacestring;
    
                    return;
                }
                catch (System.Net.Sockets.SocketException)
                {
                }
                
            throw new Exception("Unable to open a socket for listening, tried ports: " + string.Join(",", from n in ports select n.ToString()));
        }
Example #17
0
        private static HttpServer.HttpServer CreateServer(IDictionary <string, string> options)
        {
            HttpServer.HttpServer server = new HttpServer.HttpServer();

            server.Add(new AuthenticationHandler());

            server.Add(new ControlHandler());

            server.Add(new RESTHandler());

            string webroot         = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string install_webroot = System.IO.Path.Combine(Library.AutoUpdater.UpdaterManager.InstalledBaseDir, "webroot");

#if DEBUG
            // Easy test for extensions while debugging
            install_webroot = Library.AutoUpdater.UpdaterManager.InstalledBaseDir;

            if (!System.IO.Directory.Exists(System.IO.Path.Combine(webroot, "webroot")))
            {
                //For debug we go "../../../.." to get out of "GUI/Duplicati.GUI.TrayIcon/bin/debug"
                string tmpwebroot = System.IO.Path.GetFullPath(System.IO.Path.Combine(webroot, "..", "..", "..", ".."));
                tmpwebroot = System.IO.Path.Combine(tmpwebroot, "Server");
                if (System.IO.Directory.Exists(System.IO.Path.Combine(tmpwebroot, "webroot")))
                {
                    webroot = tmpwebroot;
                }
                else
                {
                    //If we are running the server standalone, we only need to exit "bin/Debug"
                    tmpwebroot = System.IO.Path.GetFullPath(System.IO.Path.Combine(webroot, "..", ".."));
                    if (System.IO.Directory.Exists(System.IO.Path.Combine(tmpwebroot, "webroot")))
                    {
                        webroot = tmpwebroot;
                    }
                }
            }
#endif

            webroot = System.IO.Path.Combine(webroot, "webroot");

            if (options.ContainsKey(OPTION_WEBROOT))
            {
                string userroot = options[OPTION_WEBROOT];
#if DEBUG
                //In debug mode we do not care where the path points
#else
                //In release mode we check that the user supplied path is located
                // in the same folders as the running application, to avoid users
                // that inadvertently expose top level folders
                if (!string.IsNullOrWhiteSpace(userroot)
                    &&
                    (
                        userroot.StartsWith(Library.Utility.Utility.AppendDirSeparator(System.Reflection.Assembly.GetExecutingAssembly().Location), Library.Utility.Utility.ClientFilenameStringComparision)
                        ||
                        userroot.StartsWith(Library.Utility.Utility.AppendDirSeparator(Program.StartupPath), Library.Utility.Utility.ClientFilenameStringComparision)
                    )
                    )
#endif
                {
                    webroot         = userroot;
                    install_webroot = webroot;
                }
            }

            if (install_webroot != webroot && System.IO.Directory.Exists(System.IO.Path.Combine(install_webroot, "customized")))
            {
                var customized_files = new FileModule("/customized/", System.IO.Path.Combine(install_webroot, "customized"));
                AddMimeTypes(customized_files);
                server.Add(customized_files);
            }

            if (install_webroot != webroot && System.IO.Directory.Exists(System.IO.Path.Combine(install_webroot, "oem")))
            {
                var oem_files = new FileModule("/oem/", System.IO.Path.Combine(install_webroot, "oem"));
                AddMimeTypes(oem_files);
                server.Add(oem_files);
            }

            if (install_webroot != webroot && System.IO.Directory.Exists(System.IO.Path.Combine(install_webroot, "package")))
            {
                var proxy_files = new FileModule("/proxy/", System.IO.Path.Combine(install_webroot, "package"));
                AddMimeTypes(proxy_files);
                server.Add(proxy_files);
            }

            var fh = new FileModule("/", webroot);
            AddMimeTypes(fh);
            server.Add(fh);

            server.Add(new IndexHtmlHandler(webroot));
#if DEBUG
            //For debugging, it is nice to know when we get a 404
            server.Add(new DebugReportHandler());
#endif
            return(server);
        }
Example #18
0
        /// <summary>
        /// Sets up the webserver and starts it
        /// </summary>
        /// <param name="options">A set of options</param>
        public Server(IDictionary <string, string> options)
        {
            int               port;
            string            portstring;
            IEnumerable <int> ports = null;

            options.TryGetValue(OPTION_PORT, out portstring);
            if (!string.IsNullOrEmpty(portstring))
            {
                ports =
                    from n in portstring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    where int.TryParse(n, out port)
                    select int.Parse(n);
            }

            if (ports == null || !ports.Any())
            {
                ports = new int[] { DEFAULT_OPTION_PORT }
            }
            ;

            string interfacestring;

            System.Net.IPAddress listenInterface;
            options.TryGetValue(OPTION_INTERFACE, out interfacestring);

            if (string.IsNullOrWhiteSpace(interfacestring))
            {
                interfacestring = Program.DataConnection.ApplicationSettings.ServerListenInterface;
            }
            if (string.IsNullOrWhiteSpace(interfacestring))
            {
                interfacestring = DEFAULT_OPTION_INTERFACE;
            }

            if (interfacestring.Trim() == "*" || interfacestring.Trim().Equals("any", StringComparison.InvariantCultureIgnoreCase))
            {
                listenInterface = System.Net.IPAddress.Any;
            }
            else if (interfacestring.Trim() == "loopback")
            {
                listenInterface = System.Net.IPAddress.Loopback;
            }
            else
            {
                listenInterface = System.Net.IPAddress.Parse(interfacestring);
            }


            // If we are in hosted mode with no specified port,
            // then try different ports
            foreach (var p in ports)
            {
                try
                {
                    // Due to the way the server is initialized,
                    // we cannot try to start it again on another port,
                    // so we create a new server for each attempt

                    var server = CreateServer(options);
                    server.Start(listenInterface, p);
                    m_server            = server;
                    m_server.ServerName = "Duplicati v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                    this.Port           = p;

                    if (interfacestring != Program.DataConnection.ApplicationSettings.ServerListenInterface)
                    {
                        Program.DataConnection.ApplicationSettings.ServerListenInterface = interfacestring;
                    }

                    return;
                }
                catch (System.Net.Sockets.SocketException)
                {
                }
            }

            throw new Exception("Unable to open a socket for listening, tried ports: " + string.Join(",", from n in ports select n.ToString()));
        }
Example #19
0
        private static HttpServer.HttpServer CreateServer(IDictionary<string, string> options)
        {
            HttpServer.HttpServer server = new HttpServer.HttpServer();

            server.Add(new AuthenticationHandler());

            server.Add(new ControlHandler());

            server.Add(new RESTHandler());

            string webroot = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string install_webroot = System.IO.Path.Combine(Library.AutoUpdater.UpdaterManager.InstalledBaseDir, "webroot");

#if DEBUG
            // Easy test for extensions while debugging
            install_webroot = Library.AutoUpdater.UpdaterManager.InstalledBaseDir;

            if (!System.IO.Directory.Exists(System.IO.Path.Combine(webroot, "webroot")))
            {
                //For debug we go "../../../.." to get out of "GUI/Duplicati.GUI.TrayIcon/bin/debug"
                string tmpwebroot = System.IO.Path.GetFullPath(System.IO.Path.Combine(webroot, "..", "..", "..", ".."));
                tmpwebroot = System.IO.Path.Combine(tmpwebroot, "Server");
                if (System.IO.Directory.Exists(System.IO.Path.Combine(tmpwebroot, "webroot")))
                    webroot = tmpwebroot;
                else
                {
                    //If we are running the server standalone, we only need to exit "bin/Debug"
                    tmpwebroot = System.IO.Path.GetFullPath(System.IO.Path.Combine(webroot, "..", ".."));
                    if (System.IO.Directory.Exists(System.IO.Path.Combine(tmpwebroot, "webroot")))
                        webroot = tmpwebroot;
                }
            }
#endif

            webroot = System.IO.Path.Combine(webroot, "webroot");

            if (options.ContainsKey(OPTION_WEBROOT))
            {
                string userroot = options[OPTION_WEBROOT];
#if DEBUG
                //In debug mode we do not care where the path points
#else
                //In release mode we check that the user supplied path is located
                // in the same folders as the running application, to avoid users
                // that inadvertently expose top level folders
                if (!string.IsNullOrWhiteSpace(userroot)
                    &&
                    (
                        userroot.StartsWith(Library.Utility.Utility.AppendDirSeparator(System.Reflection.Assembly.GetExecutingAssembly().Location), Library.Utility.Utility.ClientFilenameStringComparision)
                        ||
                        userroot.StartsWith(Library.Utility.Utility.AppendDirSeparator(Program.StartupPath), Library.Utility.Utility.ClientFilenameStringComparision)
                    )
                )
#endif
                {
                    webroot = userroot;
                    install_webroot = webroot;
                }
            }

            if (install_webroot != webroot && System.IO.Directory.Exists(System.IO.Path.Combine(install_webroot, "customized")))
            {
                var customized_files = new FileModule("/customized/", System.IO.Path.Combine(install_webroot, "customized"));
                AddMimeTypes(customized_files);
                server.Add(customized_files);
            }

			if (install_webroot != webroot && System.IO.Directory.Exists(System.IO.Path.Combine(install_webroot, "oem")))
			{
				var oem_files = new FileModule("/oem/", System.IO.Path.Combine(install_webroot, "oem"));
				AddMimeTypes(oem_files);
				server.Add(oem_files);
			}

            var fh = new FileModule("/", webroot);
            AddMimeTypes(fh);
            server.Add(fh);

            server.Add(new IndexHtmlHandler(webroot));
#if DEBUG
            //For debugging, it is nice to know when we get a 404
            server.Add(new DebugReportHandler());
#endif
            return server;
        }
Example #20
0
        /// <summary>
        /// Sets up the webserver and starts it
        /// </summary>
        /// <param name="options">A set of options</param>
        public Server(IDictionary<string, string> options)
        {
            int port;
            string portstring;
            IEnumerable<int> ports = null;
            options.TryGetValue(OPTION_PORT, out portstring);
            if (!string.IsNullOrEmpty(portstring))
                ports =
                    from n in portstring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                where int.TryParse(n, out port)
                                select int.Parse(n);

            if (ports == null || !ports.Any())
                ports = new int[] { DEFAULT_OPTION_PORT };

            string interfacestring;
            System.Net.IPAddress listenInterface;
            options.TryGetValue(OPTION_INTERFACE, out interfacestring);

            if (string.IsNullOrWhiteSpace(interfacestring))
                interfacestring = Program.DataConnection.ApplicationSettings.ServerListenInterface;
            if (string.IsNullOrWhiteSpace(interfacestring))
                interfacestring = DEFAULT_OPTION_INTERFACE;

            if (interfacestring.Trim() == "*" || interfacestring.Trim().Equals("any", StringComparison.InvariantCultureIgnoreCase))
                listenInterface = System.Net.IPAddress.Any;
            else if (interfacestring.Trim() == "loopback")
                listenInterface = System.Net.IPAddress.Loopback;
            else
                listenInterface = System.Net.IPAddress.Parse(interfacestring);

            string certificateFile;
            options.TryGetValue(OPTION_SSLCERTIFICATEFILE, out certificateFile);

            string certificateFilePassword;
            options.TryGetValue(OPTION_SSLCERTIFICATEFILEPASSWORD, out certificateFilePassword);

            X509Certificate2 cert = null;
            bool certValid = false;

            if (certificateFile == null)
            {
                try
                {
                    cert = Program.DataConnection.ApplicationSettings.ServerSSLCertificate;

                    if (cert != null)
                        certValid = cert.HasPrivateKey;
                }
                catch (Exception ex)
                {
                    Library.Logging.Log.WriteMessage("Unable to create SSL certificate using data from database. Starting without SSL.", Duplicati.Library.Logging.LogMessageType.Warning, ex);
                }
            }
            else if (certificateFile.Length == 0)
            {
                Program.DataConnection.ApplicationSettings.ServerSSLCertificate = null;
            }
            else
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(certificateFilePassword))
                        cert = new X509Certificate2(certificateFile, "", X509KeyStorageFlags.Exportable);
                    else
                        cert = new X509Certificate2(certificateFile, certificateFilePassword, X509KeyStorageFlags.Exportable);

                    certValid = cert.HasPrivateKey;
                }
                catch (Exception ex)
                {
                    throw new Exception("Unable to create SSL certificate using provided parameters. Exception detail: " + ex.Message);
                }
            }

            // If we are in hosted mode with no specified port,
            // then try different ports
            foreach (var p in ports)
                try
                {
                    // Due to the way the server is initialized,
                    // we cannot try to start it again on another port,
                    // so we create a new server for each attempt

                    var server = CreateServer(options);

                    if (!certValid)
                        server.Start(listenInterface, p);
                    else
                        server.Start(listenInterface, p, cert, System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12, null, false);

                    m_server = server;
                    m_server.ServerName = "Duplicati v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                    this.Port = p;

                    if (interfacestring !=  Program.DataConnection.ApplicationSettings.ServerListenInterface)
                        Program.DataConnection.ApplicationSettings.ServerListenInterface = interfacestring;

                    if (certValid && !cert.Equals(Program.DataConnection.ApplicationSettings.ServerSSLCertificate))
                        Program.DataConnection.ApplicationSettings.ServerSSLCertificate = cert;

                    return;
                }
                catch (System.Net.Sockets.SocketException)
                {
                }

            throw new Exception("Unable to open a socket for listening, tried ports: " + string.Join(",", from n in ports select n.ToString()));
        }
Example #21
0
        private static HttpServer.HttpServer CreateServer(IDictionary<string, string> options)
        {
            HttpServer.HttpServer server = new HttpServer.HttpServer();

            server.Add(new AuthenticationHandler());

            server.Add(new ControlHandler());

            string webroot = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            #if DEBUG
            if (!System.IO.Directory.Exists(System.IO.Path.Combine(webroot, "webroot")))
            {
                //For debug we go "../../../.." to get out of "GUI/Duplicati.GUI.TrayIcon/bin/debug"
                string tmpwebroot = System.IO.Path.GetFullPath(System.IO.Path.Combine(webroot, "..", "..", "..", ".."));
                tmpwebroot = System.IO.Path.Combine(tmpwebroot, "Server");
                if (System.IO.Directory.Exists(System.IO.Path.Combine(tmpwebroot, "webroot")))
                    webroot = tmpwebroot;
                else
                {
                    //If we are running the server standalone, we only need to exit "bin/Debug"
                    tmpwebroot = System.IO.Path.GetFullPath(System.IO.Path.Combine(webroot, "..", ".."));
                    if (System.IO.Directory.Exists(System.IO.Path.Combine(tmpwebroot, "webroot")))
                        webroot = tmpwebroot;
                }
            }
            #endif

            webroot = System.IO.Path.Combine(webroot, "webroot");

            if (options.ContainsKey(OPTION_WEBROOT))
            {
                string userroot = options[OPTION_WEBROOT];
            #if DEBUG
                //In debug mode we do not care where the path points
            #else
                //In release mode we check that the user supplied path is located
                // in the same folders as the running application, to avoid users
                // that inadvertently expose top level folders
                if (!string.IsNullOrWhiteSpace(userroot)
                    &&
                    (
                        userroot.StartsWith(Library.Utility.Utility.AppendDirSeparator(System.Reflection.Assembly.GetExecutingAssembly().Location), Library.Utility.Utility.ClientFilenameStringComparision)
                        ||
                        userroot.StartsWith(Library.Utility.Utility.AppendDirSeparator(Program.StartupPath), Library.Utility.Utility.ClientFilenameStringComparision)
                    )
                )
            #endif
                {
                    webroot = userroot;
                }
            }

            FileModule fh = new FileModule("/", webroot);
            fh.AddDefaultMimeTypes();
            fh.MimeTypes.Add("htc", "text/x-component");
            fh.MimeTypes.Add("json", "application/json");
            fh.MimeTypes.Add("map", "application/json");
            server.Add(fh);
            server.Add(new IndexHtmlHandler(System.IO.Path.Combine(webroot, "index.html")));
            #if DEBUG
            //For debugging, it is nice to know when we get a 404
            server.Add(new DebugReportHandler());
            #endif

            return server;
        }
Example #22
0
        private Program(Options options)
        {
            _daemon = options.Daemon;

            if (options.CleanStart)
                options.InteractiveSetup();

            Database.Database db = new Database.Database(options.CleanStart, options.ConnectionString);

            _server = new HttpServer.HttpServer(options.HttpPort, db.ConnectionFactory);
        }
Example #23
0
        /// <summary>
        /// Sets up the webserver and starts it
        /// </summary>
        /// <param name="options">A set of options</param>
        public Server(IDictionary <string, string> options)
        {
            string            portstring;
            IEnumerable <int> ports = null;

            options.TryGetValue(OPTION_PORT, out portstring);
            if (!string.IsNullOrEmpty(portstring))
            {
                ports =
                    from n in portstring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    where int.TryParse(n, out _)
                    select int.Parse(n);
            }

            if (ports == null || !ports.Any())
            {
                ports = new int[] { DEFAULT_OPTION_PORT }
            }
            ;

            string interfacestring;

            System.Net.IPAddress listenInterface;
            options.TryGetValue(OPTION_INTERFACE, out interfacestring);

            if (string.IsNullOrWhiteSpace(interfacestring))
            {
                interfacestring = Program.DataConnection.ApplicationSettings.ServerListenInterface;
            }
            if (string.IsNullOrWhiteSpace(interfacestring))
            {
                interfacestring = DEFAULT_OPTION_INTERFACE;
            }

            if (interfacestring.Trim() == "*" || interfacestring.Trim().Equals("any", StringComparison.OrdinalIgnoreCase) || interfacestring.Trim().Equals("all", StringComparison.OrdinalIgnoreCase))
            {
                listenInterface = System.Net.IPAddress.Any;
            }
            else if (interfacestring.Trim() == "loopback")
            {
                listenInterface = System.Net.IPAddress.Loopback;
            }
            else
            {
                listenInterface = System.Net.IPAddress.Parse(interfacestring);
            }

            string certificateFile;

            options.TryGetValue(OPTION_SSLCERTIFICATEFILE, out certificateFile);

            string certificateFilePassword;

            options.TryGetValue(OPTION_SSLCERTIFICATEFILEPASSWORD, out certificateFilePassword);

            X509Certificate2 cert      = null;
            bool             certValid = false;

            if (certificateFile == null)
            {
                try
                {
                    cert = Program.DataConnection.ApplicationSettings.ServerSSLCertificate;

                    if (cert != null)
                    {
                        certValid = cert.HasPrivateKey;
                    }
                }
                catch (Exception ex)
                {
                    Duplicati.Library.Logging.Log.WriteWarningMessage(LOGTAG, "DefectStoredSSLCert", ex, Strings.Server.DefectSSLCertInDatabase);
                }
            }
            else if (certificateFile.Length == 0)
            {
                Program.DataConnection.ApplicationSettings.ServerSSLCertificate = null;
            }
            else
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(certificateFilePassword))
                    {
                        cert = new X509Certificate2(certificateFile, "", X509KeyStorageFlags.Exportable);
                    }
                    else
                    {
                        cert = new X509Certificate2(certificateFile, certificateFilePassword, X509KeyStorageFlags.Exportable);
                    }

                    certValid = cert.HasPrivateKey;
                }
                catch (Exception ex)
                {
                    throw new Exception(Strings.Server.SSLCertificateFailure(ex.Message), ex);
                }
            }

            // If we are in hosted mode with no specified port,
            // then try different ports
            foreach (var p in ports)
            {
                try
                {
                    // Due to the way the server is initialized,
                    // we cannot try to start it again on another port,
                    // so we create a new server for each attempt

                    var server = CreateServer(options);

                    if (!certValid)
                    {
                        server.Start(listenInterface, p);
                    }
                    else
                    {
                        var secProtocols = System.Security.Authentication.SslProtocols.Tls12;

                        try
                        {
                            //try TLS 1.3 (type not available on .NET < 4.8)
                            secProtocols = System.Security.Authentication.SslProtocols.Tls12 | (System.Security.Authentication.SslProtocols) 12288;
                        }
                        catch (NotSupportedException)
                        {
                        }
                        server.Start(listenInterface, p, cert, secProtocols, null, false);
                    }

                    m_server            = server;
                    m_server.ServerName = string.Format("{0} v{1}", Library.AutoUpdater.AutoUpdateSettings.AppName, System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                    this.Port           = p;

                    if (interfacestring != Program.DataConnection.ApplicationSettings.ServerListenInterface)
                    {
                        Program.DataConnection.ApplicationSettings.ServerListenInterface = interfacestring;
                    }

                    if (certValid && !cert.Equals(Program.DataConnection.ApplicationSettings.ServerSSLCertificate))
                    {
                        Program.DataConnection.ApplicationSettings.ServerSSLCertificate = cert;
                    }

                    Duplicati.Library.Logging.Log.WriteInformationMessage(LOGTAG, "ServerListening", Strings.Server.StartedServer(listenInterface.ToString(), p));

                    return;
                }
                catch (System.Net.Sockets.SocketException)
                {
                }
            }

            throw new Exception(Strings.Server.ServerStartFailure(ports));
        }
Example #24
0
      public Server()
      {
          log4net.Config.XmlConfigurator.Configure();
          var assembly = Assembly.GetExecutingAssembly();

          Path = System.IO.Path.GetDirectoryName(assembly.Location);
          var route_config = new List <Route>()
          {
              new Route {
                  Name     = "Hello Handler",
                  UrlRegex = @"^/$",
                  Method   = "GET",
                  Callable = (HttpRequest request) => {
                      return(new HttpResponse()
                        {
                            ContentAsUTF8 = "Hello from SimpleHttpServer",
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
                  }
              }
              //,new Route()
              //    {
              //        Callable = new FileSystemRouteHandler() { BasePath = @"C:\Documents\GitHub\to-do-notifications"}.Handle,
              //        UrlRegex = "^\\/Static\\/(.*)$",
              //        Method = "GET"
              //    }
              ,
              new Route()
              {
                  Callable = new FileSystemRouteHandler()
                  {
                      BasePath = Path + @"\www\"
                  }.Handle,
                    UrlRegex = "^\\/Static\\/(.*)$",
                    Method   = "GET"
              },
              new Route {
                  Name     = "MaxSpeed",
                  UrlRegex = @"^/MaxSpeed",
                  Method   = "GET",
                  Callable = (HttpRequest request) => {
                      return(new HttpResponse()
                        {
                            ContentAsUTF8 = History.MaxSpeed,
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
                  }
              },
              new Route {
                  Name     = "Daydownload",
                  UrlRegex = @"^/Daydownload",
                  Method   = "GET",
                  Callable = (HttpRequest request) => {
                      return(new HttpResponse()
                        {
                            ContentAsUTF8 = History.Daydownload,
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
                  }
              },
              new Route {
                  Name     = "Dayupload",
                  UrlRegex = @"^/Dayupload",
                  Method   = "GET",
                  Callable = (HttpRequest request) => {
                      return(new HttpResponse()
                        {
                            ContentAsUTF8 = History.Dayupload,
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
                  }
              },
              new Route {
                  Name     = "Monthdownload",
                  UrlRegex = @"^/Monthdownload",
                  Method   = "GET",
                  Callable = (HttpRequest request) => {
                      return(new HttpResponse()
                        {
                            ContentAsUTF8 = History.Monthdownload,
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
                  }
              },
              new Route {
                  Name     = "Monthupload",
                  UrlRegex = @"^/Monthupload",
                  Method   = "GET",
                  Callable = (HttpRequest request) => {
                      return(new HttpResponse()
                        {
                            ContentAsUTF8 = History.Monthupload,
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
                  }
              }
              ,
              new Route {
                  Name     = "Totaldownload",
                  UrlRegex = @"^/Totaldownload",
                  Method   = "GET",
                  Callable = (HttpRequest request) => {
                      return(new HttpResponse()
                        {
                            ContentAsUTF8 = History.Totaldownload,
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
                  }
              },
              new Route {
                  Name     = "Totalupload",
                  UrlRegex = @"^/Totalupload",
                  Method   = "GET",
                  Callable = (HttpRequest request) => {
                      return(new HttpResponse()
                        {
                            ContentAsUTF8 = History.Totalupload,
                            ReasonPhrase = "OK",
                            StatusCode = "200"
                        });
                  }
              }
          };

          HttpServer.HttpServer httpServer = new HttpServer.HttpServer(8080, route_config);

          Thread = new Thread(new ThreadStart(httpServer.Listen));
          Thread.Start();
      }
Example #25
0
        private static HttpServer.HttpServer CreateServer(IDictionary <string, string> options)
        {
            HttpServer.HttpServer server = new HttpServer.HttpServer();

            server.Add(new AuthenticationHandler());

            server.Add(new ControlHandler());

            string webroot = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

#if DEBUG
            if (!System.IO.Directory.Exists(System.IO.Path.Combine(webroot, "webroot")))
            {
                //For debug we go "../../../.." to get out of "GUI/Duplicati.GUI.TrayIcon/bin/debug"
                string tmpwebroot = System.IO.Path.GetFullPath(System.IO.Path.Combine(webroot, "..", "..", "..", ".."));
                tmpwebroot = System.IO.Path.Combine(tmpwebroot, "Server");
                if (System.IO.Directory.Exists(System.IO.Path.Combine(tmpwebroot, "webroot")))
                {
                    webroot = tmpwebroot;
                }
                else
                {
                    //If we are running the server standalone, we only need to exit "bin/Debug"
                    tmpwebroot = System.IO.Path.GetFullPath(System.IO.Path.Combine(webroot, "..", ".."));
                    if (System.IO.Directory.Exists(System.IO.Path.Combine(tmpwebroot, "webroot")))
                    {
                        webroot = tmpwebroot;
                    }
                }
            }
#endif

            webroot = System.IO.Path.Combine(webroot, "webroot");

            if (options.ContainsKey(OPTION_WEBROOT))
            {
                string userroot = options[OPTION_WEBROOT];
#if DEBUG
                //In debug mode we do not care where the path points
#else
                //In release mode we check that the user supplied path is located
                // in the same folders as the running application, to avoid users
                // that inadvertently expose top level folders
                if (!string.IsNullOrWhiteSpace(userroot)
                    &&
                    (
                        userroot.StartsWith(Library.Utility.Utility.AppendDirSeparator(System.Reflection.Assembly.GetExecutingAssembly().Location), Library.Utility.Utility.ClientFilenameStringComparision)
                        ||
                        userroot.StartsWith(Library.Utility.Utility.AppendDirSeparator(Program.StartupPath), Library.Utility.Utility.ClientFilenameStringComparision)
                    )
                    )
#endif
                {
                    webroot = userroot;
                }
            }

            FileModule fh = new FileModule("/", webroot);
            fh.AddDefaultMimeTypes();
            fh.MimeTypes.Add("htc", "text/x-component");
            fh.MimeTypes.Add("json", "application/json");
            fh.MimeTypes.Add("map", "application/json");
            server.Add(fh);
            server.Add(new IndexHtmlHandler(System.IO.Path.Combine(webroot, "index.html")));
#if DEBUG
            //For debugging, it is nice to know when we get a 404
            server.Add(new DebugReportHandler());
#endif

            return(server);
        }
Example #26
0
 public void Init()
 {
     server = new HttpServer.HttpServer("http://test/");
 }