Job.cpp 26 KB

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