Exemplo n.º 1
0
            //-------------------
            // Run this thread to make sure connections are always being handled for inbound requests
            private async Task ListenerUpdate(string prefixURL, int numListenerThreads, CancellationToken token)
            {
                List <Task> listenerTasks = new List <Task>(numListenerThreads);

                // Create a local cancellation token source which goes away at the end of this function/task
                try
                {
                    // Turn on the webserver
                    while (token.IsCancellationRequested == false)
                    {
                        // Populate the task set in a non-concurrent dictionary
                        while (listenerTasks.Count < numListenerThreads)
                        {
                            Task t = Task <HttpListenerContext> .Run(() => { return(_listener?.GetContextAsync()); }, token).ContinueWith(HandleConnection, token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current);

                            listenerTasks.Add(t);
                            _logger?.Invoke("WebSocketServer.ListenerUpdate - adding listener", 2);
                        }

                        using (Task finished = await Task.WhenAny(listenerTasks).ConfigureAwait(false))                          // when a connection listener task is completed, terminate it
                        {
                            listenerTasks.Remove(finished);
                            _logger?.Invoke("WebSocketServer.ListenerUpdate - listener handled", 2);
                        }
                    }
                }
                catch (OperationCanceledException)                  // if the token is cancelled, we pop to here
                {
                }
                catch (Exception e)
                {
                    _logger?.Invoke($"WebSocketServer.ListenerUpdate - caught unexpected exception {e.Message}", 0);
                }
                finally
                {
                    _logger?.Invoke("WebSocketServer.ListenerUpdate - disposing listener tasks", 1);
                    for (int i = 0; i < listenerTasks.Count; i++)
                    {
                        try
                        {
                            await listenerTasks[i];                              // this should throw an OperationCanceledException
                        }
                        catch (OperationCanceledException)
                        {
                            // expected
                        }
                        catch (Exception e)
                        {
                            _logger?.Invoke($"WebSocketServer.ListenerUpdate - disposing listener tasks caught unexpected exception {e.Message}", 0);
                        }
                        listenerTasks[i].Dispose();
                    }
                    listenerTasks.Clear();
                    _logger?.Invoke("WebSocketServer.ListenerUpdate - listener tasks dead", 1);
                }
            }
Exemplo n.º 2
0
        private static async Task HandleRequests()
        {
            if (IsHandlingRequests)
            {
                return;
            }

            IsHandlingRequests = true;

            try {
                while (IsListening)
                {
                    Task <HttpListenerContext> task = HttpListener?.GetContextAsync();
                    if (task == null)
                    {
                        return;
                    }

                    HttpListenerContext context;

                    try {
                        context = await task.ConfigureAwait(false);
                    } catch (HttpListenerException e) {
                        // If HttpListener is null then we're stopping HttpListener, so this exception is expected, ignore it
                        if (HttpListener == null)
                        {
                            return;
                        }

                        // Otherwise this is an error, and HttpListener can dispose itself in this situation, so don't keep it around
                        HttpListener = null;
                        ASF.ArchiLogger.LogGenericException(e);
                        return;
                    }

                    Utilities.StartBackgroundFunction(() => HandleRequest(context), false);
                }
            } finally {
                IsHandlingRequests = false;
            }
        }
Exemplo n.º 3
0
        public static async Task SimpleRequest_Succeeds()
        {
            string url = UrlPrefix.CreateLocal();
            const string expectedResponse = "hello from HttpListener";

            using (HttpListener listener = new HttpListener())
            {
                listener.Prefixes.Add(url);
                listener.Start();

                var serverContextTask = listener.GetContextAsync();

                using (HttpClient client = new HttpClient())
                {
                    var clientTask = client.GetStringAsync(url);

                    var serverContext = await serverContextTask;
                    using (var response = serverContext.Response)
                    {
                        var responseBuffer = Encoding.UTF8.GetBytes(expectedResponse);
                        response.ContentLength64 = responseBuffer.Length;

                        using (var output = response.OutputStream)
                        {
                            await output.WriteAsync(responseBuffer, 0, responseBuffer.Length);
                        }
                    }

                    var clientString = await clientTask;

                    Assert.Equal(expectedResponse, clientString);
                }

                listener.Stop();
            }
        }
Exemplo n.º 4
0
        // Keep on handling requests
        public static async Task HandleIncomingConnections()
        {
            while (true)
            {
                // Will wait here until we hear from a connection
                HttpListenerContext ctx = await listener.GetContextAsync();

                // Peel out the requests and response objects
                HttpListenerRequest  req  = ctx.Request;
                HttpListenerResponse resp = ctx.Response;

                int    status            = 200;
                string statusDescription = "OK";
                string json = "";

                Error[] errors = new Error[1];

                if (req.Url.AbsolutePath == "/" + type)
                {
                    //OK
                    if (req.HttpMethod == "GET")
                    {   //Return sessionid
                        try
                        {
                            //Create new payment session
                            Session session = new Session(Double.Parse(req.QueryString["amount"]),
                                                          req.QueryString["purpose"]);
                            json = JsonConvert.SerializeObject(new Data(type,
                                                                        session.sessionId.ToString()));
                        }
                        catch (Exception e)
                        {
                            //Error: amount or purpose is not exists
                            errors[0]         = new Error(400, "Amount or purpose is missing!", 6);
                            json              = JsonConvert.SerializeObject(errors);
                            status            = 400;
                            statusDescription = "Bad Request";
                            Console.WriteLine(e);
                        }
                    }
                    else if (req.HttpMethod == "POST")
                    {   //Make payment
                        try
                        {
                            //Read request body
                            dynamic request = JsonConvert.DeserializeObject(
                                ReadInputStream(req.InputStream));

                            if (request.type == type)
                            {
                                Session session = Session.Find(Guid.Parse((string)request.id));
                                if (session != null)
                                {
                                    Card card = new Card((string)request.attributes.number, (int)request.attributes.CVVCVC,
                                                         (int)request.attributes.year, (int)request.attributes.mounth,
                                                         (string)request.attributes.URL);

                                    //Сheck the data is full
                                    if (card.number.Length >= 4 && card.CVVCVC >= 100 && card.CVVCVC <= 999 &&
                                        card.mounth >= 1 && card.year >= 0 && card.URL != "")
                                    {
                                        //Check the card number in Luna algorithm
                                        if (SimpleLuna(card.number))
                                        {
                                            //Payment successful
                                            json = JsonConvert.SerializeObject(new Data(type,
                                                                                        session.sessionId.ToString()));

                                            //Send http-notice
                                            HttpNotice(card.URL, session.sessionId, session.purpose,
                                                       card.number, session.amount);
                                        }
                                        else
                                        {
                                            //Error: the card number is not correct
                                            errors[0]         = new Error(400, "The card number is not correct!", 1);
                                            json              = JsonConvert.SerializeObject(errors);
                                            status            = 400;
                                            statusDescription = "Bad Request";
                                        }
                                    }
                                    else
                                    {
                                        //Error: the card data is not correct
                                        errors[0]         = new Error(400, "The card data is not correct!", 2);
                                        json              = JsonConvert.SerializeObject(errors);
                                        status            = 400;
                                        statusDescription = "Bad Request";
                                    }

                                    //Delete used session
                                    Session.list.Remove(session);
                                }
                                else
                                {
                                    //Error: dead session
                                    errors[0]         = new Error(400, "Dead session!", 3);
                                    json              = JsonConvert.SerializeObject(errors);
                                    status            = 400;
                                    statusDescription = "Bad Request";
                                }
                            }
                            else
                            {
                                //Error: unknown request type
                                errors[0]         = new Error(400, "Unknown request type!", 4);
                                json              = JsonConvert.SerializeObject(errors);
                                status            = 400;
                                statusDescription = "Bad Request";
                            }
                        }
                        catch (Exception e)
                        {
                            if (e.GetType().Name == "UriFormatException")
                            {
                                errors[0]         = new Error(400, "Invalid URL!", 4);
                                json              = JsonConvert.SerializeObject(errors);
                                status            = 400;
                                statusDescription = "Bad Request";
                            }
                            else if (e.GetType().Name == "FormatException")
                            {
                                errors[0]         = new Error(400, "Bad Request", 7);
                                json              = JsonConvert.SerializeObject(errors);
                                status            = 400;
                                statusDescription = "Bad Request";
                            }
                            else
                            {
                                //Error: 500 - Internal Server Error
                                status            = 500;
                                statusDescription = "Internal Server Error";
                                Console.WriteLine(e);
                            }
                        }
                    }
                    else
                    {
                        //Error: unknown method
                        errors[0]         = new Error(400, "Unknown method!", 5);
                        json              = JsonConvert.SerializeObject(errors);
                        status            = 400;
                        statusDescription = "Bad Request";
                    }
                }
                else
                {
                    //Error: resource not found
                    status            = 404;
                    statusDescription = "Not Found";
                }

                byte[] data = Encoding.UTF8.GetBytes(json);
                resp.StatusCode        = status;
                resp.StatusDescription = statusDescription;
                resp.ContentType       = "application/vnd.api+json";
                resp.ContentEncoding   = Encoding.UTF8;
                resp.ContentLength64   = data.LongLength;

                // Write out to the response stream (asynchronously), then close it
                await resp.OutputStream.WriteAsync(data, 0, data.Length);

                resp.Close();
            }
        }
