Stroika Library 3.0d23
 
Loading...
Searching...
No Matches
Frameworks/WebServer/Connection.cpp
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2026. All rights reserved
3 */
4#include "Stroika/Frameworks/StroikaPreComp.h"
5
6#include <algorithm>
7#include <cstdlib>
8
9#include "Stroika/Foundation/Characters/FloatConversion.h"
11#include "Stroika/Foundation/Characters/String2Int.h"
13#include "Stroika/Foundation/Containers/Common.h"
14#include "Stroika/Foundation/DataExchange/BadFormatException.h"
20#include "Stroika/Foundation/Execution/Throw.h"
23#include "Stroika/Foundation/IO/Network/HTTP/ClientErrorException.h"
24#include "Stroika/Foundation/IO/Network/HTTP/Headers.h"
26#include "Stroika/Foundation/IO/Network/HTTP/Methods.h"
29
30#include "Connection.h"
31
32using std::byte;
33
34using namespace Stroika::Foundation;
37using namespace Stroika::Foundation::Execution;
38using namespace Stroika::Foundation::Memory;
39using namespace Stroika::Foundation::Traversal;
40using namespace Stroika::Foundation::Time;
41
42using namespace Stroika::Frameworks;
43using namespace Stroika::Frameworks::WebServer;
44
48
49// Comment this in to turn on aggressive noisy DbgTrace in this module
50// #define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
51
52/*
53 ********************************************************************************
54 ******************** WebServer::Connection::MyMessage_ *************************
55 ********************************************************************************
56 */
57Connection::MyMessage_::MyMessage_ (const ConnectionOrientedStreamSocket::Ptr& socket, const Streams::InputOutputStream::Ptr<byte>& socketStream,
58 const Headers& defaultResponseHeaders, const optional<bool> autoComputeETagResponse)
59 : Message{Request{socketStream}, Response{socket, socketStream, defaultResponseHeaders}, socket.GetPeerAddress ()}
60 , fMsgHeaderInTextStream{HTTP::MessageStartTextInputStreamBinaryAdapter::New (rwRequest ().GetInputStream ())}
61{
62 if (autoComputeETagResponse) {
63 this->rwResponse ().autoComputeETag = *autoComputeETagResponse;
64 }
65}
66
67Connection::MyMessage_::ReadHeadersResult Connection::MyMessage_::ReadHeaders (
68#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
69 const function<void (const String&)>& logMsg
70#endif
71)
72{
73#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
74 logMsg ("Starting ReadHeaders_"sv);
75#endif
76
77 /*
78 * Preflight the request and make sure all the bytes of the header are available. Don't read more than needed.
79 */
80 if (not fMsgHeaderInTextStream.AssureHeaderSectionAvailable ()) {
81#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
82 logMsg ("got fMsgHeaderInTextStream.AssureHeaderSectionAvailable INCOMPLETE"sv);
83#endif
84 if (fMsgHeaderInTextStream.IsAtEOF (Streams::eDontBlock) == true) {
85 return ReadHeadersResult::eIncompleteDeadEnd;
86 }
87 return ReadHeadersResult::eIncompleteButMoreMayBeAvailable;
88 }
89
90 /*
91 * At this stage, blocking calls are fully safe - because we've assured above we've seeked to the start of a CRLFCRLF terminated region (or premature EOF)
92 */
93 Request& updatableRequest = this->rwRequest ();
94 {
95 // Read METHOD URL line
96 String line = fMsgHeaderInTextStream.ReadLine ();
97 if (line.length () == 0) {
98#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
99 logMsg ("got EOF from src stream reading headers(incomplete)"sv);
100#endif
101 return ReadHeadersResult::eIncompleteDeadEnd; // could throw here, but this is common enough we don't want the noise in the logs.
102 }
103 Sequence<String> tokens{line.Tokenize ({' '})};
104 if (tokens.size () < 3) {
105 DbgTrace ("tokens={}, line='{}', fMsgHeaderInTextStream={}"_f, tokens, line, fMsgHeaderInTextStream.ToString ());
106 Throw (ClientErrorException{"Bad METHOD Request HTTP line ({})"_f(line)});
107 }
108 updatableRequest.httpMethod = tokens[0];
109 updatableRequest.httpVersion = tokens[2];
110 if (tokens[1].empty ()) {
111 // should check if GET/PUT/DELETE etc...
112 DbgTrace ("tokens={}, line='{}'"_f, tokens, line);
113 Throw (ClientErrorException{"Bad HTTP Request line - missing host-relative URL"sv});
114 }
115 updatableRequest.url = URI::ParseRelative (tokens[1]);
116 if (updatableRequest.httpMethod ().empty ()) {
117 // should check if GET/PUT/DELETE etc...
118 DbgTrace ("tokens={}, line='{}'"_f, tokens, line);
119 static const auto kException_ = ClientErrorException{"Bad METHOD in Request HTTP line"sv};
120 Throw (kException_);
121 }
122 }
123 while (true) {
124 static const String kCRLF_{"\r\n"sv};
125 String line = fMsgHeaderInTextStream.ReadLine ();
126 if (line == kCRLF_ or line.empty ()) {
127 break; // done
128 }
129
130 // add subsequent items to the header map
131 size_t i = line.find (':');
132 if (i == string::npos) {
133 DbgTrace ("line={}"_f, line);
134 Throw (ClientErrorException{"Bad HTTP Request missing colon in headers"sv});
135 }
136 else {
137 String hdr = line.SubString (0, i).Trim ();
138 String value = line.SubString (i + 1).Trim ();
139 updatableRequest.rwHeaders ().Add (hdr, value);
140 }
141 }
142#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
143 logMsg ("ReadHeaders completed normally"sv);
144#endif
145 return ReadHeadersResult::eCompleteGood;
146}
147
148/*
149 ********************************************************************************
150 ************************* WebServer::Connection::Stats *************************
151 ********************************************************************************
152 */
154{
155 StringBuilder sb;
156 sb << "{";
157 sb << "socket: " << fSocketID;
158 sb << ", createdAt: " << fCreatedAt;
159 if (fActive) {
160 if (*fActive) {
161 sb << ", active ";
162 }
163 else {
164 sb << ", inactive ";
165 }
166 }
167#if qStroika_Framework_WebServer_Connection_TrackExtraStats
168 if (fMostRecentMessage) {
169 sb << ", mostRecentMessage: " << *fMostRecentMessage;
170 }
171 if (fHandlingThread) {
172 if (fActive == true) {
173 sb << ", handlingThread: " << fHandlingThread;
174 }
175 else {
176 sb << ", thread: " << fHandlingThread;
177 }
178 }
180 sb << ", " << fRequestWebMethod << " " << fRequestURI;
181 }
182 if (fRemotePeerAddress) {
183 sb << ", from: " << *fRemotePeerAddress;
184 }
185#endif
186 sb << "}";
187 return sb;
188}
189
190/*
191 ********************************************************************************
192 ***************************** WebServer::Connection ****************************
193 ********************************************************************************
194 */
195Connection::Connection (const ConnectionOrientedStreamSocket::Ptr& s, const InterceptorChain& interceptorChain, const Headers& defaultResponseHeaders,
196 const optional<Headers>& defaultGETResponseHeaders, const optional<bool> autoComputeETagResponse)
197 : Connection{s, Options{.fInterceptorChain = interceptorChain,
198 .fDefaultResponseHeaders = defaultResponseHeaders,
199 .fDefaultGETResponseHeaders = defaultGETResponseHeaders,
200 .fAutoComputeETagResponse = autoComputeETagResponse}}
201{
202}
203
204Connection::Connection (const ConnectionOrientedStreamSocket::Ptr& s, const Options& options)
205 : socket{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> ConnectionOrientedStreamSocket::Ptr {
206 const Connection* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &Connection::socket);
207 AssertExternallySynchronizedMutex::ReadContext declareContext{*thisObj};
208 return thisObj->fSocket_;
209 }}
210 , request{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> const Request& {
211 const Connection* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &Connection::request);
212 AssertExternallySynchronizedMutex::ReadContext declareContext{*thisObj};
213 return thisObj->fMessage_->request ();
214 }}
215 , response{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> const Response& {
216 const Connection* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &Connection::response);
217 AssertExternallySynchronizedMutex::ReadContext declareContext{*thisObj};
218 return thisObj->fMessage_->response ();
219 }}
220 , rwResponse{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Response& {
221 Connection* thisObj = const_cast<Connection*> (qStroika_Foundation_Common_Property_OuterObjPtr (property, &Connection::rwResponse));
222 AssertExternallySynchronizedMutex::WriteContext declareContext{*thisObj};
223 return thisObj->fMessage_->rwResponse ();
224 }}
225 , stats{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Stats {
226 const Connection* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &Connection::stats);
227 // NO - INTERNALLY SYNCHRONIZED!!! AssertExternallySynchronizedMutex::ReadContext declareContext{*thisObj};
228 auto uniqueID = thisObj->fSocket_.GetNativeSocket (); // safe because fSocket_ is a const Ptr, and GetNativeSocket () is a const method, so never modified and can be safely used without synchronization
229 TimePointSeconds createdAt{thisObj->fConnectionStartedAt_}; // also similar logic - const
230#if qStroika_Framework_WebServer_Connection_TrackExtraStats
231 Stats2Capture_ statsCapturedDuringMessageProcessing = thisObj->fExtraStats_.load ();
232#endif
233 Stats stats{
234 .fSocketID = uniqueID,
235 .fCreatedAt = createdAt,
236#if qStroika_Framework_WebServer_Connection_TrackExtraStats
237 .fMostRecentMessage = statsCapturedDuringMessageProcessing.fMessageStart
238 ? Range<TimePointSeconds>{statsCapturedDuringMessageProcessing.fMessageStart,
239 statsCapturedDuringMessageProcessing.fMessageCompleted}
240 : optional<Range<TimePointSeconds>>{},
241 .fHandlingThread = statsCapturedDuringMessageProcessing.fHandlingThread,
242 .fRemotePeerAddress = statsCapturedDuringMessageProcessing.fPeer,
243 .fRequestWebMethod = statsCapturedDuringMessageProcessing.fWebMethod,
244 .fRequestURI = statsCapturedDuringMessageProcessing.fRequestURI,
245#endif
246 };
247 return stats;
248 }}
250 [qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> optional<HTTP::KeepAlive> {
251 const Connection* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &Connection::remainingConnectionLimits);
252 AssertExternallySynchronizedMutex::ReadContext declareContext{*thisObj};
253 return thisObj->fRemaining_;
254 },
255 [qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] auto* property, const auto& remainingConnectionLimits) {
256 Connection* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &Connection::remainingConnectionLimits);
257 AssertExternallySynchronizedMutex::WriteContext declareContext{*thisObj};
258 thisObj->fRemaining_ = remainingConnectionLimits;
259 }}
260 , fInterceptorChain_{options.fInterceptorChain}
261 , fDefaultResponseHeaders_{options.fDefaultResponseHeaders}
262 , fDefaultGETResponseHeaders_{options.fDefaultGETResponseHeaders}
263 , fAutoComputeETagResponse_{options.fAutoComputeETagResponse}
264 , fSupportedCompressionEncodings_{options.fSupportedCompressionEncodings}
265 , fSocket_{s}
266 , fConnectionStartedAt_{Time::GetTickCount ()}
267{
268 Require (s != nullptr);
269#if USE_NOISY_TRACE_IN_THIS_MODULE_
270 DbgTrace ("Created connection for socket {}"_f, s);
271#endif
272 fSocketStream_ = SocketStream::New (fSocket_);
273#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
274 {
275 String socketName = "{}-{}"_f((long)DateTime::Now ().As<time_t> (), (int)s.GetNativeSocket ());
276 fSocketStream_ = Streams::LoggingInputOutputStream<byte>::New (
277 fSocketStream_,
278 IO::FileSystem::FileOutputStream::New (IO::FileSystem::WellKnownLocations::GetTemporary () + "socket-{}-input-trace.txt"_f(socketName)),
279 IO::FileSystem::FileOutputStream::New (IO::FileSystem::WellKnownLocations::GetTemporary () + "socket-{}output-trace.txt"_f(socketName)));
280 fLogConnectionState_ = Streams::TextToBinary::Writer::New (
281 IO::FileSystem::FileOutputStream::New (IO::FileSystem::WellKnownLocations::GetTemporary () + "socket-{}-highlevel-trace.txt"_f(socketName)),
282 Streams::TextToBinary::Writer::Format::eUTF8WithoutBOM);
283 }
284#endif
285}
286
287Connection::~Connection ()
288{
289#if USE_NOISY_TRACE_IN_THIS_MODULE_
290 DbgTrace ("Destroying connection for socket {}, message={}"_f, fSocket_, static_cast<const void*> (fMessage_.get ()));
291#endif
292 AssertExternallySynchronizedMutex::WriteContext declareContext{*this};
293#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
294 WriteLogConnectionMsg_ (L"DestroyingConnection");
295#endif
296 if (fMessage_ != nullptr) {
297 if (not fMessage_->response ().responseCompleted ()) {
298 IgnoreExceptionsForCall (fMessage_->rwResponse ().Abort ());
299 }
300 Require (fMessage_->response ().responseCompleted ());
301 }
302 /*
303 * When the connection is completed, make sure the socket is closed so that the calling client knows
304 * as quickly as possible. Probably not generally necessary since when the last reference to the socket
305 * goes away, it will also be closed, but that might take a little longer as its held in some object
306 * that hasn't gone away yet.
307 */
308 AssertNotNull (fSocket_);
309 try {
310 fSocket_.Close ();
311 }
312 catch (...) {
313 DbgTrace ("Exception ignored closing socket: {}"_f, current_exception ());
314 }
315}
316
317Connection::ReadAndProcessResult Connection::ReadAndProcessMessage () noexcept
318{
319 AssertExternallySynchronizedMutex::WriteContext declareContext{*this};
320 try {
321#if USE_NOISY_TRACE_IN_THIS_MODULE_
322 Debug::TraceContextBumper ctx{"Connection::ReadAndProcessMessage", "this->socket={}"_f, fSocket_};
323#endif
324 fMessage_ = make_unique<MyMessage_> (fSocket_, fSocketStream_, fDefaultResponseHeaders_, fAutoComputeETagResponse_);
325#if qStroika_Foundation_Debug_AssertExternallySynchronizedMutex_Enabled
326 fMessage_->SetAssertExternallySynchronizedMutexContext (GetSharedContext ());
327#endif
328
329 auto readHeaders = [&] () -> optional<ReadAndProcessResult> {
330 switch (fMessage_->ReadHeaders (
331#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
332 [this] (const String& i) -> void { WriteLogConnectionMsg_ (i); }
333#endif
334 )) {
335 case MyMessage_::eIncompleteDeadEnd: {
336 DbgTrace ("ReadHeaders failed (socket {}) - incomplete data read from client."_f,
337 fSocket_); // sometimes because the client closed the connection before we could handle: e.g. user in web browser hitting refresh button fast
338 return eClose; // don't keep-alive - so this closes connection
339 } break;
340 case MyMessage_::eIncompleteButMoreMayBeAvailable: {
341 DbgTrace ("ReadHeaders failed - incomplete header (most likely a DOS attack)."_f);
342 return ReadAndProcessResult::eTryAgainLater;
343 } break;
344 case MyMessage_::eCompleteGood: {
345 // fall through and actually process the request
346 return nullopt;
347 } break;
348 default:
350 return nullopt;
351 }
352 };
353 // First read the HTTP request line, and the headers (and abort this ReadAndProcessMessage attempt if not ready)
354 if (auto r = readHeaders ()) {
355 return *r;
356 }
357
358 // if we get this far, we always complete processing the message
359#if qStroika_Foundation_Debug_AssertionsChecked
360 [[maybe_unused]] auto&& cleanup = Finally ([&] () noexcept { Ensure (fMessage_->response ().responseCompleted ()); });
361#endif
362
363#if qStroika_Framework_WebServer_Connection_TrackExtraStats
364 [[maybe_unused]] auto&& cleanup2 =
365 Finally ([&] () noexcept { fExtraStats_.rwget ().rwref ().fMessageCompleted = Time::GetTickCount (); });
366 fExtraStats_.store (Stats2Capture_{.fMessageStart = Time::GetTickCount (),
367 .fPeer = fSocket_.GetPeerAddress (),
368 .fWebMethod = fMessage_->request ().httpMethod (),
369 .fRequestURI = fMessage_->request ().url (),
370 .fHandlingThread = std::this_thread::get_id ()});
371#endif
372
373 auto applyDefaultsToResponseHeaders = [&] () -> void {
374 if (fDefaultGETResponseHeaders_ and fMessage_->request ().httpMethod () == HTTP::Methods::kGet) {
375 fMessage_->rwResponse ().rwHeaders () += *fDefaultGETResponseHeaders_;
376 }
377 // https://tools.ietf.org/html/rfc7231#section-7.1.1.2 : ...An origin server MUST send a Date header field in all other cases
378 fMessage_->rwResponse ().rwHeaders ().date = DateTime::Now ();
379
380 // @todo can short-circuit the acceptEncoding logic if not bodyHasEntity...(but careful about checking that cuz no content yet
381 // so may need to revisit the bodyHasEntity logic) - just look at METHOD of request and http-status - oh - that cannot check
382 // yet/until done... so maybe need other check like bodyCannotHaveEntity - stuff can check before filled out response?
383 if (optional<HTTP::ContentEncodings> acceptEncoding = fMessage_->request ().headers ().acceptEncoding) {
384 optional<HTTP::ContentEncodings> oBodyEncoding = fMessage_->rwResponse ().bodyEncoding ();
385 auto addCT = [this, &oBodyEncoding] (HTTP::ContentEncoding contentEncoding2Add) {
386 fMessage_->rwResponse ().bodyEncoding = [&] () {
387 if (oBodyEncoding) {
388 auto bc = *oBodyEncoding;
389 bc += contentEncoding2Add;
390 return bc;
391 }
392 else {
393 return HTTP::ContentEncodings{contentEncoding2Add};
394 }
395 }();
396 };
397 bool needBodyEncoding = not oBodyEncoding.has_value ();
398 // prefer deflate over gzip cuz smaller header and otherwise same
399 auto maybeAddIt = [&] (HTTP::ContentEncoding ce) {
400 if (needBodyEncoding and acceptEncoding->Contains (ce) and
401 (fSupportedCompressionEncodings_ == nullopt or fSupportedCompressionEncodings_->Contains (ce))) {
402 addCT (ce);
403 needBodyEncoding = false;
404 }
405 };
406 if constexpr (DataExchange::Compression::Deflate::kSupported) {
408 }
409 if constexpr (DataExchange::Compression::GZip::kSupported) {
410 maybeAddIt (HTTP::ContentEncoding::kGZip);
411 }
412 if constexpr (DataExchange::Compression::ZStd::kSupported) {
413 maybeAddIt (HTTP::ContentEncoding::kZStd);
414 }
415 // @todo add zstd, and others? zstd best probably...
416 }
417
418 if (auto requestedINoneMatch = this->request ().headers ().ifNoneMatch ()) {
419 if (this->response ().autoComputeETag ()) {
420 this->rwResponse ().automaticTransferChunkSize =
421 Response::kNoChunkedTransfer; // cannot start response xfer til we've computed etag (meaning seen all the body bytes)
422 }
423 }
424 };
425 applyDefaultsToResponseHeaders ();
426
427 /*
428 * Now bookkeeping and handling of keepalive headers
429 */
430 auto applyKeepAliveLogic = [&] () -> bool {
431 bool thisMessageKeepAlive = fMessage_->request ().keepAliveRequested;
432 if (thisMessageKeepAlive) {
433
434 // Check for keepalive headers, and handle/merge them appropriately
435 // only meaningful HTTP 1.1 and earlier and only if Connection: keep-alive
436 if (auto keepAliveValue = fMessage_->request ().headers ().keepAlive ()) {
437 this->remainingConnectionLimits = KeepAlive::Merge (this->remainingConnectionLimits (), *keepAliveValue);
438 }
439 // if missing, no limits
440 if (auto oRemaining = remainingConnectionLimits ()) {
441 if (oRemaining->fMessages) {
442 if (oRemaining->fMessages == 0u) {
443 thisMessageKeepAlive = false;
444 }
445 else {
446 oRemaining->fMessages = *oRemaining->fMessages - 1u;
447 }
448 }
449 if (oRemaining->fTimeout) {
450 if (fConnectionStartedAt_ + *oRemaining->fTimeout < Time::GetTickCount ()) {
451 thisMessageKeepAlive = false;
452 }
453 }
454 }
455 }
456 // From https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
457 // HTTP/1.1 applications that do not support persistent connections MUST include the "close" connection option in every message.
458 this->rwResponse ().rwHeaders ().connection = thisMessageKeepAlive ? Headers::eKeepAlive : Headers::eClose;
459 return thisMessageKeepAlive;
460 };
461 bool thisMessageKeepAlive = applyKeepAliveLogic ();
462
463 /**
464 * Delegate to interceptor chain. This is the principle EXTENSION point for the Stroika Framework webserver. This is where you modify
465 * the response somehow or other (typically through routes).
466 */
467 auto invokeInterceptorChain = [&] () {
468#if USE_NOISY_TRACE_IN_THIS_MODULE_
469 DbgTrace ("Handing request {} to interceptor chain"_f, request ().ToString ());
470#endif
471#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
472 WriteLogConnectionMsg_ ("Handing request {} to interceptor chain"_f(request ()));
473#endif
474 try {
475 fInterceptorChain_.HandleMessage (*fMessage_);
476 }
477 catch (...) {
478#if USE_NOISY_TRACE_IN_THIS_MODULE_
479 DbgTrace ("Interceptor-Chain caught exception handling message: {}"_f, current_exception ());
480#endif
481#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
482 WriteLogConnectionMsg_ ("Interceptor-Chain caught exception handling message: {}"_f(current_exception ()));
483#endif
484 }
485 };
486 invokeInterceptorChain ();
487
488 auto assureRequestFullyRead = [&] () {
489 if (thisMessageKeepAlive) {
490 // be sure we advance the read pointer over the message body,
491 // lest we start reading part of the previous message as the next message
492
493 // @todo must fix this for support of Transfer-Encoding, but from:
494 //
495 /*
496 * https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
497 * The rules for when a message-body is allowed in a message differ for requests and responses.
498 *
499 * The presence of a message-body in a request is signaled by the inclusion of a Content-Length
500 * or Transfer-Encoding header field in the request's message-headers/
501 */
502 if (request ().headers ().contentLength ()) {
503#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
504 WriteLogConnectionMsg_ (L"msg is keepalive, and have content length, so making sure we read all of request body");
505#endif
506#if USE_NOISY_TRACE_IN_THIS_MODULE_
507 DbgTrace ("Assuring all data read; REQ={}"_f, request ().ToString ());
508#endif
509 // @todo - this can be more efficient in the rare case we ignore the body - but that's rare enough to not matter much
510 (void)fMessage_->rwRequest ().GetBody ();
511 }
512 }
513 };
514 assureRequestFullyRead ();
515
516 /*
517 * By this point, the response has been fully built, and so we can potentially redo the response as a 304-not-modified, by
518 * comparing the ETag with the ifNoneMatch header.
519 */
520 auto completeResponse = [&] () {
521 if (not this->response ().responseStatusSent () and HTTP::IsOK (this->response ().status)) {
522 if (auto requestedINoneMatch = this->request ().headers ().ifNoneMatch ()) {
523 if (auto actualETag = this->response ().headers ().ETag ()) {
524 bool ctm = this->response ().chunkedTransferMode ();
525 if (ctm) {
526 DbgTrace ("Warning - disregarding ifNoneMatch request (though it matched) - cuz in chunked transfer mode"_f);
527 }
528 if (requestedINoneMatch->fETags.Contains (*actualETag) and not ctm) {
529 DbgTrace ("Updating OK response to NotModified (due to ETag match)"_f);
530 this->rwResponse ().status = HTTP::StatusCodes::kNotModified; // this assignment automatically prevents sending data
531 }
532 }
533 }
534 }
535 if (not this->rwResponse ().End ()) {
536 thisMessageKeepAlive = false;
537 }
538#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
539 WriteLogConnectionMsg_ (L"Did GetResponse ().End ()");
540#endif
541 };
542 completeResponse ();
543
544 return thisMessageKeepAlive ? eTryAgainLater : eClose;
545 }
546 catch (...) {
547 DbgTrace ("ReadAndProcessMessage Exception caught ({}), so returning ReadAndProcessResult::eClose"_f, current_exception ());
548 this->rwResponse ().Abort ();
549 return Connection::ReadAndProcessResult::eClose;
550 }
551}
552
553#if qStroika_Framework_WebServer_Connection_DetailedMessagingLog
554void Connection::WriteLogConnectionMsg_ (const String& msg) const
555{
556 String useMsg = DateTime::Now ().Format () + " -- "sv + msg.Trim ();
557 fLogConnectionState_.WriteLn (useMsg);
558}
559#endif
560
561String Connection::ToString (bool abbreviatedOutput) const
562{
563 AssertExternallySynchronizedMutex::ReadContext declareContext{*this};
564 StringBuilder sb;
565 sb << "{"sv;
566 sb << "Socket: "sv << fSocket_;
567 if (not abbreviatedOutput) {
568 sb << ", Message: "sv << fMessage_;
569 sb << ", Remaining: "sv << fRemaining_;
570 }
571 sb << ", Connection-Started-At: "sv << fConnectionStartedAt_;
572 sb << "}"sv;
573 return sb;
574}
#define AssertNotNull(p)
Definition Assertions.h:334
#define AssertNotReached()
Definition Assertions.h:356
time_point< RealtimeClock, DurationSeconds > TimePointSeconds
TimePointSeconds is a simpler approach to chrono::time_point, which doesn't require using templates e...
Definition Realtime.h:82
#define DbgTrace
Definition Trace.h:317
Similar to String, but intended to more efficiently construct a String. Mutable type (String is large...
String is like std::u32string, except it is much easier to use, often much more space efficient,...
Definition String.h:201
nonvirtual size_t length() const noexcept
Definition String.inl:1051
nonvirtual String SubString(SZ from) const
nonvirtual String Trim(bool(*shouldBeTrimmed)(Character)=Character::IsWhitespace) const
Definition String.cpp:1593
nonvirtual Containers::Sequence< String > Tokenize() const
Definition String.cpp:1235
nonvirtual size_t find(Character c, size_t startAt=0) const
Definition String.inl:1067
A generalization of a vector: a container whose elements are keyed by the natural numbers.
nonvirtual WritableReference rwget()
get a read-write smart pointer to the underlying Synchronized<> object, holding the full lock the who...
nonvirtual optional< IO::Network::SocketAddress > GetPeerAddress() const
ClientErrorException is to capture exceptions caused by a bad (e.g ill-formed) request.
roughly equivalent to Association<String,String>, except that the class is smart about certain keys a...
Definition Headers.h:129
Common::Property< String > httpMethod
typically HTTP::Methods::kGet
nonvirtual PlatformNativeHandle GetNativeSocket() const
Definition Socket.inl:52
static URI ParseRelative(const String &rawRelativeURL)
Definition URI.cpp:150
InputOutputStream is single stream object that acts much as a InputStream::Ptr and an OutputStream::P...
A Connection object represents the state (and socket) for an ongoing, active, HTTP Connection,...
Common::Property< optional< HTTP::KeepAlive > > remainingConnectionLimits
const Common::ReadOnlyProperty< Stats > stats
retrieve stats about this connection, like threads used, start/end times. NB: INTERNALLY SYNCRONIZED
const Common::ReadOnlyProperty< ConnectionOrientedStreamSocket::Ptr > socket
nonvirtual ReadAndProcessResult ReadAndProcessMessage() noexcept
const Common::ReadOnlyProperty< const Request & > request
const Common::ReadOnlyProperty< const Response & > response
nonvirtual String ToString(bool abbreviatedOutput=true) const
nonvirtual void HandleMessage(Message &m) const
this represents a HTTP request object for the WebServer module
CONTAINER::value_type * End(CONTAINER &c)
For a contiguous container (such as a vector or basic_string) - find the pointer to the end of the co...
void Throw(T &&e2Throw)
identical to builtin C++ 'throw' except that it does helpful, type dependent DbgTrace() messages firs...
Definition Throw.inl:43
auto Finally(FUNCTION &&f) -> Private_::FinallySentry< FUNCTION >
Definition Finally.inl:31
constexpr bool IsOK(Status s)
several status codes considered OK, so check if it is among them
Definition Status.inl:12
Ptr New(const Streams::OutputStream::Ptr< byte > &src, const Characters::CodeCvt<> &char2OutputConverter)
Content coding values indicate an encoding transformation that has been or can be applied to an entit...
static const ContentEncoding kZStd
probably fastest/best, but NYI in Stroika as of 2024-06-20
optional< URI > fRequestURI
last requested URI (always relative uri)
optional< SocketAddress > fRemotePeerAddress
the address of the client which is talking to the server