Ejemplo n.º 1
0
 static void listener_RequestReceived(object sender, RequestEventArgs e)
 {
     var virtualPath = e.Request.Uri.AbsolutePath.TrimStart('/').Replace("/","\\");
     var stream = ProcessPath(virtualPath, "index.html");
     if (stream != null)
         CopyStream(stream, e.Response.Body);
 }
Ejemplo n.º 2
0
        private void OnRequest(object sender, HttpServer.RequestEventArgs e)
        {
            string[] paramss = e.Request.UriParts;
            HttpServer.IHttpResponse resp = e.Request.CreateResponse((IHttpClientContext)sender);

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

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

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

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

            if (paramss[0] == "reset")
            {
                reactReset(resp);
            }
        }
Ejemplo n.º 3
0
        public void OnRequestDesbloqueio(object sender, RequestEventArgs e)
        {
            e.Response.Connection.Type = ConnectionType.Close;
            e.Response.ContentType.Value = "text/xml";
            if (unlockSent == 0)
            {
                unlockSent++;

                string opcionais = "";
                int numparams = 1;
                if (checkBox1.Checked)
                {
                    opcionais += "<ParameterValueStruct><Name>InternetGatewayDevice.Services.X_Pace_Com.Services.SSH.Enable</Name><Value xsi:type=\"xsd:unsignedInt\">1</Value></ParameterValueStruct>";
                    numparams++;
                }

                timer1.Stop();
                AppendTextBox("\r\nModem conectado, enviando configuração.\r\n");
                byte[] buffer = Encoding.Default.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<soap-env:Envelope xmlns:soap-enc=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:cwmp=\"urn:dslforum-org:cwmp-1-0\"><soap-env:Header><cwmp:ID soap-env:mustUnderstand=\"1\">55882f2177ab936c3f062f8f</cwmp:ID></soap-env:Header><soap-env:Body><cwmp:SetParameterValues><ParameterList soap-enc:arrayType=\"cwmp:ParameterValueStruct["+numparams+"]\"><ParameterValueStruct><Name>InternetGatewayDevice.Services.X_Pace_Com.Services.GvtConfig.AccessClass</Name><Value xsi:type=\"xsd:unsignedInt\">4</Value></ParameterValueStruct>"+opcionais+"</ParameterList><ParameterKey/></cwmp:SetParameterValues></soap-env:Body></soap-env:Envelope>");
                e.Response.Body.Write(buffer, 0, buffer.Length);
                AppendTextBox("Finalizado.\r\n");
            }
            else if (unlockSent < 2)
            {
                unlockSent++;
                byte[] buffer = Encoding.Default.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<soap-env:Envelope xmlns:soap-enc=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:cwmp=\"urn:dslforum-org:cwmp-1-0\"><soap-env:Header><cwmp:ID soap-env:mustUnderstand=\"1\">null</cwmp:ID></soap-env:Header><soap-env:Body><cwmp:InformResponse><MaxEnvelopes>1</MaxEnvelopes></cwmp:InformResponse></soap-env:Body></soap-env:Envelope>");
                e.Response.Body.Write(buffer, 0, buffer.Length);
            }
            else
            {
                unlockSent = 1;
                e.Response.Status = HttpStatusCode.NoContent;
            }
        }
Ejemplo n.º 4
0
 public bool Handle(RequestEventArgs e)
 {
     NetworkRequest req = Multiplexor.Decode(e.Request);
     logger.Trace("Client rx: {0} p: {1} source: {2} overlord: {3}", req.Verb, req.Param, req.SourceID,
                  req.OverlordID);
     switch (req.Verb)
     {
         case "BROWSE":
             return HandleBrowse(e, req);
         case "UPDATE":
             return HandleUpdate(e, req);
         case "INFO":
             return HandleInfo(e);
         case "NOOP":
             return HandleNOOP(e, req);
         case "GET":
             return HandleGet(e, req);
         case "DISCONNECT":
             return HandleDisconnect(e);
         case "CHAT":
             return HandleChat(e, req);
         case "COMPARE":
             return HandleCompare(e, req);
         case "SEARCH":
             return HandleSearch(e, req);
         case "CONVERSTATION":
             return HandleConversation(e, req);
         case "ADDDOWNLOAD":
             return HandleAddDownload(e, req);
     }
     return false;
 }
Ejemplo n.º 5
0
 private static void OnRequest(object sender, RequestEventArgs e)
 {
     if (e.Request.Method == Method.Post)
     {
         
     }
 }
