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