Exemplo n.º 5
0
        static async Task Main(string[] args)
        {
            var users = new List<User>();
            using var listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:80/");
            listener.Start();
            const string GIVE = "GIVE";
            const string ADD = "ADD";
            const string UPDATE = "UPDATE";
            const string REMOVE = "REMOVE";
            using var contextDb = new ContextDb();
            Console.WriteLine("Готов к работе");

            while (true)
            {
                users.Clear();
                users = contextDb.Users.Where(u => u.IsDeleted == false).ToList();
                using var context = await listener.GetContextAsync();

                var request = context.Request;
                IncomeUri = request.RawUrl;
                var response = context.Response;

                //using var stream = client.GetStream();
                //var resultText = string.Empty;
                //var buffer = new byte[1024];
                //stream.Read(buffer, 0, buffer.Length);
                ////resultText += Encoding.UTF8.GetString(buffer).TrimEnd('\0');

                //var response = JsonConvert.DeserializeObject<Response>(resultText);

                if (response.Path == "user")
                {
                    if (response.Action == GIVE)
                    {
                        StringBuilder stringBuilder = ParseSpecialType(users);
                        var answer = Encoding.UTF8.GetBytes(stringBuilder.ToString());
                        stream.Write(answer, 0, answer.Length);
                        Console.WriteLine($"[{DateTime.Now}]\tОтправка таблицы с пользователями...");
                    }
                    else if (response.Action == ADD)
                    {
                        var user = new User()
                        {
                            Name = response.Value,
                        };
                        contextDb.Users.Add(user);
                        contextDb.SaveChanges();
                        Console.WriteLine($"[{DateTime.Now}]\tДобавления пользователя {user.Id} - {user.Name}...");
                    }
                    else if (response.Action == UPDATE)
                    {
                        try
                        {
                            var user = users.FirstOrDefault(x => x.Id == int.Parse(response.Value));
                            var oldName = user.Name;
                            user.Name = response.NewData;
                            contextDb.Update(user);
                            contextDb.SaveChanges();
                            Console.WriteLine($"[{DateTime.Now}]\tОбновление пользователя {user.Id} - {oldName} на {user.Id} - {response.NewData}...");
                        }
                        catch
                        {
                            var error = "Вы ввели неверный ID";
                            var answer = Encoding.UTF8.GetBytes(error);
                            stream.Write(answer, 0, answer.Length);
                        }
                    }
                    else if (response.Action == REMOVE)
                    {
                        try
                        {
                            var user = contextDb.Users.FirstOrDefault(x => x.Id == int.Parse(response.Value));
                            user.IsDeleted = true;
                            contextDb.Update(user);
                            contextDb.SaveChanges();
                            Console.WriteLine($"[{DateTime.Now}]\tУдаление пользователя {user.Id} - {user.Name}...");
                        }
                        catch
                        {
                            var error = "Вы ввели неверный ID";
                            var answer = Encoding.UTF8.GetBytes(error);
                            stream.Write(answer, 0, answer.Length);
                        }
                    }
                }

                try
                {
                    switch (context.Request.Url.AbsolutePath)
                    {
                        case "/users/give/":
                            if (context.Request.HttpMethod == POST)
                            {

                            }

                            break;
                        case "/users/add/":
                            if (context.Request.HttpMethod == ADD)
                            {
                                try
                                {
                                    using var body = context.Request.InputStream;
                                    using var reader = new StreamReader(body, context.Request.ContentEncoding);

                                    var json = reader.ReadToEnd();
                                    var user = JsonConvert.DeserializeObject<User>(json);

                                    var userDb = contextDb.Users.FirstOrDefault(x => x.Name == user.Name);
                                    if (userDb == null)
                                    {
                                        await contextDb.Users.AddAsync(user);
                                        await contextDb.SaveChangesAsync();
                                        Console.WriteLine($"[{DateTime.Now}]\tДобавления пользователя {user.Id} - {user.Name}...");
                                        response.StatusCode = (int)HttpStatusCode.Created;
                                    }
                                    else
                                    {
                                        response.StatusCode = (int)HttpStatusCode.Forbidden;
                                    }
                                }
                                catch (Exception exception)
                                {
                                    response.StatusCode = (int)HttpStatusCode.Forbidden;
                                    //var exceptionJson = JsonConvert.SerializeObject<Exception>(exception);

                                }

                            }
                            break;
                        case "/users/update":
                            if (context.Request.HttpMethod == POST)
                            {
                                try
                                {
                                    using var body = context.Request.InputStream;
                                    using var reader = new StreamReader(body, context.Request.ContentEncoding);

                                    var json = reader.ReadToEnd();
                                    var user = JsonConvert.DeserializeObject<User>(json);
                                    var user = contextDb.Users.FirstOrDefault(x => x.Id == int.Parse(user.Id));
                                    contextDb.Update(user);
                                    await contextDb.SaveChangesAsync();
                                    response.StatusCode = (int)HttpStatusCode.OK;
                                }
                                catch
                                {
                                    response.StatusCode = (int)HttpStatusCode.NotFound;
                                }
                            }
                            break;
                        case "/users/delete":
                            if (context.Request.HttpMethod == POST)
                            {

                            }
                            break;
                        default:
                            response.StatusCode = (int)HttpStatusCode.BadRequest;
                            break;
                    }

                }
                catch (Exception exception)
                {
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    response.ContentType = "application/json";
                    var buffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(exception));
                    response.ContentLength64 = buffer.Length;
                    response.OutputStream.Write(buffer, 0, buffer.Length);
                }

                response.Close();
            }
        }
Exemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="uriPrefixes"></param>
        /// <returns></returns>
        public Task Run(params string[] uriPrefixes)
        {
            Error = null;
            // Establish a host-handler context:
            _hostContext = new HostContext(this, _handler);

            _listener.IgnoreWriteExceptions = true;

            if (uriPrefixes.Length == 0)
            {
                TraceLog.WriteError("Http start listenning url is null");
            }
            // Add the server bindings:
            foreach (var prefix in uriPrefixes)
            {
                _listener.Prefixes.Add(prefix.EndsWith("/") ? prefix : prefix + "/");
            }

            return(Task.Run(async() =>
            {
                // Configure the handler:
                if (_configValues != null)
                {
                    var config = _handler as IConfigurationTrait;
                    if (config != null)
                    {
                        var task = config.Configure(_hostContext, _configValues);
                        if (task != null)
                        {
                            if (!await task)
                            {
                                return;
                            }
                        }
                    }
                }

                // Initialize the handler:
                var init = _handler as IInitializationTrait;
                if (init != null)
                {
                    var task = init.Initialize(_hostContext);
                    if (task != null)
                    {
                        if (!await task)
                        {
                            return;
                        }
                    }
                }

                try
                {
                    // Start the HTTP listener:
                    _listener.Start();
                }
                catch (HttpListenerException hlex)
                {
                    Error = hlex;
                    TraceLog.WriteError("Http start listenning error:{0}", hlex);
                    return;
                }

                // Accept connections:
                // Higher values mean more connections can be maintained yet at a much slower average response time; fewer connections will be rejected.
                // Lower values mean less connections can be maintained yet at a much faster average response time; more connections will be rejected.
                var sem = new Semaphore(_accepts, _accepts);

                while (true)
                {
                    sem.WaitOne();

#pragma warning disable 4014
                    _listener.GetContextAsync().ContinueWith(async(t) =>
                    {
                        try
                        {
                            sem.Release();
                            var ctx = await t;
                            await ProcessListenerContext(ctx, this);

                            return;
                        }
                        catch (Exception ex)
                        {
                            TraceLog.WriteError("Http request unknow error:{0}", ex);
                        }
                    });
#pragma warning restore 4014
                }
            }));
        }
Exemplo n.º 7
0
        private async void BrowserLoginForm_Load(object sender, EventArgs e)
        {
            //webBrowser1.Navigate(new Uri(tenantUrl));

            // Generates state and PKCE values.
            string state          = randomDataBase64url(32);
            string code_verifier  = randomDataBase64url(32);
            string code_challenge = base64urlencodeNoPadding(sha256(code_verifier));

            // Creates an HttpListener to listen for requests on that redirect URI.
            var http = new HttpListener();

            http.Prefixes.Add(redirectURI);

            http.Start();

            // Creates the OAuth 2.0 authorization request.
            string params_endpoint = "?client_id=" + clientID +
                                     "&scope=openid email phone address groups profile" +
                                     "&response_type=code" +
                                     "&response_mode=query" +
                                     "&nonce=" + "nonceStatic" +
                                     "&redirect_uri=" + redirectURI +
                                     "&state=" + state +
                                     "&sessionToken=" + "session_no_needed";
            string authorizationRequest = tenantUrl + "/oauth2/v1/authorize" + params_endpoint;


            // Sending request to the browser.
            //System.Diagnostics.Process.Start(authorizationRequest);
            webBrowser1.ScriptErrorsSuppressed = true;
            webBrowser1.Navigate(new Uri(authorizationRequest));

            // Waits for the OAuth authorization response.
            var context = await http.GetContextAsync();

            // Bring focus back to the app.
            this.Activate();


            // Sends an HTTP response to the browser.
            var    response       = context.Response;
            string responseString = string.Format("<html><head><meta http-equiv='refresh' content='10;url=https://okta.com'></head><body>Please return to the okta app.</body></html>");
            var    buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

            response.ContentLength64 = buffer.Length;
            var responseOutput = response.OutputStream;

            System.Threading.Tasks.Task responseTask = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) =>
            {
                responseOutput.Close();
                http.Stop();
                Console.WriteLine("HTTP server stopped.");
            });

            // Checks for errors.
            if (context.Request.QueryString.Get("error") != null)
            {
                //output(String.Format("OAuth authorization error: {0}.", context.Request.QueryString.Get("error")));
                return;
            }
            if (context.Request.QueryString.Get("code") == null ||
                context.Request.QueryString.Get("state") == null)
            {
                //output("Malformed authorization response. " + context.Request.QueryString);
                return;
            }

            // extracts the code
            var code           = context.Request.QueryString.Get("code");
            var incoming_state = context.Request.QueryString.Get("state");

            // Compares the receieved state to the expected value, to ensure that
            // this app made the request which resulted in authorization.
            if (incoming_state != state)
            {
                //output(String.Format("Received request with invalid state ({0})", incoming_state));
                return;
            }
            //output("Authorization code: " + code);

            // Starts the code exchange at the Token Endpoint.
            getAccessToken(code, code_verifier, redirectURI);
        }
Exemplo n.º 8
0
        public static async Task HandleIncomingConnections()
        {
            bool runServer = true;

            // While a user hasn't visited the `shutdown` url, keep on handling requests
            while (runServer)
            {
                // Will wait here until we hear from a connection
                HttpListenerContext ctx = await listener.GetContextAsync();

                // Peel out the requests and response objects
                HttpListenerRequest  req  = ctx.Request;
                HttpListenerResponse resp = ctx.Response;

                // Print out some info about the request
                Console.WriteLine("Request #: {0}", ++requestCount);
                Console.WriteLine(req.Url.ToString());
                Console.WriteLine(req.HttpMethod);
                Console.WriteLine(req.UserHostName);
                Console.WriteLine(req.UserAgent);
                Console.WriteLine();
                var pageData = "";
                // If `shutdown` url requested w/ POST, then shutdown the server after serving the page
                if ((req.HttpMethod == "GET"))
                {
                    switch (req.Url.AbsolutePath)
                    {
                    case "/kick":
                    {
                        if (req.QueryString.Get("player") != "")
                        {
                            var player = playerManager.getPlayer(req.QueryString.Get("player"));
                            if (player != null)
                            {
                                player.Kick("ai lua muie");
                                pageData = $"Playerul {player.Name} a fost dat afara";
                            }
                            else
                            {
                                pageData = $"Playerul nu este online.";
                            }
                        }
                        break;
                    }

                    case "/send":
                    {
                        if (req.QueryString.Get("msg") != "")
                        {
                            NAPI.Chat.SendChatMessageToAll("SERVER: " + req.QueryString.Get("msg"));
                        }
                        break;
                    }

                    case "/playerList":
                    {
                        foreach (var item in NAPI.Pools.GetAllPlayers())
                        {
                            pageData += $"Name: {item.Name} IP Address: {item.Address} Position {NAPI.Util.ToJson(item.Position)}";
                        }
                    }
                    break;
                    }
                }

                // Make sure we don't increment the page views counter if `favicon.ico` is requested
                if (req.Url.AbsolutePath != "/favicon.ico")
                {
                    pageViews += 1;
                }

                // Write the response info
                string disableSubmit = !runServer ? "disabled" : "";
                byte[] data          = Encoding.UTF8.GetBytes(pageData);
                resp.ContentType     = "text/html";
                resp.ContentEncoding = Encoding.UTF8;
                resp.ContentLength64 = data.LongLength;

                // Write out to the response stream (asynchronously), then close it
                await resp.OutputStream.WriteAsync(data, 0, data.Length);

                resp.Close();
            }
        }
