blob: 84e666f23cfc7de30a2c1146de9f2eccf18e5fce [file] [log] [blame]
Ed Tanousfca2cbe2021-01-28 14:49:59 -08001#pragma once
2#include "bmcweb_config.h"
3
4#include "async_resp.hpp"
5#include "authentication.hpp"
6#include "complete_response_fields.hpp"
Ed Tanous325310d2024-03-15 09:05:04 -07007#include "http_body.hpp"
Ed Tanousfca2cbe2021-01-28 14:49:59 -08008#include "http_response.hpp"
9#include "http_utility.hpp"
10#include "logging.hpp"
11#include "mutual_tls.hpp"
12#include "nghttp2_adapters.hpp"
13#include "ssl_key_handler.hpp"
14#include "utility.hpp"
15
Ed Tanousfca2cbe2021-01-28 14:49:59 -080016#include <boost/asio/io_context.hpp>
17#include <boost/asio/ip/tcp.hpp>
18#include <boost/asio/ssl/stream.hpp>
19#include <boost/asio/steady_timer.hpp>
Ed Tanousfca2cbe2021-01-28 14:49:59 -080020#include <boost/beast/http/error.hpp>
21#include <boost/beast/http/parser.hpp>
22#include <boost/beast/http/read.hpp>
23#include <boost/beast/http/serializer.hpp>
Ed Tanousfca2cbe2021-01-28 14:49:59 -080024#include <boost/beast/http/write.hpp>
Ed Tanousfca2cbe2021-01-28 14:49:59 -080025#include <boost/beast/websocket.hpp>
Ed Tanousd0882182024-01-26 23:45:25 -080026#include <boost/system/error_code.hpp>
Ed Tanousfca2cbe2021-01-28 14:49:59 -080027
Ed Tanousd0882182024-01-26 23:45:25 -080028#include <array>
Ed Tanousfca2cbe2021-01-28 14:49:59 -080029#include <atomic>
30#include <chrono>
Ed Tanousd0882182024-01-26 23:45:25 -080031#include <functional>
32#include <memory>
Ed Tanous89cda632024-04-16 08:45:54 -070033#include <string>
Ed Tanousfca2cbe2021-01-28 14:49:59 -080034#include <vector>
35
36namespace crow
37{
38
39struct Http2StreamData
40{
Jonathan Doman102a4cd2024-04-15 16:56:23 -070041 std::shared_ptr<Request> req = std::make_shared<Request>();
Ed Tanous325310d2024-03-15 09:05:04 -070042 std::optional<bmcweb::HttpBody::reader> reqReader;
Ed Tanous89cda632024-04-16 08:45:54 -070043 std::string accept;
Ed Tanous47f29342024-03-19 12:18:06 -070044 Response res;
Ed Tanousb2896142024-01-31 15:25:47 -080045 std::optional<bmcweb::HttpBody::writer> writer;
Ed Tanousfca2cbe2021-01-28 14:49:59 -080046};
47
48template <typename Adaptor, typename Handler>
49class HTTP2Connection :
50 public std::enable_shared_from_this<HTTP2Connection<Adaptor, Handler>>
51{
52 using self_type = HTTP2Connection<Adaptor, Handler>;
53
54 public:
55 HTTP2Connection(Adaptor&& adaptorIn, Handler* handlerIn,
Ed Tanous52e31622024-01-23 16:31:11 -080056 std::function<std::string()>& getCachedDateStrF) :
Ed Tanousfca2cbe2021-01-28 14:49:59 -080057 adaptor(std::move(adaptorIn)),
Ed Tanous52e31622024-01-23 16:31:11 -080058 ngSession(initializeNghttp2Session()), handler(handlerIn),
59 getCachedDateStr(getCachedDateStrF)
Ed Tanousfca2cbe2021-01-28 14:49:59 -080060 {}
61
62 void start()
63 {
64 // Create the control stream
Ed Tanousf42e8592023-08-25 10:47:44 -070065 streams[0];
Ed Tanousfca2cbe2021-01-28 14:49:59 -080066
67 if (sendServerConnectionHeader() != 0)
68 {
Ed Tanous62598e32023-07-17 17:06:25 -070069 BMCWEB_LOG_ERROR("send_server_connection_header failed");
Ed Tanousfca2cbe2021-01-28 14:49:59 -080070 return;
71 }
72 doRead();
73 }
74
75 int sendServerConnectionHeader()
76 {
Ed Tanous62598e32023-07-17 17:06:25 -070077 BMCWEB_LOG_DEBUG("send_server_connection_header()");
Ed Tanousfca2cbe2021-01-28 14:49:59 -080078
79 uint32_t maxStreams = 4;
80 std::array<nghttp2_settings_entry, 2> iv = {
81 {{NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, maxStreams},
82 {NGHTTP2_SETTINGS_ENABLE_PUSH, 0}}};
83 int rv = ngSession.submitSettings(iv);
84 if (rv != 0)
85 {
Ed Tanous62598e32023-07-17 17:06:25 -070086 BMCWEB_LOG_ERROR("Fatal error: {}", nghttp2_strerror(rv));
Ed Tanousfca2cbe2021-01-28 14:49:59 -080087 return -1;
88 }
Ed Tanousd0882182024-01-26 23:45:25 -080089 writeBuffer();
Ed Tanousfca2cbe2021-01-28 14:49:59 -080090 return 0;
91 }
92
93 static ssize_t fileReadCallback(nghttp2_session* /* session */,
Ed Tanousf42e8592023-08-25 10:47:44 -070094 int32_t streamId, uint8_t* buf,
Ed Tanousfca2cbe2021-01-28 14:49:59 -080095 size_t length, uint32_t* dataFlags,
Ed Tanousf42e8592023-08-25 10:47:44 -070096 nghttp2_data_source* /*source*/,
97 void* userPtr)
Ed Tanousfca2cbe2021-01-28 14:49:59 -080098 {
Ed Tanousf42e8592023-08-25 10:47:44 -070099 self_type& self = userPtrToSelf(userPtr);
100
101 auto streamIt = self.streams.find(streamId);
102 if (streamIt == self.streams.end())
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800103 {
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800104 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
105 }
Ed Tanousf42e8592023-08-25 10:47:44 -0700106 Http2StreamData& stream = streamIt->second;
Ed Tanous62598e32023-07-17 17:06:25 -0700107 BMCWEB_LOG_DEBUG("File read callback length: {}", length);
Ed Tanousd547d8d2024-03-16 18:04:41 -0700108 if (!stream.writer)
109 {
110 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
111 }
Ed Tanous52e31622024-01-23 16:31:11 -0800112 boost::beast::error_code ec;
113 boost::optional<std::pair<boost::asio::const_buffer, bool>> out =
114 stream.writer->getWithMaxSize(ec, length);
115 if (ec)
Ed Tanous27b0cf92023-08-07 12:02:40 -0700116 {
Ed Tanous325310d2024-03-15 09:05:04 -0700117 BMCWEB_LOG_CRITICAL("Failed to get buffer");
Ed Tanous27b0cf92023-08-07 12:02:40 -0700118 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
119 }
Ed Tanous52e31622024-01-23 16:31:11 -0800120 if (!out)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800121 {
Ed Tanous325310d2024-03-15 09:05:04 -0700122 BMCWEB_LOG_ERROR("Empty file, setting EOF");
Ed Tanous52e31622024-01-23 16:31:11 -0800123 *dataFlags |= NGHTTP2_DATA_FLAG_EOF;
124 return 0;
125 }
126
127 BMCWEB_LOG_DEBUG("Send chunk of size: {}", out->first.size());
128 if (length < out->first.size())
129 {
Ed Tanous325310d2024-03-15 09:05:04 -0700130 BMCWEB_LOG_CRITICAL(
131 "Buffer overflow that should never happen happened");
Ed Tanous52e31622024-01-23 16:31:11 -0800132 // Should never happen because of length limit on get() above
133 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
134 }
Ed Tanous325310d2024-03-15 09:05:04 -0700135 boost::asio::mutable_buffer writeableBuf(buf, length);
Ed Tanous52e31622024-01-23 16:31:11 -0800136 BMCWEB_LOG_DEBUG("Copying {} bytes to buf", out->first.size());
Ed Tanous325310d2024-03-15 09:05:04 -0700137 size_t copied = boost::asio::buffer_copy(writeableBuf, out->first);
138 if (copied != out->first.size())
139 {
140 BMCWEB_LOG_ERROR(
141 "Couldn't copy all {} bytes into buffer, only copied {}",
142 out->first.size(), copied);
143 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
144 }
Ed Tanous52e31622024-01-23 16:31:11 -0800145
146 if (!out->second)
147 {
Ed Tanous325310d2024-03-15 09:05:04 -0700148 BMCWEB_LOG_DEBUG("Setting EOF flag");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800149 *dataFlags |= NGHTTP2_DATA_FLAG_EOF;
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800150 }
Ed Tanous325310d2024-03-15 09:05:04 -0700151 return static_cast<ssize_t>(copied);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800152 }
153
154 nghttp2_nv headerFromStringViews(std::string_view name,
Ed Tanous52e31622024-01-23 16:31:11 -0800155 std::string_view value, uint8_t flags)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800156 {
157 uint8_t* nameData = std::bit_cast<uint8_t*>(name.data());
158 uint8_t* valueData = std::bit_cast<uint8_t*>(value.data());
Ed Tanous52e31622024-01-23 16:31:11 -0800159 return {nameData, valueData, name.size(), value.size(), flags};
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800160 }
161
162 int sendResponse(Response& completedRes, int32_t streamId)
163 {
Ed Tanous62598e32023-07-17 17:06:25 -0700164 BMCWEB_LOG_DEBUG("send_response stream_id:{}", streamId);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800165
166 auto it = streams.find(streamId);
167 if (it == streams.end())
168 {
169 close();
170 return -1;
171 }
Ed Tanous499b5b42024-04-06 08:39:18 -0700172 Http2StreamData& stream = it->second;
173 Response& res = stream.res;
174 res = std::move(completedRes);
Ed Tanous499b5b42024-04-06 08:39:18 -0700175
Ed Tanous89cda632024-04-16 08:45:54 -0700176 completeResponseFields(stream.accept, res);
Ed Tanous499b5b42024-04-06 08:39:18 -0700177 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
178 res.preparePayload();
179
180 boost::beast::http::fields& fields = res.fields();
181 std::string code = std::to_string(res.resultInt());
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800182 std::vector<nghttp2_nv> hdr;
Ed Tanous52e31622024-01-23 16:31:11 -0800183 hdr.emplace_back(
184 headerFromStringViews(":status", code, NGHTTP2_NV_FLAG_NONE));
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800185 for (const boost::beast::http::fields::value_type& header : fields)
186 {
Ed Tanous52e31622024-01-23 16:31:11 -0800187 hdr.emplace_back(headerFromStringViews(
Ed Tanousd0882182024-01-26 23:45:25 -0800188 header.name_string(), header.value(), NGHTTP2_NV_FLAG_NONE));
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800189 }
Ed Tanousb2896142024-01-31 15:25:47 -0800190 http::response<bmcweb::HttpBody>& fbody = res.response;
Ed Tanous52e31622024-01-23 16:31:11 -0800191 stream.writer.emplace(fbody.base(), fbody.body());
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800192
193 nghttp2_data_provider dataPrd{
Ed Tanousf42e8592023-08-25 10:47:44 -0700194 .source = {.fd = 0},
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800195 .read_callback = fileReadCallback,
196 };
197
198 int rv = ngSession.submitResponse(streamId, hdr, &dataPrd);
199 if (rv != 0)
200 {
Ed Tanous62598e32023-07-17 17:06:25 -0700201 BMCWEB_LOG_ERROR("Fatal error: {}", nghttp2_strerror(rv));
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800202 close();
203 return -1;
204 }
Ed Tanousd0882182024-01-26 23:45:25 -0800205 writeBuffer();
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800206
207 return 0;
208 }
209
210 nghttp2_session initializeNghttp2Session()
211 {
212 nghttp2_session_callbacks callbacks;
213 callbacks.setOnFrameRecvCallback(onFrameRecvCallbackStatic);
214 callbacks.setOnStreamCloseCallback(onStreamCloseCallbackStatic);
215 callbacks.setOnHeaderCallback(onHeaderCallbackStatic);
216 callbacks.setOnBeginHeadersCallback(onBeginHeadersCallbackStatic);
Ed Tanous325310d2024-03-15 09:05:04 -0700217 callbacks.setOnDataChunkRecvCallback(onDataChunkRecvStatic);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800218
219 nghttp2_session session(callbacks);
220 session.setUserData(this);
221
222 return session;
223 }
224
225 int onRequestRecv(int32_t streamId)
226 {
Ed Tanous62598e32023-07-17 17:06:25 -0700227 BMCWEB_LOG_DEBUG("on_request_recv");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800228
229 auto it = streams.find(streamId);
230 if (it == streams.end())
231 {
232 close();
233 return -1;
234 }
Ed Tanousd547d8d2024-03-16 18:04:41 -0700235 auto& reqReader = it->second.reqReader;
236 if (reqReader)
Ed Tanous325310d2024-03-15 09:05:04 -0700237 {
238 boost::beast::error_code ec;
Ed Tanousd547d8d2024-03-16 18:04:41 -0700239 reqReader->finish(ec);
Ed Tanous325310d2024-03-15 09:05:04 -0700240 if (ec)
241 {
242 BMCWEB_LOG_CRITICAL("Failed to finalize payload");
243 close();
244 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
245 }
246 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700247 crow::Request& thisReq = *it->second.req;
Ed Tanous8e8245d2024-04-11 22:21:38 -0700248 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
249 &adaptor.get_executor().context());
Ed Tanous89cda632024-04-16 08:45:54 -0700250
251 it->second.accept = thisReq.getHeaderValue("Accept");
252
Ed Tanous62598e32023-07-17 17:06:25 -0700253 BMCWEB_LOG_DEBUG("Handling {} \"{}\"", logPtr(&thisReq),
254 thisReq.url().encoded_path());
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800255
Ed Tanousf42e8592023-08-25 10:47:44 -0700256 crow::Response& thisRes = it->second.res;
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800257
258 thisRes.setCompleteRequestHandler(
259 [this, streamId](Response& completeRes) {
Ed Tanous62598e32023-07-17 17:06:25 -0700260 BMCWEB_LOG_DEBUG("res.completeRequestHandler called");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800261 if (sendResponse(completeRes, streamId) != 0)
262 {
263 close();
264 return;
265 }
266 });
267 auto asyncResp =
Ed Tanousf42e8592023-08-25 10:47:44 -0700268 std::make_shared<bmcweb::AsyncResp>(std::move(it->second.res));
Ed Tanous83328312024-05-09 15:48:09 -0700269 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH)
Ed Tanous325310d2024-03-15 09:05:04 -0700270 {
Ed Tanous83328312024-05-09 15:48:09 -0700271 thisReq.session = crow::authentication::authenticate(
272 {}, asyncResp->res, thisReq.method(), thisReq.req, nullptr);
273 if (!crow::authentication::isOnAllowlist(thisReq.url().path(),
274 thisReq.method()) &&
275 thisReq.session == nullptr)
Ed Tanous499b5b42024-04-06 08:39:18 -0700276 {
Ed Tanous83328312024-05-09 15:48:09 -0700277 BMCWEB_LOG_WARNING("Authentication failed");
278 forward_unauthorized::sendUnauthorized(
279 thisReq.url().encoded_path(),
280 thisReq.getHeaderValue("X-Requested-With"),
281 thisReq.getHeaderValue("Accept"), asyncResp->res);
282 return 0;
Ed Tanous499b5b42024-04-06 08:39:18 -0700283 }
Ed Tanous325310d2024-03-15 09:05:04 -0700284 }
Ed Tanous83328312024-05-09 15:48:09 -0700285 std::string_view expected =
286 thisReq.getHeaderValue(boost::beast::http::field::if_none_match);
287 BMCWEB_LOG_DEBUG("Setting expected hash {}", expected);
288 if (!expected.empty())
289 {
290 asyncResp->res.setExpectedHash(expected);
291 }
292 handler->handle(it->second.req, asyncResp);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800293 return 0;
294 }
295
Ed Tanous325310d2024-03-15 09:05:04 -0700296 int onDataChunkRecvCallback(uint8_t /*flags*/, int32_t streamId,
297 const uint8_t* data, size_t len)
298 {
299 auto thisStream = streams.find(streamId);
300 if (thisStream == streams.end())
301 {
302 BMCWEB_LOG_ERROR("Unknown stream{}", streamId);
303 close();
304 return -1;
305 }
Ed Tanousd547d8d2024-03-16 18:04:41 -0700306
307 std::optional<bmcweb::HttpBody::reader>& reqReader =
308 thisStream->second.reqReader;
309 if (!reqReader)
Ed Tanous325310d2024-03-15 09:05:04 -0700310 {
Ed Tanous8e5cc7b2024-04-02 11:00:54 -0700311 reqReader.emplace(
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700312 bmcweb::HttpBody::reader(thisStream->second.req->req.base(),
313 thisStream->second.req->req.body()));
Ed Tanous325310d2024-03-15 09:05:04 -0700314 }
315 boost::beast::error_code ec;
Ed Tanousd547d8d2024-03-16 18:04:41 -0700316 reqReader->put(boost::asio::const_buffer(data, len), ec);
Ed Tanous325310d2024-03-15 09:05:04 -0700317 if (ec)
318 {
319 BMCWEB_LOG_CRITICAL("Failed to write payload");
320 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
321 }
322 return 0;
323 }
324
325 static int onDataChunkRecvStatic(nghttp2_session* /* session */,
326 uint8_t flags, int32_t streamId,
327 const uint8_t* data, size_t len,
328 void* userData)
329 {
330 BMCWEB_LOG_DEBUG("on_frame_recv_callback");
331 if (userData == nullptr)
332 {
333 BMCWEB_LOG_CRITICAL("user data was null?");
334 return NGHTTP2_ERR_CALLBACK_FAILURE;
335 }
336 return userPtrToSelf(userData).onDataChunkRecvCallback(flags, streamId,
337 data, len);
338 }
339
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800340 int onFrameRecvCallback(const nghttp2_frame& frame)
341 {
Ed Tanous62598e32023-07-17 17:06:25 -0700342 BMCWEB_LOG_DEBUG("frame type {}", static_cast<int>(frame.hd.type));
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800343 switch (frame.hd.type)
344 {
345 case NGHTTP2_DATA:
346 case NGHTTP2_HEADERS:
347 // Check that the client request has finished
348 if ((frame.hd.flags & NGHTTP2_FLAG_END_STREAM) != 0)
349 {
350 return onRequestRecv(frame.hd.stream_id);
351 }
352 break;
353 default:
354 break;
355 }
356 return 0;
357 }
358
359 static int onFrameRecvCallbackStatic(nghttp2_session* /* session */,
360 const nghttp2_frame* frame,
361 void* userData)
362 {
Ed Tanous62598e32023-07-17 17:06:25 -0700363 BMCWEB_LOG_DEBUG("on_frame_recv_callback");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800364 if (userData == nullptr)
365 {
Ed Tanous62598e32023-07-17 17:06:25 -0700366 BMCWEB_LOG_CRITICAL("user data was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800367 return NGHTTP2_ERR_CALLBACK_FAILURE;
368 }
369 if (frame == nullptr)
370 {
Ed Tanous62598e32023-07-17 17:06:25 -0700371 BMCWEB_LOG_CRITICAL("frame was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800372 return NGHTTP2_ERR_CALLBACK_FAILURE;
373 }
374 return userPtrToSelf(userData).onFrameRecvCallback(*frame);
375 }
376
377 static self_type& userPtrToSelf(void* userData)
378 {
379 // This method exists to keep the unsafe reinterpret cast in one
380 // place.
381 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
382 return *reinterpret_cast<self_type*>(userData);
383 }
384
385 static int onStreamCloseCallbackStatic(nghttp2_session* /* session */,
386 int32_t streamId,
387 uint32_t /*unused*/, void* userData)
388 {
Ed Tanous62598e32023-07-17 17:06:25 -0700389 BMCWEB_LOG_DEBUG("on_stream_close_callback stream {}", streamId);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800390 if (userData == nullptr)
391 {
Ed Tanous62598e32023-07-17 17:06:25 -0700392 BMCWEB_LOG_CRITICAL("user data was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800393 return NGHTTP2_ERR_CALLBACK_FAILURE;
394 }
Ed Tanousf42e8592023-08-25 10:47:44 -0700395 if (userPtrToSelf(userData).streams.erase(streamId) <= 0)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800396 {
397 return -1;
398 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800399 return 0;
400 }
401
402 int onHeaderCallback(const nghttp2_frame& frame,
403 std::span<const uint8_t> name,
404 std::span<const uint8_t> value)
405 {
406 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
407 std::string_view nameSv(reinterpret_cast<const char*>(name.data()),
408 name.size());
409 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
410 std::string_view valueSv(reinterpret_cast<const char*>(value.data()),
411 value.size());
412
Ed Tanous62598e32023-07-17 17:06:25 -0700413 BMCWEB_LOG_DEBUG("on_header_callback name: {} value {}", nameSv,
414 valueSv);
Ed Tanousa07e9812024-03-19 10:31:13 -0700415 if (frame.hd.type != NGHTTP2_HEADERS)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800416 {
Ed Tanousa07e9812024-03-19 10:31:13 -0700417 return 0;
418 }
419 if (frame.headers.cat != NGHTTP2_HCAT_REQUEST)
420 {
421 return 0;
422 }
423 auto thisStream = streams.find(frame.hd.stream_id);
424 if (thisStream == streams.end())
425 {
426 BMCWEB_LOG_ERROR("Unknown stream{}", frame.hd.stream_id);
427 close();
428 return -1;
429 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800430
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700431 crow::Request& thisReq = *thisStream->second.req;
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800432
Ed Tanousa07e9812024-03-19 10:31:13 -0700433 if (nameSv == ":path")
434 {
435 thisReq.target(valueSv);
436 }
437 else if (nameSv == ":method")
438 {
439 boost::beast::http::verb verb =
440 boost::beast::http::string_to_verb(valueSv);
441 if (verb == boost::beast::http::verb::unknown)
442 {
443 BMCWEB_LOG_ERROR("Unknown http verb {}", valueSv);
444 close();
445 return -1;
446 }
Myung Bae1873a042024-04-01 09:27:39 -0500447 thisReq.method(verb);
Ed Tanousa07e9812024-03-19 10:31:13 -0700448 }
449 else if (nameSv == ":scheme")
450 {
451 // Nothing to check on scheme
452 }
453 else
454 {
Myung Bae1873a042024-04-01 09:27:39 -0500455 thisReq.addHeader(nameSv, valueSv);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800456 }
457 return 0;
458 }
459
460 static int onHeaderCallbackStatic(nghttp2_session* /* session */,
461 const nghttp2_frame* frame,
462 const uint8_t* name, size_t namelen,
463 const uint8_t* value, size_t vallen,
464 uint8_t /* flags */, void* userData)
465 {
466 if (userData == nullptr)
467 {
Ed Tanous62598e32023-07-17 17:06:25 -0700468 BMCWEB_LOG_CRITICAL("user data was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800469 return NGHTTP2_ERR_CALLBACK_FAILURE;
470 }
471 if (frame == nullptr)
472 {
Ed Tanous62598e32023-07-17 17:06:25 -0700473 BMCWEB_LOG_CRITICAL("frame was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800474 return NGHTTP2_ERR_CALLBACK_FAILURE;
475 }
476 if (name == nullptr)
477 {
Ed Tanous62598e32023-07-17 17:06:25 -0700478 BMCWEB_LOG_CRITICAL("name was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800479 return NGHTTP2_ERR_CALLBACK_FAILURE;
480 }
481 if (value == nullptr)
482 {
Ed Tanous62598e32023-07-17 17:06:25 -0700483 BMCWEB_LOG_CRITICAL("value was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800484 return NGHTTP2_ERR_CALLBACK_FAILURE;
485 }
486 return userPtrToSelf(userData).onHeaderCallback(*frame, {name, namelen},
487 {value, vallen});
488 }
489
490 int onBeginHeadersCallback(const nghttp2_frame& frame)
491 {
492 if (frame.hd.type == NGHTTP2_HEADERS &&
493 frame.headers.cat == NGHTTP2_HCAT_REQUEST)
494 {
Ed Tanous62598e32023-07-17 17:06:25 -0700495 BMCWEB_LOG_DEBUG("create stream for id {}", frame.hd.stream_id);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800496
Ed Tanous3a499412024-06-05 16:05:35 -0700497 streams.emplace(frame.hd.stream_id, Http2StreamData());
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800498 }
499 return 0;
500 }
501
502 static int onBeginHeadersCallbackStatic(nghttp2_session* /* session */,
503 const nghttp2_frame* frame,
504 void* userData)
505 {
Ed Tanous62598e32023-07-17 17:06:25 -0700506 BMCWEB_LOG_DEBUG("on_begin_headers_callback");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800507 if (userData == nullptr)
508 {
Ed Tanous62598e32023-07-17 17:06:25 -0700509 BMCWEB_LOG_CRITICAL("user data was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800510 return NGHTTP2_ERR_CALLBACK_FAILURE;
511 }
512 if (frame == nullptr)
513 {
Ed Tanous62598e32023-07-17 17:06:25 -0700514 BMCWEB_LOG_CRITICAL("frame was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800515 return NGHTTP2_ERR_CALLBACK_FAILURE;
516 }
517 return userPtrToSelf(userData).onBeginHeadersCallback(*frame);
518 }
519
520 static void afterWriteBuffer(const std::shared_ptr<self_type>& self,
521 const boost::system::error_code& ec,
522 size_t sendLength)
523 {
524 self->isWriting = false;
Ed Tanous62598e32023-07-17 17:06:25 -0700525 BMCWEB_LOG_DEBUG("Sent {}", sendLength);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800526 if (ec)
527 {
528 self->close();
529 return;
530 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800531 self->writeBuffer();
532 }
533
534 void writeBuffer()
535 {
536 if (isWriting)
537 {
538 return;
539 }
Ed Tanousd0882182024-01-26 23:45:25 -0800540 std::span<const uint8_t> data = ngSession.memSend();
541 if (data.empty())
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800542 {
543 return;
544 }
545 isWriting = true;
Ed Tanous325310d2024-03-15 09:05:04 -0700546 boost::asio::async_write(
547 adaptor, boost::asio::const_buffer(data.data(), data.size()),
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800548 std::bind_front(afterWriteBuffer, shared_from_this()));
549 }
550
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800551 void close()
552 {
553 if constexpr (std::is_same_v<Adaptor,
Ed Tanous003301a2024-04-16 09:59:19 -0700554 boost::asio::ssl::stream<
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800555 boost::asio::ip::tcp::socket>>)
556 {
557 adaptor.next_layer().close();
558 }
559 else
560 {
561 adaptor.close();
562 }
563 }
564
Ed Tanousd0882182024-01-26 23:45:25 -0800565 void afterDoRead(const std::shared_ptr<self_type>& /*self*/,
566 const boost::system::error_code& ec,
567 size_t bytesTransferred)
568 {
569 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
570 bytesTransferred);
571
572 if (ec)
573 {
574 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
575 ec.message());
576 close();
577 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
578 return;
579 }
580 std::span<uint8_t> bufferSpan{inBuffer.data(), bytesTransferred};
581
582 ssize_t readLen = ngSession.memRecv(bufferSpan);
583 if (readLen < 0)
584 {
585 BMCWEB_LOG_ERROR("nghttp2_session_mem_recv returned {}", readLen);
586 close();
587 return;
588 }
589 writeBuffer();
590
591 doRead();
592 }
593
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800594 void doRead()
595 {
Ed Tanous62598e32023-07-17 17:06:25 -0700596 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800597 adaptor.async_read_some(
Ed Tanousd0882182024-01-26 23:45:25 -0800598 boost::asio::buffer(inBuffer),
599 std::bind_front(&self_type::afterDoRead, this, shared_from_this()));
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800600 }
601
602 // A mapping from http2 stream ID to Stream Data
Ed Tanous52e31622024-01-23 16:31:11 -0800603 std::map<int32_t, Http2StreamData> streams;
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800604
Ed Tanousd0882182024-01-26 23:45:25 -0800605 std::array<uint8_t, 8192> inBuffer{};
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800606
607 Adaptor adaptor;
608 bool isWriting = false;
609
610 nghttp2_session ngSession;
611
612 Handler* handler;
613 std::function<std::string()>& getCachedDateStr;
614
615 using std::enable_shared_from_this<
616 HTTP2Connection<Adaptor, Handler>>::shared_from_this;
617
618 using std::enable_shared_from_this<
619 HTTP2Connection<Adaptor, Handler>>::weak_from_this;
620};
621} // namespace crow