ConnectionFromClient.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /*
  2. * Copyright (c) 2018-2024, Andreas Kling <andreas@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Badge.h>
  7. #include <AK/IDAllocator.h>
  8. #include <AK/NonnullOwnPtr.h>
  9. #include <AK/RefCounted.h>
  10. #include <AK/Weakable.h>
  11. #include <LibCore/Proxy.h>
  12. #include <LibCore/Socket.h>
  13. #include <LibWebSocket/ConnectionInfo.h>
  14. #include <LibWebSocket/Message.h>
  15. #include <RequestServer/ConnectionFromClient.h>
  16. #include <RequestServer/RequestClientEndpoint.h>
  17. #include <curl/curl.h>
  18. #include <netdb.h>
  19. namespace RequestServer {
  20. ByteString g_default_certificate_path;
  21. static HashMap<int, RefPtr<ConnectionFromClient>> s_connections;
  22. static IDAllocator s_client_ids;
  23. struct ConnectionFromClient::ActiveRequest {
  24. CURLM* multi { nullptr };
  25. CURL* easy { nullptr };
  26. i32 request_id { 0 };
  27. RefPtr<Core::Notifier> notifier;
  28. WeakPtr<ConnectionFromClient> client;
  29. int writer_fd { 0 };
  30. HTTP::HeaderMap headers;
  31. bool got_all_headers { false };
  32. size_t downloaded_so_far { 0 };
  33. String url;
  34. ByteBuffer body;
  35. ActiveRequest(ConnectionFromClient& client, CURLM* multi, CURL* easy, i32 request_id, int writer_fd)
  36. : multi(multi)
  37. , easy(easy)
  38. , request_id(request_id)
  39. , client(client)
  40. , writer_fd(writer_fd)
  41. {
  42. }
  43. ~ActiveRequest()
  44. {
  45. MUST(Core::System::close(writer_fd));
  46. auto result = curl_multi_remove_handle(multi, easy);
  47. VERIFY(result == CURLM_OK);
  48. curl_easy_cleanup(easy);
  49. }
  50. void flush_headers_if_needed()
  51. {
  52. if (got_all_headers)
  53. return;
  54. got_all_headers = true;
  55. long http_status_code = 0;
  56. auto result = curl_easy_getinfo(easy, CURLINFO_RESPONSE_CODE, &http_status_code);
  57. VERIFY(result == CURLE_OK);
  58. client->async_headers_became_available(request_id, headers, http_status_code);
  59. }
  60. };
  61. size_t ConnectionFromClient::on_header_received(void* buffer, size_t size, size_t nmemb, void* user_data)
  62. {
  63. auto* request = static_cast<ActiveRequest*>(user_data);
  64. size_t total_size = size * nmemb;
  65. auto header_line = StringView { static_cast<char const*>(buffer), total_size };
  66. if (auto colon_index = header_line.find(':'); colon_index.has_value()) {
  67. auto name = header_line.substring_view(0, colon_index.value()).trim_whitespace();
  68. auto value = header_line.substring_view(colon_index.value() + 1, header_line.length() - colon_index.value() - 1).trim_whitespace();
  69. request->headers.set(name, value);
  70. }
  71. return total_size;
  72. }
  73. size_t ConnectionFromClient::on_data_received(void* buffer, size_t size, size_t nmemb, void* user_data)
  74. {
  75. auto* request = static_cast<ActiveRequest*>(user_data);
  76. request->flush_headers_if_needed();
  77. size_t total_size = size * nmemb;
  78. size_t remaining_length = total_size;
  79. u8 const* remaining_data = static_cast<u8 const*>(buffer);
  80. while (remaining_length > 0) {
  81. auto result = Core::System::write(request->writer_fd, { remaining_data, remaining_length });
  82. if (result.is_error()) {
  83. if (result.error().code() != EAGAIN) {
  84. dbgln("on_data_received: write failed: {}", result.error());
  85. VERIFY_NOT_REACHED();
  86. }
  87. sched_yield();
  88. continue;
  89. }
  90. auto nwritten = result.value();
  91. if (nwritten == 0) {
  92. dbgln("on_data_received: write returned 0");
  93. VERIFY_NOT_REACHED();
  94. }
  95. remaining_data += nwritten;
  96. remaining_length -= nwritten;
  97. }
  98. Optional<u64> content_length_for_ipc;
  99. curl_off_t content_length = -1;
  100. auto res = curl_easy_getinfo(request->easy, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &content_length);
  101. if (res == CURLE_OK && content_length != -1) {
  102. content_length_for_ipc = content_length;
  103. }
  104. request->downloaded_so_far += total_size;
  105. return total_size;
  106. }
  107. int ConnectionFromClient::on_socket_callback(CURL*, int sockfd, int what, void* user_data, void*)
  108. {
  109. auto* client = static_cast<ConnectionFromClient*>(user_data);
  110. if (what == CURL_POLL_REMOVE) {
  111. client->m_read_notifiers.remove(sockfd);
  112. client->m_write_notifiers.remove(sockfd);
  113. return 0;
  114. }
  115. if (what & CURL_POLL_IN) {
  116. client->m_read_notifiers.ensure(sockfd, [client, sockfd, multi = client->m_curl_multi] {
  117. auto notifier = Core::Notifier::construct(sockfd, Core::NotificationType::Read);
  118. notifier->on_activation = [client, sockfd, multi] {
  119. int still_running = 0;
  120. auto result = curl_multi_socket_action(multi, sockfd, CURL_CSELECT_IN, &still_running);
  121. VERIFY(result == CURLM_OK);
  122. client->check_active_requests();
  123. };
  124. notifier->set_enabled(true);
  125. return notifier;
  126. });
  127. }
  128. if (what & CURL_POLL_OUT) {
  129. client->m_write_notifiers.ensure(sockfd, [client, sockfd, multi = client->m_curl_multi] {
  130. auto notifier = Core::Notifier::construct(sockfd, Core::NotificationType::Write);
  131. notifier->on_activation = [client, sockfd, multi] {
  132. int still_running = 0;
  133. auto result = curl_multi_socket_action(multi, sockfd, CURL_CSELECT_OUT, &still_running);
  134. VERIFY(result == CURLM_OK);
  135. client->check_active_requests();
  136. };
  137. notifier->set_enabled(true);
  138. return notifier;
  139. });
  140. }
  141. return 0;
  142. }
  143. int ConnectionFromClient::on_timeout_callback(void*, long timeout_ms, void* user_data)
  144. {
  145. auto* client = static_cast<ConnectionFromClient*>(user_data);
  146. if (timeout_ms < 0) {
  147. client->m_timer->stop();
  148. } else {
  149. client->m_timer->restart(timeout_ms);
  150. }
  151. return 0;
  152. }
  153. ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<Core::LocalSocket> socket)
  154. : IPC::ConnectionFromClient<RequestClientEndpoint, RequestServerEndpoint>(*this, move(socket), s_client_ids.allocate())
  155. {
  156. s_connections.set(client_id(), *this);
  157. m_curl_multi = curl_multi_init();
  158. auto set_option = [this](auto option, auto value) {
  159. auto result = curl_multi_setopt(m_curl_multi, option, value);
  160. VERIFY(result == CURLM_OK);
  161. };
  162. set_option(CURLMOPT_SOCKETFUNCTION, &on_socket_callback);
  163. set_option(CURLMOPT_SOCKETDATA, this);
  164. set_option(CURLMOPT_TIMERFUNCTION, &on_timeout_callback);
  165. set_option(CURLMOPT_TIMERDATA, this);
  166. m_timer = Core::Timer::create_single_shot(0, [this] {
  167. int still_running = 0;
  168. auto result = curl_multi_socket_action(m_curl_multi, CURL_SOCKET_TIMEOUT, 0, &still_running);
  169. VERIFY(result == CURLM_OK);
  170. check_active_requests();
  171. });
  172. }
  173. ConnectionFromClient::~ConnectionFromClient()
  174. {
  175. }
  176. void ConnectionFromClient::die()
  177. {
  178. auto client_id = this->client_id();
  179. s_connections.remove(client_id);
  180. s_client_ids.deallocate(client_id);
  181. if (s_connections.is_empty())
  182. Core::EventLoop::current().quit(0);
  183. }
  184. Messages::RequestServer::ConnectNewClientResponse ConnectionFromClient::connect_new_client()
  185. {
  186. int socket_fds[2] {};
  187. if (auto err = Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, socket_fds); err.is_error()) {
  188. dbgln("Failed to create client socketpair: {}", err.error());
  189. return IPC::File {};
  190. }
  191. auto client_socket_or_error = Core::LocalSocket::adopt_fd(socket_fds[0]);
  192. if (client_socket_or_error.is_error()) {
  193. close(socket_fds[0]);
  194. close(socket_fds[1]);
  195. dbgln("Failed to adopt client socket: {}", client_socket_or_error.error());
  196. return IPC::File {};
  197. }
  198. auto client_socket = client_socket_or_error.release_value();
  199. // Note: A ref is stored in the static s_connections map
  200. auto client = adopt_ref(*new ConnectionFromClient(move(client_socket)));
  201. return IPC::File::adopt_fd(socket_fds[1]);
  202. }
  203. Messages::RequestServer::IsSupportedProtocolResponse ConnectionFromClient::is_supported_protocol(ByteString const& protocol)
  204. {
  205. return protocol == "http"sv || protocol == "https"sv;
  206. }
  207. void ConnectionFromClient::start_request(i32 request_id, ByteString const& method, URL::URL const& url, HTTP::HeaderMap const& request_headers, ByteBuffer const& request_body, Core::ProxyData const& proxy_data)
  208. {
  209. if (!url.is_valid()) {
  210. dbgln("StartRequest: Invalid URL requested: '{}'", url);
  211. async_request_finished(request_id, false, 0);
  212. return;
  213. }
  214. auto* easy = curl_easy_init();
  215. if (!easy) {
  216. dbgln("StartRequest: Failed to initialize curl easy handle");
  217. return;
  218. }
  219. auto fds_or_error = Core::System::pipe2(O_NONBLOCK);
  220. if (fds_or_error.is_error()) {
  221. dbgln("StartRequest: Failed to create pipe: {}", fds_or_error.error());
  222. return;
  223. }
  224. auto fds = fds_or_error.release_value();
  225. auto writer_fd = fds[1];
  226. auto reader_fd = fds[0];
  227. async_request_started(request_id, IPC::File::adopt_fd(reader_fd));
  228. auto request = make<ActiveRequest>(*this, m_curl_multi, easy, request_id, writer_fd);
  229. request->url = url.to_string().value();
  230. auto set_option = [easy](auto option, auto value) {
  231. auto result = curl_easy_setopt(easy, option, value);
  232. if (result != CURLE_OK) {
  233. dbgln("StartRequest: Failed to set curl option: {}", curl_easy_strerror(result));
  234. return false;
  235. }
  236. return true;
  237. };
  238. set_option(CURLOPT_PRIVATE, request.ptr());
  239. if (!g_default_certificate_path.is_empty())
  240. set_option(CURLOPT_CAINFO, g_default_certificate_path.characters());
  241. set_option(CURLOPT_ACCEPT_ENCODING, "gzip, deflate, br");
  242. set_option(CURLOPT_URL, url.to_string().value().to_byte_string().characters());
  243. set_option(CURLOPT_PORT, url.port_or_default());
  244. if (method == "GET"sv) {
  245. set_option(CURLOPT_HTTPGET, 1L);
  246. } else if (method == "POST"sv) {
  247. request->body = request_body;
  248. set_option(CURLOPT_POSTFIELDSIZE, request->body.size());
  249. set_option(CURLOPT_POSTFIELDS, request->body.data());
  250. } else if (method == "HEAD") {
  251. set_option(CURLOPT_NOBODY, 1L);
  252. }
  253. set_option(CURLOPT_CUSTOMREQUEST, method.characters());
  254. set_option(CURLOPT_FOLLOWLOCATION, 0);
  255. struct curl_slist* curl_headers = nullptr;
  256. for (auto const& header : request_headers.headers()) {
  257. auto header_string = ByteString::formatted("{}: {}", header.name, header.value);
  258. curl_headers = curl_slist_append(curl_headers, header_string.characters());
  259. }
  260. set_option(CURLOPT_HTTPHEADER, curl_headers);
  261. // FIXME: Set up proxy if applicable
  262. (void)proxy_data;
  263. set_option(CURLOPT_WRITEFUNCTION, &on_data_received);
  264. set_option(CURLOPT_WRITEDATA, reinterpret_cast<void*>(request.ptr()));
  265. set_option(CURLOPT_HEADERFUNCTION, &on_header_received);
  266. set_option(CURLOPT_HEADERDATA, reinterpret_cast<void*>(request.ptr()));
  267. auto result = curl_multi_add_handle(m_curl_multi, easy);
  268. VERIFY(result == CURLM_OK);
  269. m_active_requests.set(request_id, move(request));
  270. }
  271. void ConnectionFromClient::check_active_requests()
  272. {
  273. int msgs_in_queue = 0;
  274. while (auto* msg = curl_multi_info_read(m_curl_multi, &msgs_in_queue)) {
  275. if (msg->msg != CURLMSG_DONE)
  276. continue;
  277. ActiveRequest* request = nullptr;
  278. auto result = curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &request);
  279. VERIFY(result == CURLE_OK);
  280. request->flush_headers_if_needed();
  281. async_request_finished(request->request_id, msg->data.result == CURLE_OK, request->downloaded_so_far);
  282. m_active_requests.remove(request->request_id);
  283. }
  284. }
  285. Messages::RequestServer::StopRequestResponse ConnectionFromClient::stop_request(i32 request_id)
  286. {
  287. auto request = m_active_requests.take(request_id);
  288. if (!request.has_value()) {
  289. dbgln("StopRequest: Request ID {} not found", request_id);
  290. return false;
  291. }
  292. return true;
  293. }
  294. void ConnectionFromClient::did_receive_headers(Badge<Request>, Request&)
  295. {
  296. }
  297. void ConnectionFromClient::did_finish_request(Badge<Request>, Request&, bool)
  298. {
  299. }
  300. void ConnectionFromClient::did_progress_request(Badge<Request>, Request&)
  301. {
  302. }
  303. void ConnectionFromClient::did_request_certificates(Badge<Request>, Request&)
  304. {
  305. TODO();
  306. }
  307. Messages::RequestServer::SetCertificateResponse ConnectionFromClient::set_certificate(i32 request_id, ByteString const& certificate, ByteString const& key)
  308. {
  309. (void)request_id;
  310. (void)certificate;
  311. (void)key;
  312. TODO();
  313. }
  314. void ConnectionFromClient::ensure_connection(URL::URL const& url, ::RequestServer::CacheLevel const& cache_level)
  315. {
  316. if (!url.is_valid()) {
  317. dbgln("EnsureConnection: Invalid URL requested: '{}'", url);
  318. return;
  319. }
  320. (void)cache_level;
  321. dbgln("FIXME: EnsureConnection: Pre-connect to {}", url);
  322. }
  323. void ConnectionFromClient::websocket_connect(i64 websocket_id, URL::URL const& url, ByteString const& origin, Vector<ByteString> const& protocols, Vector<ByteString> const& extensions, HTTP::HeaderMap const& additional_request_headers)
  324. {
  325. if (!url.is_valid()) {
  326. dbgln("WebSocket::Connect: Invalid URL requested: '{}'", url);
  327. return;
  328. }
  329. WebSocket::ConnectionInfo connection_info(url);
  330. connection_info.set_origin(origin);
  331. connection_info.set_protocols(protocols);
  332. connection_info.set_extensions(extensions);
  333. connection_info.set_headers(additional_request_headers);
  334. auto connection = WebSocket::WebSocket::create(move(connection_info));
  335. connection->on_open = [this, websocket_id]() {
  336. async_websocket_connected(websocket_id);
  337. };
  338. connection->on_message = [this, websocket_id](auto message) {
  339. async_websocket_received(websocket_id, message.is_text(), message.data());
  340. };
  341. connection->on_error = [this, websocket_id](auto message) {
  342. async_websocket_errored(websocket_id, (i32)message);
  343. };
  344. connection->on_close = [this, websocket_id](u16 code, ByteString reason, bool was_clean) {
  345. async_websocket_closed(websocket_id, code, move(reason), was_clean);
  346. };
  347. connection->on_ready_state_change = [this, websocket_id](auto state) {
  348. async_websocket_ready_state_changed(websocket_id, (u32)state);
  349. };
  350. connection->start();
  351. m_websockets.set(websocket_id, move(connection));
  352. }
  353. void ConnectionFromClient::websocket_send(i64 websocket_id, bool is_text, ByteBuffer const& data)
  354. {
  355. if (auto connection = m_websockets.get(websocket_id).value_or({}); connection && connection->ready_state() == WebSocket::ReadyState::Open)
  356. connection->send(WebSocket::Message { data, is_text });
  357. }
  358. void ConnectionFromClient::websocket_close(i64 websocket_id, u16 code, ByteString const& reason)
  359. {
  360. if (auto connection = m_websockets.get(websocket_id).value_or({}); connection && connection->ready_state() == WebSocket::ReadyState::Open)
  361. connection->close(code, reason);
  362. }
  363. Messages::RequestServer::WebsocketSetCertificateResponse ConnectionFromClient::websocket_set_certificate(i64 websocket_id, ByteString const&, ByteString const&)
  364. {
  365. auto success = false;
  366. if (auto connection = m_websockets.get(websocket_id).value_or({}); connection) {
  367. // NO OP here
  368. // connection->set_certificate(certificate, key);
  369. success = true;
  370. }
  371. return success;
  372. }
  373. }