public static BufferingConsumer Consume(this IDataProducer producer) { var c = new BufferingConsumer(); producer.Connect(c); return(c); }
public void OnRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var env = new Environment(); if (context != null) foreach (var kv in context) env[kv.Key] = kv.Value; env.Headers = head.Headers ?? new Dictionary<string, string>(); env.Method = head.Method ?? ""; env.Path = head.Path ?? ""; env.PathBase = ""; env.QueryString = head.QueryString ?? ""; env.Scheme = "http"; // XXX env.Version = "1.0"; if (body == null) env.Body = null; else env.Body = (onData, onError, onEnd) => { var d = body.Connect(new DataConsumer(onData, onError, onEnd)); return () => { if (d != null) d.Dispose(); }; }; appDelegate(env, HandleResponse(response), HandleError(response)); }
public void OnRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var env = new Dictionary<string, object>(); var request = new RequestEnvironment(env); if (context != null) foreach (var kv in context) env[kv.Key] = kv.Value; if (head.Headers == null) request.Headers = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); else request.Headers = head.Headers.ToDictionary(kv => kv.Key, kv => new[] { kv.Value }, StringComparer.OrdinalIgnoreCase); request.Method = head.Method ?? ""; request.Path = head.Path ?? ""; request.PathBase = ""; request.QueryString = head.QueryString ?? ""; request.Scheme = "http"; // XXX request.Version = "1.0"; if (body == null) request.BodyDelegate = null; else request.BodyDelegate = (write, end, cancellationToken) => { var d = body.Connect(new DataConsumer( write, end, () => end(null))); cancellationToken.Register(d.Dispose); }; appDelegate(env, HandleResponse(response), HandleError(response)); }
private static async void HandleRequest(HttpRequestHead request, IDataProducer body, IHttpResponseDelegate response, IRequestHandler handler) { _log.DebugFormat("Matched a handler {0}:{1} {2}", handler.Method, handler.Path, DumpQueryParams(handler.QueryParams)); if (handler.ResponseDelay > TimeSpan.Zero) { await Task.Delay(handler.ResponseDelay); } IDataProducer dataProducer = GetDataProducer(request, handler); if (request.HasBody()) { body.Connect(new BufferedConsumer( bufferedBody => { handler.RecordRequest(request, bufferedBody); _log.DebugFormat("Body: {0}", bufferedBody); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); }, error => { _log.DebugFormat("Error while reading body {0}", error.Message); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); } )); } else { response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); handler.RecordRequest(request, null); } _log.DebugFormat("End Processing request for : {0}:{1}", request.Method, request.Uri); }
private void ProcessPOSTRequest(IDataProducer body, IHttpResponseDelegate response) { body.Connect(new BufferedConsumer( (payload) => { try { _parent._systemMetrics.LogCount("listeners.http.bytes", Encoding.UTF8.GetByteCount(payload)); // Further split by ',' to match the GET while keeping backward compatibility and allowing you to use the join for both methods. string[] lines = payload.Replace("\r", "").Split(new char[] { '\n', ',' }, StringSplitOptions.RemoveEmptyEntries); for (int index = 0; index < lines.Length; index++) { _parent._target.Post(lines[index]); } _parent._systemMetrics.LogCount("listeners.http.lines", lines.Length); Respond(response, "200 OK"); } catch { Respond(response, "400 bad request"); } }, (error) => { Respond(response, "500 Internal server error"); })); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var verror = "404 Not Found"; var errorString = "Not Found"; try { var path = request.Uri; if (path == "/api") { var method = request.Method; var stream = new MemoryStream(); if (method == "POST") { requestBody.Connect(new BufferedConsumer(bufferedBody => { var data = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(bufferedBody).Split(new[] { "\r\n\r\n" }, 2, StringSplitOptions.RemoveEmptyEntries)[1]); stream.Write(data, 0, data.Length); stream.Position = 0; HandleAPIRequest(stream, method, response); }, error => { Log.Error(error.ToString()); })); } else { HandleAPIRequest(stream, method, response); } return; } } catch (Exception ex) { verror = "500 Internal Server Error"; Log.Error(ex.ToString()); errorString = ex.ToString(); } response.OnResponse(new HttpResponseHead() { Status = verror, Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", errorString.Length.ToString() } } }, new BufferedProducer(errorString)); }
void BeginResponse() { RenderHeaders(); if (body == null) { consumer.OnEnd(); } else { abortBody = body.Connect(consumer); } }
public void ConnectRequestBody() { var consumer = new MockDataConsumer() { OnDataAction = data => userCode.OnRequestBodyData(this, Encoding.ASCII.GetString(data.Array, data.Offset, data.Count)), OnEndAction = () => userCode.OnRequestBodyEnd(this) }; if (disconnect != null) { throw new Exception("got connect and disconnect was not null"); } disconnect = requestBody.Connect(consumer); }
void DoWriteResponse() { transaction.OnResponse(head); if (body != null) { // XXX there is no cancel. body.Connect(this); } else { transaction.OnResponseEnd(); HandOffTransactionIfPossible(); } }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var ea = new RequestReceivedEventArgs(); ea.RequestHead = request; ea.ResponseHead = ResponseMessageHelper.GetHttpResponseHead(); string contentType = string.Empty; if (ea.RequestHead.Headers.ContainsKey("Content-Type")) { contentType = ea.RequestHead.Headers["Content-Type"]; } int contentSize = 0; if (ea.RequestHead.Headers.ContainsKey("Content-Length")) { int.TryParse(ea.RequestHead.Headers["Content-Length"], out contentSize); } BufferedConsumer bc = new BufferedConsumer(bodyContents => { try { ea.RequestBody = bodyContents; //Called when request body is read to end if (RequestReceived != null) { RequestReceived(this, ea); } var bp = ea.ResponseBodyProducer as BufferedProducer; if (bp != null) { ea.ResponseHead.Headers["Content-Length"] = bp.GetContentLength().ToString(); } } finally { response.OnResponse(ea.ResponseHead, ea.ResponseBodyProducer); } }, error => { }, contentType, contentSize); //Gets complete HTTP Request and runs code defined over requestBody.Connect(bc); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var ea = new RequestReceivedEventArgs(); ea.RequestHead = request; ea.ResponseHead = ResponseMessageHelper.GetHttpResponseHead(); string contentType = string.Empty; if(ea.RequestHead.Headers.ContainsKey("Content-Type")) contentType=ea.RequestHead.Headers["Content-Type"]; int contentSize = 0; if(ea.RequestHead.Headers.ContainsKey("Content-Length")) { int.TryParse(ea.RequestHead.Headers["Content-Length"],out contentSize); } BufferedConsumer bc=new BufferedConsumer(bodyContents => { try { ea.RequestBody = bodyContents; //Called when request body is read to end if (RequestReceived != null) { RequestReceived(this, ea); } var bp = ea.ResponseBodyProducer as BufferedProducer; if (bp != null) { ea.ResponseHead.Headers["Content-Length"] = bp.GetContentLength().ToString(); } } finally { response.OnResponse(ea.ResponseHead, ea.ResponseBodyProducer); } }, error => { }, contentType,contentSize); //Gets complete HTTP Request and runs code defined over requestBody.Connect(bc); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Method.ToUpperInvariant() == "POST" && request.Uri.StartsWith("/bufferedecho")) { // when you subecribe to the request body before calling OnResponse, // the server will automatically send 100-continue if the client is // expecting it. requestBody.Connect(new BufferedConsumer(bufferedBody => { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", request.Headers["Content-Length"] }, { "Connection", "close" } } }; response.OnResponse(headers, new BufferedProducer(bufferedBody)); }, error => { // XXX // uh oh, what happens? })); } else if (request.Method.ToUpperInvariant() == "POST" && request.Uri.StartsWith("/echo")) { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Connection", "close" } } }; if (request.Headers.ContainsKey("Content-Length")) headers.Headers["Content-Length"] = request.Headers["Content-Length"]; // if you call OnResponse before subscribing to the request body, // 100-continue will not be sent before the response is sent. // per rfc2616 this response must have a 'final' status code, // but the server does not enforce it. response.OnResponse(headers, requestBody); } else if (request.Uri.StartsWith("/")) { var body = string.Format( "Hello world.\r\nHello.\r\n\r\nUri: {0}\r\nPath: {1}\r\nQuery:{2}\r\nFragment: {3}\r\n", request.Uri, request.Path, request.QueryString, request.Fragment); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new BufferedProducer(responseBody); response.OnResponse(headers, body); } }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { try { InputHTTPResult.INPUTCOMMAND command = getCommand(request); //POST if (command != InputHTTPResult.INPUTCOMMAND.NOTIMPLEMENTED && command != InputHTTPResult.INPUTCOMMAND.ERROR && request.Method.ToUpperInvariant() == "POST") { requestBody.Connect(new BufferedConsumer(bufferedBody => { Dictionary<String, String> parameters = new Dictionary<String, String>(); foreach (String k in bufferedBody.Split(new char[] { '&' })) { String[] kv = k.Split(new char[] { '=' }); if (kv.Length == 2) parameters.Add(kv[0], System.Web.HttpUtility.UrlDecode(kv[1])); } try { String msg = action.Execute(new InputHTTPResult(command, parameters)); if (msg.Equals("")) msg = "OK"; send200(request, requestBody, response, msg); } catch (Exception e) { send400(request, requestBody, response, e.Message); } }, error => { send400(request, requestBody, response, "no POST variables"); })); } //GET else if (command != InputHTTPResult.INPUTCOMMAND.NOTIMPLEMENTED && command != InputHTTPResult.INPUTCOMMAND.ERROR && request.Method.ToUpperInvariant() == "GET") { Dictionary<String, String> parameters = new Dictionary<String, String>(); foreach (String k in request.QueryString.Split(new char[] { '&' })) { String[] kv = k.Split(new char[] { '=' }); if (kv.Length == 2) parameters.Add(kv[0], System.Web.HttpUtility.UrlDecode(kv[1])); } try { String msg = action.Execute(new InputHTTPResult(command, parameters)); if (msg.Equals("")) msg = "OK"; send200(request, requestBody, response, msg); } catch (Exception e) { send400(request, requestBody, response, e.Message); } } else { send404(request, requestBody, response); } } catch (Exception e) { send400(request, requestBody, response, e.Message); } }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { var verror = "404 Not Found"; var errorString = "Not Found"; try { var path = request.Uri; if (path == "/api") { var method = request.Method; var stream = new MemoryStream(); if (method == "POST") { requestBody.Connect(new BufferedConsumer(bufStream => { HandleAPIRequest(bufStream, method, response); }, error => { Log.Error(error.ToString()); })); } else { HandleAPIRequest(stream, method, response); } return; } else if (path == "/status") { HandleStatusRequest(response); return; } else if (path.StartsWith("/touch/")) { HandleTouchRequest(path, response); return; } else if (path.StartsWith("/flag/")) { HandleFlagRequest(path, response); return; } } catch (Exception ex) { verror = "500 Internal Server Error"; Log.Error(ex.ToString()); errorString = ex.ToString(); } response.OnResponse(new HttpResponseHead() { Status = verror, Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", errorString.Length.ToString() } } }, new BufferedProducer(errorString)); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Uri == "/") { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", "20" }, } }; var body = new BufferedProducer("Hello world.\r\nHello."); response.OnResponse(headers, body); } else if (request.Uri == "/bufferedecho") { // when you subecribe to the request body before calling OnResponse, // the server will automatically send 100-continue if the client is // expecting it. requestBody.Connect(new BufferedConsumer(bufferedBody => { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", request.Headers["Content-Length"] }, { "Connection", "close" } } }; response.OnResponse(headers, new BufferedProducer(bufferedBody)); }, error => { // XXX // uh oh, what happens? })); } else if (request.Uri == "/echo") { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", request.Headers["Content-Length"] }, { "Connection", "close" } } }; // if you call OnResponse before subscribing to the request body, // 100-continue will not be sent before the response is sent. // per rfc2616 this response must have a 'final' status code, // but the server does not enforce it. response.OnResponse(headers, requestBody); } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary<string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new BufferedProducer(responseBody); response.OnResponse(headers, body); } }
/// <summary> /// IHttpRequestHandler.OnRequest internal handler /// </summary> internal void onRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { RESTMethod method; if (Enum.TryParse<RESTMethod>(head.Method, out method)) { Pair<ResourceInstance, object[]> resourceParameterPair = retrieveResource(head.Path, method); ResourceInstance resource = resourceParameterPair.V1; object[] resourceParameters = resourceParameterPair.V2; if (resource != null) { ResourceMethod resourceMethod = resource.GetResourceMethod(method); if (resourceMethod != null) { if (resourceMethod.Parameters.Length == resourceParameters.Length + 1) { NameValueCollection getQuery = HttpUtility.ParseQueryString(head.QueryString ?? ""); // now, if it's a POST, read POST data then if (method == RESTMethod.POST) { var consumer = new BufferedConsumer(bufferedBody => { HttpMultipartParser.MultipartFormDataParser parser = new HttpMultipartParser.MultipartFormDataParser(new MemoryStream(Encoding.Default.GetBytes(bufferedBody))); NameValueCollection postQuery = new NameValueCollection(); foreach (var param in parser.Parameters) postQuery.Add(param.Key, param.Value.Data); Context invocationContext = new Context(new Request(head, postQuery, getQuery)); giveResponse(resourceMethod, invocationContext, response, resourceParameters); }, error => { _logger.Error("IDataProducer.Connect failed", error); }); body.Connect(consumer); } else { Context invocationContext = new Context(new Request(head, getParameters: getQuery)); giveResponse(resourceMethod, invocationContext, response, resourceParameters); } } else { Response notFoundResponse = Response.Error(HttpStatusCode.NotFound); response.OnResponse(notFoundResponse.Head, notFoundResponse.Body); } } else { Response notImplementedResponse = Response.Error(HttpStatusCode.NotImplemented); response.OnResponse(notImplementedResponse.Head, notImplementedResponse.Body); } } else { Response notFoundResponse = Response.Error(HttpStatusCode.NotFound); response.OnResponse(notFoundResponse.Head, notFoundResponse.Body); } } else { Response methodNotAllowedResponse = Response.Error(HttpStatusCode.MethodNotAllowed); response.OnResponse(methodNotAllowedResponse.Head, methodNotAllowedResponse.Body); } }
private static void HandleRequest(HttpRequestHead request, IDataProducer body, IHttpResponseDelegate response, IRequestHandler handler) { _log.DebugFormat("Matched a handler {0}:{1} {2}", handler.Method, handler.Path, DumpQueryParams(handler.QueryParams)); IDataProducer dataProducer = GetDataProducer(request, handler); if (request.HasBody()) { body.Connect(new BufferedConsumer( bufferedBody => { handler.RecordRequest(request, bufferedBody); _log.DebugFormat("Body: {0}", bufferedBody); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); }, error => { _log.DebugFormat("Error while reading body {0}", error.Message); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); } )); } else { response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); handler.RecordRequest(request, null); } _log.DebugFormat("End Processing request for : {0}:{1}", request.Method, request.Uri); }
private void ProcessPOSTRequest(IDataProducer body, IHttpResponseDelegate response) { body.Connect(new BufferedConsumer( (payload) => { try { _parent._systemMetrics.LogCount("listeners.http.bytes", Encoding.UTF8.GetByteCount(payload)); string[] lines = payload.Replace("\r", "").Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); for (int index = 0; index < lines.Length; index++) { _parent._target.Post(lines[index]); } _parent._systemMetrics.LogCount("listeners.http.lines", lines.Length); Respond(response, "200 OK"); } catch { Respond(response, "400 bad request"); } }, (error) => { Respond(response, "500 Internal server error"); })); }
public void OnRequest( HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var env = ToOwinEnvironment(head); if (body == null) env["owin.RequestBody"] = null; else { BodyAction bodyFunc = (onData, onError, onEnd) => { var d = body.Connect(new DataConsumer(onData, onError, onEnd)); return () => { if (d != null) d.Dispose(); }; }; env["owin.RequestBody"] = bodyFunc; } owin(env, HandleResponse(response), HandleError(response)); }
public void OnRequest(HttpRequestHead request, IDataProducer body, IHttpResponseDelegate response) { _log.DebugFormat("Start Processing request for : {0}:{1}", request.Method, request.Uri); if (GetHandlerCount() < 1) { ReturnHttpMockNotFound(response); return; } RequestHandler handler = MatchHandler(request); if (handler == null) { _log.DebugFormat("No Handlers matched"); ReturnHttpMockNotFound(response); return; } _log.DebugFormat("Matched a handler {0},{1}, {2}", handler.Method, handler.Path, DumpQueryParams(handler.QueryParams)); IDataProducer dataProducer = GetDataProducer(request, handler); if (request.HasBody()) { body.Connect(new BufferedConsumer( bufferedBody => { handler.RecordRequest(request, bufferedBody); _log.DebugFormat("Body: {0}", bufferedBody); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); }, error => { _log.DebugFormat("Error while reading body {0}", error.Message); response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); } )); } else { response.OnResponse(handler.ResponseBuilder.BuildHeaders(), dataProducer); handler.RecordRequest(request, null); } _log.DebugFormat("End Processing request for : {0}:{1}", request.Method, request.Uri); }
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response) { if (request.Method.ToUpperInvariant() == "POST" && request.Uri.StartsWith("/bufferedecho")) { // when you subecribe to the request body before calling OnResponse, // the server will automatically send 100-continue if the client is // expecting it. requestBody.Connect(new BufferedConsumer(bufferedBody => { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", request.Headers["Content-Length"] }, { "Connection", "close" } } }; response.OnResponse(headers, new BufferedProducer(bufferedBody)); }, error => { // XXX // uh oh, what happens? })); } else if (request.Method.ToUpperInvariant() == "POST" && request.Uri.StartsWith("/echo")) { var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Connection", "close" } } }; if (request.Headers.ContainsKey("Content-Length")) { headers.Headers["Content-Length"] = request.Headers["Content-Length"]; } // if you call OnResponse before subscribing to the request body, // 100-continue will not be sent before the response is sent. // per rfc2616 this response must have a 'final' status code, // but the server does not enforce it. response.OnResponse(headers, requestBody); } else if (request.Uri.StartsWith("/")) { var body = string.Format( "Hello world.\r\nHello.\r\n\r\nUri: {0}\r\nPath: {1}\r\nQuery:{2}\r\nFragment: {3}\r\n", request.Uri, request.Path, request.QueryString, request.Fragment); var headers = new HttpResponseHead() { Status = "200 OK", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", body.Length.ToString() }, } }; response.OnResponse(headers, new BufferedProducer(body)); } else { var responseBody = "The resource you requested ('" + request.Uri + "') could not be found."; var headers = new HttpResponseHead() { Status = "404 Not Found", Headers = new Dictionary <string, string>() { { "Content-Type", "text/plain" }, { "Content-Length", responseBody.Length.ToString() } } }; var body = new BufferedProducer(responseBody); response.OnResponse(headers, body); } }