Exemplo n.º 9
0
        private async Task AcceptConnections(CancellationToken cancelToken)
        {
            try
            {
                while (true)
                {
                    if (cancelToken.IsCancellationRequested)
                    {
                        break;
                    }
                    if (!_Listener.IsListening)
                    {
                        Task.Delay(100).Wait();
                        continue;
                    }

                    HttpListenerContext ctx = await _Listener.GetContextAsync().ConfigureAwait(false);

                    string ip     = ctx.Request.RemoteEndPoint.Address.ToString();
                    int    port   = ctx.Request.RemoteEndPoint.Port;
                    string ipPort = ip + ":" + port;

                    lock (_PermittedIpsLock)
                    {
                        if (PermittedIpAddresses != null &&
                            PermittedIpAddresses.Count > 0 &&
                            !PermittedIpAddresses.Contains(ip))
                        {
                            Logger?.Invoke(_Header + "rejecting " + ipPort + " (not permitted)");
                            ctx.Response.StatusCode = 401;
                            ctx.Response.Close();
                            continue;
                        }
                    }

                    if (!ctx.Request.IsWebSocketRequest)
                    {
                        if (HttpHandler == null)
                        {
                            Logger?.Invoke(_Header + "non-websocket request rejected from " + ipPort);
                            ctx.Response.StatusCode = 400;
                            ctx.Response.Close();
                        }
                        else
                        {
                            Logger?.Invoke(_Header + "non-websocket request from " + ipPort + " HTTP-forwarded: " + ctx.Request.HttpMethod.ToString() + " " + ctx.Request.RawUrl);
                            HttpHandler.Invoke(ctx);
                        }

                        continue;
                    }
                    else
                    {
                        /*
                         * HttpListenerRequest req = ctx.Request;
                         * Console.WriteLine(Environment.NewLine + req.HttpMethod.ToString() + " " + req.RawUrl);
                         * if (req.Headers != null && req.Headers.Count > 0)
                         * {
                         *  Console.WriteLine("Headers:");
                         *  var items = req.Headers.AllKeys.SelectMany(req.Headers.GetValues, (k, v) => new { key = k, value = v });
                         *  foreach (var item in items)
                         *  {
                         *      Console.WriteLine("  {0}: {1}", item.key, item.value);
                         *  }
                         * }
                         */
                    }

                    await Task.Run(() =>
                    {
                        Logger?.Invoke(_Header + "starting data receiver for " + ipPort);

                        CancellationTokenSource tokenSource = new CancellationTokenSource();
                        CancellationToken token             = tokenSource.Token;

                        Task.Run(async() =>
                        {
                            WebSocketContext wsContext = await ctx.AcceptWebSocketAsync(subProtocol: null);
                            WebSocket ws      = wsContext.WebSocket;
                            ClientMetadata md = new ClientMetadata(ctx, ws, wsContext, tokenSource);

                            _Clients.TryAdd(md.IpPort, md);

                            ClientConnected?.Invoke(this, new ClientConnectedEventArgs(md.IpPort, ctx.Request));
                            await Task.Run(() => DataReceiver(md), token);
                        }, token);
                    }, _Token).ConfigureAwait(false);
                }
            }

            /*
             * catch (HttpListenerException)
             * {
             *  // thrown when disposed
             * }
             */
            catch (TaskCanceledException)
            {
                // thrown when disposed
            }
            catch (OperationCanceledException)
            {
                // thrown when disposed
            }
            catch (ObjectDisposedException)
            {
                // thrown when disposed
            }
            catch (Exception e)
            {
                Logger?.Invoke(_Header + "listener exception:" + Environment.NewLine + e.ToString());
            }
            finally
            {
                ServerStopped?.Invoke(this, EventArgs.Empty);
            }
        }
Exemplo n.º 10
0
        public static async Task <string> GetRefreshToken(string clientId, string clientSecret, string appName, GoogleScopes googleScope)
        {
            // Generates state and PKCE values.
            var          state               = RandomDataBase64Url(32);
            var          codeVerifier        = RandomDataBase64Url(32);
            var          codeChallenge       = Base64UrlencodeNoPadding(Sha256(codeVerifier));
            const string CodeChallengeMethod = "S256";

            // Creates a redirect URI using an available port on the loopback address.
            var redirectUri = $"http://{IPAddress.Loopback}:{GetRandomUnusedPort()}/";

            // Creates an HttpListener to listen for requests on that redirect URI.
            var http = new HttpListener();

            http.Prefixes.Add(redirectUri);
            http.Start();
            var scope = GoogleScopes[googleScope];
            // Creates the OAuth 2.0 authorization request.
            var authorizationRequest =
                $"{AuthorizationEndpoint}?response_type=code" +
                $"&scope=openid%20{scope}" +
                $"&redirect_uri={System.Uri.EscapeDataString(redirectUri)}" +
                $"&client_id={clientId}" +
                $"&state={state}" +
                $"&code_challenge={codeChallenge}" +
                $"&code_challenge_method={CodeChallengeMethod}";

            // Opens request in the browser.
            System.Diagnostics.Process.Start(authorizationRequest);

            // Waits for the OAuth authorization response.
            var context = await http.GetContextAsync();

            // Sends an HTTP response to the browser.
            var response       = context.Response;
            var responseString = $"<html><head><meta http-equiv=\'refresh\' content=\'10;url=https://google.com\'></head><body>Please return to the {appName}.</body></html>";
            var buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

            response.ContentLength64 = buffer.Length;
            var responseOutput = response.OutputStream;
            await responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) =>
            {
                responseOutput.Close();
                http.Stop();
            });

            // Checks for errors.
            if (context.Request.QueryString.Get("error") != null)
            {
                throw new GoogleException($"OAuth authorization error: {context.Request.QueryString.Get("error")}.");
            }
            if (context.Request.QueryString.Get("code") == null ||
                context.Request.QueryString.Get("state") == null)
            {
                throw new GoogleException("Malformed authorization response. " + context.Request.QueryString);
            }

            // extracts the code
            var code          = context.Request.QueryString.Get("code");
            var incomingState = context.Request.QueryString.Get("state");

            // Compares the receieved state to the expected value, to ensure that
            // this app made the request which resulted in authorization.
            if (incomingState != state)
            {
                throw new GoogleException($"Received request with invalid state ({incomingState})");
            }

            // Starts the code exchange at the Token Endpoint.
            return(await PerformCodeExchange(clientId, clientSecret, code, codeVerifier, redirectUri));
        }
Exemplo n.º 11
0
        internal async Task Start()
        {
            string fullPrefix = "/" + prefix + "/";

            using (HttpListener listener = new HttpListener())
            {
                listener.Prefixes.Add("http://localhost:" + port + "/" + prefix + "/");
                listener.Start();

                int requestId = 0;
                while (true)
                {
                    HttpListenerContext context = await listener.GetContextAsync();

                    HttpListenerRequest request = context.Request;

                    if (!request.Url.AbsolutePath.StartsWith(fullPrefix))
                    {
                        Console.WriteLine("Unexpected request for " + request.Url);
                        await WriteErrorResponse(context, HttpStatusCode.NotFound, "Unknown url");

                        continue;
                    }

                    requestId++;

                    string relativePath = request.Url.AbsolutePath.Substring(fullPrefix.Length);
                    if (relativePath == "quit")
                    {
                        using (HttpListenerResponse response = context.Response)
                        {
                            response.StatusCode  = (int)HttpStatusCode.OK;
                            response.ContentType = "text/plain";
                            await WriteResponseBody(response, "Shutting down");
                        }
                        break;
                    }

                    string[] parts = relativePath.Split('/');

                    if (parts.Length != 2)
                    {
                        Console.WriteLine("Expected target/method relative path; was " + relativePath);
                        await WriteErrorResponse(context, HttpStatusCode.BadRequest, "Bad path");

                        continue;
                    }

                    object target;
                    if (!targets.TryGetValue(parts[0], out target))
                    {
                        Console.WriteLine("Unknown target for " + request.Url);
                        await WriteErrorResponse(context, HttpStatusCode.NotFound, "Unknown target");

                        continue;
                    }

                    // TODO: Make this cleaner. Possibly use a linked list?
                    Task task = HandleRequestAsync(context, target, parts[1], requestId);
                    outstandingRequests[requestId] = task;
                    int thisRequestId = requestId;
#pragma warning disable 4014
                    task.ContinueWith(t => outstandingRequests.TryRemove(thisRequestId, out task));
#pragma warning restore
                }
                Console.WriteLine("Shutting down... waiting for {0} outstanding requests", outstandingRequests.Count);
                await Task.WhenAll(outstandingRequests.Values);

                listener.Stop();
            }
        }
Exemplo n.º 12
0
		async Task HandleHttpRequestAsync (Action<HttpListenerRequest, HttpListenerResponse> handler)
		{
			var ctx = await listener.GetContextAsync ();
			handler (ctx.Request, ctx.Response);
			ctx.Response.Close ();
		}
Exemplo n.º 13
0
        public static async Task <string> GetAuthorizationCodeFromBrower(this MicrosoftAuthenticator authenticator, bool activateMainWindow = false)
        {
            string url = "https://login.live.com/oauth20_authorize.srf" +
                         $"?client_id={authenticator.ClientId}" +
                         "&response_type=code" +
                         $"&redirect_uri={authenticator.RedirectUri}" +
                         "&scope=XboxLive.signin%20offline_access" +
                         "&prompt=select_account";

            var httpListener = new HttpListener();

            httpListener.Prefixes.Add($"{authenticator.RedirectUri.TrimEnd('/')}/");
            httpListener.Start();

            using var process = new Process()
                  {
                      StartInfo = new ProcessStartInfo
                      {
                          UseShellExecute       = false,
                          CreateNoWindow        = true,
                          RedirectStandardInput = true,
                          FileName = "cmd"
                      },
                  };

            process.Start();
            process.StandardInput.WriteLine($"start \"\" \"{url}\"");
            process.StandardInput.WriteLine("exit");
            process.WaitForExit();

            string code;
            var    res = await httpListener.GetContextAsync();

            using (var stream = res.Response.OutputStream)
            {
                code = res.Request.Url.ToString().Split('=')[1];

                if (code.Contains("error"))
                {
                    stream.Write(Encoding.Default.GetBytes("Login Failed ! Please Back to Launcher to Retry"));
                }
                else
                {
                    stream.Write(Encoding.Default.GetBytes("Login Successfully ! Please Back to Launcher to Check"));
                }

                stream.Flush();
                await Task.Delay(1000);
            }

            httpListener.Stop();
            httpListener.Close();

            if (activateMainWindow)
            {
                NativeWin32MethodExtend.SetForegroundWindow(Process.GetCurrentProcess().MainWindowHandle);
            }

            if (code.Contains("error"))
            {
                return(res.Request.Url.ToString().Replace(authenticator.RedirectUri, ""));
            }

            return(code);
        }
