Job.cpp 29 KB

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