Example #1
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;
            }
        }
Example #2
0
 private static void OnRequest(object sender, RequestEventArgs e)
 {
     if (e.Request.Method == Method.Post)
     {
         
     }
 }
Example #3
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);
 }
Example #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;
 }
Example #5
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();
        }
Example #6
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();
            }
        }
Example #7
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
 }
Example #8
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(" ");
        }
Example #9
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);
        }
Example #10
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);
        }
Example #11
0
 private void OnRequestReceived(object sender, RequestEventArgs e)
 {
     RequestReceived(sender, e);
 }
Example #12
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;
 }
Example #13
0
 private void OnHttpListenerRequestReceived(object sender, RequestEventArgs e)
 {
   IHttpClientContext context = (IHttpClientContext)sender;
   lock (_serverData.SyncObj)
     if (!_serverData.IsActive)
       return;
   HandleHTTPRequest_NoLock(context, e.Request);
 }
Example #14
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;
        }
Example #15
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." } };
        }
Example #16
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);
 }
Example #17
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;
 }
Example #18
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;
        }
Example #19
0
File: Rest.cs Project: 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;
        }
Example #20
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;
 }
Example #21
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;
        }
Example #22
0
 private void SendOk(RequestEventArgs e)
 {
     e.Response.Status = HttpStatusCode.OK;
     var generator = new ResponseWriter();
     generator.SendHeaders(e.Context, e.Response);
 }
Example #23
0
 private bool HandleDisconnect(RequestEventArgs e)
 {
     SendOk(e);
     return true;
 }
Example #24
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;
 }
        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);
            }

        }
Example #26
0
File: Rest.cs Project: 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."}
                   	};
        }
Example #27
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();
		}
Example #28
0
File: Rest.cs Project: 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;
        }
Example #29
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);
            }
        }
Example #30
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;
 }