Job.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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, String 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.has_value()) {
  34. dbgln("Job::handle_content_encoding: Gzip::decompress() failed.");
  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. // FIXME: MemoryStream is both read and write, however we only need the read part here
  68. auto bufstream_result = Core::Stream::MemoryStream::construct({ const_cast<u8*>(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_all();
  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<String> 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 String::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("{}", String::copy(raw_request));
  193. }
  194. bool success = m_socket->write_or_error(raw_request);
  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 line", m_request.url());
  219. auto maybe_buf = receive(64);
  220. if (maybe_buf.is_error()) {
  221. dbgln_if(JOB_DEBUG, "Job {} cannot read any bytes!", m_request.url());
  222. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  223. }
  224. dbgln_if(JOB_DEBUG, "{} bytes was read", maybe_buf.value().bytes().size());
  225. return;
  226. }
  227. auto maybe_line = read_line(PAGE_SIZE);
  228. if (maybe_line.is_error()) {
  229. dbgln_if(JOB_DEBUG, "Job {} could not read line: {}", m_request.url(), maybe_line.error());
  230. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  231. }
  232. auto line = maybe_line.release_value();
  233. dbgln_if(JOB_DEBUG, "Job {} read line of length {}", m_request.url(), line.length());
  234. if (line.is_null()) {
  235. dbgln("Job: Expected HTTP status");
  236. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  237. }
  238. auto parts = line.split_view(' ');
  239. if (parts.size() < 2) {
  240. dbgln("Job: Expected 2-part or 3-part HTTP status line, got '{}'", line);
  241. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  242. }
  243. if (!parts[0].matches("HTTP/?.?"sv, CaseSensitivity::CaseSensitive) || !is_ascii_digit(parts[0][5]) || !is_ascii_digit(parts[0][7])) {
  244. dbgln("Job: Expected HTTP-Version to be of the form 'HTTP/X.Y', got '{}'", parts[0]);
  245. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  246. }
  247. auto http_major_version = parse_ascii_digit(parts[0][5]);
  248. auto http_minor_version = parse_ascii_digit(parts[0][7]);
  249. m_legacy_connection = http_major_version < 1 || (http_major_version == 1 && http_minor_version == 0);
  250. auto code = parts[1].to_uint();
  251. if (!code.has_value()) {
  252. dbgln("Job: Expected numeric HTTP status");
  253. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  254. }
  255. m_code = code.value();
  256. m_state = State::InHeaders;
  257. auto can_read_without_blocking = m_socket->can_read_without_blocking();
  258. if (can_read_without_blocking.is_error())
  259. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  260. if (!can_read_without_blocking.value())
  261. return;
  262. }
  263. while (m_state == State::InHeaders || m_state == State::Trailers) {
  264. auto can_read_line = m_socket->can_read_line();
  265. if (can_read_line.is_error()) {
  266. dbgln_if(JOB_DEBUG, "Job {} could not figure out whether we could read a line", m_request.url());
  267. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  268. }
  269. if (!can_read_line.value()) {
  270. dbgln_if(JOB_DEBUG, "Can't read lines anymore :(");
  271. return;
  272. }
  273. // There's no max limit defined on headers, but for our sanity, let's limit it to 32K.
  274. auto maybe_line = read_line(32 * KiB);
  275. if (maybe_line.is_error()) {
  276. dbgln_if(JOB_DEBUG, "Job {} could not read a header line: {}", m_request.url(), maybe_line.error());
  277. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  278. }
  279. auto line = maybe_line.release_value();
  280. if (line.is_null()) {
  281. if (m_state == State::Trailers) {
  282. // Some servers like to send two ending chunks
  283. // use this fact as an excuse to ignore anything after the last chunk
  284. // that is not a valid trailing header.
  285. return finish_up();
  286. }
  287. dbgln("Job: Expected HTTP header");
  288. return did_fail(Core::NetworkJob::Error::ProtocolFailed);
  289. }
  290. if (line.is_empty()) {
  291. if (m_state == State::Trailers) {
  292. return finish_up();
  293. }
  294. if (on_headers_received) {
  295. if (!m_set_cookie_headers.is_empty())
  296. m_headers.set("Set-Cookie", JsonArray { m_set_cookie_headers }.to_string());
  297. on_headers_received(m_headers, m_code > 0 ? m_code : Optional<u32> {});
  298. }
  299. m_state = State::InBody;
  300. // We've reached the end of the headers, there's a possibility that the server
  301. // responds with nothing (content-length = 0 with normal encoding); if that's the case,
  302. // quit early as we won't be reading anything anyway.
  303. if (auto result = m_headers.get("Content-Length"sv).value_or(""sv).to_uint(); result.has_value()) {
  304. if (result.value() == 0 && !m_headers.get("Transfer-Encoding"sv).value_or(""sv).view().trim_whitespace().equals_ignoring_case("chunked"sv))
  305. return finish_up();
  306. }
  307. // There's also the possibility that the server responds with 204 (No Content),
  308. // and manages to set a Content-Length anyway, in such cases ignore Content-Length and quit early;
  309. // As the HTTP spec explicitly prohibits presence of Content-Length when the response code is 204.
  310. if (m_code == 204)
  311. return finish_up();
  312. break;
  313. }
  314. auto parts = line.split_view(':');
  315. if (parts.is_empty()) {
  316. if (m_state == State::Trailers) {
  317. // Some servers like to send two ending chunks
  318. // use this fact as an excuse to ignore anything after the last chunk
  319. // that is not a valid trailing header.
  320. return finish_up();
  321. }
  322. dbgln("Job: Expected HTTP header with key/value");
  323. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  324. }
  325. auto name = parts[0];
  326. if (line.length() < name.length() + 2) {
  327. if (m_state == State::Trailers) {
  328. // Some servers like to send two ending chunks
  329. // use this fact as an excuse to ignore anything after the last chunk
  330. // that is not a valid trailing header.
  331. return finish_up();
  332. }
  333. dbgln("Job: Malformed HTTP header: '{}' ({})", line, line.length());
  334. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  335. }
  336. auto value = line.substring(name.length() + 2, line.length() - name.length() - 2);
  337. if (name.equals_ignoring_case("Set-Cookie"sv)) {
  338. dbgln_if(JOB_DEBUG, "Job: Received Set-Cookie header: '{}'", value);
  339. m_set_cookie_headers.append(move(value));
  340. auto can_read_without_blocking = m_socket->can_read_without_blocking();
  341. if (can_read_without_blocking.is_error())
  342. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  343. if (!can_read_without_blocking.value())
  344. return;
  345. } else if (auto existing_value = m_headers.get(name); existing_value.has_value()) {
  346. StringBuilder builder;
  347. builder.append(existing_value.value());
  348. builder.append(',');
  349. builder.append(value);
  350. m_headers.set(name, builder.build());
  351. } else {
  352. m_headers.set(name, value);
  353. }
  354. if (name.equals_ignoring_case("Content-Encoding"sv)) {
  355. // Assume that any content-encoding means that we can't decode it as a stream :(
  356. dbgln_if(JOB_DEBUG, "Content-Encoding {} detected, cannot stream output :(", value);
  357. m_can_stream_response = false;
  358. } else if (name.equals_ignoring_case("Content-Length"sv)) {
  359. auto length = value.to_uint();
  360. if (length.has_value())
  361. m_content_length = length.value();
  362. }
  363. dbgln_if(JOB_DEBUG, "Job: [{}] = '{}'", name, value);
  364. auto can_read_without_blocking = m_socket->can_read_without_blocking();
  365. if (can_read_without_blocking.is_error())
  366. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  367. if (!can_read_without_blocking.value()) {
  368. dbgln_if(JOB_DEBUG, "Can't read headers anymore, byebye :(");
  369. return;
  370. }
  371. }
  372. VERIFY(m_state == State::InBody);
  373. while (true) {
  374. auto can_read_without_blocking = m_socket->can_read_without_blocking();
  375. if (can_read_without_blocking.is_error())
  376. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  377. if (!can_read_without_blocking.value())
  378. break;
  379. auto read_size = 64 * KiB;
  380. if (m_current_chunk_remaining_size.has_value()) {
  381. read_chunk_size:;
  382. auto remaining = m_current_chunk_remaining_size.value();
  383. if (remaining == -1) {
  384. // read size
  385. auto maybe_size_data = read_line(PAGE_SIZE);
  386. if (maybe_size_data.is_error()) {
  387. dbgln_if(JOB_DEBUG, "Job: Could not receive chunk: {}", maybe_size_data.error());
  388. }
  389. auto size_data = maybe_size_data.release_value();
  390. if (m_should_read_chunk_ending_line) {
  391. VERIFY(size_data.is_empty());
  392. m_should_read_chunk_ending_line = false;
  393. continue;
  394. }
  395. auto size_lines = size_data.view().lines();
  396. dbgln_if(JOB_DEBUG, "Job: Received a chunk with size '{}'", size_data);
  397. if (size_lines.size() == 0) {
  398. if (!m_socket->is_eof())
  399. break;
  400. dbgln("Job: Reached end of stream");
  401. finish_up();
  402. break;
  403. } else {
  404. auto chunk = size_lines[0].split_view(';', SplitBehavior::KeepEmpty);
  405. String size_string = chunk[0];
  406. char* endptr;
  407. auto size = strtoul(size_string.characters(), &endptr, 16);
  408. if (*endptr) {
  409. // invalid number
  410. deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  411. break;
  412. }
  413. if (size == 0) {
  414. // This is the last chunk
  415. // '0' *[; chunk-ext-name = chunk-ext-value]
  416. // We're going to ignore _all_ chunk extensions
  417. read_size = 0;
  418. m_current_chunk_total_size = 0;
  419. m_current_chunk_remaining_size = 0;
  420. dbgln_if(JOB_DEBUG, "Job: Received the last chunk with extensions '{}'", size_string.substring_view(1, size_string.length() - 1));
  421. } else {
  422. m_current_chunk_total_size = size;
  423. m_current_chunk_remaining_size = size;
  424. read_size = size;
  425. dbgln_if(JOB_DEBUG, "Job: Chunk of size '{}' started", size);
  426. }
  427. }
  428. } else {
  429. read_size = remaining;
  430. dbgln_if(JOB_DEBUG, "Job: Resuming chunk with '{}' bytes left over", remaining);
  431. }
  432. } else {
  433. auto transfer_encoding = m_headers.get("Transfer-Encoding");
  434. if (transfer_encoding.has_value()) {
  435. // HTTP/1.1 3.3.3.3:
  436. // If a message is received with both a Transfer-Encoding and a Content-Length header field, the Transfer-Encoding overrides the Content-Length. [...]
  437. // https://httpwg.org/specs/rfc7230.html#message.body.length
  438. m_content_length = {};
  439. // Note: Some servers add extra spaces around 'chunked', see #6302.
  440. auto encoding = transfer_encoding.value().trim_whitespace();
  441. dbgln_if(JOB_DEBUG, "Job: This content has transfer encoding '{}'", encoding);
  442. if (encoding.equals_ignoring_case("chunked"sv)) {
  443. m_current_chunk_remaining_size = -1;
  444. goto read_chunk_size;
  445. } else {
  446. dbgln("Job: Unknown transfer encoding '{}', the result will likely be wrong!", encoding);
  447. }
  448. }
  449. }
  450. can_read_without_blocking = m_socket->can_read_without_blocking();
  451. if (can_read_without_blocking.is_error())
  452. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  453. if (!can_read_without_blocking.value())
  454. break;
  455. dbgln_if(JOB_DEBUG, "Waiting for payload for {}", m_request.url());
  456. auto maybe_payload = receive(read_size);
  457. if (maybe_payload.is_error()) {
  458. dbgln_if(JOB_DEBUG, "Could not read the payload: {}", maybe_payload.error());
  459. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  460. }
  461. auto payload = maybe_payload.release_value();
  462. if (payload.is_empty() && m_socket->is_eof()) {
  463. finish_up();
  464. break;
  465. }
  466. bool read_everything = false;
  467. if (m_content_length.has_value()) {
  468. auto length = m_content_length.value();
  469. if (m_received_size + payload.size() >= length) {
  470. payload.resize(length - m_received_size);
  471. read_everything = true;
  472. }
  473. }
  474. m_received_buffers.append(make<ReceivedBuffer>(payload));
  475. m_buffered_size += payload.size();
  476. m_received_size += payload.size();
  477. flush_received_buffers();
  478. deferred_invoke([this] { did_progress(m_content_length, m_received_size); });
  479. if (read_everything) {
  480. VERIFY(m_received_size <= m_content_length.value());
  481. finish_up();
  482. break;
  483. }
  484. // Check after reading all the buffered data if we have reached the end of stream
  485. // for cases where the server didn't send a content length, chunked encoding but is
  486. // directly closing the connection.
  487. if (!m_content_length.has_value() && !m_current_chunk_remaining_size.has_value() && m_socket->is_eof()) {
  488. finish_up();
  489. break;
  490. }
  491. if (m_current_chunk_remaining_size.has_value()) {
  492. auto size = m_current_chunk_remaining_size.value() - payload.size();
  493. dbgln_if(JOB_DEBUG, "Job: We have {} bytes left over in this chunk", size);
  494. if (size == 0) {
  495. dbgln_if(JOB_DEBUG, "Job: Finished a chunk of {} bytes", m_current_chunk_total_size.value());
  496. if (m_current_chunk_total_size.value() == 0) {
  497. m_state = State::Trailers;
  498. break;
  499. }
  500. // we've read everything, now let's get the next chunk
  501. size = -1;
  502. auto can_read_line = m_socket->can_read_line();
  503. if (can_read_line.is_error())
  504. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  505. if (can_read_line.value()) {
  506. auto maybe_line = read_line(PAGE_SIZE);
  507. if (maybe_line.is_error()) {
  508. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  509. }
  510. VERIFY(maybe_line.value().is_empty());
  511. } else {
  512. m_should_read_chunk_ending_line = true;
  513. }
  514. }
  515. m_current_chunk_remaining_size = size;
  516. }
  517. }
  518. if (!m_socket->is_open()) {
  519. dbgln_if(JOB_DEBUG, "Connection appears to have closed, finishing up");
  520. finish_up();
  521. }
  522. });
  523. }
  524. void Job::timer_event(Core::TimerEvent& event)
  525. {
  526. event.accept();
  527. finish_up();
  528. if (m_buffered_size == 0)
  529. stop_timer();
  530. }
  531. void Job::finish_up()
  532. {
  533. VERIFY(!m_has_scheduled_finish);
  534. m_state = State::Finished;
  535. if (!m_can_stream_response) {
  536. auto maybe_flattened_buffer = ByteBuffer::create_uninitialized(m_buffered_size);
  537. if (maybe_flattened_buffer.is_error())
  538. return did_fail(Core::NetworkJob::Error::TransmissionFailed);
  539. auto flattened_buffer = maybe_flattened_buffer.release_value();
  540. u8* flat_ptr = flattened_buffer.data();
  541. for (auto& received_buffer : m_received_buffers) {
  542. memcpy(flat_ptr, received_buffer.pending_flush.data(), received_buffer.pending_flush.size());
  543. flat_ptr += received_buffer.pending_flush.size();
  544. }
  545. m_received_buffers.clear();
  546. // For the time being, we cannot stream stuff with content-encoding set to _anything_.
  547. // FIXME: LibCompress exposes a streaming interface, so this can be resolved
  548. auto content_encoding = m_headers.get("Content-Encoding");
  549. if (content_encoding.has_value()) {
  550. if (auto result = handle_content_encoding(flattened_buffer, content_encoding.value()); result.has_value())
  551. flattened_buffer = result.release_value();
  552. else
  553. return did_fail(Core::NetworkJob::Error::TransmissionFailed);
  554. }
  555. m_buffered_size = flattened_buffer.size();
  556. m_received_buffers.append(make<ReceivedBuffer>(move(flattened_buffer)));
  557. m_can_stream_response = true;
  558. }
  559. flush_received_buffers();
  560. if (m_buffered_size != 0) {
  561. // We have to wait for the client to consume all the downloaded data
  562. // before we can actually call `did_finish`. in a normal flow, this should
  563. // never be hit since the client is reading as we are writing, unless there
  564. // are too many concurrent downloads going on.
  565. dbgln_if(JOB_DEBUG, "Flush finished with {} bytes remaining, will try again later", m_buffered_size);
  566. if (!has_timer())
  567. start_timer(50);
  568. return;
  569. }
  570. m_has_scheduled_finish = true;
  571. auto response = HttpResponse::create(m_code, move(m_headers), m_received_size);
  572. deferred_invoke([this, response = move(response)] {
  573. // If the server responded with "Connection: close", close the connection
  574. // as the server may or may not want to close the socket. Also, if this is
  575. // a legacy HTTP server (1.0 or older), assume close is the default value.
  576. if (auto result = response->headers().get("Connection"sv); result.has_value() ? result->equals_ignoring_case("close"sv) : m_legacy_connection)
  577. shutdown(ShutdownMode::CloseSocket);
  578. did_finish(response);
  579. });
  580. }
  581. }