Ejemplo n.º 6
0
 protected virtual ProcessingResult OnPrepareRequest(RequestContext context, RequestEventArgs e)
 {
     PrepareRequest(this, e);
     if (e.IsHandled)
     {
         return(ProcessingResult.SendResponse);
     }
     return(ProcessingResult.Continue);
 }
Ejemplo n.º 7
0
        private void OnSecureRequest(object source, RequestEventArgs args)
        {
            IHttpClientContext context = (IHttpClientContext)source;
            IHttpRequest request = args.Request;

            // Here we create a response object, instead of using the client directly.
            // we can use methods like Redirect etc with it,
            // and we dont need to keep track of any headers etc.
        	IHttpResponse response = request.CreateResponse(context);

            byte[] body = Encoding.UTF8.GetBytes("Hello secure you!");
            response.Body.Write(body, 0, body.Length);
            response.Send();
        }
Ejemplo n.º 8
0
        private void On100Continue(object sender, ContinueEventArgs e)
        {
            var response = new Response(e.Request.HttpVersion, HttpStatusCode.Continue, "Please continue mate.");
            var args     = new RequestEventArgs((IHttpContext)sender, e.Request, response);

            ContinueResponseRequested(sender, args);

            string responseString = string.Format("{0} {1} {2}\r\n\r\n", "HTTP/1.0", (int)response.Status,
                                                  response.Reason);

            byte[] buffer = Encoding.ASCII.GetBytes(responseString);
            HttpContext.Current.Stream.Write(buffer, 0, buffer.Length);
            HttpContext.Current.Stream.Flush();
            _logger.Info(responseString);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Process result (check if it should be sent back or not)
        /// </summary>
        /// <param name="result"></param>
        /// <param name="e"></param>
        /// <returns><c>true</c> if request was processed properly.; otherwise <c>false</c>.</returns>
        protected virtual bool ProcessResult(ProcessingResult result, RequestEventArgs e)
        {
            if (result == ProcessingResult.Abort)
            {
                e.IsHandled = true;
                return(true);
            }

            if (result == ProcessingResult.SendResponse)
            {
                SendResponse(e.Context, e.Request, e.Response);
                e.IsHandled = true;
                return(true);
            }

            return(false);
        }
Ejemplo n.º 10
0
        void RequestHandler(object sender, RequestEventArgs e)
        {
            IHttpClientContext context = (IHttpClientContext)sender;
            IHttpRequest       request = e.Request;

            if (_requestQueue.ShouldQueue)
            {
                _requestQueue.Enqueue(context, request);
                return;
            }

            ProcessRequestWrapper(context, request);

            // no need to lock, if all threads are busy,
            // someone is bound to trigger the thread correctly =)
            _requestQueue.Trigger();
        }
Ejemplo n.º 11
0
        private ProcessingResult HandleRequest(RequestEventArgs e)
        {
            var context = new RequestContext
            {
                HttpContext = e.Context,
                Request     = e.Request,
                Response    = e.Response
            };

            OnAuthentication(context);
            OnBeforeRequest(context);
            //PrepareRequest(this, e);
            InternalPrepareRequest(this, e);
            ProcessingResult ret = OnPrepareRequest(context, e);

            if (ProcessResult(ret, e))
            {
                return(ret);
            }

            if (e.Request.ContentLength.Value > 0)
            {
                DecodeBody(e.Request);
            }

            // Process routers.
            ProcessingResult result = ProcessRouters(context);

            if (ProcessResult(result, e))
            {
                _logger.Debug("Routers processed the request.");
            }


            // process modules.
            result = ProcessModules(context);
            if (ProcessResult(result, e))
            {
                return(result);
            }

            RequestReceived(this, e);


            return(ProcessingResult.Continue);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Received from a <see cref="IHttpClientContext"/> when a request have been parsed successfully.
        /// </summary>
        /// <param name="source"><see cref="IHttpClientContext"/> that received the request.</param>
        /// <param name="args">The request.</param>
        private void OnRequest(object source, RequestEventArgs args)
        {
            IHttpClientContext context = (IHttpClientContext)source;
            IHttpRequest       request = args.Request;

            if (_requestQueue.ShouldQueue)
            {
                _requestQueue.Enqueue(context, request);
                return;
            }

            ProcessRequestWrapper(context, request);

            // no need to lock, if all threads are busy,
            // someone is bound to trigger the thread correctly =)
            _requestQueue.Trigger();
        }
Ejemplo n.º 13
0
        /// <exception cref="Exception">Throwing exception if in debug mode and not exception handler have been specified.</exception>
        private void OnRequest(object sender, RequestEventArgs e)
        {
            var context = (HttpContext)sender;

            HttpFactory.Current = Factory;
            HttpContext.Current = context;

            try
            {
                var args = new RequestEventArgs(context, e.Request, e.Response);
                RequestReceived(this, args);
                if (!args.IsHandled)
                {
                    // need to respond to the context.
                    var generator = new ResponseWriter();
                    generator.Send(context, args.Response);
                }

                // Disconnect when done.
                if (e.Response.HttpVersion == "HTTP/1.0" || e.Response.Connection.Type == ConnectionType.Close)
                {
                    context.Disconnect();
                }
            }
            catch (Exception err)
            {
                if (err is HttpException)
                {
                    var exception = (HttpException)err;
                    ErrorPage(e.Request, e.Response, exception);
                }
                else
                {
                    _logger.Debug("Request failed.", err);
#if DEBUG
                    if (ExceptionThrown.GetInvocationList().Length == 1)
                    {
                        throw;
                    }
#endif
                    ExceptionThrown(this, new ExceptionEventArgs(err));
                    SendInternalServerError(context, err);
                }
            }
        }
Ejemplo n.º 14
0
        private void OnRequest(object source, RequestEventArgs args)
        {
            IHttpClientContext context = (IHttpClientContext)source;
            IHttpRequest request = args.Request;

            // Respond is a small convenience function that let's you send one string to the browser.
            // you can also use the Send, SendHeader and SendBody methods to have total control.
            if (request.Uri.AbsolutePath == "/hello")
                context.Respond("Hello to you too!"); 

            else if (request.UriParts.Length == 1 && request.UriParts[0] == "goodbye")
            {
            	IHttpResponse response = request.CreateResponse(context);
                StreamWriter writer = new StreamWriter(response.Body);
                writer.WriteLine("Goodbye to you too!");
                writer.Flush();
                response.Send();
            }
        }
Ejemplo n.º 15
0
 private static void OnRequest(object sender, RequestEventArgs e)
 {
     #if DEBUG
     lock (_lockObj)
     {
         Console.WriteLine(("Begin Request").Wrap("-", Console.WindowWidth));
         Console.WriteLine(string.Format("Request from {0}", e.Context.RemoteEndPoint.Address.ToString()));
         if (e.Response.Status == HttpStatusCode.OK)
         {
             Console.WriteLine(string.Format("The request for {0} was successful", e.Request.Uri.ToString()));
         }
         else
         {
             Console.WriteLine(string.Format("The request for {0} failed", e.Request.Uri.ToString()));
         }
         Console.WriteLine(("End Request").Wrap("-", Console.WindowWidth));
     }
     #endif
 }
Ejemplo n.º 16
0
        private void OnRequest(object sender, RequestEventArgs e)
        {
            String url = "https://v.whatsapp.net" + e.Request.Uri.PathAndQuery;
            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            e.Response.ContentType.Value = response.ContentType;
            e.Response.ContentLength.Value = response.ContentLength;

            Stream responseStream = response.GetResponseStream();
            StreamReader responseReader = new StreamReader(responseStream);
            String data = responseReader.ReadToEnd();

            byte[] data2 = Encoding.Default.GetBytes(data);

            e.Response.Body.Write(data2, 0, data2.Length);

            this.AddListItem("REQUEST:  " + e.Request.Uri.AbsoluteUri);
            this.AddListItem("RESPONSE: " + data);
            this.AddListItem(" ");
        }
Ejemplo n.º 17
0
        private ProcessingResult HandleRequest(RequestEventArgs e)
        {
            var context = new RequestContext
            {
                HttpContext = e.Context,
                Request     = e.Request,
                Response    = e.Response
            };

            PrepareRequest(this, e);

            // standard headers.
            e.Response.Add(new DateHeader("Date", DateTime.UtcNow));
            e.Response.Add(new StringHeader("Server", "C# WebServer"));


            if (e.Request.ContentLength.Value > 0)
            {
                DecodeBody(e.Request);
            }

            // Process routers.
            ProcessingResult result = ProcessRouters(context);

            if (ProcessResult(result, e))
            {
                _logger.Debug("Routers processed the request.");
            }

            // process modules.
            result = ProcessModules(context);
            if (ProcessResult(result, e))
            {
                return(result);
            }

            RequestReceived(this, e);


            return(ProcessingResult.Continue);
        }
Ejemplo n.º 18
0
        private void OnRequest(object sender, RequestEventArgs e)
        {
            _server = this;

            Exception exception;

            try
            {
                ProcessingResult result = HandleRequest(e);
                if (result != ProcessingResult.Continue)
                {
                    return;
                }

                exception = null;
            }
            catch (HttpException err)
            {
                _logger.Error("Got an HTTP exception.", err);
                e.Response.Status = err.Code;
                e.Response.Reason = err.Message;
                exception         = err;
            }
            catch (Exception err)
            {
                _logger.Error("Got an unhandled exception.", err);
                exception         = err;
                e.Response.Status = HttpStatusCode.InternalServerError;
                e.Response.Reason = "Failed to process request.";
            }


            if (exception == null)
            {
                e.Response.Status = HttpStatusCode.NotFound;
                e.Response.Reason = "Requested resource is not found. Sorry ;(";
                exception         = new HttpException(HttpStatusCode.NotFound, "Failed to find uri " + e.Request.Uri);
            }
            DisplayErrorPage(e.Context, exception);
            e.IsHandled = true;
        }
Ejemplo n.º 19
0
        private void OnRequest(object sender, RequestEventArgs e)
        {
            _server = this;

            Exception exception;

            try
            {
                if (HandleRequest(e) != ProcessingResult.Continue)
                {
                    return;
                }

                exception = null;
            }
            catch (HttpException err)
            {
                _logger.Error("Got an HTTP exception.", err);
                e.Response.Status = err.Code;
                e.Response.Reason = err.Message;
                exception         = err;
            }
            catch (Exception err)
            {
                _logger.Error("Got an exception.", err);
                var args = new ExceptionEventArgs(err);
                TriggerExceptionThrown(args);
                exception         = err;
                e.Response.Status = HttpStatusCode.InternalServerError;
                e.Response.Reason = "Failed to process request.";
            }


            if (exception == null)
            {
                e.Response.Status = HttpStatusCode.NotFound;
                e.Response.Reason = "Requested resource is not found. Sorry ;(";
            }
            SendErrorPage(e, exception);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Received from a <see cref="IHttpClientContext"/> when a request have been parsed successfully.
        /// </summary>
        /// <param name="source"><see cref="IHttpClientContext"/> that received the request.</param>
        /// <param name="args">The request.</param>
        private void OnRequest(object source, RequestEventArgs args)
        {
            _current = this;
            IHttpClientContext context = (IHttpClientContext)source;
            IHttpRequest       request = args.Request;

            if (_requestQueue.ShouldQueue)
            {
                // Do not use unfinished _requestQueue:
                //_requestQueue.Enqueue(context, request);

                context.Respond("HTTP/1.0", HttpStatusCode.ServiceUnavailable, HttpStatusCode.ServiceUnavailable.ToString(), "Request Queue is full", "text/plain");
                return;
            }

            ProcessRequestWrapper(context, request);

            // no need to lock, if all threads are busy,
            // someone is bound to trigger the thread correctly =)
            // Update: Trigger body does not (yet) have any implementation.
            //_requestQueue.Trigger();
        }
Ejemplo n.º 21
0
        protected override object ExecuteCommand(RestCommand cmd, RestVerbs verbs, IParameterCollection parms, RequestEventArgs e)
        {
            if (cmd.RequiresToken)
            {
                var strtoken = parms["token"];
                if (strtoken == null)
                    return new Dictionary<string, string>
                           	{{"status", "401"}, {"error", "Not authorized. The specified API endpoint requires a token."}};

                object token;
                if (!Tokens.TryGetValue(strtoken, out token))
                    return new Dictionary<string, string>
                           	{
                           		{"status", "403"},
                           		{
                           			"error",
                           			"Not authorized. The specified API endpoint requires a token, but the provided token was not valid."
                           			}
                           	};
            }
            return base.ExecuteCommand(cmd, verbs, parms, e);
        }
Ejemplo n.º 22
0
        /// <exception cref="Exception">Throwing exception if in debug mode and not exception handler have been specified.</exception>
        private void OnRequest(object sender, RequestEventArgs e)
        {
            var context = (HttpContext)sender;

            HttpFactory.Current = Factory;
            HttpContext.Current = context;

            try
            {
                var args = new RequestEventArgs(context, e.Request, e.Response);
                RequestReceived(this, args);
                if (!args.IsHandled)
                {
                    // need to respond to the context.
                    var generator = new ResponseWriter();
                    generator.Send(context, args.Response);
                }

                // Disconnect when done.
                if (e.Response.HttpVersion == "HTTP/1.0" || e.Response.Connection.Type == ConnectionType.Close)
                {
                    context.Disconnect();
                }
            }
            catch (Exception err)
            {
                if (err is HttpException)
                {
                    var exception = (HttpException)err;
                    SendErrorPage(exception);
                }
                else
                {
                    _logger.Debug("Request failed.", err);
                    SendErrorPage(err);
                }
                e.IsHandled = true;
            }
        }
Ejemplo n.º 23
0
        private void SendErrorPage(RequestEventArgs e, Exception err)
        {
            var args = new ErrorPageEventArgs(e.Context, e.Request, e.Response)
            {
                Exception = err
            };

            ErrorPageRequested(this, args);
            e.IsHandled = true;

            // use a ugly default error page.
            if (!args.IsHandled)
            {
#if DEBUG
                byte[] body = Encoding.UTF8.GetBytes(err != null ? err.ToString() : e.Response.Reason);
#else
                byte[] body = Encoding.UTF8.GetBytes(e.Response.Reason);
#endif
                e.Response.Body.Write(body, 0, body.Length);
            }

            SendResponse(e.Context, args.Request, args.Response);
        }
Ejemplo n.º 24
0
        private void listener_RequestReceived(object sender, RequestEventArgs e)
        {
            e.IsHandled = true;
            e.Response.Reason = string.Empty;
            string userAgent = string.Empty;
            IHeader uahead =
                e.Request.Headers.Where(h => string.Equals("User-Agent", h.Name, StringComparison.OrdinalIgnoreCase)).
                    FirstOrDefault();
            if (null != uahead)
                userAgent = uahead.HeaderValue;

            //Send to the correct handler
            if (userAgent.StartsWith("FAP"))
            {
                if (OnRequest(RequestType.FAP, e))
                    return;
            }
            if (OnRequest(RequestType.HTTP, e))
                return;
            e.Response.Reason = "Handler error";
            e.Response.Status = HttpStatusCode.InternalServerError;
            var generator = new ResponseWriter();
            generator.SendHeaders(e.Context, e.Response);
        }
Ejemplo n.º 25
0
Archivo: Rest.cs Proyecto: Ijwu/TShock
        protected virtual void OnRequest(object sender, RequestEventArgs e)
        {
            var obj = ProcessRequest(sender, e);
            if (obj == null)
                throw new NullReferenceException("obj");

            if (OnRestRequestCall(e))
                return;

            var str = JsonConvert.SerializeObject(obj, Formatting.Indented);
            var jsonp = e.Request.Parameters["jsonp"];
            if (!string.IsNullOrWhiteSpace(jsonp))
            {
                str = string.Format("{0}({1});", jsonp, str);
            }
            e.Response.Connection.Type = ConnectionType.Close;
            e.Response.ContentType = new ContentTypeHeader("application/json; charset=utf-8");
            e.Response.Add(serverHeader);
            var bytes = Encoding.UTF8.GetBytes(str);
            e.Response.Body.Write(bytes, 0, bytes.Length);
            e.Response.Status = HttpStatusCode.OK;
        }
Ejemplo n.º 26
0
 private void OnHttpListenerRequestReceived(object sender, RequestEventArgs e)
 {
   IHttpClientContext context = (IHttpClientContext)sender;
   lock (_serverData.SyncObj)
     if (!_serverData.IsActive)
       return;
   HandleHTTPRequest_NoLock(context, e.Request);
 }
Ejemplo n.º 27
0
        protected virtual object ProcessRequest(object sender, RequestEventArgs e)
        {
            var uri = e.Request.Uri.AbsolutePath;
            uri = uri.TrimEnd('/');

            foreach (var com in commands)
            {
                var verbs = new RestVerbs();
                if (com.HasVerbs)
                {
                    var match = Regex.Match(uri, com.UriVerbMatch);
                    if (!match.Success)
                        continue;
                    if ((match.Groups.Count - 1) != com.UriVerbs.Length)
                        continue;

                    for (int i = 0; i < com.UriVerbs.Length; i++)
                        verbs.Add(com.UriVerbs[i], match.Groups[i + 1].Value);
                }
                else if (com.UriTemplate.ToLower() != uri.ToLower())
                {
                    continue;
                }

                var obj = ExecuteCommand(com, verbs, e.Request.Parameters);
                if (obj != null)
                    return obj;

            }
            return new Dictionary<string, string> { { "status", "404" }, { "error", "Specified API endpoint doesn't exist. Refer to the documentation for a list of valid endpoints." } };
        }
Ejemplo n.º 28
0
        protected virtual void OnRequest(object sender, RequestEventArgs e)
        {
            var obj = ProcessRequest(sender, e);
            if (obj == null)
                throw new NullReferenceException("obj");

            var str = JsonConvert.SerializeObject(obj, Formatting.Indented);
            e.Response.Connection.Type = ConnectionType.Close;
            e.Response.Body.Write(Encoding.ASCII.GetBytes(str), 0, str.Length);
            e.Response.Status = HttpStatusCode.OK;
            return;
        }
Ejemplo n.º 29
0
Archivo: Rest.cs Proyecto: Ijwu/TShock
        private static bool OnRestRequestCall(RequestEventArgs request)
        {
            if (RestRequestEvent == null)
                return false;

            var args = new RestRequestEventArgs
            {
                Request = request,
            };
            RestRequestEvent.Invoke(null, args);
            return args.Handled;
        }
Ejemplo n.º 30
0
Archivo: Rest.cs Proyecto: Ijwu/TShock
        protected virtual object ProcessRequest(object sender, RequestEventArgs e)
        {
            try
            {
                var uri = e.Request.Uri.AbsolutePath;
                uri = uri.TrimEnd('/');

                foreach (var com in commands)
                {
                    var verbs = new RestVerbs();
                    if (com.HasVerbs)
                    {
                        var match = Regex.Match(uri, com.UriVerbMatch);
                        if (!match.Success)
                            continue;
                        if ((match.Groups.Count - 1) != com.UriVerbs.Length)
                            continue;

                        for (int i = 0; i < com.UriVerbs.Length; i++)
                            verbs.Add(com.UriVerbs[i], match.Groups[i + 1].Value);
                    }
                    else if (com.UriTemplate.ToLower() != uri.ToLower())
                    {
                        continue;
                    }

                    var obj = ExecuteCommand(com, verbs, e.Request.Parameters, e.Request);
                    if (obj != null)
                        return obj;
                }
            }
            catch (Exception exception)
            {
                return new RestObject("500")
                       	{
                       		{"error", "Internal server error."},
                       		{"errormsg", exception.Message},
                       		{"stacktrace", exception.StackTrace},
                       	};
            }
            return new RestObject("404")
                   	{
                   		{"error", "Specified API endpoint doesn't exist. Refer to the documentation for a list of valid endpoints."}
                   	};
        }
Ejemplo n.º 31
0
 private bool HandleSearch(RequestEventArgs e, NetworkRequest req)
 {
     //We dont do this on a server..
     var verb = new SearchVerb(shareInfoService);
     NetworkRequest result = verb.ProcessRequest(req);
     byte[] data = Encoding.UTF8.GetBytes(result.Data);
     var generator = new ResponseWriter();
     e.Response.ContentLength.Value = data.Length;
     generator.SendHeaders(e.Context, e.Response);
     e.Context.Stream.Write(data, 0, data.Length);
     e.Context.Stream.Flush();
     data = null;
     return true;
 }
Ejemplo n.º 32
0
        private bool HandleGet(RequestEventArgs e, NetworkRequest req)
        {
            //No url?
            if (string.IsNullOrEmpty(req.Param))
                return false;

            string[] possiblePaths;


            if (shareInfoService.ToLocalPath(req.Param, out possiblePaths))
            {
                foreach (string possiblePath in possiblePaths)
                {
                    if (File.Exists(possiblePath))
                    {
                        var ffu = new FAPFileUploader(bufferService, serverUploadLimiterService);
                        var session = new TransferSession(ffu);
                        model.TransferSessions.Add(session);
                        try
                        {
                            //Try to find the username of the request
                            string userName = e.Context.RemoteEndPoint.Address.ToString();
                            Node search = model.Network.Nodes.ToList().Where(n => n.ID == req.SourceID).FirstOrDefault();
                            if (null != search && !string.IsNullOrEmpty(search.Nickname))
                                userName = search.Nickname;

                            using (
                                FileStream fs = File.Open(possiblePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                ffu.DoUpload(e.Context, fs, userName, possiblePath);
                            }

                            //Add log of upload
                            double seconds = (DateTime.Now - ffu.TransferStart).TotalSeconds;
                            var txlog = new TransferLog();
                            txlog.Nickname = userName;
                            txlog.Completed = DateTime.Now;
                            txlog.Filename = Path.GetFileName(possiblePath);
                            txlog.Path = Path.GetDirectoryName(req.Param);
                            if (!string.IsNullOrEmpty(txlog.Path))
                            {
                                txlog.Path = txlog.Path.Replace('\\', '/');
                                if (txlog.Path.StartsWith("/"))
                                    txlog.Path = txlog.Path.Substring(1);
                            }

                            txlog.Size = ffu.Length - ffu.ResumePoint;
                            if (txlog.Size < 0)
                                txlog.Size = 0;
                            if (0 != seconds)
                                txlog.Speed = (int) (txlog.Size/seconds);
                            model.CompletedUploads.Add(txlog);
                        }
                        finally
                        {
                            model.TransferSessions.Remove(session);
                        }
                        return true;
                    }
                }
            }

            e.Response.Status = HttpStatusCode.NotFound;
            var generator = new ResponseWriter();
            generator.SendHeaders(e.Context, e.Response);
            return true;
        }
Ejemplo n.º 33
0
 private void SendOk(RequestEventArgs e)
 {
     e.Response.Status = HttpStatusCode.OK;
     var generator = new ResponseWriter();
     generator.SendHeaders(e.Context, e.Response);
 }
Ejemplo n.º 34
0
 private void On100Continue(object sender, RequestEventArgs e)
 {
     ContinueResponseRequested(this, e);
 }
Ejemplo n.º 35
0
 private void OnRequestReceived(object sender, RequestEventArgs e)
 {
     RequestReceived(sender, e);
 }
Ejemplo n.º 36
0
		/// <summary>
		/// Received from a <see cref="IHttpClientContext"/> when a request have been parsed successfully.
		/// </summary>
		/// <param name="source"><see cref="IHttpClientContext"/> that received the request.</param>
		/// <param name="args">The request.</param>
		private void OnRequest(object source, RequestEventArgs args)
		{
			_current = this;
		    IHttpClientContext context = (IHttpClientContext) source;
		    IHttpRequest request = args.Request;
			if (_requestQueue.ShouldQueue)
			{
				_requestQueue.Enqueue(context, request);
				return;
			}

			ProcessRequestWrapper(context, request);

			// no need to lock, if all threads are busy,
			// someone is bound to trigger the thread correctly =)
			_requestQueue.Trigger();
		}
Ejemplo n.º 37
0
 private bool HandleChat(RequestEventArgs e, NetworkRequest req)
 {
     var verb = new ChatVerb();
     verb.ReceiveResponse(req);
     model.Messages.AddRotate(verb.Nickname + ":" + verb.Message, 50);
     SendOk(e);
     SafeObservingCollectionManager.UpdateNowAsync();
     return true;
 }
Ejemplo n.º 38
0
        private bool HandleCompare(RequestEventArgs e, NetworkRequest req)
        {
            var verb = new CompareVerb(model);

            NetworkRequest result = verb.ProcessRequest(req);
            byte[] data = Encoding.UTF8.GetBytes(result.Data);
            var generator = new ResponseWriter();
            e.Response.ContentLength.Value = data.Length;
            generator.SendHeaders(e.Context, e.Response);
            e.Context.Stream.Write(data, 0, data.Length);
            e.Context.Stream.Flush();
            data = null;

            return true;
        }
Ejemplo n.º 39
0
 private void OnRequestReceived(object sender, RequestEventArgs e)
 {
     RequestReceived(sender, e);
 }
Ejemplo n.º 40
0
 private bool HandleUpdate(RequestEventArgs e, NetworkRequest req)
 {
     if (req.AuthKey == model.Network.Overlord.Secret)
     {
         model.Network.Overlord.LastUpdate = Environment.TickCount;
         var verb = new UpdateVerb();
         verb.ProcessRequest(req);
         foreach (Node node in verb.Nodes)
         {
             Node search = model.Network.Nodes.Where(i => i.ID == node.ID).FirstOrDefault();
             if (search == null)
             {
                 //Dont allow partial updates to create clients.  Only full updates should contain the online flag.
                 if (node.ContainsKey("Online") && node.ContainsKey("Nickname") && node.ContainsKey("ID"))
                     model.Network.Nodes.Add(node);
             }
             else
             {
                 foreach (var param in node.Data)
                     search.SetData(param.Key, param.Value);
                 //Has the client disconnected?
                 if (!search.Online)
                 {
                     model.Network.Nodes.Remove(node);
                     logger.Trace("Client: Node offline update: " + node.ID);
                 }
             }
         }
         SendOk(e);
         return true;
     }
     return false;
 }
Ejemplo n.º 41
0
        private void OnRequest(object source, RequestEventArgs args)
        {
            IHttpClientContext context = (IHttpClientContext)source;
            IHttpRequest request = args.Request;
            

            PollServiceEventArgs psEvArgs;
            if (TryGetPollServiceHTTPHandler(request.UriPath.ToString(), out psEvArgs))
            {
                
                m_PollServiceManager.Enqueue(new PollServiceHttpRequest(psEvArgs, context, request));
                //DoHTTPGruntWork(psEvArgs.NoEvents(),new OSHttpResponse(new HttpResponse(context, request)));
            }
            else
            {
                OnHandleRequestIOThread(context, request);
            }

        }
Ejemplo n.º 42
0
 private bool HandleInfo(RequestEventArgs e)
 {
     e.Response.Status = HttpStatusCode.OK;
     var verb = new InfoVerb();
     verb.Node = model.LocalNode;
     NetworkRequest result = verb.CreateRequest();
     byte[] data = Encoding.UTF8.GetBytes(result.Data);
     var generator = new ResponseWriter();
     e.Response.ContentLength.Value = data.Length;
     generator.SendHeaders(e.Context, e.Response);
     e.Context.Stream.Write(data, 0, data.Length);
     e.Context.Stream.Flush();
     return true;
 }
Ejemplo n.º 43
0
 private static void OnRequest(object sender, RequestEventArgs e)
 {
     // Write info to the buffer.
     byte[] buffer = Encoding.Default.GetBytes("Hello secure world");
     e.Response.Body.Write(buffer, 0, buffer.Length);
 }
Ejemplo n.º 44
0
 private bool HandleNOOP(RequestEventArgs e, NetworkRequest req)
 {
     //Noop is usually used as a heartbeat message however if the authkey is set then it came from a overlord
     //Check the authkey is correct for our current overlord just incase we disconnected incorrectly and reconnected elsewhere
     if (string.IsNullOrEmpty(req.AuthKey) || req.AuthKey == model.Network.Overlord.Secret)
         SendOk(e);
     return true;
 }
Ejemplo n.º 45
0
        private void OnRequest(object source, RequestEventArgs args)
        {
            try
            {
                IHttpClientContext context = (IHttpClientContext)source;
                IHttpRequest request = args.Request;

                PollServiceEventArgs psEvArgs;

                if (TryGetPollServiceHTTPHandler(request.UriPath.ToString(), out psEvArgs))
                {
                    PollServiceHttpRequest psreq = new PollServiceHttpRequest(psEvArgs, context, request);

                    if (psEvArgs.Request != null)
                    {
                        OSHttpRequest req = new OSHttpRequest(context, request);

                        Stream requestStream = req.InputStream;

                        Encoding encoding = Encoding.UTF8;
                        StreamReader reader = new StreamReader(requestStream, encoding);

                        string requestBody = reader.ReadToEnd();

                        Hashtable keysvals = new Hashtable();
                        Hashtable headervals = new Hashtable();

                        string[] querystringkeys = req.QueryString.AllKeys;
                        string[] rHeaders = req.Headers.AllKeys;

                        keysvals.Add("body", requestBody);
                        keysvals.Add("uri", req.RawUrl);
                        keysvals.Add("content-type", req.ContentType);
                        keysvals.Add("http-method", req.HttpMethod);

                        foreach (string queryname in querystringkeys)
                        {
                            keysvals.Add(queryname, req.QueryString[queryname]);
                        }

                        foreach (string headername in rHeaders)
                        {
                            headervals[headername] = req.Headers[headername];
                        }

                        keysvals.Add("headers", headervals);
                        keysvals.Add("querystringkeys", querystringkeys);

                        psEvArgs.Request(psreq.RequestID, keysvals);
                    }

                    m_PollServiceManager.Enqueue(psreq);
                }
                else
                {
                    OnHandleRequestIOThread(context, request);
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[BASE HTTP SERVER]: OnRequest() failed with {0}{1}", e.Message, e.StackTrace);
            }
        }
Ejemplo n.º 46
0
 private bool HandleDisconnect(RequestEventArgs e)
 {
     SendOk(e);
     return true;
 }