void HandleRequest(WebServerClient client, WebData data) { // add acl headers if (Certificate != null) { data.Result.Headers["Strict-Transport-Security"] = "max-age=604800; includeSubDomains"; } data.Result.Headers["Access-Control-Allow-Headers"] = "Session"; if (data.Method?.PageAttribute?.AuthType == WebServerAuthType.Basic) { data.Result.Headers["Access-Control-Allow-Credentials"] = "true"; data.Result.Headers["Access-Control-Allow-Headers"] += ", Authorization"; } if (!data.Result.Headers.ContainsKey("Access-Control-Allow-Origin")) { data.Result.Headers["Access-Control-Allow-Origin"] = string.IsNullOrEmpty(data.Request.Origin) ? "*" : data.Request.Origin; } if (!data.Result.Headers.ContainsKey("Access-Control-Allow-Methods")) { data.Result.Headers["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"; } if (data.Method?.PageAttribute?.AllowHeaders != null) { data.Result.Headers["Access-Control-Allow-Headers"] += ", " + data.Method.PageAttribute.AllowHeaders; } if (data.Request.Command == WebCommand.OPTIONS) { data.Result.AddMessage(data.Method, "Options transfered successfully."); client.SendAnswer(data); return; } data.Request.LoadPost(client); if (data.Method == null) { Trace.TraceInformation("Static Request: {0}", data.Request); if (StaticRequest != null) { var e = new WebPageEventArgs(data); StaticRequest(this, e); if (e.Handled) { client.SendAnswer(data); return; } } if (EnableTemplates && RunTemplate(data)) { Trace.TraceInformation("Template: {0} {1}", data.Request, data.Result); client.SendAnswer(data); return; } // no method - send static file ? WebAnswer staticFile = GetStaticFile(data.Request); if (staticFile != null) { // file present, send answer Trace.TraceInformation("Static file: {0} {1}", data.Request, staticFile); SetStaticCacheTime(staticFile, StaticPathCacheTime); client.SendAnswer(staticFile); return; } // static path access -> set cache time SetStaticCacheTime(data, StaticPathCacheTime); // file not present, check special functions if (EnableExplain && (data.Request.DecodedUrl.ToLower() == "/explain" || data.Request.DecodedUrl.ToLower() == "/functionlist")) { // special page (function list / explain) explain.Explain(data); } else if (EnableFileListing) { // list files GetStaticFileListing(data); } else { // no static -> error data.Result.AddMessage(data.Request.PlainUrl, WebError.NotFound, $"The requested URL {data.Request.DecodedUrl} was not found on this server."); } client.SendAnswer(data); return; } // invoke method CallMethod(data); // send answer client.SendAnswer(data); }
/// <summary>Handles a client stage1 (preparations).</summary> /// <remarks>Performs the firewall checks and enters stage2.</remarks> internal void HandleClient(WebServerClient client) { System.Globalization.CultureInfo threadCulture = Thread.CurrentThread.CurrentCulture; int threadId = Thread.CurrentThread.ManagedThreadId; WebResultBuilder result = null; try { // callback for connected client ClientConnected?.Invoke(this, new WebClientEventArgs(client)); // do request handling int requestNumber = 0; if (PerformanceChecks) { Trace.TraceInformation( $"HandleClient [{threadId}] <cyan>{client.RemoteEndPoint}<default> ready to receive request. " + $"Elapsed <cyan>{client.StopWatch.Elapsed.FormatTime()}<default>."); } while (client.IsConnected) { result = null; if (PerformanceChecks && requestNumber > 0) { Trace.TraceInformation( $"HandleClient [{threadId}] <cyan>{client.RemoteEndPoint}<default> request <green>{requestNumber}<default> handling completed. " + $"Elapsed <cyan>{client.StopWatch.Elapsed.FormatTime()}<default>."); } // read first request line string firstLine = client.Reader.ReadLine(); client.StopWatch.Reset(); if (PerformanceChecks) { Trace.TraceInformation( $"HandleClient [{threadId}] <cyan>{client.RemoteEndPoint}<default> start handling request <cyan>{++requestNumber}<default>. " + $"Elapsed <cyan>{client.StopWatch.Elapsed.FormatTime()}<default>."); } // load request var request = WebRequest.Load(this, firstLine, client); // prepare web data object var data = new WebData(request, client.StopWatch); result = data.Result; // update thread culture Thread.CurrentThread.CurrentCulture = data.Request.Culture; // handle request but change some default exceptions to web exceptions try { HandleRequest(client, data); } catch (ObjectDisposedException) { Trace.TraceInformation($"HandleClient [{threadId}] <red>{client.RemoteEndPoint}<default> Connection closed"); } catch (InvalidOperationException ex) { throw new WebServerException(ex, WebError.InvalidOperation, 0, ex.Message); } catch (ArgumentException ex) { throw new WebServerException(ex, WebError.InvalidParameters, 0, ex.Message); } } } catch (WebServerException ex) { Trace.TraceInformation(ex.ToString()); if (result == null) { result = new WebResultBuilder(this); } result.AddMessage(WebMessage.Create(ex)); if (ex.Error == WebError.AuthenticationRequired || ex.Error == WebError.InvalidTransactionKey) { result.Headers["WWW-Authenticate"] = $"Basic realm=\"{AssemblyVersionInfo.Program.Company} - {AssemblyVersionInfo.Program.Product}\""; } result.CloseAfterAnswer = true; client.SendAnswer(result.ToAnswer()); } catch (SocketException) { Trace.TraceInformation($"HandleClient [{threadId}] <red>{client.RemoteEndPoint}<default> Connection closed"); /*client closed connection*/ } catch (EndOfStreamException) { /*client closed connection*/ Trace.TraceInformation($"HandleClient [{threadId}] <red>{client.RemoteEndPoint}<default> Connection closed"); } catch (Exception ex) { if (ex.InnerException is SocketException) { Trace.TraceInformation($"HandleClient [{threadId}] <red>{client.RemoteEndPoint}<default> Connection closed"); return; } string supportCode = Base32.Safe.Encode(Environment.TickCount); Trace.TraceError("<red>Unhandled Internal Server Error<default> Code {1}\n{0}", ex.ToString(), supportCode); if (result == null) { result = new WebResultBuilder(this); } result.AddMessage(ex.Source, WebError.InternalServerError, $"Internal Server Error\nUnexpected result on request.\nPlease contact support!\nSupport Code = {supportCode}"); result.CloseAfterAnswer = true; client.SendAnswer(result.ToAnswer()); } finally { while (client.IsConnected && client.Reader.Available == 0) { Thread.Sleep(1); } client.Close(); if (client != null) { ClientDisconnected?.Invoke(this, new WebClientEventArgs(client)); } // reset thread culture if (Thread.CurrentThread.CurrentCulture != threadCulture) { Thread.CurrentThread.CurrentCulture = threadCulture; } } }