public Respond ( Stream outputStream ) : void | ||
outputStream | Stream | The stream in which to copy the output. Does not close the stream |
return | void |
internal void HandleRequest(HTTPRequest request, HTTPResponse response, Stream stream) { try { bool matchFound = false; RouteMapper mapper = null; int i = 0; for (;;) { lock (_routes) { if (i < _routes.Count) { mapper = _routes[i++]; } else { break; } } string regex = "^" + mapper.Route; if (!mapper.AcceptSubroutes) { regex += "$"; } if (Regex.IsMatch(request.BaseURL, regex)) { if ((mapper.Methods & request.Method) != 0) { if (mapper.AcceptSubroutes) { int pos = request.BaseURL.IndexOf(mapper.Route); request.Subroute = request.BaseURL.Substring(0, pos) + request.BaseURL.Substring(pos + mapper.Route.Length); } matchFound = true; break; } } } if (!matchFound) { response.WriteError(HTTPStatusCode.NotFound, "Not Found"); response.Respond(stream); OnError(RoutingErrorType.NO_MATCHES, "No route found for request", request); } else { mapper.HandleRequest(request, response); response.Respond(stream); } } catch (Exception e) { response.WriteError(HTTPStatusCode.InternalServerError, String.Format("Internal Server Error {0}", e.Message)); response.Respond(stream); OnError(RoutingErrorType.INTERNAL, "A RouteHandler threw an exception.", request); } }
private void HandleClient(TcpClient client) { lock (_openTcpClients) _openTcpClients.Add(client); try { Stream stream = client.GetStream(); try { foreach (PreRouteProcessor processor in PreRouteProcessors) { stream = processor.ProcessStream(stream); } bool leaveOpen = true; HTTPResponse response = null; HTTPRequest request = null; StreamReader reader = new StreamReader(stream, Encoding.UTF8, false, 4096); try { while (leaveOpen && !_aborted) { response = new HTTPResponse(); /* * Parse the first line of the HTTP Request * Examples: * GET / HTTP/1.1 * POST /submit HTTP/1.1 */ string requestString; try { requestString = reader.ReadLine(); } catch (Exception) { requestString = null; leaveOpen = false; break; } if (requestString == null) { break; } string[] parts = requestString.Split(' '); if (parts.Length != 3) { throw new HandlingException(HTTPStatusCode.BadRequest, "Bad Request"); } string method = parts[0].ToUpper(); string url = parts[1]; string version = parts[2].ToUpper(); //Check if the version is what we expect if (version != "HTTP/1.1" && version != "HTTP/1.0") { throw new HandlingException(HTTPStatusCode.HttpVersionNotSupported, "HTTP Version Not Supported"); } //Check if the method is supported if (!_supportedMethods.ContainsKey(method)) { throw new HandlingException(HTTPStatusCode.NotImplemented, method + " Method Not Implemented"); } HTTPMethod httpMethod = _supportedMethods[method]; url = HttpUtility.UrlDecode(url); //Build the request object request = new HTTPRequest(httpMethod, url); //Add all headers to the request object FillHeaders(request, reader); //Handle encoding for this request Encoding clientEncoding = InferEncoding(request); //Extract all the data from the URL (base and query) ExtractQuery(request, clientEncoding); //Extract and decode all the POST data ExtractPOST(request, reader, clientEncoding); bool keepAlive = false; // According to spec, Keep-Alive is ON by default if (version == "HTTP/1.1") { keepAlive = true; } if (request.Headers.ContainsKey(HTTPHeader.Connection)) { if (request.Headers[HTTPHeader.Connection].ToLower().Equals("close")) { keepAlive = false; response.SetHeader(HTTPHeader.Connection, "close"); } } //Keep-Alive can only work on a multithreaded server! if (!keepAlive || !MultiThreaded) { leaveOpen = false; response.SetHeader(HTTPHeader.Connection, "close"); } //Pass this on to the route solver OnLog(request, null); Routes.HandleRequest(request, response, stream); OnLog(request, response); } } catch (HandlingException e) { if (response != null) { try { // try to return the response response.WriteError(e.Status, e.ErrorMessage); response.Respond(stream); } catch { // ignore silently if it is not posible } OnLog(request, response); } } catch (ThreadAbortException) { // Do nothing, server is terminating } catch (Exception e) { if (response != null) { try { // try to return the response response.WriteError(HTTPStatusCode.InternalServerError, "Internal Server Error. " + e.Message); response.Respond(stream); } catch { // ignore silently if it is not posible } OnLog(request, response); } } finally { reader.Close(); } } finally { stream.Dispose(); } } finally { lock (_openTcpClients) _openTcpClients.Remove(client); } }
private void HandleClient(TcpClient client) { lock (_openTcpClients) _openTcpClients.Add(client); try { Stream stream = client.GetStream(); try { foreach (PreRouteProcessor processor in PreRouteProcessors) { stream = processor.ProcessStream(stream); } bool leaveOpen = true; HTTPResponse response = null; HTTPRequest request = null; StreamReader reader = new StreamReader(stream, Encoding.UTF8, false, 4096); try { while (leaveOpen && !_aborted) { response = new HTTPResponse(); /* * Parse the first line of the HTTP Request * Examples: * GET / HTTP/1.1 * POST /submit HTTP/1.1 */ string requestString; try { requestString = reader.ReadLine(); } catch (Exception) { requestString = null; leaveOpen = false; break; } if (requestString == null) break; string[] parts = requestString.Split(' '); if (parts.Length != 3) { throw new HandlingException(HTTPStatusCode.BadRequest, "Bad Request"); } string method = parts[0].ToUpper(); string url = parts[1]; string version = parts[2].ToUpper(); //Check if the version is what we expect if (version != "HTTP/1.1" && version != "HTTP/1.0") { throw new HandlingException(HTTPStatusCode.HttpVersionNotSupported, "HTTP Version Not Supported"); } //Check if the method is supported if (!_supportedMethods.ContainsKey(method)) { throw new HandlingException(HTTPStatusCode.NotImplemented, method + " Method Not Implemented"); } HTTPMethod httpMethod = _supportedMethods[method]; url = HttpUtility.UrlDecode(url); //Build the request object request = new HTTPRequest(httpMethod, url); //Add all headers to the request object FillHeaders(request, reader); //Handle encoding for this request Encoding clientEncoding = InferEncoding(request); //Extract all the data from the URL (base and query) ExtractQuery(request, clientEncoding); //Extract and decode all the POST data ExtractPOST(request, reader, clientEncoding); bool keepAlive = false; // According to spec, Keep-Alive is ON by default if (version == "HTTP/1.1") keepAlive = true; if (request.Headers.ContainsKey(HTTPHeader.Connection)) { if (request.Headers[HTTPHeader.Connection].ToLower().Equals("close")) { keepAlive = false; response.SetHeader(HTTPHeader.Connection, "close"); } } //Keep-Alive can only work on a multithreaded server! if (!keepAlive || !MultiThreaded) { leaveOpen = false; response.SetHeader(HTTPHeader.Connection, "close"); } //Pass this on to the route solver OnLog(request, null); Routes.HandleRequest(request, response, stream); OnLog(request, response); } } catch (HandlingException e) { if (response != null) { try { // try to return the response response.WriteError(e.Status, e.ErrorMessage); response.Respond(stream); } catch { // ignore silently if it is not posible } OnLog(request, response); } } catch (ThreadAbortException) { // Do nothing, server is terminating } catch (Exception e) { if (response != null) { try { // try to return the response response.WriteError(HTTPStatusCode.InternalServerError, "Internal Server Error. " + e.Message); response.Respond(stream); } catch { // ignore silently if it is not posible } OnLog(request, response); } } finally { reader.Close(); } } finally { stream.Dispose(); } } finally { lock (_openTcpClients) _openTcpClients.Remove(client); } }
internal void HandleRequest(HTTPRequest request, HTTPResponse response, Stream stream) { try { bool matchFound = false; RouteMapper mapper = null; int i = 0; for (;;) { lock (_routes) { if (i < _routes.Count) mapper = _routes[i++]; else break; } string regex = "^" + mapper.Route; if (!mapper.AcceptSubroutes) { regex += "$"; } if (Regex.IsMatch(request.BaseURL, regex)) { if ((mapper.Methods & request.Method) != 0) { if (mapper.AcceptSubroutes) { int pos = request.BaseURL.IndexOf(mapper.Route); request.Subroute = request.BaseURL.Substring(0, pos) + request.BaseURL.Substring(pos + mapper.Route.Length); } matchFound = true; break; } } } if (!matchFound) { response.WriteError(HTTPStatusCode.NotFound, "Not Found"); response.Respond(stream); OnError(RoutingErrorType.NO_MATCHES, "No route found for request", request); } else { mapper.HandleRequest(request, response); response.Respond(stream); } } catch (Exception e) { response.WriteError(HTTPStatusCode.InternalServerError, String.Format("Internal Server Error {0}", e.Message)); response.Respond(stream); OnError(RoutingErrorType.INTERNAL, "A RouteHandler threw an exception.", request); } }