Job.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/Debug.h>
  9. #include <AK/JsonObject.h>
  10. #include <LibCompress/Brotli.h>
  11. #include <LibCompress/Gzip.h>
  12. #include <LibCompress/Zlib.h>
  13. #include <LibCore/Event.h>
  14. #include <LibCore/MemoryStream.h>
  15. #include <LibHTTP/HttpResponse.h>
  16. #include <LibHTTP/Job.h>
  17. #include <stdio.h>
  18. #include <unistd.h>
  19. namespace HTTP {
  20. static Optional<ByteBuffer> handle_content_encoding(ByteBuffer const& buf, DeprecatedString const& content_encoding)
  21. {
  22. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: buf has content_encoding={}", content_encoding);
  23. // FIXME: Actually do the decompression of the data using streams, instead of all at once when everything has been
  24. // received. This will require that some of the decompression algorithms are implemented in a streaming way.
  25. // Gzip and Deflate are implemented using AK::Stream, while Brotli uses the newer Core::Stream. The Gzip and
  26. // Deflate implementations will likely need to be changed to LibCore::Stream for this to work easily.
  27. if (content_encoding == "gzip") {
  28. if (!Compress::GzipDecompressor::is_likely_compressed(buf)) {
  29. dbgln("Job::handle_content_encoding: buf is not gzip compressed!");
  30. }
  31. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: buf is gzip compressed!");
  32. auto uncompressed = Compress::GzipDecompressor::decompress_all(buf);
  33. if (uncompressed.is_error()) {
  34. dbgln("Job::handle_content_encoding: Gzip::decompress() failed: {}", uncompressed.error());
  35. return {};
  36. }
  37. if constexpr (JOB_DEBUG) {
  38. dbgln("Job::handle_content_encoding: Gzip::decompress() successful.");
  39. dbgln(" Input size: {}", buf.size());
  40. dbgln(" Output size: {}", uncompressed.value().size());
  41. }
  42. return uncompressed.release_value();
  43. } else if (content_encoding == "deflate") {
  44. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: buf is deflate compressed!");
  45. // Even though the content encoding is "deflate", it's actually deflate with the zlib wrapper.
  46. // https://tools.ietf.org/html/rfc7230#section-4.2.2
  47. auto uncompressed = Compress::Zlib::decompress_all(buf);
  48. if (!uncompressed.has_value()) {
  49. // From the RFC:
  50. // "Note: Some non-conformant implementations send the "deflate"
  51. // compressed data without the zlib wrapper."
  52. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: Zlib::decompress_all() failed. Trying DeflateDecompressor::decompress_all()");
  53. uncompressed = Compress::DeflateDecompressor::decompress_all(buf);
  54. if (!uncompressed.has_value()) {
  55. dbgln("Job::handle_content_encoding: DeflateDecompressor::decompress_all() failed.");
  56. return {};
  57. }
  58. }
  59. if constexpr (JOB_DEBUG) {
  60. dbgln("Job::handle_content_encoding: Deflate decompression successful.");
  61. dbgln(" Input size: {}", buf.size());
  62. dbgln(" Output size: {}", uncompressed.value().size());
  63. }
  64. return uncompressed.release_value();
  65. } else if (content_encoding == "br") {
  66. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: buf is brotli compressed!");
  67. auto bufstream_result = Core::Stream::MemoryStream::construct({ buf.data(), buf.size() });
  68. if (bufstream_result.is_error()) {
  69. dbgln("Job::handle_content_encoding: MemoryStream::construct() failed.");
  70. return {};
  71. }
  72. auto bufstream = bufstream_result.release_value();
  73. auto brotli_stream = Compress::BrotliDecompressionStream { *bufstream };
  74. auto uncompressed = brotli_stream.read_all();
  75. if (uncompressed.is_error()) {
  76. dbgln("Job::handle_content_encoding: Brotli::decompress() failed: {}.", uncompressed.error());
  77. return {};
  78. }
  79. if constexpr (JOB_DEBUG) {
  80. dbgln("Job::handle_content_encoding: Brotli::decompress() successful.");
  81. dbgln(" Input size: {}", buf.size());
  82. dbgln(" Output size: {}", uncompressed.value().size());
  83. }
  84. return uncompressed.release_value();
  85. }
  86. return buf;
  87. }
  88. Job::Job(HttpRequest&& request, Core::Stream::Stream& output_stream)
  89. : Core::NetworkJob(output_stream)
  90. , m_request(move(request))
  91. {
  92. }
  93. void Job::start(Core::Stream::Socket& socket)
  94. {
  95. VERIFY(!m_socket);
  96. m_socket = static_cast<Core::Stream::BufferedSocketBase*>(&socket);
  97. dbgln_if(HTTPJOB_DEBUG, "Reusing previous connection for {}", url());
  98. deferred_invoke([this] {
  99. dbgln_if(HTTPJOB_DEBUG, "HttpJob: on_connected callback");
  100. on_socket_connected();
  101. });
  102. }
  103. void Job::shutdown(ShutdownMode mode)
  104. {
  105. if (!m_socket)
  106. return;
  107. if (mode == ShutdownMode::CloseSocket) {
  108. m_socket->close();
  109. m_socket->on_ready_to_read = nullptr;
  110. } else {
  111. m_socket->on_ready_to_read = nullptr;
  112. m_socket = nullptr;
  113. }
  114. }
  115. void Job::flush_received_buffers()
  116. {
  117. if (!m_can_stream_response || m_buffered_size == 0)
  118. return;
  119. dbgln_if(JOB_DEBUG, "Job: Flushing received buffers: have {} bytes in {} buffers for {}", m_buffered_size, m_received_buffers.size(), m_request.url());
  120. for (size_t i = 0; i < m_received_buffers.size(); ++i) {
  121. auto& payload = m_received_buffers[i].pending_flush;
  122. auto result = do_write(payload);
  123. if (result.is_error()) {
  124. if (!result.error().is_errno()) {
  125. dbgln_if(JOB_DEBUG, "Job: Failed to flush received buffers: {}", result.error());
  126. continue;
  127. }
  128. if (result.error().code() == EINTR) {
  129. i--;
  130. continue;
  131. }
  132. break;
  133. }
  134. auto written = result.release_value();
  135. m_buffered_size -= written;
  136. if (written == payload.size()) {
  137. // FIXME: Make this a take-first-friendly object?
  138. (void)m_received_buffers.take_first();
  139. --i;
  140. continue;
  141. }
  142. VERIFY(written < payload.size());
  143. payload = payload.slice(written, payload.size() - written);
  144. break;
  145. }
  146. dbgln_if(JOB_DEBUG, "Job: Flushing received buffers done: have {} bytes in {} buffers for {}", m_buffered_size, m_received_buffers.size(), m_request.url());
  147. }
  148. void Job::register_on_ready_to_read(Function<void()> callback)
  149. {
  150. m_socket->on_ready_to_read = [this, callback = move(callback)] {
  151. callback();
  152. // As `m_socket` is a buffered object, we might not get notifications for data in the buffer
  153. // so exhaust the buffer to ensure we don't end up waiting forever.
  154. auto can_read_without_blocking = m_socket->can_read_without_blocking();
  155. if (can_read_without_blocking.is_error())
  156. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  157. if (can_read_without_blocking.value() && m_state != State::Finished && !has_error()) {
  158. deferred_invoke([this] {
  159. if (m_socket && m_socket->on_ready_to_read)
  160. m_socket->on_ready_to_read();
  161. });
  162. }
  163. };
  164. }
  165. ErrorOr<DeprecatedString> Job::read_line(size_t size)
  166. {
  167. auto buffer = TRY(ByteBuffer::create_uninitialized(size));
  168. auto bytes_read = TRY(m_socket->read_until(buffer, "\r\n"sv));
  169. return DeprecatedString::copy(bytes_read);
  170. }
  171. ErrorOr<ByteBuffer> Job::receive(size_t size)
  172. {
  173. if (size == 0)
  174. return ByteBuffer {};
  175. auto buffer = TRY(ByteBuffer::create_uninitialized(size));
  176. size_t nread;
  177. do {
  178. auto result = m_socket->read(buffer);
  179. if (result.is_error() && result.error().is_errno() && result.error().code() == EINTR)
  180. continue;
  181. nread = TRY(result).size();
  182. break;
  183. } while (true);
  184. return buffer.slice(0, nread);
  185. }
  186. void Job::on_socket_connected()
  187. {
  188. auto raw_request = m_request.to_raw_request();
  189. if constexpr (JOB_DEBUG) {
  190. dbgln("Job: raw_request:");
  191. dbgln("{}", DeprecatedString::copy(raw_request));
  192. }
  193. bool success = m_socket->write_or_error(raw_request);
  194. if (!success)
  195. deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  196. register_on_ready_to_read([&] {
  197. dbgln_if(JOB_DEBUG, "Ready to read for {}, state = {}, cancelled = {}", m_request.url(), to_underlying(m_state), is_cancelled());
  198. if (is_cancelled())
  199. return;
  200. if (m_state == State::Finished) {
  201. // We have everything we want, at this point, we can either get an EOF, or a bunch of extra newlines
  202. // (unless "Connection: close" isn't specified)
  203. // So just ignore everything after this.
  204. return;
  205. }
  206. if (m_socket->is_eof()) {
  207. dbgln_if(JOB_DEBUG, "Read failure: Actually EOF!");
  208. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  209. }
  210. while (m_state == State::InStatus) {
  211. auto can_read_line = m_socket->can_read_line();
  212. if (can_read_line.is_error()) {
  213. dbgln_if(JOB_DEBUG, "Job {} could not figure out whether we could read a line", m_request.url());
  214. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  215. }
  216. if (!can_read_line.value()) {
  217. dbgln_if(JOB_DEBUG, "Job {} cannot read line", m_request.url());
  218. auto maybe_buf = receive(64);
  219. if (maybe_buf.is_error()) {
  220. dbgln_if(JOB_DEBUG, "Job {} cannot read any bytes!", m_request.url());
  221. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  222. }
  223. dbgln_if(JOB_DEBUG, "{} bytes was read", maybe_buf.value().bytes().size());
  224. return;
  225. }
  226. auto maybe_line = read_line(PAGE_SIZE);
  227. if (maybe_line.is_error()) {
  228. dbgln_if(JOB_DEBUG, "Job {} could not read line: {}", m_request.url(), maybe_line.error());
  229. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  230. }
  231. auto line = maybe_line.release_value();
  232. dbgln_if(JOB_DEBUG, "Job {} read line of length {}", m_request.url(), line.length());
  233. if (line.is_null()) {
  234. dbgln("Job: Expected HTTP status");
  235. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  236. }
  237. auto parts = line.split_view(' ');
  238. if (parts.size() < 2) {
  239. dbgln("Job: Expected 2-part or 3-part HTTP status line, got '{}'", line);
  240. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  241. }
  242. if (!parts[0].matches("HTTP/?.?"sv, CaseSensitivity::CaseSensitive) || !is_ascii_digit(parts[0][5]) || !is_ascii_digit(parts[0][7])) {
  243. dbgln("Job: Expected HTTP-Version to be of the form 'HTTP/X.Y', got '{}'", parts[0]);
  244. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  245. }
  246. auto http_major_version = parse_ascii_digit(parts[0][5]);
  247. auto http_minor_version = parse_ascii_digit(parts[0][7]);
  248. m_legacy_connection = http_major_version < 1 || (http_major_version == 1 && http_minor_version == 0);
  249. auto code = parts[1].to_uint();
  250. if (!code.has_value()) {
  251. dbgln("Job: Expected numeric HTTP status");
  252. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  253. }
  254. m_code = code.value();
  255. m_state = State::InHeaders;
  256. auto can_read_without_blocking = m_socket->can_read_without_blocking();
  257. if (can_read_without_blocking.is_error())
  258. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  259. if (!can_read_without_blocking.value())
  260. return;
  261. }
  262. while (m_state == State::InHeaders || m_state == State::Trailers) {
  263. auto can_read_line = m_socket->can_read_line();
  264. if (can_read_line.is_error()) {
  265. dbgln_if(JOB_DEBUG, "Job {} could not figure out whether we could read a line", m_request.url());
  266. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  267. }
  268. if (!can_read_line.value()) {
  269. dbgln_if(JOB_DEBUG, "Can't read lines anymore :(");
  270. return;
  271. }
  272. // There's no max limit defined on headers, but for our sanity, let's limit it to 32K.
  273. auto maybe_line = read_line(32 * KiB);
  274. if (maybe_line.is_error()) {
  275. dbgln_if(JOB_DEBUG, "Job {} could not read a header line: {}", m_request.url(), maybe_line.error());
  276. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  277. }
  278. auto line = maybe_line.release_value();
  279. if (line.is_null()) {
  280. if (m_state == State::Trailers) {
  281. // Some servers like to send two ending chunks
  282. // use this fact as an excuse to ignore anything after the last chunk
  283. // that is not a valid trailing header.
  284. return finish_up();
  285. }
  286. dbgln("Job: Expected HTTP header");
  287. return did_fail(Core::NetworkJob::Error::ProtocolFailed);
  288. }
  289. if (line.is_empty()) {
  290. if (m_state == State::Trailers) {
  291. return finish_up();
  292. }
  293. if (on_headers_received) {
  294. if (!m_set_cookie_headers.is_empty())
  295. m_headers.set("Set-Cookie", JsonArray { m_set_cookie_headers }.to_deprecated_string());
  296. on_headers_received(m_headers, m_code > 0 ? m_code : Optional<u32> {});
  297. }
  298. m_state = State::InBody;
  299. // We've reached the end of the headers, there's a possibility that the server
  300. // responds with nothing (content-length = 0 with normal encoding); if that's the case,
  301. // quit early as we won't be reading anything anyway.
  302. if (auto result = m_headers.get("Content-Length"sv).value_or(""sv).to_uint(); result.has_value()) {
  303. if (result.value() == 0 && !m_headers.get("Transfer-Encoding"sv).value_or(""sv).view().trim_whitespace().equals_ignoring_case("chunked"sv))
  304. return finish_up();
  305. }
  306. // There's also the possibility that the server responds with 204 (No Content),
  307. // and manages to set a Content-Length anyway, in such cases ignore Content-Length and quit early;
  308. // As the HTTP spec explicitly prohibits presence of Content-Length when the response code is 204.
  309. if (m_code == 204)
  310. return finish_up();
  311. break;
  312. }
  313. auto parts = line.split_view(':');
  314. if (parts.is_empty()) {
  315. if (m_state == State::Trailers) {
  316. // Some servers like to send two ending chunks
  317. // use this fact as an excuse to ignore anything after the last chunk
  318. // that is not a valid trailing header.
  319. return finish_up();
  320. }
  321. dbgln("Job: Expected HTTP header with key/value");
  322. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  323. }
  324. auto name = parts[0];
  325. if (line.length() < name.length() + 2) {
  326. if (m_state == State::Trailers) {
  327. // Some servers like to send two ending chunks
  328. // use this fact as an excuse to ignore anything after the last chunk
  329. // that is not a valid trailing header.
  330. return finish_up();
  331. }
  332. dbgln("Job: Malformed HTTP header: '{}' ({})", line, line.length());
  333. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  334. }
  335. auto value = line.substring(name.length() + 2, line.length() - name.length() - 2);
  336. if (name.equals_ignoring_case("Set-Cookie"sv)) {
  337. dbgln_if(JOB_DEBUG, "Job: Received Set-Cookie header: '{}'", value);
  338. m_set_cookie_headers.append(move(value));
  339. auto can_read_without_blocking = m_socket->can_read_without_blocking();
  340. if (can_read_without_blocking.is_error())
  341. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  342. if (!can_read_without_blocking.value())
  343. return;
  344. } else if (auto existing_value = m_headers.get(name); existing_value.has_value()) {
  345. StringBuilder builder;
  346. builder.append(existing_value.value());
  347. builder.append(',');
  348. builder.append(value);
  349. m_headers.set(name, builder.build());
  350. } else {
  351. m_headers.set(name, value);
  352. }
  353. if (name.equals_ignoring_case("Content-Encoding"sv)) {
  354. // Assume that any content-encoding means that we can't decode it as a stream :(
  355. dbgln_if(JOB_DEBUG, "Content-Encoding {} detected, cannot stream output :(", value);
  356. m_can_stream_response = false;
  357. } else if (name.equals_ignoring_case("Content-Length"sv)) {
  358. auto length = value.to_uint();
  359. if (length.has_value())
  360. m_content_length = length.value();
  361. }
  362. dbgln_if(JOB_DEBUG, "Job: [{}] = '{}'", name, value);
  363. auto can_read_without_blocking = m_socket->can_read_without_blocking();
  364. if (can_read_without_blocking.is_error())
  365. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  366. if (!can_read_without_blocking.value()) {
  367. dbgln_if(JOB_DEBUG, "Can't read headers anymore, byebye :(");
  368. return;
  369. }
  370. }
  371. VERIFY(m_state == State::InBody);
  372. while (true) {
  373. auto can_read_without_blocking = m_socket->can_read_without_blocking();
  374. if (can_read_without_blocking.is_error())
  375. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  376. if (!can_read_without_blocking.value())
  377. break;
  378. auto read_size = 64 * KiB;
  379. if (m_current_chunk_remaining_size.has_value()) {
  380. read_chunk_size:;
  381. auto remaining = m_current_chunk_remaining_size.value();
  382. if (remaining == -1) {
  383. // read size
  384. auto maybe_size_data = read_line(PAGE_SIZE);
  385. if (maybe_size_data.is_error()) {
  386. dbgln_if(JOB_DEBUG, "Job: Could not receive chunk: {}", maybe_size_data.error());
  387. }
  388. auto size_data = maybe_size_data.release_value();
  389. if (m_should_read_chunk_ending_line) {
  390. VERIFY(size_data.is_empty());
  391. m_should_read_chunk_ending_line = false;
  392. continue;
  393. }
  394. auto size_lines = size_data.view().lines();
  395. dbgln_if(JOB_DEBUG, "Job: Received a chunk with size '{}'", size_data);
  396. if (size_lines.size() == 0) {
  397. if (!m_socket->is_eof())
  398. break;
  399. dbgln("Job: Reached end of stream");
  400. finish_up();
  401. break;
  402. } else {
  403. auto chunk = size_lines[0].split_view(';', SplitBehavior::KeepEmpty);
  404. DeprecatedString size_string = chunk[0];
  405. char* endptr;
  406. auto size = strtoul(size_string.characters(), &endptr, 16);
  407. if (*endptr) {
  408. // invalid number
  409. deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  410. break;
  411. }
  412. if (size == 0) {
  413. // This is the last chunk
  414. // '0' *[; chunk-ext-name = chunk-ext-value]
  415. // We're going to ignore _all_ chunk extensions
  416. read_size = 0;
  417. m_current_chunk_total_size = 0;
  418. m_current_chunk_remaining_size = 0;
  419. dbgln_if(JOB_DEBUG, "Job: Received the last chunk with extensions '{}'", size_string.substring_view(1, size_string.length() - 1));
  420. } else {
  421. m_current_chunk_total_size = size;
  422. m_current_chunk_remaining_size = size;
  423. read_size = size;
  424. dbgln_if(JOB_DEBUG, "Job: Chunk of size '{}' started", size);
  425. }
  426. }
  427. } else {
  428. read_size = remaining;
  429. dbgln_if(JOB_DEBUG, "Job: Resuming chunk with '{}' bytes left over", remaining);
  430. }
  431. } else {
  432. auto transfer_encoding = m_headers.get("Transfer-Encoding");
  433. if (transfer_encoding.has_value()) {
  434. // HTTP/1.1 3.3.3.3:
  435. // If a message is received with both a Transfer-Encoding and a Content-Length header field, the Transfer-Encoding overrides the Content-Length. [...]
  436. // https://httpwg.org/specs/rfc7230.html#message.body.length
  437. m_content_length = {};
  438. // Note: Some servers add extra spaces around 'chunked', see #6302.
  439. auto encoding = transfer_encoding.value().trim_whitespace();
  440. dbgln_if(JOB_DEBUG, "Job: This content has transfer encoding '{}'", encoding);
  441. if (encoding.equals_ignoring_case("chunked"sv)) {
  442. m_current_chunk_remaining_size = -1;
  443. goto read_chunk_size;
  444. } else {
  445. dbgln("Job: Unknown transfer encoding '{}', the result will likely be wrong!", encoding);
  446. }
  447. }
  448. }
  449. can_read_without_blocking = m_socket->can_read_without_blocking();
  450. if (can_read_without_blocking.is_error())
  451. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  452. if (!can_read_without_blocking.value())
  453. break;
  454. dbgln_if(JOB_DEBUG, "Waiting for payload for {}", m_request.url());
  455. auto maybe_payload = receive(read_size);
  456. if (maybe_payload.is_error()) {
  457. dbgln_if(JOB_DEBUG, "Could not read the payload: {}", maybe_payload.error());
  458. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  459. }
  460. auto payload = maybe_payload.release_value();
  461. if (payload.is_empty() && m_socket->is_eof()) {
  462. finish_up();
  463. break;
  464. }
  465. bool read_everything = false;
  466. if (m_content_length.has_value()) {
  467. auto length = m_content_length.value();
  468. if (m_received_size + payload.size() >= length) {
  469. payload.resize(length - m_received_size);
  470. read_everything = true;
  471. }
  472. }
  473. m_received_buffers.append(make<ReceivedBuffer>(payload));
  474. m_buffered_size += payload.size();
  475. m_received_size += payload.size();
  476. flush_received_buffers();
  477. deferred_invoke([this] { did_progress(m_content_length, m_received_size); });
  478. if (read_everything) {
  479. VERIFY(m_received_size <= m_content_length.value());
  480. finish_up();
  481. break;
  482. }
  483. // Check after reading all the buffered data if we have reached the end of stream
  484. // for cases where the server didn't send a content length, chunked encoding but is
  485. // directly closing the connection.
  486. if (!m_content_length.has_value() && !m_current_chunk_remaining_size.has_value() && m_socket->is_eof()) {
  487. finish_up();
  488. break;
  489. }
  490. if (m_current_chunk_remaining_size.has_value()) {
  491. auto size = m_current_chunk_remaining_size.value() - payload.size();
  492. dbgln_if(JOB_DEBUG, "Job: We have {} bytes left over in this chunk", size);
  493. if (size == 0) {
  494. dbgln_if(JOB_DEBUG, "Job: Finished a chunk of {} bytes", m_current_chunk_total_size.value());
  495. if (m_current_chunk_total_size.value() == 0) {
  496. m_state = State::Trailers;
  497. break;
  498. }
  499. // we've read everything, now let's get the next chunk
  500. size = -1;
  501. auto can_read_line = m_socket->can_read_line();
  502. if (can_read_line.is_error())
  503. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  504. if (can_read_line.value()) {
  505. auto maybe_line = read_line(PAGE_SIZE);
  506. if (maybe_line.is_error()) {
  507. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  508. }
  509. VERIFY(maybe_line.value().is_empty());
  510. } else {
  511. m_should_read_chunk_ending_line = true;
  512. }
  513. }
  514. m_current_chunk_remaining_size = size;
  515. }
  516. }
  517. if (!m_socket->is_open()) {
  518. dbgln_if(JOB_DEBUG, "Connection appears to have closed, finishing up");
  519. finish_up();
  520. }
  521. });
  522. }
  523. void Job::timer_event(Core::TimerEvent& event)
  524. {
  525. event.accept();
  526. finish_up();
  527. if (m_buffered_size == 0)
  528. stop_timer();
  529. }
  530. void Job::finish_up()
  531. {
  532. VERIFY(!m_has_scheduled_finish);
  533. m_state = State::Finished;
  534. if (!m_can_stream_response) {
  535. auto maybe_flattened_buffer = ByteBuffer::create_uninitialized(m_buffered_size);
  536. if (maybe_flattened_buffer.is_error())
  537. return did_fail(Core::NetworkJob::Error::TransmissionFailed);
  538. auto flattened_buffer = maybe_flattened_buffer.release_value();
  539. u8* flat_ptr = flattened_buffer.data();
  540. for (auto& received_buffer : m_received_buffers) {
  541. memcpy(flat_ptr, received_buffer.pending_flush.data(), received_buffer.pending_flush.size());
  542. flat_ptr += received_buffer.pending_flush.size();
  543. }
  544. m_received_buffers.clear();
  545. // For the time being, we cannot stream stuff with content-encoding set to _anything_.
  546. // FIXME: LibCompress exposes a streaming interface, so this can be resolved
  547. auto content_encoding = m_headers.get("Content-Encoding");
  548. if (content_encoding.has_value()) {
  549. if (auto result = handle_content_encoding(flattened_buffer, content_encoding.value()); result.has_value())
  550. flattened_buffer = result.release_value();
  551. else
  552. return did_fail(Core::NetworkJob::Error::TransmissionFailed);
  553. }
  554. m_buffered_size = flattened_buffer.size();
  555. m_received_buffers.append(make<ReceivedBuffer>(move(flattened_buffer)));
  556. m_can_stream_response = true;
  557. }
  558. flush_received_buffers();
  559. if (m_buffered_size != 0) {
  560. // We have to wait for the client to consume all the downloaded data
  561. // before we can actually call `did_finish`. in a normal flow, this should
  562. // never be hit since the client is reading as we are writing, unless there
  563. // are too many concurrent downloads going on.
  564. dbgln_if(JOB_DEBUG, "Flush finished with {} bytes remaining, will try again later", m_buffered_size);
  565. if (!has_timer())
  566. start_timer(50);
  567. return;
  568. }
  569. m_has_scheduled_finish = true;
  570. auto response = HttpResponse::create(m_code, move(m_headers), m_received_size);
  571. deferred_invoke([this, response = move(response)] {
  572. // If the server responded with "Connection: close", close the connection
  573. // as the server may or may not want to close the socket. Also, if this is
  574. // a legacy HTTP server (1.0 or older), assume close is the default value.
  575. if (auto result = response->headers().get("Connection"sv); result.has_value() ? result->equals_ignoring_case("close"sv) : m_legacy_connection)
  576. shutdown(ShutdownMode::CloseSocket);
  577. did_finish(response);
  578. });
  579. }
  580. }