Exemplo n.º 14
0
        private async Task StartServer()
        {
            //serv = serv??new HttpListener();
            var selectedIP = _ips.ElementAt(comboIPs.SelectedIndex).Item2;

            var url = string.Format("http://{0}:{1}", selectedIP, numPort.Value.ToString());

            txtURL.Text = url;
            serv.Prefixes.Clear();
            serv.Prefixes.Add("http://localhost:" + numPort.Value.ToString() + "/");
            //serv.Prefixes.Add("http://*:" + numPort.Value.ToString() + "/"); // Uncomment this to Allow Public IP Over Internet. [Commented for Security Reasons.]
            serv.Prefixes.Add(url + "/");
            serv.Start();
            Log("Server Started Successfuly!");
            Log("Private Network URL : " + url);
            Log("Localhost URL : " + "http://localhost:" + numPort.Value.ToString() + "/");
            while (isWorking)
            {
                var ctx = await serv.GetContextAsync();

                //Screenshot();
                var resPath = ctx.Request.Url.LocalPath;
                if (resPath == "/") // Route The Root Dir to the Index Page
                {
                    resPath += "index.html";
                }
                var page = Application.StartupPath + "/WebServer" + resPath;
                if (OnceTranslation.Checked)
                {
                    page = Application.StartupPath + "/OtherWebserver" + resPath;
                }
                else if (!OnceTranslation.Checked)
                {
                    page = Application.StartupPath + "/WebServer" + resPath;
                }
                bool fileExist;
                lock (locker)
                    fileExist = File.Exists(page);
                if (!fileExist)
                {
                    var errorPage = Encoding.UTF8.GetBytes("<h1 style=\"color:red\">Error 404 , File Not Found </h1><hr><a href=\".\\\">Back to Home</a>");
                    ctx.Response.ContentType = "text/html";
                    ctx.Response.StatusCode  = 404;
                    try
                    {
                        await ctx.Response.OutputStream.WriteAsync(errorPage, 0, errorPage.Length);
                    }
                    catch (Exception ex)
                    {
                    }
                    ctx.Response.Close();
                    continue;
                }


                if (isPrivateTask)
                {
                    if (!ctx.Request.Headers.AllKeys.Contains("Authorization"))
                    {
                        ctx.Response.StatusCode = 401;
                        ctx.Response.AddHeader("WWW-Authenticate", "Basic realm=Screen Task Authentication : ");
                        ctx.Response.Close();
                        continue;
                    }
                    else
                    {
                        var auth1 = ctx.Request.Headers["Authorization"];
                        auth1 = auth1.Remove(0, 6); // Remove "Basic " From The Header Value
                        auth1 = Encoding.UTF8.GetString(Convert.FromBase64String(auth1));
                        var auth2 = string.Format("{0}:{1}", txtUser.Text, txtPassword.Text);
                        if (auth1 != auth2)
                        {
                            // MessageBox.Show(auth1+"\r\n"+auth2);
                            Log(string.Format("Bad Login from {0} using {1}", ctx.Request.RemoteEndPoint.Address.ToString(), auth1));
                            var errorPage = Encoding.UTF8.GetBytes("<h1 style=\"color:red\">Not Authorized !!! </h1><hr><a href=\"./\">Back to Home</a>");
                            ctx.Response.ContentType = "text/html";
                            ctx.Response.StatusCode  = 401;
                            ctx.Response.AddHeader("WWW-Authenticate", "Basic realm=Screen Task Authentication : ");
                            try
                            {
                                await ctx.Response.OutputStream.WriteAsync(errorPage, 0, errorPage.Length);
                            }
                            catch (Exception ex)
                            {
                            }
                            ctx.Response.Close();
                            continue;
                        }
                    }
                }

                //Everything OK! ??? Then Read The File From HDD as Bytes and Send it to the Client
                byte[] filedata;

                // Required for One-Time Access of the file {Reader\Writer Problem in OS}
                rwl.AcquireReaderLock(Timeout.Infinite);
                filedata = File.ReadAllBytes(page);
                rwl.ReleaseReaderLock();

                var fileinfo = new FileInfo(page);
                if (fileinfo.Extension == ".css") // important for IE -> Content-Type must be defiend for CSS files unless will ignored !!!
                {
                    ctx.Response.ContentType = "text/css";
                }
                else if (fileinfo.Extension == ".html" || fileinfo.Extension == ".htm")
                {
                    ctx.Response.ContentType = "text/html"; // Important For Chrome Otherwise will display the HTML as plain text.
                }
                ctx.Response.StatusCode = 200;
                try
                {
                    await ctx.Response.OutputStream.WriteAsync(filedata, 0, filedata.Length);
                }
                catch (Exception ex)
                {
                    /*
                     *  Do Nothing !!! this is the Only Effective Solution for this Exception :
                     *  the specified network name is no longer available
                     */
                }

                ctx.Response.Close();
            }
        }
Exemplo n.º 15
0
        private static async Task <Dictionary <string, string> > getAccessCodeAsync()
        {
            // Generates state and PKCE values.
            string       state                 = randomDataBase64url(32);
            string       code_verifier         = randomDataBase64url(32);
            string       code_challenge        = base64urlencodeNoPadding(sha256(code_verifier));
            const string code_challenge_method = "S256";

            // Creates a redirect URI using an available port on the loopback address.
            string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, GetRandomUnusedPort());

            // Creates the OAuth 2.0 authorization request.
            string authorizationRequest = string.Format("{0}?response_type=code&scope={1}&redirect_uri={2}&client_id={3}&state={4}&code_challenge={5}&code_challenge_method={6}",
                                                        AUTH_ENDPOINT,
                                                        System.Uri.EscapeDataString(SCOPE),
                                                        System.Uri.EscapeDataString(redirectURI),
                                                        CLIENT_ID,
                                                        state,
                                                        code_challenge,
                                                        code_challenge_method);

            // Opens request in the browser.
            System.Diagnostics.Process.Start(authorizationRequest);

            // Creates an HttpListener to listen for requests on that redirect URI.
            var http = new HttpListener();

            http.Prefixes.Add(redirectURI);
            http.Start();

            // Waits for the OAuth authorization response.
            var context = await http.GetContextAsync();

            // Sends an HTTP response to the browser.
            var    response       = context.Response;
            string responseString = string.Format("<html><head></head><body>Authentication Successful. You may close the browser.</body></html>");
            var    buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

            response.ContentLength64 = buffer.Length;
            var  responseOutput = response.OutputStream;
            Task responseTask   = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) =>
            {
                responseOutput.Close();
                http.Stop();
                LOG.Info("HTTP server stopped.");
            });

            // Checks for errors.
            if (context.Request.QueryString.Get("error") != null)
            {
                throw new System.Exception(context.Request.QueryString.Get("error"));
            }
            if (context.Request.QueryString.Get("code") == null ||
                context.Request.QueryString.Get("state") == null)
            {
                throw new System.Exception("Malformed authorization response. " + context.Request.QueryString);
            }

            // extracts the code
            var code           = context.Request.QueryString.Get("code");
            var incoming_state = context.Request.QueryString.Get("state");

            // Compares the receieved state to the expected value, to ensure that
            // this app made the request which resulted in authorization.
            if (incoming_state != state)
            {
                throw new System.Exception(System.String.Format("Received request with invalid state ({0})", incoming_state));
            }

            return(PerformCodeExchange(code, code_verifier, redirectURI).Result);
        }
Exemplo n.º 16
0
        public static async Task HandleIncomingConnections()
        {
            bool runServer = true;

            // While a user hasn't visited the `shutdown` url, keep on handling requests
            while (runServer)
            {
                // Will wait here until we hear from a connection
                HttpListenerContext ctx = await listener.GetContextAsync();

                // Peel out the requests and response objects
                HttpListenerRequest  req  = ctx.Request;
                HttpListenerResponse resp = ctx.Response;

                // Set default Response values
                var responseCode    = 200;
                var responseMessage = "OK";

                // Print out some info about the request
                Console.WriteLine(req.Url.ToString());
                Console.WriteLine(req.HttpMethod);
                Console.WriteLine(req.UserHostName);
                Console.WriteLine(req.UserAgent);

                // If `shutdown` url requested w/ POST, then shutdown the server after serving the page
                if ((req.HttpMethod == "POST") && (req.Url.AbsolutePath == "/shutdown"))
                {
                    Console.WriteLine("Shutdown requested");
                    runServer = false;
                }

                var guid = req.Url.AbsolutePath.Replace("/hangman/", "");
                if (req.HttpMethod == "POST" && Guid.TryParse(guid, out var gameId))
                {
                    Console.WriteLine("Hangman initialized");
                    var bodyStream = new StreamReader(req.InputStream);
                    var bodyText   = bodyStream.ReadToEnd();
                    //send StartGame Command
                    Console.WriteLine(bodyText);
                    dynamic body = JsonConvert.DeserializeObject(bodyText);
                    Console.WriteLine(body.command);

                    const int DEFAULTPORT = 1113;
                    var       settings    = ConnectionSettings.Create();
                    var       conn        = EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, DEFAULTPORT));
                    conn.ConnectAsync().Wait();
                    var cmdHandler = new HangmanCommandHandler(new EventStoreRepository(conn, "HangmanBackend.Domain.Game"));

                    try
                    {
                        switch (body.command.ToString())
                        {
                        case "StartGame":
                            cmdHandler.handleStartGame(new StartGame(gameId, new Guid(), "word",
                                                                     DifficultySetting.EASY));

                            break;

                        case "GuessLetter":
                            cmdHandler.handleGuessLetter(new GuessLetter(gameId, (char)body.letter),
                                                         (int)body.version);
                            break;

                        case "GuessWord":
                            cmdHandler.handleGuessWord(new GuessWord(gameId, body.word.ToString()),
                                                       (int)body.version);
                            break;

                        default:
                            Console.WriteLine("Command not found");
                            break;
                        }
                    }
                    catch (System.AggregateException ex)
                    {
                        responseCode    = 400;
                        responseMessage = $"Game already exists! Cannot start same game twice: {ex.Message}";
                        Console.WriteLine(responseMessage);
                    }
                    catch (DomainException ex)
                    {
                        responseCode    = 400;
                        responseMessage = $"Domain Error: {ex.Message}";
                        Console.WriteLine(responseMessage);
                    }
                }

                // Write the response info
                string disableSubmit = !runServer ? "disabled" : "";
                byte[] data          = Encoding.UTF8.GetBytes(String.Format(pageData, responseMessage, disableSubmit));
                resp.ContentType     = "text/html";
                resp.ContentEncoding = Encoding.UTF8;
                resp.ContentLength64 = data.LongLength;
                resp.StatusCode      = responseCode;

                // Write out to the response stream (asynchronously), then close it
                await resp.OutputStream.WriteAsync(data, 0, data.Length);

                resp.Close();
            }
        }
