SNode.C
Loading...
Searching...
No Matches
Response.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
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/server/Response.h"
43
44#include "SocketContext.h"
45#include "core/file/FileReader.h"
46#include "core/socket/stream/SocketConnection.h"
47#include "web/http/MimeTypes.h"
48#include "web/http/StatusCodes.h"
49#include "web/http/server/SocketContextUpgradeFactorySelector.h"
50
51#ifndef DOXYGEN_SHOULD_SKIP_THIS
52
53#include "log/Logger.h"
54#include "utils/system/time.h"
55#include "web/http/CiStringMap.h"
56#include "web/http/http_utils.h"
57
58#include <cerrno>
59#include <filesystem>
60#include <iterator>
61#include <numeric>
62#include <sstream>
63#include <system_error>
64#include <utility>
65
66#endif /* DOXYGEN_SHOULD_SKIP_THIS */
67
68#define to_hex_str(int_val) (static_cast<std::ostringstream const&>(std::ostringstream() << std::uppercase << std::hex << int_val)).str()
69
70namespace web::http::server {
71
73 : socketContext(socketContext) {
74 }
75
77 if (socketContext != nullptr && Sink::isStreaming()) {
79 }
80 }
81
83 stop();
84 }
85
86 void Response::init() {
87 statusCode = 200;
88 httpMajor = 1;
89 httpMinor = 1;
90 headers.clear();
91 cookies.clear();
92 trailer.clear();
93 contentLength = 0;
94 contentSent = 0;
97 }
98
99 Response& Response::status(int statusCode) {
100 this->statusCode = statusCode;
101
102 return *this;
103 }
104
105 Response& Response::append(const std::string& field, const std::string& value) {
106 const std::map<std::string, std::string>::iterator it = headers.find(field);
107
108 if (it != headers.end()) {
109 set(field, it->second.append(", ").append(value));
110 } else {
111 set(field, value);
112 }
113
114 return *this;
115 }
116
117 Response& Response::set(const std::map<std::string, std::string>& headers, bool overwrite) {
118 for (const auto& [field, value] : headers) {
119 set(field, value, overwrite);
120 }
121
122 return *this;
123 }
124
125 Response& Response::set(const std::string& field, const std::string& value, bool overwrite) {
126 if (!value.empty()) {
127 if (overwrite) {
128 headers.insert_or_assign(field, value);
129 } else {
130 headers.insert({field, value});
131 }
132
133 if (web::http::ciEquals(field, "Connection")) {
134 if (web::http::ciContains(headers[field], "keep-alive")) {
136 } else if (web::http::ciContains(headers[field], "close")) {
138 }
139 } else if (web::http::ciEquals(field, "Content-Length")) {
140 contentLength = std::stoul(value);
142 headers.erase("Transfer-Encoding");
143 } else if (web::http::ciEquals(field, "Transfer-Encoding")) {
144 if (web::http::ciContains(headers[field], "chunked")) {
146 headers.erase("Content-Length");
147 }
148 if (web::http::ciContains(headers[field], "compressed")) {
149 }
150 if (web::http::ciContains(headers[field], "deflate")) {
151 }
152 if (web::http::ciContains(headers[field], "gzip")) {
153 }
154 } else if (web::http::ciEquals(field, "Content-Encoding")) {
155 if (web::http::ciContains(headers[field], "compressed")) {
156 }
157 if (web::http::ciContains(headers[field], "deflate")) {
158 }
159 if (web::http::ciContains(headers[field], "gzip")) {
160 }
161 if (web::http::ciContains(headers[field], "br")) {
162 }
163 }
164 } else {
165 headers.erase(field);
166 }
167
168 return *this;
169 }
170
171 Response& Response::type(const std::string& type) {
172 return set("Content-Type", type);
173 }
174
175 Response& Response::cookie(const std::string& name, const std::string& value, const std::map<std::string, std::string>& options) {
176 cookies.insert({name, CookieOptions(value, options)});
177
178 return *this;
179 }
180
181 Response& Response::clearCookie(const std::string& name, const std::map<std::string, std::string>& options) {
182 std::map<std::string, std::string> opts = options;
183
184 opts.erase("Max-Age");
185 const time_t time = 0;
186 opts["Expires"] = httputils::to_http_date(utils::system::gmtime(&time));
187
188 return cookie(name, "", opts);
189 }
190
191 Response& Response::setTrailer(const std::string& field, const std::string& value, bool overwrite) {
192 if (!value.empty()) {
193 if (overwrite) {
194 trailer.insert_or_assign(field, value);
195 } else {
196 trailer.insert({field, value});
197 }
198 if (!headers.contains("Trailer")) {
199 set("Trailer", field);
200 } else {
201 headers["Trailer"].append("," + field);
202 }
203 } else {
204 trailer.erase(field);
205 }
206
207 return *this;
208 }
209
210 void Response::send(const char* chunk, std::size_t chunkLen) {
211 if (chunkLen > 0) {
212 set("Content-Type", "application/octet-stream", false);
213 }
214 set("Content-Length", std::to_string(chunkLen));
215
217 sendFragment(chunk, chunkLen);
219 }
220
221 void Response::send(const std::string& chunk) {
222 if (!chunk.empty()) {
223 set("Content-Type", "text/html; charset=utf-8", false);
224 }
225
226 send(chunk.data(), chunk.size());
227 }
228
229 void Response::sendStatus(int statusCode) {
230 status(statusCode);
231
233 }
234
235 /* Just an UML-Sequence diagram test */
236 /** Sequence diagram of res.upgrade(req).
237@startuml
238!include web/http/server/pu/response_upgrade.pu
239@enduml
240 */
241 void Response::upgrade(const std::shared_ptr<Request>& request, const std::function<void(const std::string&)>& status) {
242 const std::string connectionName = socketContext->getSocketConnection()->getConnectionName();
243
244 std::string name;
245
246 LOG(DEBUG) << connectionName << " HTTP: Initiating upgrade: " << request->method << " " << request->url
247 << " HTTP/" + std::to_string(httpMajor) + "." + std::to_string(httpMinor) << "\n"
249 request->url,
250 "HTTP/" + std::to_string(request->httpMajor) + "." + std::to_string(request->httpMinor),
251 request->queries,
252 request->headers,
253 request->cookies,
254 std::vector<char>());
255
256 if (socketContext != nullptr) {
257 if (request != nullptr) {
258 if (web::http::ciContains(request->get("connection"), "Upgrade")) {
259 SocketContextUpgradeFactory* socketContextUpgradeFactory =
261
262 if (socketContextUpgradeFactory != nullptr) {
263 name = socketContextUpgradeFactory->name();
264
265 LOG(DEBUG) << connectionName << " HTTP upgrade: SocketContextUpgradeFactory create success for: " << name;
266
267 core::socket::stream::SocketContext* socketContextUpgrade =
268 socketContextUpgradeFactory->create(socketContext->getSocketConnection());
269
270 if (socketContextUpgrade != nullptr) {
271 LOG(DEBUG) << connectionName << " HTTP upgrade: SocketContextUpgrade create success for: " << name;
272
273 socketContext->switchSocketContext(socketContextUpgrade);
274 } else {
275 LOG(DEBUG) << connectionName << " HTTP upgrade: SocketContextUpgrade create failed for: " << name;
276
277 set("Connection", "close").status(404);
278 }
279 } else {
280 LOG(DEBUG) << connectionName
281 << " SocketContextUpgradeFactory create failed for all of: " << request->get("upgrade");
282
283 set("Connection", "close").status(404);
284 }
285 } else {
286 LOG(DEBUG) << connectionName << " HTTP upgrade: No upgrade requested";
287
288 set("Connection", "close").status(400);
289 }
290 } else {
291 LOG(ERROR) << connectionName << " HTTP upgrade: Request has gone away";
292
293 set("Connection", "close").status(500);
294 }
295 } else {
296 LOG(ERROR) << connectionName << "HTTP upgrade: Unexpected disconnect";
297 }
298
299 LOG(DEBUG) << connectionName << " HTTP: Upgrade bootstrap " << (!name.empty() ? "success" : "failed");
300 LOG(DEBUG) << " Protocol selected: " << name;
301 LOG(DEBUG) << " requested: " << request->get("upgrade");
302 LOG(DEBUG) << " Subprotocol selected: " << header("upgrade");
303 LOG(DEBUG) << " requested: " << request->get("Sec-WebSocket-Protocol");
304
305 status(name);
306 }
307
308 void Response::sendFile(const std::string& file, const std::function<void(int)>& callback) {
309 if (socketContext != nullptr) {
310 std::string absolutFileName = file;
311
312 if (std::filesystem::exists(absolutFileName)) {
313 std::error_code ec;
314 absolutFileName = std::filesystem::canonical(absolutFileName);
315
316 if (std::filesystem::is_regular_file(absolutFileName, ec) && !ec) {
317 core::file::FileReader::open(absolutFileName)->pipe(this, [this, &absolutFileName, &callback](int errnum) {
318 callback(errnum);
319
320 if (errnum == 0) {
321 set("Content-Type", web::http::MimeTypes::contentType(absolutFileName), false);
322 set("Last-Modified", httputils::file_mod_http_date(absolutFileName), false);
323 if (httpMajor == 1) {
324 if (httpMinor == 1) {
325 set("Transfer-Encoding", "chunked");
326 } else {
327 set("Content-Length", std::to_string(std::filesystem::file_size(absolutFileName)));
328 }
329 }
330 } else {
331 status(404);
332 }
333 });
334 } else {
335 status(404);
336 errno = EEXIST;
337 callback(errno);
338 }
339 } else {
340 errno = ENOENT;
341 callback(errno);
342 }
343 }
344 }
345
346 void Response::end() {
347 send("");
348 }
349
351 if (socketContext != nullptr) {
353
354 socketContext->sendToPeer("HTTP/" + std::to_string(httpMajor)
355 .append(".")
356 .append(std::to_string(httpMinor))
357 .append(" ")
358 .append(std::to_string(statusCode))
359 .append(" ")
361 .append("\r\n"));
363
364 set("X-Powered-By", "snode.c");
365
366 for (const auto& [field, value] : headers) {
367 socketContext->sendToPeer(std::string(field).append(": ").append(value).append("\r\n"));
368 }
369
370 for (const auto& [cookie, cookieValue] : cookies) {
371 const std::string cookieString = std::accumulate(
372 cookieValue.getOptions().begin(),
373 cookieValue.getOptions().end(),
374 cookie + "=" + cookieValue.getValue(),
375 [](const std::string& str, const std::pair<const std::string&, const std::string&> option) -> std::string {
376 return str + "; " + option.first + (!option.second.empty() ? "=" + option.second : "");
377 });
378 socketContext->sendToPeer("Set-Cookie: " + cookieString + "\r\n");
379 }
380
382 }
383
384 return *this;
385 }
386
387 Response& Response::sendFragment(const char* chunk, std::size_t chunkLen) {
388 if (socketContext != nullptr) {
390 socketContext->sendToPeer(to_hex_str(chunkLen).append("\r\n"));
391 }
392
393 socketContext->sendToPeer(chunk, chunkLen);
394 contentSent += chunkLen;
395
398 contentLength += chunkLen;
399 }
400 }
401
402 return *this;
403 }
404
405 Response& Response::sendFragment(const std::string& chunk) {
406 return sendFragment(chunk.data(), chunk.size());
407 }
408
411 sendFragment(""); // For transfer encoding chunked. Terminate the chunk sequence.
412
413 if (!trailer.empty()) {
414 for (auto& [field, value] : trailer) {
415 socketContext->sendToPeer(std::string(field).append(":").append(value).append("\r\n"));
416 }
417
419 }
420 }
421
422 if (socketContext != nullptr) {
424 }
425 }
426
427 void Response::onSourceConnect(core::pipe::Source* source) {
428 if (socketContext != nullptr) {
431
432 source->start();
433 } else {
434 source->stop();
435 }
436 } else {
437 source->stop();
438 }
439 }
440
441 void Response::onSourceData(const char* chunk, std::size_t chunkLen) {
442 sendFragment(chunk, chunkLen);
443 }
444
446 if (socketContext != nullptr) {
448 }
449
451 }
452
453 void Response::onSourceError(int errnum) {
454 errno = errnum;
455
456 if (socketContext != nullptr) {
459 }
460
462 }
463
464 const std::string& Response::header(const std::string& field) {
465 return headers[field];
466 }
467
469 return socketContext;
470 }
471
472} // namespace web::http::server
static FileReader * open(const std::string &path)
void stop()
Definition Sink.cpp:68
bool isStreaming()
Definition Sink.cpp:64
virtual void stop()=0
void pipe(Sink *sink, const std::function< void(int)> &callback)
Definition Source.cpp:60
virtual void start()=0
void sendToPeer(const std::string &data) const
const std::string & getConnectionName() const
SocketConnection * getSocketConnection() const
virtual void switchSocketContext(SocketContext *newSocketContext)
void sendToPeer(const char *chunk, std::size_t chunkLen) const final
bool streamToPeer(core::pipe::Source *source) const
const std::map< std::string, std::string > & getOptions() const
CookieOptions(const std::string &value, const std::map< std::string, std::string > &options)
const std::string & getValue() const
static std::string contentType(const std::string &file)
core::socket::stream::SocketContext * create(core::socket::stream::SocketConnection *socketConnection) final
static std::string reason(int status)
CiStringMap< std::string > cookies
Definition Request.h:87
CiStringMap< std::string > headers
Definition Request.h:86
CiStringMap< std::string > queries
Definition Request.h:85
const std::string & get(const std::string &key, int i=0) const
Definition Request.cpp:53
void onSourceData(const char *chunk, std::size_t chunkLen) override
Definition Response.cpp:441
Response(SocketContext *socketContext)
Definition Response.cpp:72
SocketContext * getSocketContext() const
Definition Response.cpp:468
void onSourceConnect(core::pipe::Source *source) override
Definition Response.cpp:427
web::http::CiStringMap< web::http::CookieOptions > cookies
Definition Response.h:126
Response & status(int statusCode)
Definition Response.cpp:99
void send(const std::string &chunk)
Definition Response.cpp:221
void send(const char *chunk, std::size_t chunkLen)
Definition Response.cpp:210
Response & setTrailer(const std::string &field, const std::string &value, bool overwrite=true)
Definition Response.cpp:191
Response & set(const std::map< std::string, std::string > &headers, bool overwrite=true)
Definition Response.cpp:117
web::http::CiStringMap< std::string > trailer
Definition Response.h:127
web::http::CiStringMap< std::string > headers
Definition Response.h:125
Response & set(const std::string &field, const std::string &value, bool overwrite=true)
Definition Response.cpp:125
TransferEncoding transferEncoding
Definition Response.h:136
void upgrade(const std::shared_ptr< Request > &request, const std::function< void(const std::string &)> &status)
Definition Response.cpp:241
Response & type(const std::string &type)
Definition Response.cpp:171
void onSourceError(int errnum) override
Definition Response.cpp:453
Response & sendFragment(const std::string &chunk)
Definition Response.cpp:405
Response & cookie(const std::string &name, const std::string &value, const std::map< std::string, std::string > &options={})
Definition Response.cpp:175
web::http::server::SocketContext * socketContext
Definition Response.h:133
Response & append(const std::string &field, const std::string &value)
Definition Response.cpp:105
void sendStatus(int statusCode)
Definition Response.cpp:229
Response & sendFragment(const char *chunk, std::size_t chunkLen)
Definition Response.cpp:387
void onSourceEof() override
Definition Response.cpp:445
void sendFile(const std::string &file, const std::function< void(int)> &callback)
Definition Response.cpp:308
Response & clearCookie(const std::string &name, const std::map< std::string, std::string > &options={})
Definition Response.cpp:181
ConnectionState connectionState
Definition Response.h:135
const std::string & header(const std::string &field)
Definition Response.cpp:464
SocketContextUpgradeFactory * select(Request &req, Response &res) override
std::string to_http_date(struct tm *tm)
std::string file_mod_http_date(const std::string &filePath)
std::string toString(const std::string &method, const std::string &url, const std::string &version, const web::http::CiStringMap< std::string > &queries, const web::http::CiStringMap< std::string > &header, const web::http::CiStringMap< std::string > &cookies, const std::vector< char > &body)
struct tm * gmtime(const time_t *timep)
Definition time.cpp:62
bool ciEquals(const std::string &str1, const std::string &str2)
bool ciContains(const std::string &str1, const std::string &str2)
#define to_hex_str(int_val)
Definition Request.cpp:71