コード例 #1
0
        private void OnRequest(object sender, HttpServer.RequestEventArgs e)
        {
            string[] paramss = e.Request.UriParts;
            HttpServer.IHttpResponse resp = e.Request.CreateResponse((IHttpClientContext)sender);

            if (paramss[0] == "favicon.ico")
            {
                reactFavIco(resp);
            }

            if (paramss[0] == "fire")
            {
                reactFire(resp);
            }

            if (paramss[0] == "move")
            {
                reactMove(resp, paramss[1]);
            }

            if (paramss[0] == "laser")
            {
                reactLaser(resp);
            }

            if (paramss[0] == "reset")
            {
                reactReset(resp);
            }
        }
コード例 #2
0
        public override bool Process(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session)
        {
            var path = this.GetPath(request.Uri);
            var html = System.IO.Path.Combine(path, "index.html");
            var htm  = System.IO.Path.Combine(path, "index.htm");

            if (System.IO.Directory.Exists(path) && (System.IO.File.Exists(html) || System.IO.File.Exists(htm)))
            {
                if (!request.Uri.AbsolutePath.EndsWith("/", StringComparison.Ordinal))
                {
                    response.Redirect(request.Uri.AbsolutePath + "/");
                    return(true);
                }

                response.Status      = System.Net.HttpStatusCode.OK;
                response.Reason      = "OK";
                response.ContentType = "text/html; charset=utf-8";
                response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0");

                using (var fs = System.IO.File.OpenRead(System.IO.File.Exists(html) ? html : htm))
                {
                    response.ContentLength = fs.Length;
                    response.Body          = fs;
                    response.Send();
                }

                return(true);
            }

            return(false);
        }