Exemplo n.º 17
0
    public async void StartRedditAuthentication()
    {
        //Randomize state and change url to port you want.
        ConfigureStateAndRedirectUri();

        OpenBrowserForRedditAuth(headers);

        var result = await StartListeningForResponse();

        var uriData = result.GetHeadersFromUriData();

        if (uriData == null)
        {
            return;
        }
        if (uriData.Contains("error"))
        {
            Debug.LogError(uriData["error"]);
        }

        AccessToken = uriData["access_token"];
        if (this.GetComponent <RedditManager>() != null)
        {
            GetComponent <RedditManager>().InitReddit();
        }

        async Task <string> StartListeningForResponse()
        {
            HttpListener listener = new HttpListener();

            listener.Prefixes.Add($"http://localhost:{listeningPort}/");
            listener.Start();
            //Hard code file
            string responseString = Resources.Load <TextAsset>("magic_redirect_fragment_to_data").text;

            byte[] htmlWeb = Encoding.UTF8.GetBytes(responseString);
            string text;

            while (true)
            {
                var context = await listener.GetContextAsync().ConfigureAwait(false);

                try {
                    HttpListenerRequest  request  = context.Request;
                    HttpListenerResponse response = context.Response;

                    response.ContentLength64 = htmlWeb.Length;
                    Stream output = response.OutputStream;
                    output.Write(htmlWeb, 0, htmlWeb.Length);
                    output.Close();

                    // URl with /# symbol (fragment part of URI that not send to http) will be redirect using html code just to get fragments part.
                    // http://localhost:21345/?%2F=#access_token=214252035530-umX7LjfFWPvK7g82F0FaxrgE69k&token_type=bearer&state=6cc0633b-dda7-4f06-9408-0ae5a129fb04&expires_in=3600&scope=edit+history+identity+modposts+mysubreddits+read+save+submit
                    if (request.RawUrl.Contains("access_token"))
                    {
                        //Debug.Log(request.RawUrl);
                        // Meaning we have a full url : http://localhost:21345/?access_token=token & stuff
                        //RawURL look like: /access_token=214252035530-GKCNDtDglx8_3vYakCPcLYed0Pw&token_type=bearer&state=2a7e89b8-2aad-488a-b59b-97702a94f859&expires_in=3600&scope=edit+history+identity+modposts+mysubreddits+read+save+submit
                        text = request.RawUrl.Replace("/", ""); // Remove 1st character
                        break;
                    }
                }
                catch (Exception ex) { Debug.LogError(ex); }
            }

            listener.Stop();
            listener.Close();
            return(text);
        }
    }
Exemplo n.º 18
0
        async Task HTTPList()
        {
            while (true)
            {
                var context = await http.GetContextAsync();

                switch (context.Request.RawUrl)
                {
                case "/device":
                    if (context.Request.HttpMethod == "GET")
                    {
                        context.Response.StatusCode  = 200;
                        context.Response.ContentType = "application/json";
                        context.Response.AddHeader("Charset", "UTF-8");
                        StreamWriter write = new StreamWriter(context.Response.OutputStream);
                        await write.WriteAsync(JsonConvert.SerializeObject(Device.devices.Values.ToArray()));

                        write.Close();
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod == "POST")
                    {
                        try
                        {
                            StreamReader reader = new StreamReader(context.Request.InputStream);
                            var          device = JsonConvert.DeserializeObject <IdStatusDevice>(await reader.ReadToEndAsync());
                            reader.Close();
                            if (string.IsNullOrWhiteSpace(device.id) || device.status == null || device.status.Length == 0)
                            {
                                context.Response.StatusCode = 400;
                                context.Response.Close();
                                break;
                            }
                            if (!Device.devices.TryGetValue(device.id, out var currentDevice))
                            {
                                context.Response.StatusCode = 400;
                                context.Response.Close();
                                break;
                            }
                            currentDevice[0] = bool.Parse(device.status[0].ToString());
                            if (currentDevice.statusData.Length > 1 && device.status.Length > 1)
                            {
                                currentDevice[1] = device.status[1];
                            }
                            context.Response.StatusCode = 200;
                            context.Response.Close();
                        }
                        catch (InvalidCastException)
                        {
                            context.Response.StatusCode = 400;
                            context.Response.Close();
                            break;
                        }
                        catch (FormatException)
                        {
                            context.Response.StatusCode = 400;
                            context.Response.Close();
                            break;
                        }
                    }
                    break;
                }
            }
        }
