SNode.C
Loading...
Searching...
No Matches
SocketContext.cpp
Go to the documentation of this file.
1/*
2 * SNode.C - A Slim Toolkit for Network Communication
3 * Copyright (C) Volker Christian <me@vchrist.at>
4 * 2020, 2021, 2022, 2023, 2024, 2025, 2026
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20/*
21 * MIT License
22 *
23 * Permission is hereby granted, free of charge, to any person obtaining a copy
24 * of this software and associated documentation files (the "Software"), to deal
25 * in the Software without restriction, including without limitation the rights
26 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27 * copies of the Software, and to permit persons to whom the Software is
28 * furnished to do so, subject to the following conditions:
29 *
30 * The above copyright notice and this permission notice shall be included in
31 * all copies or substantial portions of the Software.
32 *
33 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 * THE SOFTWARE.
40 */
41
42#include "web/http/client/SocketContext.h" // IWYU pragma: export
43
44#include "core/EventReceiver.h"
45#include "core/socket/stream/SocketConnection.h"
46#include "web/http/CookieOptions.h"
47#include "web/http/client/Request.h"
48
49#ifndef DOXYGEN_SHOULD_SKIP_THIS
50
51#include "log/Logger.h"
52#include "utils/Timeval.h"
53#include "web/http/http_utils.h"
54
55#include <utility>
56
57#endif /* DOXYGEN_SHOULD_SKIP_THIS */
58
59// #define TRUE 1
60// #define FALSE 0
61
62namespace web::http::client {
63
64 SocketContext::SocketContext(core::socket::stream::SocketConnection* socketConnection,
65 const std::function<void(const std::shared_ptr<MasterRequest>&)>& onHttpConnected,
66 const std::function<void(const std::shared_ptr<MasterRequest>&)>& onHttpDisconnected,
67 const std::string& hostHeader,
68 bool pipelinedRequests)
69 : Super(socketConnection)
70 , onHttpConnected(onHttpConnected)
71 , onHttpDisconnected(onHttpDisconnected)
72 , pipelinedRequests(pipelinedRequests)
73 , masterRequest(std::make_shared<MasterRequest>(this, hostHeader))
74 , parser(
75 this,
76 [this]() {
78 },
79 [this](web::http::client::Response& response) {
80 deliverResponse(std::make_shared<Response>(std::move(response)));
81 },
82 [this](int status, const std::string& reason) {
84 }) {
86 }
87
89 if (!deliveredRequests.empty()) {
90 LOG(DEBUG) << getSocketConnection()->getConnectionName() << " HTTP: Responses missed";
91 for (const std::shared_ptr<MasterRequest>& request : deliveredRequests) {
92 LOG(DEBUG) << " " << request->method << " " << request->url << " HTTP/" << request->httpMajor << "." << request->httpMinor;
93 }
94 }
95
96 if (!pendingRequests.empty()) {
97 LOG(DEBUG) << getSocketConnection()->getConnectionName() << " HTTP: Requests ignored";
98 for (const std::shared_ptr<MasterRequest>& request : pendingRequests) {
99 LOG(DEBUG) << " " << request->method << " " << request->url << " HTTP/" << request->httpMajor << "." << request->httpMinor;
100 }
101 }
102 }
103
104 void SocketContext::requestPrepared(const std::shared_ptr<MasterRequest>& request) {
105 const std::string requestLine = std::string(request->method)
106 .append(" ")
107 .append(request->url)
108 .append(" HTTP/")
109 .append(std::to_string(request->httpMajor))
110 .append(".")
111 .append(std::to_string(request->httpMinor));
112
115 LOG(INFO) << getSocketConnection()->getConnectionName() << " HTTP: Request (" << request->count
116 << ") accepted: " << requestLine;
117 flags = (flags & Flags::HTTP11) | ((request->httpMajor == 1 && request->httpMinor == 1) ? Flags::HTTP11 : Flags::NONE);
118 flags = (flags & Flags::HTTP10) | ((request->httpMajor == 1 && request->httpMinor == 0) ? Flags::HTTP10 : Flags::NONE);
120 (web::http::ciContains(request->header("Connection"), "keep-alive") ? Flags::KEEPALIVE : Flags::NONE);
121 flags = (flags & Flags::CLOSE) | (web::http::ciContains(request->header("Connection"), "close") ? Flags::CLOSE : Flags::NONE);
122
123 pendingRequests.push_back(request);
124
125 LOG(DEBUG) << getSocketConnection()->getConnectionName() << " HTTP: Request (" << request->count << ") queued: " << requestLine
126 << " - QueueSize = " << pendingRequests.size() << " - Flags: " << flags << " - "
127 << web::http::ciContains(request->header("Connection"), "close");
128
129 if (pendingRequests.size() == 1 && (deliveredRequests.empty() || pipelinedRequests)) {
131 }
132 } else {
133 LOG(WARNING) << getSocketConnection()->getConnectionName() << " HTTP: Request (" << request->count
134 << ") rejected: " << requestLine;
135
137 request->url,
138 "HTTP/" + std::to_string(request->httpMajor) + "." + std::to_string(request->httpMinor),
139 request->getQueries(),
140 request->getHeaders(),
141 request->getTrailer(),
142 request->getCookies(),
143 {});
144 }
145 }
146
148 if (!pendingRequests.empty()) {
149 const std::shared_ptr<MasterRequest>& request = pendingRequests.front();
150
151 const std::string requestLine = std::string(request->method)
152 .append(" ")
153 .append(request->url)
154 .append(" HTTP/")
155 .append(std::to_string(request->httpMajor))
156 .append(".")
157 .append(std::to_string(request->httpMinor));
158
159 LOG(DEBUG) << getSocketConnection()->getConnectionName() << " HTTP: Request (" << request->count << ") start: " << requestLine;
160
161 if (!request->initiate(request)) {
162 LOG(WARNING) << getSocketConnection()->getConnectionName() << " HTTP: Request (" << request->count
163 << ") delivering failed: " << requestLine;
164
165 core::EventReceiver::atNextTick([this, masterRequest = static_cast<std::weak_ptr<Request>>(masterRequest)]() {
166 pendingRequests.pop_front();
167 if (!masterRequest.expired() && !pendingRequests.empty()) {
168 const std::shared_ptr<Request>& request = pendingRequests.front();
169
170 LOG(DEBUG) << getSocketConnection()->getConnectionName() << " HTTP: Request (" << request->count
171 << ") dequeued: " << request->method << " " << request->url << " HTTP/" << request->httpMajor << "."
172 << request->httpMinor;
173
175 }
176 });
177 }
178 }
179 }
180
181 void SocketContext::requestDelivered(bool success) {
182 const std::shared_ptr<MasterRequest> currentRequest = std::move(pendingRequests.front());
183 pendingRequests.pop_front();
184
185 const std::string requestLine = std::string(currentRequest->method)
186 .append(" ")
187 .append(currentRequest->url)
188 .append(" HTTP/")
189 .append(std::to_string(currentRequest->httpMajor))
190 .append(".")
191 .append(std::to_string(currentRequest->httpMinor));
192
193 if (success) {
194 LOG(DEBUG) << getSocketConnection()->getConnectionName() << " HTTP: Request (" << currentRequest->count
195 << ") delivered: " << requestLine << " " << pendingRequests.size();
196
197 deliveredRequests.push_back(currentRequest);
198
199 if (pipelinedRequests && !pendingRequests.empty()) {
200 core::EventReceiver::atNextTick([this, masterRequest = static_cast<std::weak_ptr<Request>>(masterRequest)]() {
201 if (!masterRequest.expired()) {
202 const std::shared_ptr<Request>& request = pendingRequests.front();
203
204 LOG(DEBUG) << getSocketConnection()->getConnectionName() << " HTTP: Request (" << request->count
205 << ") dequeued: " << request->method << " " << request->url << " HTTP/" << request->httpMajor << "."
206 << request->httpMinor;
207
209 }
210 });
211 }
212 } else {
213 LOG(WARNING) << getSocketConnection()->getConnectionName() << " HTTP: Request (" << currentRequest->count
214 << ") deliver failed: " << requestLine;
215
217 }
218 }
219
221 if (deliveredRequests.empty()) {
222 LOG(ERROR) << getSocketConnection()->getConnectionName() << " HTTP: Response without delivered request";
223
224 close();
225 }
226 }
227
228 void SocketContext::deliverResponse(const std::shared_ptr<Response>& response) {
229 const std::shared_ptr<MasterRequest> request = std::move(deliveredRequests.front());
230 deliveredRequests.pop_front();
231
232 const std::string requestLine = std::string(request->method)
233 .append(" ")
234 .append(request->url)
235 .append(" HTTP/")
236 .append(std::to_string(request->httpMajor))
237 .append(".")
238 .append(std::to_string(request->httpMinor));
239
240 LOG(INFO) << getSocketConnection()->getConnectionName() << " HTTP: Response received for request (" << request->count
241 << "): " << requestLine;
242
243 LOG(INFO) << getSocketConnection()->getConnectionName() << " HTTP/" << response->httpMajor << "." << response->httpMinor << " "
244 << response->statusCode << " " << response->reason;
245
246 request->deliverResponse(request, response);
247
248 LOG(INFO) << getSocketConnection()->getConnectionName() << " HTTP: Request (" << request->count << ") completed: " << requestLine;
249
250 requestCompleted(response);
251 }
252
253 void SocketContext::deliverResponseParseError(int status, const std::string& reason) {
254 const std::shared_ptr<MasterRequest> request = std::move(deliveredRequests.front());
255 deliveredRequests.pop_front();
256
257 const std::string requestLine = std::string(request->method)
258 .append(" ")
259 .append(request->url)
260 .append(" HTTP/")
261 .append(std::to_string(request->httpMajor))
262 .append(".")
263 .append(std::to_string(request->httpMinor));
264
265 LOG(WARNING) << getSocketConnection()->getConnectionName() << " HTTP: Response parse error: " << reason << " (" << status
266 << ") for request (" << request->count << "): " << requestLine
267 << std::string(request->method)
268 .append(" ")
269 .append(request->url)
270 .append(" HTTP/")
271 .append(std::to_string(request->httpMajor))
272 .append(".")
273 .append(std::to_string(request->httpMinor));
274
275 request->deliverResponseParseError(request, reason);
276
277 close();
278 }
279
280 void SocketContext::requestCompleted(const std::shared_ptr<Response>& response) {
283 ((response->httpMajor == 0 && response->httpMinor == 0) || (response->httpMajor == 1 && response->httpMinor == 0)));
284
285 if (httpClose) {
286 LOG(DEBUG) << getSocketConnection()->getConnectionName() << " HTTP: Connection = Close";
287
289 } else {
290 LOG(DEBUG) << getSocketConnection()->getConnectionName() << " HTTP: Connection = Keep-Alive";
291
292 if (!pipelinedRequests && !pendingRequests.empty()) {
293 core::EventReceiver::atNextTick([this, masterRequest = static_cast<std::weak_ptr<Request>>(masterRequest)]() {
294 if (!masterRequest.expired()) {
295 const std::shared_ptr<Request>& request = pendingRequests.front();
296
297 LOG(DEBUG) << getSocketConnection()->getConnectionName() << " HTTP: Initiating request (" << request->count
298 << "): " << request->method << " " << request->url << " HTTP/" << request->httpMajor << "."
299 << request->httpMinor;
300
302 }
303 });
304 }
305 }
306 }
307
308 void SocketContext::setSseEventReceiver(const std::function<std::size_t()>& onServerSentEvent) {
309 this->onServerSentEvent = onServerSentEvent;
310
312 }
313
319
321 std::size_t consumed = 0;
322
323 if (!httpClose && (!deliveredRequests.empty() || onServerSentEvent)) {
324 if (!onServerSentEvent) {
325 consumed = parser.parse();
326 } else {
327 consumed = onServerSentEvent();
328 }
329 }
330
331 return consumed;
332 }
333
335 while (!deliveredRequests.empty()) {
336 const std::shared_ptr<Response> response(new Response());
337 response->httpVersion = "HTTP/1.1";
338 response->httpMajor = 1;
339 response->httpMinor = 1;
340 response->statusCode = "0";
341 response->reason = "Connection loss";
342
343 deliverResponse(response);
344 }
345
347
348 LOG(INFO) << getSocketConnection()->getConnectionName() << " HTTP: Received disconnect";
349 }
350
351 bool SocketContext::onSignal([[maybe_unused]] int signum) {
352 LOG(INFO) << getSocketConnection()->getConnectionName() << " HTTP: Received signal " << signum;
353
354 return true;
355 }
356
358 // Do nothing in case of an write error
359 }
360
361} // namespace web::http::client
#define LOG(level)
Definition Logger.h:148
static void atNextTick(const std::function< void(void)> &callBack)
virtual void setWriteTimeout(const utils::Timeval &timeout)=0
const std::string & getConnectionName() const
SocketConnection * getSocketConnection() const
SocketContext(core::socket::stream::SocketConnection *socketConnection)
LogMessage(Level level, int verboseLevel=-1, bool withErrno=false)
Definition Logger.cpp:280
std::size_t parse()
Definition Parser.cpp:125
void deliverResponseParseError(const std::shared_ptr< MasterRequest > &request, const std::string &message)
Definition Request.cpp:720
void deliverResponse(const std::shared_ptr< MasterRequest > &request, const std::shared_ptr< Response > &response)
Definition Request.cpp:716
bool initiate(const std::shared_ptr< MasterRequest > &request)
Definition Request.cpp:543
void setMasterRequest(const std::shared_ptr< MasterRequest > &masterRequest)
Definition Request.cpp:106
const CiStringMap< std::string > & getCookies() const
Definition Request.cpp:253
const std::map< std::string, std::string > & getQueries() const
Definition Request.cpp:241
std::string header(const std::string &field) const
Definition Request.cpp:235
const CiStringMap< std::string > & getTrailer() const
Definition Request.cpp:249
const CiStringMap< std::string > & getHeaders() const
Definition Request.cpp:245
ResponseParser(core::socket::stream::SocketContext *socketContext, const std::function< void()> &onResponseStart, const std::function< void(Response &)> &onResponseParsed, const std::function< void(int, const std::string &)> &onResponseParseError)
ConnectionState connectionState
Definition Response.h:74
core::socket::stream::SocketContext Super
void setSseEventReceiver(const std::function< std::size_t()> &onServerSentEvent)
void deliverResponseParseError(int status, const std::string &reason)
web::http::client::Response Response
SocketContext(core::socket::stream::SocketConnection *socketConnection, const std::function< void(const std::shared_ptr< MasterRequest > &)> &onHttpConnected, const std::function< void(const std::shared_ptr< MasterRequest > &)> &onHttpDisconnected, const std::string &hostHeader, bool pipelinedRequests)
std::function< void(const std::shared_ptr< MasterRequest > &)> onHttpConnected
std::size_t onReceivedFromPeer() override
std::function< std::size_t()> onServerSentEvent
std::list< std::shared_ptr< MasterRequest > > deliveredRequests
void onWriteError(int errnum) override
std::function< void(const std::shared_ptr< MasterRequest > &)> onHttpDisconnected
bool onSignal(int signum) override
void requestPrepared(const std::shared_ptr< MasterRequest > &request)
std::shared_ptr< MasterRequest > masterRequest
void deliverResponse(const std::shared_ptr< Response > &response)
std::list< std::shared_ptr< MasterRequest > > pendingRequests
void requestCompleted(const std::shared_ptr< Response > &response)
std::string toString(const std::string &method, const std::string &url, const std::string &version, const std::map< std::string, std::string > &queries, const web::http::CiStringMap< std::string > &header, const web::http::CiStringMap< std::string > &trailer, const web::http::CiStringMap< std::string > &cookies, const std::vector< char > &body)
bool ciContains(const std::string &str1, const std::string &str2)