コード例 #3
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
        private void ExportBackup(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
        {
            var input = request.Method.ToUpper() == "POST" ? request.Form : request.QueryString;
            var key   = string.Format("{0}/export", Library.Utility.Uri.UrlPathEncode(input["id"].Value));

            RESTHandler.DoProcess(request, response, session, request.Method, typeof(RESTMethods.Backup).Name.ToLowerInvariant(), key);
        }
コード例 #4
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
        private void CreateRemoteFolder(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
        {
            var input = request.Method.ToUpper() == "POST" ? request.Form : request.QueryString;
            var key   = string.Format("{0}/create", Library.Utility.Uri.UrlPathEncode(input["url"].Value));

            RESTHandler.DoProcess(request, response, session, request.Method, typeof(RESTMethods.RemoteOperation).Name.ToLowerInvariant(), key);
        }
コード例 #5
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
        private void ValidatePath(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
        {
            var input = request.Method.ToUpper() == "POST" ? request.Form : request.QueryString;
            var key   = string.Format("{0}/validate", Library.Utility.Uri.UrlPathEncode(input["path"].Value));

            RESTHandler.DoProcess(request, response, session, "GET", typeof(RESTMethods.Filesystem).Name.ToLowerInvariant(), key);
        }
コード例 #6
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
        private void ListBackupSets(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
        {
            var input = request.Method.ToUpper() == "POST" ? request.Form : request.QueryString;
            var key   = string.Format("{0}/filesets", input["id"].Value);

            RESTHandler.DoProcess(request, response, session, request.Method, typeof(RESTMethods.Backup).Name.ToLowerInvariant(), key);
        }
コード例 #7
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
        private void SearchBackupFiles(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
        {
            var input = request.Method.Equals("POST", StringComparison.InvariantCultureIgnoreCase) ? request.Form : request.QueryString;
            var key   = string.Format("{0}/files/{1}", input["id"].Value, input["filter"].Value);

            RESTHandler.DoProcess(request, response, session, request.Method, typeof(RESTMethods.Backup).Name.ToLowerInvariant(), key);
        }
コード例 #8
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
        private void ReportError(HttpServer.IHttpResponse response, BodyWriter bw, string message)
        {
            response.Status = System.Net.HttpStatusCode.InternalServerError;
            response.Reason = message;

            bw.WriteJsonObject(new { Error = message });
        }
コード例 #9
0
        public static NetworkStream GetNetworkStream(HttpServer.IHttpResponse response)
        {
            HttpClientContext context = GetContext(response) as HttpClientContext;

            if (context != null)
            {
                var f = context.GetType().GetField("_stream", BindingFlags.Instance | BindingFlags.NonPublic);
                return(f.GetValue(context) as NetworkStream);
            }
            return(null);
        }
コード例 #10
0
        public static Socket GetNetworkSocket(HttpServer.IHttpResponse response)
        {
            NetworkStream stream = GetNetworkStream(response); // internal ReusableSocketNetworkStream

            if (stream != null)
            {
                var f = stream.GetType().GetProperty("Socket", BindingFlags.Instance | BindingFlags.NonPublic);
                return(f.GetValue(stream, null) as Socket);
            }
            return(null);
        }
コード例 #11
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
        private void ReadLogData(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
        {
            HttpServer.HttpInput input = request.Method.ToUpper() == "POST" ? request.Form : request.QueryString;

            if (string.IsNullOrEmpty(input["id"].Value))
            {
                RESTHandler.HandleControlCGI(request, response, session, bw, typeof(RESTMethods.LogData));
            }
            else
            {
                var key = string.Format("{0}/{1}", input["id"].Value, Duplicati.Library.Utility.Utility.ParseBool(input["remotelog"].Value, false) ? "remotelog" : "log");
                RESTHandler.DoProcess(request, response, session, request.Method, typeof(RESTMethods.Backup).Name.ToLowerInvariant(), key);
            }
        }
コード例 #12
0
        public static void DebugPrintResponse(HttpServer.IHttpResponse response)
        {
            // TODO this should be precomputed a single time and reused
            var f = response.GetType().GetField("_headers", BindingFlags.Instance | BindingFlags.NonPublic);

            var headers = (NameValueCollection)f.GetValue(response);

            Console.WriteLine(response.ProtocolVersion + " " + response.Status.ToString());
            Console.WriteLine(response.ContentType);
            foreach (string headerKey in headers.Keys)
            {
                Console.WriteLine(headerKey + ": " + headers[headerKey]);
            }
            Console.WriteLine("-----------------------------");
        }
コード例 #13
0
        private bool AddXSRFTokenToRespone(HttpServer.IHttpResponse response)
        {
            if (m_activexsrf.Count > 500)
            {
                return(false);
            }

            var buf     = new byte[32];
            var expires = DateTime.UtcNow.AddMinutes(XSRF_TIMEOUT_MINUTES);

            m_prng.GetBytes(buf);
            var token = Convert.ToBase64String(buf);

            m_activexsrf.Add(token, expires);
            response.Cookies.Add(new HttpServer.ResponseCookie(XSRF_COOKIE_NAME, token, expires));
            return(true);
        }
コード例 #14
0
        public override bool Process(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session)
        {
            if ((request.Uri.AbsolutePath == "/" || request.Uri.AbsolutePath == "/index.html" || request.Uri.AbsolutePath == "/index.htm") && System.IO.File.Exists(m_defaultdoc))
            {
                response.Status      = System.Net.HttpStatusCode.OK;
                response.Reason      = "OK";
                response.ContentType = "text/html";

                using (var fs = System.IO.File.OpenRead(m_defaultdoc))
                {
                    response.ContentLength = fs.Length;
                    response.Body          = fs;
                    response.Send();
                }

                return(true);
            }

            return(false);
        }
コード例 #15
0
        private bool AddXSRFTokenToRespone(HttpServer.IHttpResponse response)
        {
            if (m_activexsrf.Count > 500)
            {
                return(false);
            }

            var buf     = new byte[32];
            var expires = DateTime.UtcNow.AddMinutes(XSRF_TIMEOUT_MINUTES);

            m_prng.GetBytes(buf);
            var token = Convert.ToBase64String(buf);

            m_activexsrf.AddOrUpdate(token, key => expires, (key, existingExpires) =>
            {
                // Simulate the original behavior => if the random token, against all odds, is already used
                // we throw an ArgumentException
                throw new ArgumentException("An element with the same key already exists in the dictionary.");
            });

            response.Cookies.Add(new HttpServer.ResponseCookie(XSRF_COOKIE_NAME, token, expires));
            return(true);
        }
コード例 #16
0
ファイル: Logout.cs プロジェクト: rubencosta/ArchBench
        public bool Process(HttpServer.IHttpRequest aRequest, HttpServer.IHttpResponse aResponse, HttpServer.Sessions.IHttpSession aSession)
        {
            if (!aRequest.Uri.AbsolutePath.StartsWith("/logout"))
            {
                return(false);
            }
            foreach (RequestCookie cookie in aRequest.Cookies)
            {
                Host.Logger.WriteLine("Cookie({0}) = {1}", cookie.Name, cookie.Value);
            }

            Host.Logger.WriteLine("Logout PlugIn: {0}", aRequest.Uri.AbsolutePath);
            StreamWriter writer = new StreamWriter(aResponse.Body);

            writer.WriteLine("Goodbye {0}!", aSession["Username"]);
            writer.Flush();
            aResponse.Send();

            //clear the session
            aSession.Clear();


            return(true);
        }
コード例 #17
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
 private void PollLogMessages(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
 {
     RESTHandler.DoProcess(request, response, session, "GET", typeof(RESTMethods.LogData).Name.ToLowerInvariant(), "poll");
 }
コード例 #18
0
        public override bool Process(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session)
        {
            HttpServer.HttpInput input = request.Method.ToUpper() == "POST" ? request.Form : request.QueryString;

            var auth_token = FindAuthCookie(request);
            var xsrf_token = FindXSRFToken(request);

            if (!HasXSRFCookie(request))
            {
                var cookieAdded = AddXSRFTokenToRespone(response);

                if (!cookieAdded)
                {
                    response.Status = System.Net.HttpStatusCode.ServiceUnavailable;
                    response.Reason = "Too Many Concurrent Request, try again later";
                    return(true);
                }
            }
            Tuple <DateTime, string> tmpTuple;
            DateTime tmpDateTime;

            if (LOGOUT_SCRIPT_URI.Equals(request.Uri.AbsolutePath, StringComparison.OrdinalIgnoreCase))
            {
                if (!string.IsNullOrWhiteSpace(auth_token))
                {
                    // Remove the active auth token
                    m_activeTokens.TryRemove(auth_token, out tmpDateTime);
                }

                response.Status = System.Net.HttpStatusCode.NoContent;
                response.Reason = "OK";

                return(true);
            }
            else if (LOGIN_SCRIPT_URI.Equals(request.Uri.AbsolutePath, StringComparison.OrdinalIgnoreCase))
            {
                // Remove expired nonces
                foreach (var k in (from n in m_activeNonces where DateTime.UtcNow > n.Value.Item1 select n.Key))
                {
                    m_activeNonces.TryRemove(k, out tmpTuple);
                }

                if (input["get-nonce"] != null && !string.IsNullOrWhiteSpace(input["get-nonce"].Value))
                {
                    if (m_activeNonces.Count > 50)
                    {
                        response.Status = System.Net.HttpStatusCode.ServiceUnavailable;
                        response.Reason = "Too many active login attempts";
                        return(true);
                    }

                    var password = Program.DataConnection.ApplicationSettings.WebserverPassword;

                    if (request.Headers[TRAYICONPASSWORDSOURCE_HEADER] == "database")
                    {
                        password = Program.DataConnection.ApplicationSettings.WebserverPasswordTrayIconHash;
                    }

                    var buf     = new byte[32];
                    var expires = DateTime.UtcNow.AddMinutes(AUTH_TIMEOUT_MINUTES);
                    m_prng.GetBytes(buf);
                    var nonce = Convert.ToBase64String(buf);

                    var sha256 = System.Security.Cryptography.SHA256.Create();
                    sha256.TransformBlock(buf, 0, buf.Length, buf, 0);
                    buf = Convert.FromBase64String(password);
                    sha256.TransformFinalBlock(buf, 0, buf.Length);
                    var pwd = Convert.ToBase64String(sha256.Hash);

                    m_activeNonces.AddOrUpdate(nonce, key => new Tuple <DateTime, string>(expires, pwd), (key, existingValue) =>
                    {
                        // Simulate the original behavior => if the nonce, against all odds, is already used
                        // we throw an ArgumentException
                        throw new ArgumentException("An element with the same key already exists in the dictionary.");
                    });

                    response.Cookies.Add(new HttpServer.ResponseCookie(NONCE_COOKIE_NAME, nonce, expires));
                    using (var bw = new BodyWriter(response, request))
                    {
                        bw.OutputOK(new {
                            Status = "OK",
                            Nonce  = nonce,
                            Salt   = Program.DataConnection.ApplicationSettings.WebserverPasswordSalt
                        });
                    }
                    return(true);
                }
                else
                {
                    if (input["password"] != null && !string.IsNullOrWhiteSpace(input["password"].Value))
                    {
                        var nonce_el   = request.Cookies[NONCE_COOKIE_NAME] ?? request.Cookies[Library.Utility.Uri.UrlEncode(NONCE_COOKIE_NAME)];
                        var nonce      = nonce_el == null || string.IsNullOrWhiteSpace(nonce_el.Value) ? "" : nonce_el.Value;
                        var urldecoded = nonce == null ? "" : Duplicati.Library.Utility.Uri.UrlDecode(nonce);
                        if (m_activeNonces.ContainsKey(urldecoded))
                        {
                            nonce = urldecoded;
                        }

                        if (!m_activeNonces.ContainsKey(nonce))
                        {
                            response.Status      = System.Net.HttpStatusCode.Unauthorized;
                            response.Reason      = "Unauthorized";
                            response.ContentType = "application/json";
                            return(true);
                        }

                        var pwd = m_activeNonces[nonce].Item2;

                        // Remove the nonce
                        m_activeNonces.TryRemove(nonce, out tmpTuple);

                        if (pwd != input["password"].Value)
                        {
                            response.Status      = System.Net.HttpStatusCode.Unauthorized;
                            response.Reason      = "Unauthorized";
                            response.ContentType = "application/json";
                            return(true);
                        }

                        var buf     = new byte[32];
                        var expires = DateTime.UtcNow.AddHours(1);
                        m_prng.GetBytes(buf);
                        var token = Duplicati.Library.Utility.Utility.Base64UrlEncode(buf);
                        while (token.Length > 0 && token.EndsWith("=", StringComparison.Ordinal))
                        {
                            token = token.Substring(0, token.Length - 1);
                        }

                        m_activeTokens.AddOrUpdate(token, key => expires, (key, existingValue) =>
                        {
                            // Simulate the original behavior => if the token, against all odds, is already used
                            // we throw an ArgumentException
                            throw new ArgumentException("An element with the same key already exists in the dictionary.");
                        });

                        response.Cookies.Add(new  HttpServer.ResponseCookie(AUTH_COOKIE_NAME, token, expires));

                        using (var bw = new BodyWriter(response, request))
                            bw.OutputOK();

                        return(true);
                    }
                }
            }

            var limitedAccess =
                request.Uri.AbsolutePath.StartsWith(RESTHandler.API_URI_PATH, StringComparison.OrdinalIgnoreCase)
            ;

            // Override to allow the CAPTCHA call to go through
            if (request.Uri.AbsolutePath.StartsWith(CAPTCHA_IMAGE_URI, StringComparison.OrdinalIgnoreCase) && request.Method == "GET")
            {
                limitedAccess = false;
            }

            if (limitedAccess)
            {
                if (xsrf_token != null && m_activexsrf.ContainsKey(xsrf_token))
                {
                    var expires = DateTime.UtcNow.AddMinutes(XSRF_TIMEOUT_MINUTES);
                    m_activexsrf[xsrf_token] = expires;
                    response.Cookies.Add(new ResponseCookie(XSRF_COOKIE_NAME, xsrf_token, expires));
                }
                else
                {
                    response.Status = System.Net.HttpStatusCode.BadRequest;
                    response.Reason = "Missing XSRF Token. Please reload the page";

                    return(true);
                }
            }

            if (string.IsNullOrWhiteSpace(Program.DataConnection.ApplicationSettings.WebserverPassword))
            {
                return(false);
            }

            foreach (var k in (from n in m_activeTokens where DateTime.UtcNow > n.Value select n.Key))
            {
                m_activeTokens.TryRemove(k, out tmpDateTime);
            }


            // If we have a valid token, proceed
            if (!string.IsNullOrWhiteSpace(auth_token))
            {
                DateTime expires;
                var      found = m_activeTokens.TryGetValue(auth_token, out expires);
                if (!found)
                {
                    auth_token = Duplicati.Library.Utility.Uri.UrlDecode(auth_token);
                    found      = m_activeTokens.TryGetValue(auth_token, out expires);
                }

                if (found && DateTime.UtcNow < expires)
                {
                    expires = DateTime.UtcNow.AddHours(1);

                    m_activeTokens[auth_token] = expires;
                    response.Cookies.Add(new ResponseCookie(AUTH_COOKIE_NAME, auth_token, expires));
                    return(false);
                }
            }

            if ("/".Equals(request.Uri.AbsolutePath, StringComparison.OrdinalIgnoreCase) || "/index.html".Equals(request.Uri.AbsolutePath, StringComparison.OrdinalIgnoreCase))
            {
                response.Redirect("/login.html");
                return(true);
            }

            if (limitedAccess)
            {
                response.Status = System.Net.HttpStatusCode.Unauthorized;
                response.Reason = "Not logged in";
                response.AddHeader("Location", "login.html");

                return(true);
            }

            return(false);
        }
コード例 #19
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
 private void DownloadBugReport(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
 {
     RESTHandler.HandleControlCGI(request, response, session, bw, typeof(RESTMethods.BugReport));
 }
コード例 #20
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
 private void SetServerOptions(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
 {
     request.Method = "PATCH";
     RESTHandler.HandleControlCGI(request, response, session, bw, typeof(RESTMethods.ServerSettings));
 }
コード例 #21
0
        public static IHttpClientContext GetContext(HttpServer.IHttpResponse response)
        {
            var f = response.GetType().GetField("_context", BindingFlags.Instance | BindingFlags.NonPublic);

            return((IHttpClientContext)f.GetValue(response));
        }
コード例 #22
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
 private void ImportBackup(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
 {
     RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.Backups).Name.ToLowerInvariant(), "import");
 }
コード例 #23
0
        public override bool Process(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session)
        {
            if (!request.Uri.AbsolutePath.StartsWith("/capture"))
            {
                return(false);
            }
            HttpServerUtil.DebugPrintRequest(request);

            HttpInputItem        deviceIdParam = request.Param["id"];
            CaptureDevice        device;
            CaptureDeviceHandler captureDevice;

            // First, get the specified lowlevel capture device
            if (deviceIdParam.Count == 1)
            {
                device = WasapiLoopbackCapture2.GetLoopbackCaptureDevices()[int.Parse(deviceIdParam.Value)];
            }
            else
            {
                device = WasapiLoopbackCapture2.GetDefaultLoopbackCaptureDevice();
            }

            // Then, get the capture device handler
            if (captureDevices.ContainsKey(device))
            {
                captureDevice = captureDevices[device];
            }
            else
            {
                captureDevice = new CaptureDeviceHandler(device);
                captureDevices.Add(device, captureDevice);
            }

            response.ContentLength = long.MaxValue;
            response.ContentType   = String.Format("audio/L16;rate={0};channels={1}",
                                                   captureDevice.WaveFormat.SampleRate,
                                                   captureDevice.WaveFormat.Channels);
            response.AddHeader("TransferMode.DLNA.ORG", "Streaming");
            response.AddHeader("Server", "UPnP/1.0 DLNADOC/1.50 LAB/1.0");
            response.AddHeader("icy-name", "Local Audio Broadcast");

            // create local output buffers
            CircleBuffer captureBuffer = new CircleBuffer(BUFFER_SIZE);

            byte[] buffer         = new byte[BUFFER_SIZE];
            byte[] emptiness100ms = new byte[captureDevice.WaveFormat.SampleRate / 10
                                             * captureDevice.WaveFormat.Channels
                                             * (captureDevice.WaveFormat.BitsPerSample / 8)];

            // register buffer for being filled with loopback samples
            captureDevice.Add(captureBuffer);

            IDataSource data = captureBuffer;

            EventHandler <TrackInfoChangedEventArgs> trackInfoHandler = null;

            if (request.Headers["Icy-MetaData"] == "1")
            {
                ShoutcastMetadataEmbedder me = new ShoutcastMetadataEmbedder(
                    captureDevice.WaveFormat.SampleRate * 2, // 1 second interval
                    captureBuffer);
                response.ProtocolVersion = "ICY";
                response.AddHeader("icy-metaint", me.Interval + "");
                data = me;
                me.SetTrackInfo(trackInfoProvider.TrackInfo);
                trackInfoHandler = new EventHandler <TrackInfoChangedEventArgs>(delegate(object sender, TrackInfoChangedEventArgs e) {
                    me.SetTrackInfo(e.TrackInfo);
                });
                trackInfoProvider.TrackInfoChanged += trackInfoHandler;
            }

            HttpServerUtil.DebugPrintResponse(response);
            Socket socket = HttpServerUtil.GetNetworkSocket(response);

            response.SendHeaders();

            int bytesRead = 0;

            while (socket.Connected)
            {
                Thread.Sleep(100);
                while (captureBuffer.Empty)
                {
                    //Thread.Sleep(200);
                    captureBuffer.Write(emptiness100ms, 0, emptiness100ms.Length);
                }
                lock (captureDevice.lockObject) {
                    bytesRead = data.Read(buffer, 0, buffer.Length);
                }
                //Console.WriteLine("buffer-{3} r {0} - {1} = {2}%", loopbackBuffer.FillLevel + bytesRead, bytesRead,
                //    (float)loopbackBuffer.FillLevel / loopbackBuffer.Length * 100, loopbackBuffer.GetHashCode());
                response.SendBody(buffer, 0, bytesRead);

                Console.WriteLine("sending {0} bytes = {1:0.00} secs", bytesRead, bytesRead /
                                  (double)captureDevice.loopbackCapture.WaveFormat.AverageBytesPerSecond);
            }

            if (trackInfoHandler != null)
            {
                trackInfoProvider.TrackInfoChanged -= trackInfoHandler;
            }

            // remove local output buffer
            captureDevice.Remove(captureBuffer);

            Console.WriteLine("request processing finished");

            return(true);
        }
コード例 #24
0
        public override bool Process(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session)
        {
            HttpServer.HttpInput input = request.Method.ToUpper() == "POST" ? request.Form : request.QueryString;

            var authcookie = request.Cookies[AUTH_COOKIE_NAME] ?? request.Cookies[Library.Utility.Uri.UrlEncode(AUTH_COOKIE_NAME)];
            var authinput  = input["auth-token"] ?? input[Library.Utility.Uri.UrlEncode("auth-token")];

            var auth_token = authcookie == null || string.IsNullOrWhiteSpace(authcookie.Value) ? null : authcookie.Value;

            if (authinput != null && !string.IsNullOrWhiteSpace(authinput.Value))
            {
                auth_token = input["auth-token"].Value;
            }

            if (request.Uri.AbsolutePath == "/logout.cgi")
            {
                if (!string.IsNullOrWhiteSpace(auth_token))
                {
                    if (m_activeTokens.ContainsKey(auth_token))
                    {
                        m_activeTokens.Remove(auth_token);
                    }
                }

                response.Status = System.Net.HttpStatusCode.NoContent;
                response.Reason = "OK";

                return(true);
            }
            else if (request.Uri.AbsolutePath == "/login.cgi")
            {
                foreach (var k in (from n in m_activeNonces where DateTime.UtcNow > n.Value.Item1 select n.Key).ToList())
                {
                    m_activeNonces.Remove(k);
                }

                if (input["get-nonce"] != null && !string.IsNullOrWhiteSpace(input["get-nonce"].Value))
                {
                    if (m_activeNonces.Count > 50)
                    {
                        response.Status = System.Net.HttpStatusCode.ServiceUnavailable;
                        response.Reason = "Too many active login attempts";
                        return(true);
                    }

                    var buf     = new byte[32];
                    var expires = DateTime.UtcNow.AddMinutes(10);
                    m_prng.GetBytes(buf);
                    var nonce = Convert.ToBase64String(buf);

                    var sha256 = System.Security.Cryptography.SHA256.Create();
                    sha256.TransformBlock(buf, 0, buf.Length, buf, 0);
                    buf = Convert.FromBase64String(Program.DataConnection.ApplicationSettings.WebserverPassword);
                    sha256.TransformFinalBlock(buf, 0, buf.Length);
                    var pwd = Convert.ToBase64String(sha256.Hash);

                    m_activeNonces.Add(nonce, new Tuple <DateTime, string>(expires, pwd));

                    response.Cookies.Add(new HttpServer.ResponseCookie(NONCE_COOKIE_NAME, nonce, expires));
                    using (var bw = new BodyWriter(response))
                    {
                        bw.OutputOK(new {
                            Status = "OK",
                            Nonce  = nonce,
                            Salt   = Program.DataConnection.ApplicationSettings.WebserverPasswordSalt
                        });
                    }
                    return(true);
                }
                else
                {
                    if (input["password"] != null && !string.IsNullOrWhiteSpace(input["password"].Value))
                    {
                        var nonce_el   = request.Cookies[NONCE_COOKIE_NAME] ?? request.Cookies[Library.Utility.Uri.UrlEncode(NONCE_COOKIE_NAME)];
                        var nonce      = nonce_el == null || string.IsNullOrWhiteSpace(nonce_el.Value) ? "" : nonce_el.Value;
                        var urldecoded = nonce == null ? "" : Duplicati.Library.Utility.Uri.UrlDecode(nonce);
                        if (m_activeNonces.ContainsKey(urldecoded))
                        {
                            nonce = urldecoded;
                        }

                        if (!m_activeNonces.ContainsKey(nonce))
                        {
                            response.Status      = System.Net.HttpStatusCode.Unauthorized;
                            response.Reason      = "Unauthorized";
                            response.ContentType = "application/json";
                            return(true);
                        }

                        var pwd = m_activeNonces[nonce].Item2;
                        m_activeNonces.Remove(nonce);

                        if (pwd != input["password"].Value)
                        {
                            response.Status      = System.Net.HttpStatusCode.Unauthorized;
                            response.Reason      = "Unauthorized";
                            response.ContentType = "application/json";
                            return(true);
                        }

                        var buf     = new byte[32];
                        var expires = DateTime.UtcNow.AddHours(1);
                        m_prng.GetBytes(buf);
                        var token = Duplicati.Library.Utility.Utility.Base64UrlEncode(buf);
                        while (token.Length > 0 && token.EndsWith("="))
                        {
                            token = token.Substring(0, token.Length - 1);
                        }

                        m_activeTokens.Add(token, expires);
                        response.Cookies.Add(new  HttpServer.ResponseCookie(AUTH_COOKIE_NAME, token, expires));

                        using (var bw = new BodyWriter(response))
                            bw.OutputOK();

                        return(true);
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(Program.DataConnection.ApplicationSettings.WebserverPassword))
            {
                return(false);
            }

            foreach (var k in (from n in m_activeTokens where DateTime.UtcNow > n.Value select n.Key).ToList())
            {
                m_activeTokens.Remove(k);
            }


            // If we have a valid token, proceeed
            if (!string.IsNullOrWhiteSpace(auth_token))
            {
                DateTime expires;
                var      found = m_activeTokens.TryGetValue(auth_token, out expires);
                if (!found)
                {
                    auth_token = Duplicati.Library.Utility.Uri.UrlDecode(auth_token);
                    found      = m_activeTokens.TryGetValue(auth_token, out expires);
                }

                if (found && DateTime.UtcNow < expires)
                {
                    expires = DateTime.UtcNow.AddHours(1);
                    m_activeTokens[auth_token] = expires;
                    response.Cookies.Add(new ResponseCookie(AUTH_COOKIE_NAME, auth_token, expires));
                    return(false);
                }
            }

            if (request.Uri.AbsolutePath == "/" || request.Uri.AbsolutePath == "/index.html")
            {
                response.Redirect("/login.html");
                return(true);
            }

            if (request.Uri.AbsolutePath == "/control.cgi")
            {
                response.Status = System.Net.HttpStatusCode.Unauthorized;
                response.Reason = "Not logged in";
                response.AddHeader("Location", "login.html");

                return(true);
            }

            return(false);
        }
コード例 #25
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
 private void GetNotifications(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
 {
     RESTHandler.HandleControlCGI(request, response, session, bw, typeof(RESTMethods.Notifications));
 }
コード例 #26
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
 private void DismissNotification(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
 {
     request.Method = "DELETE";
     RESTHandler.HandleControlCGI(request, response, session, bw, typeof(RESTMethods.Notification));
 }
コード例 #27
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
 private void GetUISettingSchemes(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
 {
     RESTHandler.HandleControlCGI(request, response, session, bw, typeof(RESTMethods.UISettings));
 }
コード例 #28
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
        public override bool Process(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session)
        {
            //We use the fake entry point /control.cgi to listen for requests
            //This ensures that the rest of the webserver can just serve plain files
            if (!request.Uri.AbsolutePath.Equals(CONTROL_HANDLER_URI, StringComparison.InvariantCultureIgnoreCase))
            {
                return(false);
            }

            HttpServer.HttpInput input = request.Method.ToUpper() == "POST" ? request.Form : request.QueryString;

            string action = input["action"].Value ?? "";

            //Lookup the actual handler method
            ProcessSub method;

            SUPPORTED_METHODS.TryGetValue(action, out method);

            if (method == null)
            {
                response.Status = System.Net.HttpStatusCode.NotImplemented;
                response.Reason = "Unsupported action: " + (action == null ? "<null>" : "");
                response.Send();
            }
            else
            {
                //Default setup
                response.Status = System.Net.HttpStatusCode.OK;
                response.Reason = "OK";
                #if DEBUG
                response.ContentType = "text/plain";
                #else
                response.ContentType = "text/json";
                #endif
                using (BodyWriter bw = new BodyWriter(response, request))
                {
                    try
                    {
                        method(request, response, session, bw);
                    }
                    catch (Exception ex)
                    {
                        Program.DataConnection.LogError("", string.Format("Request for {0} gave error", action), ex);
                        Console.WriteLine(ex.ToString());

                        try
                        {
                            if (!response.HeadersSent)
                            {
                                response.Status      = System.Net.HttpStatusCode.InternalServerError;
                                response.Reason      = "Error";
                                response.ContentType = "text/plain";

                                bw.WriteJsonObject(new
                                {
                                    Message = ex.Message,
                                    Type    = ex.GetType().Name,
                                    #if DEBUG
                                    Stacktrace = ex.ToString()
                                    #endif
                                });
                                bw.Flush();
                            }
                        }
                        catch (Exception flex)
                        {
                            Program.DataConnection.LogError("", "Reporting error gave error", flex);
                        }
                    }
                }
            }

            return(true);
        }
コード例 #29
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
        private void SendCommand(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
        {
            HttpServer.HttpInput input = request.Method.ToUpper() == "POST" ? request.Form : request.QueryString;

            string command = input["command"].Value ?? "";

            switch (command.ToLowerInvariant())
            {
            case "check-update":
                RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.Updates).Name.ToLowerInvariant(), "check");
                return;

            case "install-update":
                RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.Updates).Name.ToLowerInvariant(), "install");
                return;

            case "activate-update":
                RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.Updates).Name.ToLowerInvariant(), "activate");
                return;

            case "pause":
                RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.ServerState).Name.ToLowerInvariant(), "pause");
                return;

            case "resume":
                RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.ServerState).Name.ToLowerInvariant(), "resume");
                return;

            case "stop":
            case "abort":
            {
                var key = string.Format("{0}/{1}", input["taskid"].Value, command);
                RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.Task).Name.ToLowerInvariant(), key);
            }
                return;

            case "is-backup-active":
            {
                var key = string.Format("{0}/isactive", Library.Utility.Uri.UrlPathEncode(input["id"].Value));
                RESTHandler.DoProcess(request, response, session, "GET", typeof(RESTMethods.Backup).Name.ToLowerInvariant(), key);
            }
                return;

            case "run":
            case "run-backup":
            {
                var key = string.Format("{0}/start", Library.Utility.Uri.UrlPathEncode(input["id"].Value));
                RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.Backup).Name.ToLowerInvariant(), key);
            }
                return;

            case "run-verify":
            {
                var key = string.Format("{0}/verify", Library.Utility.Uri.UrlPathEncode(input["id"].Value));
                RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.Backup).Name.ToLowerInvariant(), key);
            }
                return;

            case "run-repair-update":
            {
                var key = string.Format("{0}/repairupdate", Library.Utility.Uri.UrlPathEncode(input["id"].Value));
                RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.Backup).Name.ToLowerInvariant(), key);
            }
                return;

            case "run-repair":
            {
                var key = string.Format("{0}/repair", Library.Utility.Uri.UrlPathEncode(input["id"].Value));
                RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.Backup).Name.ToLowerInvariant(), key);
            }
                return;

            case "create-report":
            {
                var key = string.Format("{0}/createreport", Library.Utility.Uri.UrlPathEncode(input["id"].Value));
                RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.Backup).Name.ToLowerInvariant(), key);
            }
                return;

            default:
            {
                var key = string.Format("{0}", Library.Utility.Uri.UrlPathEncode(input["command"].Value));
                RESTHandler.DoProcess(request, response, session, "POST", typeof(RESTMethods.WebModule).Name.ToLowerInvariant(), key);
                return;
            }
            }
        }
コード例 #30
0
ファイル: ControlHandler.cs プロジェクト: xuchrist/duplicati
 private void GetBackupDefaults(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
 {
     RESTHandler.HandleControlCGI(request, response, session, bw, typeof(RESTMethods.BackupDefaults));
 }