Job.cpp 28 KB

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