Exemplo n.º 19
0
        private static async Task DispatchHttpRequestsAsync(HttpListener httpListener, CancellationToken cancellationToken, int maxThreadCount = Int32.MaxValue)
        {
            // Create a request handler factory that uses basic authentication
            var requestHandlerFactory = new WebDavMailRu.CloudStore.Mailru.RequestHandlerFactory();

            // Create WebDAV dispatcher
            var homeFolder       = new MailruStore();
            var webDavDispatcher = new WebDavDispatcher(homeFolder, requestHandlerFactory);

            try
            {
                using (var sem = new SemaphoreSlim(maxThreadCount))
                {
                    var semclo = sem;
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        var httpListenerContext = await httpListener.GetContextAsync().ConfigureAwait(false);

                        if (httpListenerContext == null)
                        {
                            break;
                        }

                        //if (httpListenerContext.Request.IsAuthenticated)
                        //    httpContext = new HttpBasicContext(httpListenerContext, i => i.Name == webdavUsername && i.Password == webdavPassword);
                        //else httpContext = new HttpContext(httpListenerContext);

                        HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)httpListenerContext.User.Identity;
                        IHttpContext httpContext           = new HttpBasicContext(httpListenerContext, i => i.Name == identity.Name && i.Password == identity.Password);

                        await semclo.WaitAsync(cancellationToken);

                        // ReSharper disable once UnusedVariable
                        Task tsk = Task
                                   .Run(async() =>
                        {
                            try
                            {
                                await webDavDispatcher.DispatchRequestAsync(httpContext);
                            }
                            catch (Exception ex)
                            {
                                Logger.Error("Exception", ex);
                            }
                        }, cancellationToken)
                                   .ContinueWith(t => semclo.Release(), cancellationToken);
                    }
                }
            }
            catch (HttpListenerException excListener)
            {
                if (excListener.ErrorCode != ERROR_OPERATION_ABORTED)
                {
                    throw;
                }
            }
            catch (Exception e)
            {
                Logger.Error("Global exception", e);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Await connections.
        /// </summary>
        private async void StartConnectionListener(HttpListener listener)
        {
            ResponsePacket resp = null;

            // Wait for a connection.  Return to caller while we wait.
            HttpListenerContext context = await listener.GetContextAsync();

            Session session = sessionManager.GetSession(context.Request.RemoteEndPoint);

            OnRequest.IfNotNull(r => r(session, context));

            // Release the semaphore so that another listener can be immediately started up.
            sem.Release();
            Log(context.Request);

            HttpListenerRequest request = context.Request;

            try
            {
                string path  = request.RawUrl.LeftOf("?");                                      // Only the path, not any of the parameters
                string verb  = request.HttpMethod;                                              // get, post, delete, etc.
                string parms = request.RawUrl.RightOf("?");                                     // Params on the URL itself follow the URL and are separated by a ?
                Dictionary <string, object> kvParams = GetKeyValues(parms);                     // Extract into key-value entries.
                string data = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding).ReadToEnd();
                // GetKeyValues(data, kvParams);
                kvParams["Data"] = data;
                Log(kvParams);

                if (!VerifyCsrf(session, verb, kvParams))
                {
                    Console.WriteLine("CSRF did not match.  Terminating connection.");
                    context.Response.OutputStream.Close();
                }
                else
                {
                    resp = router.Route(session, verb, path, kvParams);

                    // Update session last connection after getting the response, as the router itself validates session expiration only on pages requiring authentication.
                    session.UpdateLastConnectionTime();

                    if (resp.Error != ServerError.OK)
                    {
                        resp.Redirect = OnError(resp.Error);
                    }

                    // TODO: Nested exception: is this best?

                    try
                    {
                        Respond(request, context.Response, resp);
                    }
                    catch (Exception reallyBadException)
                    {
                        // The response failed!
                        // TODO: We need to put in some decent logging!
                        Console.WriteLine(reallyBadException.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                resp = new ResponsePacket()
                {
                    Redirect = OnError(ServerError.ServerError)
                };
            }
        }
Exemplo n.º 21
0
        private async Task ServerTask()
        {
            while (_httpListener != null && _httpListener.IsListening)
            {
                _lastRequestTime = DateTime.Now;

                var server = await _httpListener.GetContextAsync();

                var path = server.Request.Url.LocalPath;

                if (_debugMode)
                {
                    Log(path);
                }

                var key = path.Replace(_challengePrefix, "").ToLower();

                if (key == _controlKey.ToLower())
                {
                    server.Response.StatusCode  = (int)HttpStatusCode.OK;
                    server.Response.ContentType = "text/plain";
                    using (var stream = new StreamWriter(server.Response.OutputStream))
                    {
                        stream.Write("Stopping");
                        stream.Flush();
                        stream.Close();
                    }
                    server.Response.Close();
                    Stop();
                    return;
                }

                if (key == _checkKey.ToLower())
                {
                    if (_debugMode)
                    {
                        Log("Check key sent. OK.");
                    }
                    server.Response.StatusCode  = (int)HttpStatusCode.OK;
                    server.Response.ContentType = "text/plain";

                    using (var stream = new StreamWriter(server.Response.OutputStream))
                    {
                        stream.Write("OK");
                        stream.Flush();
                        stream.Close();
                    }
                }
                else
                {
                    if (key.Length > 8 && !_challengeResponses.ContainsKey(key))
                    {
                        // if challenge response not in our cache, fetch from local API
                        try
                        {
                            _maxServiceLookups--;

                            var apiUrl = $"{_baseUri}managedcertificates/currentchallenges/";

                            if (_debugMode)
                            {
                                Log($"Key {key} not found: Refreshing challenges.. {apiUrl}");
                            }
                            var response = await _apiClient.GetAsync(apiUrl);

                            if (response.IsSuccessStatusCode)
                            {
                                var json = await response.Content.ReadAsStringAsync();

                                if (_debugMode)
                                {
                                    Log(json);
                                }
                                var list = Newtonsoft.Json.JsonConvert.DeserializeObject <List <SimpleAuthorizationChallengeItem> >(json);
                                _challengeResponses = new Dictionary <string, string>();
                                list.ForEach(i => _challengeResponses.Add(i.Key.ToLower(), i.Value));
                            }
                            else
                            {
                                Log("Failed to refresh current challenges");
                            }
                        }
                        catch (Exception exp)
                        {
                            Log(exp.ToString());
                        }
                    }

                    if (_challengeResponses.ContainsKey(key))
                    {
                        var value = _challengeResponses[key];

                        if (value != null)
                        {
                            // System.Console.Out.WriteLine(value);

                            server.Response.StatusCode  = (int)HttpStatusCode.OK;
                            server.Response.ContentType = "text/plain";

                            using (var stream = new StreamWriter(server.Response.OutputStream))
                            {
                                stream.Write(value);
                                stream.Flush();
                                stream.Close();
                            }

                            Log($"Responded with Key: {key} Value:{value}");
                        }
                        else
                        {
                            server.Response.StatusCode = (int)HttpStatusCode.NotFound;

                            Log($"Requested key not found: {key}");
                        }
                    }
                    else
                    {
                        server.Response.StatusCode = 404;
                    }
                }

                server.Response.Close();

                if (_debugMode)
                {
                    Log("End request.");
                }

                if (_maxServiceLookups == 0)
                {
                    // give up trying to resolve challenges, we have been queried too many times for
                    // challenge responses we don't know about
                    Stop();

                    if (_debugMode)
                    {
                        Log("Max lookups failed.");
                    }
                }
            }
        }
Exemplo n.º 22
0
        internal static async Task <Result> GetToken(
            string clientId,
            string clientSecret,
            string state,
            string redirectUri,
            string htmlResponseToShowInBrowser)
        {
            // Creates an HttpListener to listen for requests on that redirect URI.
            var http = new HttpListener();

            http.Prefixes.Add(redirectUri);
            Debug("Listening on " + redirectUri);
            http.Start();

            // Creates the OAuth 2.0 authorization request.
            RequestIdentity.Request(clientId, state, redirectUri);

            // Waits for the OAuth authorization response.
            var context = await http.GetContextAsync();

            // Brings the Console to Focus.
            ConsoleHack.BringConsoleToFront();

            // Sends an HTTP response to the browser.
            var response = context.Response;

            var buffer = System.Text.Encoding.UTF8.GetBytes(htmlResponseToShowInBrowser);

            response.ContentLength64 = buffer.Length;
            var responseOutput = response.OutputStream;

            Task responseTask = responseOutput.WriteAsync(
                buffer, 0, buffer.Length).ContinueWith((task) =>
            {
                responseOutput.Close();
                http.Stop();
                Debug("HTTP server stopped.");
            });

            // Checks for errors.
            if (context.Request.QueryString.Get("error") != null)
            {
                return(new Result()
                {
                    Token = null,
                    Error = string.Format("OAuth authorization error: {0}.",
                                          context.Request.QueryString.Get("error"))
                });
            }

            if (context.Request.QueryString.Get("code") == null ||
                context.Request.QueryString.Get("state") == null)
            {
                return(new Result()
                {
                    Token = null,
                    Error = "Malformed authorization response. " + context.Request.QueryString
                });
            }

            // extracts the code
            var code           = context.Request.QueryString.Get("code");
            var incoming_state = context.Request.QueryString.Get("state");

            // Compares the receieved state to the expected value, to ensure that
            // this app made the request which resulted in authorization.
            if (incoming_state != state)
            {
                return(new Result()
                {
                    Token = null,
                    Error = string.Format(
                        "Received request with invalid state ({0})", incoming_state)
                });
            }

            Debug("Authorization code: " + code);
            return(new Result()
            {
                Token = await RequestToken.Get(clientId, clientSecret, code, redirectUri, state),
                Error = null
            });
        }
Exemplo n.º 23
0
        private async Task AcceptConnections(CancellationToken token)
        {
            try
            {
                #region Process-Requests

                while (_HttpListener.IsListening)
                {
                    if (_RequestCount >= _Settings.IO.MaxRequests)
                    {
                        await Task.Delay(100, token).ConfigureAwait(false);

                        continue;
                    }

                    HttpListenerContext listenerCtx = await _HttpListener.GetContextAsync().ConfigureAwait(false);

                    Interlocked.Increment(ref _RequestCount);
                    HttpContext ctx = null;

                    Task unawaited = Task.Run(async() =>
                    {
                        DateTime startTime = DateTime.Now;

                        try
                        {
                            #region Build-Context

                            Events.HandleConnectionReceived(this, new ConnectionEventArgs(
                                                                listenerCtx.Request.RemoteEndPoint.Address.ToString(),
                                                                listenerCtx.Request.RemoteEndPoint.Port));

                            ctx = new HttpContext(listenerCtx, _Settings, Events);

                            Events.HandleRequestReceived(this, new RequestEventArgs(ctx));

                            if (_Settings.Debug.Requests)
                            {
                                Events.Logger?.Invoke(
                                    _Header + ctx.Request.Source.IpAddress + ":" + ctx.Request.Source.Port + " " +
                                    ctx.Request.Method.ToString() + " " + ctx.Request.Url.RawWithoutQuery);
                            }

                            Statistics.IncrementRequestCounter(ctx.Request.Method);
                            Statistics.IncrementReceivedPayloadBytes(ctx.Request.ContentLength);

                            #endregion

                            #region Check-Access-Control

                            if (!_Settings.AccessControl.Permit(ctx.Request.Source.IpAddress))
                            {
                                Events.HandleRequestDenied(this, new RequestEventArgs(ctx));

                                if (_Settings.Debug.AccessControl)
                                {
                                    Events.Logger?.Invoke(_Header + ctx.Request.Source.IpAddress + ":" + ctx.Request.Source.Port + " denied due to access control");
                                }

                                listenerCtx.Response.StatusCode = 403;
                                listenerCtx.Response.Close();
                                return;
                            }

                            #endregion

                            #region Process-Preflight-Requests

                            if (ctx.Request.Method == HttpMethod.OPTIONS)
                            {
                                if (_Routes.Preflight != null)
                                {
                                    if (_Settings.Debug.Routing)
                                    {
                                        Events.Logger?.Invoke(
                                            _Header + "preflight route for " + ctx.Request.Source.IpAddress + ":" + ctx.Request.Source.Port + " " +
                                            ctx.Request.Method.ToString() + " " + ctx.Request.Url.RawWithoutQuery);
                                    }

                                    await _Routes.Preflight(ctx).ConfigureAwait(false);
                                    return;
                                }
                            }

                            #endregion

                            #region Pre-Routing-Handler

                            bool terminate = false;
                            if (_Routes.PreRouting != null)
                            {
                                terminate = await _Routes.PreRouting(ctx).ConfigureAwait(false);
                                if (terminate)
                                {
                                    if (_Settings.Debug.Routing)
                                    {
                                        Events.Logger?.Invoke(
                                            _Header + "prerouting terminated connection for " + ctx.Request.Source.IpAddress + ":" + ctx.Request.Source.Port + " " +
                                            ctx.Request.Method.ToString() + " " + ctx.Request.Url.RawWithoutQuery);
                                    }

                                    return;
                                }
                            }

                            #endregion

                            #region Content-Routes

                            if (ctx.Request.Method == HttpMethod.GET || ctx.Request.Method == HttpMethod.HEAD)
                            {
                                ContentRoute cr = null;
                                if (_Routes.Content.Match(ctx.Request.Url.RawWithoutQuery, out cr))
                                {
                                    if (_Settings.Debug.Routing)
                                    {
                                        Events.Logger?.Invoke(
                                            _Header + "content route for " + ctx.Request.Source.IpAddress + ":" + ctx.Request.Source.Port + " " +
                                            ctx.Request.Method.ToString() + " " + ctx.Request.Url.RawWithoutQuery);
                                    }

                                    ctx.RouteType = RouteTypeEnum.Content;
                                    ctx.Route     = cr;
                                    await _Routes.ContentHandler.Process(ctx, token).ConfigureAwait(false);
                                    return;
                                }
                            }

                            #endregion

                            #region Static-Routes

                            StaticRoute sr = null;
                            Func <HttpContext, Task> handler = _Routes.Static.Match(ctx.Request.Method, ctx.Request.Url.RawWithoutQuery, out sr);
                            if (handler != null)
                            {
                                if (_Settings.Debug.Routing)
                                {
                                    Events.Logger?.Invoke(
                                        _Header + "static route for " + ctx.Request.Source.IpAddress + ":" + ctx.Request.Source.Port + " " +
                                        ctx.Request.Method.ToString() + " " + ctx.Request.Url.RawWithoutQuery);
                                }

                                ctx.RouteType = RouteTypeEnum.Static;
                                ctx.Route     = sr;
                                await handler(ctx).ConfigureAwait(false);
                                return;
                            }

                            #endregion

                            #region Parameter-Routes

                            ParameterRoute pr = null;
                            Dictionary <string, string> parameters = null;
                            handler = _Routes.Parameter.Match(ctx.Request.Method, ctx.Request.Url.RawWithoutQuery, out parameters, out pr);
                            if (handler != null)
                            {
                                ctx.Request.Url.Parameters = new Dictionary <string, string>(parameters);

                                if (_Settings.Debug.Routing)
                                {
                                    Events.Logger?.Invoke(
                                        _Header + "parameter route for " + ctx.Request.Source.IpAddress + ":" + ctx.Request.Source.Port + " " +
                                        ctx.Request.Method.ToString() + " " + ctx.Request.Url.RawWithoutQuery);
                                }

                                ctx.RouteType = RouteTypeEnum.Parameter;
                                ctx.Route     = pr;
                                await handler(ctx).ConfigureAwait(false);
                                return;
                            }

                            #endregion

                            #region Dynamic-Routes

                            DynamicRoute dr = null;
                            handler         = _Routes.Dynamic.Match(ctx.Request.Method, ctx.Request.Url.RawWithoutQuery, out dr);
                            if (handler != null)
                            {
                                if (_Settings.Debug.Routing)
                                {
                                    Events.Logger?.Invoke(
                                        _Header + "dynamic route for " + ctx.Request.Source.IpAddress + ":" + ctx.Request.Source.Port + " " +
                                        ctx.Request.Method.ToString() + " " + ctx.Request.Url.RawWithoutQuery);
                                }

                                ctx.RouteType = RouteTypeEnum.Dynamic;
                                ctx.Route     = dr;
                                await handler(ctx).ConfigureAwait(false);
                                return;
                            }

                            #endregion

                            #region Default-Route

                            if (_Routes.Default != null)
                            {
                                if (_Settings.Debug.Routing)
                                {
                                    Events.Logger?.Invoke(
                                        _Header + "default route for " + ctx.Request.Source.IpAddress + ":" + ctx.Request.Source.Port + " " +
                                        ctx.Request.Method.ToString() + " " + ctx.Request.Url.RawWithoutQuery);
                                }

                                ctx.RouteType = RouteTypeEnum.Default;
                                await _Routes.Default(ctx).ConfigureAwait(false);
                                return;
                            }
                            else
                            {
                                if (_Settings.Debug.Routing)
                                {
                                    Events.Logger?.Invoke(
                                        _Header + "default route not found for " + ctx.Request.Source.IpAddress + ":" + ctx.Request.Source.Port + " " +
                                        ctx.Request.Method.ToString() + " " + ctx.Request.Url.RawWithoutQuery);
                                }

                                ctx.Response.StatusCode  = 404;
                                ctx.Response.ContentType = Pages.Default404Page.ContentType;
                                await ctx.Response.Send(Pages.Default404Page.Content).ConfigureAwait(false);
                                return;
                            }

                            #endregion
                        }
                        catch (Exception eInner)
                        {
                            ctx.Response.StatusCode  = 500;
                            ctx.Response.ContentType = Pages.Default500Page.ContentType;
                            await ctx.Response.Send(Pages.Default500Page.Content).ConfigureAwait(false);
                            Events.HandleExceptionEncountered(this, new ExceptionEventArgs(ctx, eInner));
                        }
                        finally
                        {
                            Interlocked.Decrement(ref _RequestCount);

                            if (ctx != null && ctx.Response != null && ctx.Response.ResponseSent)
                            {
                                Events.HandleResponseSent(this, new ResponseEventArgs(ctx, TotalMsFrom(startTime)));
                                Statistics.IncrementSentPayloadBytes(ctx.Response.ContentLength);
                            }
                        }
                    }, token);
                }

                #endregion
            }
            catch (TaskCanceledException)
            {
            }
            catch (OperationCanceledException)
            {
            }
            catch (HttpListenerException)
            {
            }
            catch (Exception e)
            {
                Events.HandleExceptionEncountered(this, new ExceptionEventArgs(null, e));
            }
            finally
            {
                Events.HandleServerStopped(this, EventArgs.Empty);
            }
        }
Exemplo n.º 24
0
            internal static async void Start()
            {
                string Prefix             = "http://localhost:8080/";
                string AuthenticationType = "none";

                if (!HttpListener.IsSupported)
                {
                    throw new NotSupportedException(
                              "Server is not supported.");
                }

                if (httplistener.IsListening)
                {
                    return;
                }

                try
                {
                    if (Helpers.Xml.AppConfigQuery(ApplicationSettings.ApplicationStructure.HttpAuthenticationPath).Count > 0)
                    {
                        Prefix = "http://" + Helpers.Xml.AppConfigQuery(
                            ApplicationSettings.ApplicationStructure.HttpHostNamePath)
                                 .Item(0).InnerText + ":" +
                                 Helpers.Xml.AppConfigQuery(
                            ApplicationSettings.ApplicationStructure.HttpPortPath)
                                 .Item(0).InnerText + "/";
                    }
                    if (Helpers.Xml.AppConfigQuery(ApplicationSettings.ApplicationStructure.HttpAuthenticationPath).Count > 0)
                    {
                        AuthenticationType = Helpers.Xml.AppConfigQuery(
                            ApplicationSettings.ApplicationStructure.HttpAuthenticationPath)
                                             .Item(0).InnerText;
                    }
                }
                catch (NullReferenceException e)
                {
                    Logger.Instance.Append("obj [ Server.Web.Start <Exception> ]: NullReferenceException [ " + e.Message + " ]");
                    return;
                }

                httplistener.Prefixes.Clear();
                httplistener.Prefixes.Add(Prefix);
                httplistener.AuthenticationSchemes = AuthenticationType.ToLower() == "basic" ?
                                                     httplistener.AuthenticationSchemes = AuthenticationSchemes.Basic :
                                                                                          httplistener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                httplistener.IgnoreWriteExceptions = true;
                httplistener.Start();

                while (httplistener.IsListening)
                {
                    try
                    {
                        var ctx = await httplistener.GetContextAsync();

                        Task.Run(() => ProcessRequestAsync(ctx));
                    }
                    catch (HttpListenerException e)
                    {
                        Logger.Instance.Append("obj [ Server.Web.Start <Exception> ]: HttpListenerException [ " + e.Message + " ]");
                        //Restart();
                    }
                    catch (InvalidOperationException)
                    {
                        //FileSystem.Log.Append("obj [ Server.Web.Start <Exception> ]: InvalidOperationException [ " + e.Message + " ]");
                        //Restart();
                    }
                    catch (Exception e)
                    {
                        Logger.Instance.Append("obj [ Server.Web.Start <Exception> ]: Generic [ " + e.Message + " ]");
                        //Restart();
                    }
                }
            }
Exemplo n.º 25
0
 public async Task <IHttpListenerContext> GetContextAsync()
 {
     return(new HttpListenerContextWrapper(await inner.GetContextAsync()));
 }
Exemplo n.º 26
0
        /// <summary>
        /// Loguje użytkownika przez konto Google (OAuth 2)
        /// </summary>
        private async Task AuthenticateWithGoogle()
        {
            // Generates state and PKCE values.
            string       state                 = RandomDataBase64url(32);
            string       code_verifier         = RandomDataBase64url(32);
            string       code_challenge        = Base64urlencodeNoPadding(Sha256(code_verifier));
            const string code_challenge_method = "S256";

            // Creates a redirect URI using an available port on the loopback address.
            string redirectURI = "http://localhost:8080/";

            // Creates an HttpListener to listen for requests on that redirect URI.
            using (HttpListener http = new HttpListener())
            {
                http.Prefixes.Add(redirectURI);
                http.Start();

                // Creates the OAuth 2.0 authorization request.
                string authorizationRequest = string.Format(CultureInfo.InvariantCulture, "{0}?response_type=code&scope=profile%20profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}&access_type=offline&approval_prompt=force",
                                                            authorizationEndpoint,
                                                            System.Uri.EscapeDataString(redirectURI),
                                                            clientID,
                                                            state,
                                                            code_challenge,
                                                            code_challenge_method);

                // Opens request in the browser.
                Process.Start(new ProcessStartInfo(authorizationRequest)
                {
                    UseShellExecute = true
                });

                // Waits for the OAuth authorization response.
                HttpListenerContext context = await http.GetContextAsync().ConfigureAwait(false);

                // Sends an HTTP response to the browser.
                HttpListenerResponse response = context.Response;
                string responseString         = string.Format(CultureInfo.InvariantCulture, "<html><head><meta http-equiv='refresh' content='10;url=https://google.com'></head><body>Please return to the app.</body></html>");
                byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                Stream responseOutput = response.OutputStream;
                Task   responseTask   = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) =>
                {
                    responseOutput.Close();
                    http.Stop();
                });

                // Checks for errors.
                if (context.Request.QueryString.Get("error") != null)
                {
                    return;
                }
                if (context.Request.QueryString.Get("code") == null ||
                    context.Request.QueryString.Get("state") == null)
                {
                    return;
                }

                // extracts the code
                string code           = context.Request.QueryString.Get("code");
                string incoming_state = context.Request.QueryString.Get("state");

                // Compares the receieved state to the expected value, to ensure that
                // this app made the request which resulted in authorization.
                if (incoming_state != state)
                {
                    return;
                }

                // Starts the code exchange at the Token Endpoint.
                await PerformCodeExchange(code, code_verifier, redirectURI).ConfigureAwait(false);

                return;
            }
        }
Exemplo n.º 27
0
        private async Task StartServer()
        {
            var selectedIP = _ips.ElementAt(cIPs.SelectedIndex).Item2;

            var url = string.Format("http://{0}:{1}", selectedIP, numPort.Value.ToString());

            txtURL.Text = url;
            serv.Prefixes.Clear();
            serv.Prefixes.Add("http://localhost:" + numPort.Value.ToString() + "/");

            serv.Prefixes.Add(url + "/");
            serv.Start();
            Log("Server Started Successfuly!");
            Log("Private Network URL : " + url);
            Log("Localhost URL : " + "http://localhost:" + numPort.Value.ToString() + "/");
            while (isWorking)
            {
                var ctx = await serv.GetContextAsync();

                // 统计用户数量
                if ((DateTime.Now.Second + 11) % 20 == 0)
                {
                    usersum.Clear();
                }

                if (ctx.Request.RemoteEndPoint != null)
                {
                    string ipAddress = ctx.Request.RemoteEndPoint.Address.ToString();
                    if (!usersum.Contains(ipAddress))
                    {
                        usersum.Add(ipAddress);
                    }
                }

                sumlog.Text  = "当前在线用户数:" + usersum.Count() + "\r\n";
                sumlog.Text += "IP分别为:" + "\r\n";

                for (int i = 0; i < usersum.Count(); i++)
                {
                    sumlog.Text += usersum[i] + "\r\n";
                }

                /* // 检测dsm安全性
                 * if (!DSMSecurity.isSecurity())
                 * {
                 *   Log("检测到有加密文档打开,停止服务!");
                 *   btnStartServer.Tag = "start";
                 *   btnStartServer.Text = "Start Server";
                 *   isWorking = false;
                 *   isTakingScreenshots = false;
                 *
                 * }*/



                //Screenshot();
                var resPath = ctx.Request.Url.LocalPath;
                if (resPath == "/")
                {
                    resPath += "index.html";
                }
                var  page = Application.StartupPath + "/WebServer" + resPath;
                bool fileExist;
                lock (locker)
                    fileExist = File.Exists(page);
                if (!fileExist)
                {
                    var errorPage = Encoding.UTF8.GetBytes("<h1 style=\"color:red\">Error 404 , File Not Found </h1><hr><a href=\".\\\">Back to Home</a>");
                    ctx.Response.ContentType = "text/html";
                    ctx.Response.StatusCode  = 404;
                    try
                    {
                        await ctx.Response.OutputStream.WriteAsync(errorPage, 0, errorPage.Length);
                    }
                    catch (Exception ex)
                    {
                    }
                    ctx.Response.Close();
                    continue;
                }


                if (isPrivateTask)
                {
                    if (!ctx.Request.Headers.AllKeys.Contains("Authorization"))
                    {
                        ctx.Response.StatusCode = 401;
                        ctx.Response.AddHeader("WWW-Authenticate", "Basic realm=Screen Task Authentication : ");
                        ctx.Response.Close();
                        continue;
                    }
                    else
                    {
                        var auth1 = ctx.Request.Headers["Authorization"];
                        auth1 = auth1.Remove(0, 6); // Remove "Basic " From The Header Value
                        auth1 = Encoding.UTF8.GetString(Convert.FromBase64String(auth1));
                        var auth2 = string.Format("{0}:{1}", txtUser.Text, txtPassword.Text);
                        if (auth1 != auth2)
                        {
                            // MessageBox.Show(auth1+"\r\n"+auth2);
                            Log(string.Format("Bad Login from {0} using {1}", ctx.Request.RemoteEndPoint.Address.ToString(), auth1));
                            var errorPage = Encoding.UTF8.GetBytes("<h1 style=\"color:red\">Not Authorized !!! </h1><hr><a href=\"./\">Back to Home</a>");
                            ctx.Response.ContentType = "text/html";
                            ctx.Response.StatusCode  = 401;
                            ctx.Response.AddHeader("WWW-Authenticate", "Basic realm=Screen Task Authentication : ");
                            try
                            {
                                await ctx.Response.OutputStream.WriteAsync(errorPage, 0, errorPage.Length);
                            }
                            catch (Exception ex)
                            {
                            }
                            ctx.Response.Close();
                            continue;
                        }
                    }
                }


                byte[] filedata;


                rwl.AcquireReaderLock(Timeout.Infinite);
                filedata = File.ReadAllBytes(page);
                rwl.ReleaseReaderLock();

                var fileinfo = new FileInfo(page);
                if (fileinfo.Extension == ".css") // important for IE -> Content-Type must be defiend for CSS files unless will ignored !!!
                {
                    ctx.Response.ContentType = "text/css";
                }
                else if (fileinfo.Extension == ".html" || fileinfo.Extension == ".htm")
                {
                    ctx.Response.ContentType = "text/html"; // Important For Chrome Otherwise will display the HTML as plain text.
                }
                ctx.Response.StatusCode = 200;
                try
                {
                    await ctx.Response.OutputStream.WriteAsync(filedata, 0, filedata.Length);
                }
                catch (Exception ex)
                {
                }

                ctx.Response.Close();
            }
        }
Exemplo n.º 28
0
        protected override Task StartServer(CancellationToken cancel)
        {
            // This will ensure that any failures to start are nicely thrown from StartServerAsync.
            _httpListener.Start();

            // Kick off the actual processing to a new thread and return a Task for the processing thread.
            return(Task.Factory.StartNew(delegate
            {
                try
                {
                    while (!cancel.IsCancellationRequested)
                    {
                        // There is no way to give a CancellationToken to GCA() so, we need to hack around it a bit.
                        var getContext = _httpListener.GetContextAsync();
                        getContext.Wait(cancel);
                        var context = getContext.Result;

                        // Kick the request off to a background thread for processing.
                        _ = Task.Factory.StartNew(async delegate
                        {
                            var request = context.Request;
                            var response = context.Response;

                            try
                            {
                                try
                                {
                                    // We first touch the response.OutputStream only in the callback because touching
                                    // it means we can no longer send headers (the status code).
                                    var serializer = new TextSerializer(delegate
                                    {
                                        response.ContentType = PrometheusConstants.ExporterContentType;
                                        response.StatusCode = 200;
                                        return response.OutputStream;
                                    });

                                    await _registry.CollectAndSerializeAsync(serializer, cancel);
                                    response.OutputStream.Dispose();
                                }
                                catch (ScrapeFailedException ex)
                                {
                                    // This can only happen before anything is written to the stream, so it
                                    // should still be safe to update the status code and report an error.
                                    response.StatusCode = 503;

                                    if (!string.IsNullOrWhiteSpace(ex.Message))
                                    {
                                        using (var writer = new StreamWriter(response.OutputStream))
                                            writer.Write(ex.Message);
                                    }
                                }
                            }
                            catch (Exception ex) when(!(ex is OperationCanceledException))
                            {
                                if (!_httpListener.IsListening)
                                {
                                    return;   // We were shut down.
                                }
                                Trace.WriteLine(string.Format("Error in MetricsServer: {0}", ex));

                                try
                                {
                                    response.StatusCode = 500;
                                }
                                catch
                                {
                                    // Might be too late in request processing to set response code, so just ignore.
                                }
                            }
                            finally
                            {
                                response.Close();
                            }
                        }, TaskCreationOptions.LongRunning);
                    }
                }
                finally
                {
                    _httpListener.Stop();
                    // This should prevent any currently processed requests from finishing.
                    _httpListener.Close();
                }
            }, TaskCreationOptions.LongRunning));
        }
        private async void runServerSession()
        {
            while (server.IsListening)
            {
                try
                {
                    Task <HttpListenerContext> getContext = server.GetContextAsync();
                    getContext.Wait();
                    pingedStudio = true;

                    HttpListenerContext context = getContext.Result;
                    HttpListenerRequest request = context.Request;

                    HttpListenerResponse response = context.Response;
                    string query = request.Headers.Get("Query");
                    Console.WriteLine("Received Query {0}", query);
                    if (query != null)
                    {
                        if (query == "GetStringList")
                        {
                            Console.Beep();
                            while (!stringListReady)
                            {
                                await Task.Delay(100);
                            }

                            string file      = string.Join("\n", stringList);
                            Stream outStream = response.OutputStream;
                            byte[] buffer    = Encoding.ASCII.GetBytes(file);
                            outStream.Write(buffer, 0, buffer.Length);
                            windowState = 5;
                        }
                        else if (query == "PingProgress")
                        {
                            windowState = 0;
                            string s_processed = request.Headers.Get("Count");
                            if (s_processed != null)
                            {
                                int.TryParse(s_processed, out processed);
                            }
                        }
                        else if (query == "SendFVariables")
                        {
                            string fvarChunk = request.Headers.Get("FVariables");
                            if (fvarChunk != null)
                            {
                                foreach (string fvar in fvarChunk.Split(';'))
                                {
                                    fvars.Add(fvar);
                                }
                            }
                        }
                        else if (query == "Finished")
                        {
                            finished = true;
                            editor.receiveFVariableScan(fvars);
                        }
                    }
                    response.Close();
                }
                catch {}
            }
        }
        public Task StartAsync(string hostName, int listenPort)
        {
            if (Status == HttpAsyncHostStatus.Uninitialised)
            {
                throw new InvalidOperationException("Host is in an invalid state. Initialization may have failed.");
            }
            if (_listener != null)
            {
                throw new InvalidOperationException("Host has already been started.");
            }

            SetStatus(HttpAsyncHostStatus.Starting);

            // Establish a host-handler context:
            //_hostContext = new HostContext(this, _handler);

            _listener = new HttpListener
            {
                IgnoreWriteExceptions = true
            };

            _listener.Prefixes.Add(string.Format("http://{0}:{1}/", hostName, listenPort));

            return(Task.Run(() =>
            {
                // Configure the handler:
                //if (_configValues != null)
                //{
                //    var config = _handler as IConfigurationTrait;
                //    if (config != null)
                //    {
                //        var task = config.Configure(_hostContext, _configValues);
                //        if (task != null)
                //            if (!await task) return;
                //    }
                //}

                // Initialize the handler:
                //var init = _handler as IInitializationTrait;
                //if (init != null)
                //{
                //    var task = init.Initialize(_hostContext);
                //    if (task != null)
                //        if (!await task) return;
                //}

                try
                {
                    _stop = false;
                    // Start the HTTP listener:
                    _listener.Start();
                }
                catch (HttpListenerException ex)
                {
                    Console.Error.WriteLine(ex.Message);
                    return;
                }

                // Accept connections:
                // Higher values mean more connections can be maintained yet at a much slower average response time; fewer connections will be rejected.
                // Lower values mean less connections can be maintained yet at a much faster average response time; more connections will be rejected.
                var semaphore = new Semaphore(_accepts, _accepts);

                SetStatus(HttpAsyncHostStatus.Running);

                while (!_stop)
                {
                    semaphore.WaitOne();

#pragma warning disable 4014
                    _listener?.GetContextAsync().ContinueWith(async(t) =>
                    {
                        string errMessage;

                        try
                        {
                            semaphore.Release();

                            var context = await t;
                            await ProcessListenerContext(context, this);
                            return;
                        }
                        catch (Exception ex)
                        {
                            errMessage = ex.ToString();
                        }

                        await Console.Error.WriteLineAsync(errMessage);
                    });
#pragma warning restore 4014
                }

                SetStatus(HttpAsyncHostStatus.Initialised);
            }));
        }
Exemplo n.º 31
0
        async Task StartServerAsync(HttpListener listener, CancellationToken cancellationToken = default(CancellationToken))
        {
            var actionMap = new Dictionary <Tuple <string, Regex>, Action <HttpListenerRequest, HttpListenerResponse> >()
            {
                { Tuple.Create("GET", new Regex($@"^{RelativeUrlRoot}api/v1/gameObjects/list$")), (req, res) => {
                      res.ContentType = "application/json";

                      var responseData = new ResponseObjects()
                      {
                          objects = new List <Object>()
                      };
                      foreach (GameObject obj in UnityEngine.Resources.FindObjectsOfTypeAll(typeof(GameObject)))
                      {
                          AppendSceneObject(responseData.objects, obj);
                      }

                      var responseJson = Encoding.ASCII.GetBytes(JsonUtility.ToJson(responseData));
                      res.OutputStream.Write(responseJson, 0, responseJson.Length);
                      res.Close();
                  } },
                { Tuple.Create("PUT", new Regex($@"^{RelativeUrlRoot}api/v1/gameObjects/transforms$")), (req, res) => {
                      res.ContentType = "application/json";
                      if (!req.HasEntityBody)
                      {
                          res.StatusCode = 400;
                          res.Close();
                          return;
                      }
                      var request = JsonUtility.FromJson <RequestPutObjectTransform>(ReadRequestBody(req));
                      if (request == null)
                      {
                          res.StatusCode = 400;
                          res.Close();
                          return;
                      }

                      var responseData = new ResponseObjects()
                      {
                          objects = new List <Object>()
                      };
                      var objects = (IEnumerable <GameObject>)UnityEngine.Resources.FindObjectsOfTypeAll(typeof(GameObject));
                      foreach (var t in request.transforms)
                      {
                          var obj = objects.FirstOrDefault(o => o.GetInstanceID() == t.instanceId);
                          if (obj == null)
                          {
                              continue;
                          }
                          AssignTransform(obj.transform, t);
                          if (!responseData.objects.Any(p => p.instanceId == t.instanceId))
                          {
                              AppendSceneObject(responseData.objects, obj);
                          }
                      }

                      var responseJson = Encoding.ASCII.GetBytes(JsonUtility.ToJson(responseData));
                      res.OutputStream.Write(responseJson, 0, responseJson.Length);
                      res.Close();
                  } },
                { Tuple.Create("GET", new Regex($@"^{RelativeUrlRoot}")), (req, res) => {
                      string relativePath = req.RawUrl.Remove(req.RawUrl.IndexOf(RelativeUrlRoot), RelativeUrlRoot.Length);
                      if (relativePath.Contains(".."))
                      {
                          res.StatusCode = 404;
                          res.Close();
                      }

                      if (relativePath == "")
                      {
                          relativePath = "index.html";
                      }

                      string zipFilePath = Path.Combine(Application.streamingAssetsPath, ZipFileName);

                      byte[] content = GetBytesFromZip(zipFilePath, relativePath);
                      if (content == null)
                      {
                          res.StatusCode = 404;
                          res.Close();
                          return;
                      }

                      string contentType;
                      if (!ExtensionContentTypeDict.TryGetValue(Path.GetExtension(relativePath), out contentType))
                      {
                          contentType = ExtensionContentTypeDict[".html"];
                      }
                      res.ContentType = contentType;

                      res.OutputStream.Write(content, 0, content.Length);
                      res.Close();
                  } },
            };

            listener.Start();

            while (true)
            {
                var context = await listener.GetContextAsync();

                cancellationToken.ThrowIfCancellationRequested();

                var req = context.Request;
                var res = context.Response;

                var action = actionMap.FirstOrDefault(a => a.Key.Item1 == req.HttpMethod && a.Key.Item2.IsMatch(req.RawUrl));

                if (action.Value == null)
                {
                    res.StatusCode = 404;
                    res.Close();
                    continue;
                }

                action.Value(req, res);
            }
        }