Job.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <LibCompress/Gzip.h>
  8. #include <LibCompress/Zlib.h>
  9. #include <LibCore/Event.h>
  10. #include <LibCore/TCPSocket.h>
  11. #include <LibHTTP/HttpResponse.h>
  12. #include <LibHTTP/Job.h>
  13. #include <stdio.h>
  14. #include <unistd.h>
  15. namespace HTTP {
  16. static Optional<ByteBuffer> handle_content_encoding(const ByteBuffer& buf, const String& content_encoding)
  17. {
  18. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: buf has content_encoding={}", content_encoding);
  19. if (content_encoding == "gzip") {
  20. if (!Compress::GzipDecompressor::is_likely_compressed(buf)) {
  21. dbgln("Job::handle_content_encoding: buf is not gzip compressed!");
  22. }
  23. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: buf is gzip compressed!");
  24. auto uncompressed = Compress::GzipDecompressor::decompress_all(buf);
  25. if (!uncompressed.has_value()) {
  26. dbgln("Job::handle_content_encoding: Gzip::decompress() failed.");
  27. return {};
  28. }
  29. if constexpr (JOB_DEBUG) {
  30. dbgln("Job::handle_content_encoding: Gzip::decompress() successful.");
  31. dbgln(" Input size: {}", buf.size());
  32. dbgln(" Output size: {}", uncompressed.value().size());
  33. }
  34. return uncompressed.value();
  35. } else if (content_encoding == "deflate") {
  36. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: buf is deflate compressed!");
  37. // Even though the content encoding is "deflate", it's actually deflate with the zlib wrapper.
  38. // https://tools.ietf.org/html/rfc7230#section-4.2.2
  39. auto uncompressed = Compress::Zlib::decompress_all(buf);
  40. if (!uncompressed.has_value()) {
  41. // From the RFC:
  42. // "Note: Some non-conformant implementations send the "deflate"
  43. // compressed data without the zlib wrapper."
  44. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: Zlib::decompress_all() failed. Trying DeflateDecompressor::decompress_all()");
  45. uncompressed = Compress::DeflateDecompressor::decompress_all(buf);
  46. if (!uncompressed.has_value()) {
  47. dbgln("Job::handle_content_encoding: DeflateDecompressor::decompress_all() failed.");
  48. return {};
  49. }
  50. }
  51. if constexpr (JOB_DEBUG) {
  52. dbgln("Job::handle_content_encoding: Deflate decompression successful.");
  53. dbgln(" Input size: {}", buf.size());
  54. dbgln(" Output size: {}", uncompressed.value().size());
  55. }
  56. return uncompressed.value();
  57. }
  58. return buf;
  59. }
  60. Job::Job(const HttpRequest& request, OutputStream& output_stream)
  61. : Core::NetworkJob(output_stream)
  62. , m_request(request)
  63. {
  64. }
  65. Job::~Job()
  66. {
  67. }
  68. void Job::flush_received_buffers()
  69. {
  70. if (!m_can_stream_response || m_buffered_size == 0)
  71. return;
  72. dbgln_if(JOB_DEBUG, "Job: Flushing received buffers: have {} bytes in {} buffers for {}", m_buffered_size, m_received_buffers.size(), m_request.url());
  73. for (size_t i = 0; i < m_received_buffers.size(); ++i) {
  74. auto& payload = m_received_buffers[i];
  75. auto written = do_write(payload);
  76. m_buffered_size -= written;
  77. if (written == payload.size()) {
  78. // FIXME: Make this a take-first-friendly object?
  79. m_received_buffers.take_first();
  80. --i;
  81. continue;
  82. }
  83. VERIFY(written < payload.size());
  84. payload = payload.slice(written, payload.size() - written);
  85. break;
  86. }
  87. dbgln_if(JOB_DEBUG, "Job: Flushing received buffers done: have {} bytes in {} buffers for {}", m_buffered_size, m_received_buffers.size(), m_request.url());
  88. }
  89. void Job::on_socket_connected()
  90. {
  91. register_on_ready_to_write([&] {
  92. if (m_sent_data)
  93. return;
  94. m_sent_data = true;
  95. auto raw_request = m_request.to_raw_request();
  96. if constexpr (JOB_DEBUG) {
  97. dbgln("Job: raw_request:");
  98. dbgln("{}", String::copy(raw_request));
  99. }
  100. bool success = write(raw_request);
  101. if (!success)
  102. deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  103. });
  104. register_on_ready_to_read([&] {
  105. dbgln_if(JOB_DEBUG, "Ready to read for {}, state = {}, cancelled = {}", m_request.url(), to_underlying(m_state), is_cancelled());
  106. if (is_cancelled())
  107. return;
  108. if (m_state == State::Finished) {
  109. // We have everything we want, at this point, we can either get an EOF, or a bunch of extra newlines
  110. // (unless "Connection: close" isn't specified)
  111. // So just ignore everything after this.
  112. return;
  113. }
  114. if (eof())
  115. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  116. if (m_state == State::InStatus) {
  117. if (!can_read_line()) {
  118. dbgln_if(JOB_DEBUG, "Job {} cannot read line", m_request.url());
  119. return;
  120. }
  121. auto line = read_line(PAGE_SIZE);
  122. dbgln_if(JOB_DEBUG, "Job {} read line of length {}", m_request.url(), line.length());
  123. if (line.is_null()) {
  124. dbgln("Job: Expected HTTP status");
  125. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  126. }
  127. auto parts = line.split_view(' ');
  128. if (parts.size() < 3) {
  129. dbgln("Job: Expected 3-part HTTP status, got '{}'", line);
  130. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  131. }
  132. auto code = parts[1].to_uint();
  133. if (!code.has_value()) {
  134. dbgln("Job: Expected numeric HTTP status");
  135. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  136. }
  137. m_code = code.value();
  138. m_state = State::InHeaders;
  139. return;
  140. }
  141. if (m_state == State::InHeaders || m_state == State::Trailers) {
  142. if (!can_read_line())
  143. return;
  144. // There's no max limit defined on headers, but for our sanity, let's limit it to 32K.
  145. auto line = read_line(32 * KiB);
  146. if (line.is_null()) {
  147. if (m_state == State::Trailers) {
  148. // Some servers like to send two ending chunks
  149. // use this fact as an excuse to ignore anything after the last chunk
  150. // that is not a valid trailing header.
  151. return finish_up();
  152. }
  153. dbgln("Job: Expected HTTP header");
  154. return did_fail(Core::NetworkJob::Error::ProtocolFailed);
  155. }
  156. if (line.is_empty()) {
  157. if (m_state == State::Trailers) {
  158. return finish_up();
  159. } else {
  160. if (on_headers_received)
  161. on_headers_received(m_headers, m_code > 0 ? m_code : Optional<u32> {});
  162. m_state = State::InBody;
  163. }
  164. // We've reached the end of the headers, there's a possibility that the server
  165. // responds with nothing (content-length = 0 with normal encoding); if that's the case,
  166. // quit early as we won't be reading anything anyway.
  167. if (auto result = m_headers.get("Content-Length"sv).value_or(""sv).to_uint(); result.has_value()) {
  168. if (result.value() == 0 && !m_headers.get("Transfer-Encoding"sv).value_or(""sv).view().trim_whitespace().equals_ignoring_case("chunked"sv))
  169. return finish_up();
  170. }
  171. return;
  172. }
  173. auto parts = line.split_view(':');
  174. if (parts.is_empty()) {
  175. if (m_state == State::Trailers) {
  176. // Some servers like to send two ending chunks
  177. // use this fact as an excuse to ignore anything after the last chunk
  178. // that is not a valid trailing header.
  179. return finish_up();
  180. }
  181. dbgln("Job: Expected HTTP header with key/value");
  182. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  183. }
  184. auto name = parts[0];
  185. if (line.length() < name.length() + 2) {
  186. if (m_state == State::Trailers) {
  187. // Some servers like to send two ending chunks
  188. // use this fact as an excuse to ignore anything after the last chunk
  189. // that is not a valid trailing header.
  190. return finish_up();
  191. }
  192. dbgln("Job: Malformed HTTP header: '{}' ({})", line, line.length());
  193. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  194. }
  195. auto value = line.substring(name.length() + 2, line.length() - name.length() - 2);
  196. m_headers.set(name, value);
  197. if (name.equals_ignoring_case("Content-Encoding")) {
  198. // Assume that any content-encoding means that we can't decode it as a stream :(
  199. dbgln_if(JOB_DEBUG, "Content-Encoding {} detected, cannot stream output :(", value);
  200. m_can_stream_response = false;
  201. } else if (name.equals_ignoring_case("Content-Length")) {
  202. auto length = value.to_uint();
  203. if (length.has_value())
  204. m_content_length = length.value();
  205. }
  206. dbgln_if(JOB_DEBUG, "Job: [{}] = '{}'", name, value);
  207. return;
  208. }
  209. VERIFY(m_state == State::InBody);
  210. VERIFY(can_read());
  211. read_while_data_available([&] {
  212. auto read_size = 64 * KiB;
  213. if (m_current_chunk_remaining_size.has_value()) {
  214. read_chunk_size:;
  215. auto remaining = m_current_chunk_remaining_size.value();
  216. if (remaining == -1) {
  217. // read size
  218. auto size_data = read_line(PAGE_SIZE);
  219. if (m_should_read_chunk_ending_line) {
  220. VERIFY(size_data.is_empty());
  221. m_should_read_chunk_ending_line = false;
  222. return IterationDecision::Continue;
  223. }
  224. auto size_lines = size_data.view().lines();
  225. dbgln_if(JOB_DEBUG, "Job: Received a chunk with size '{}'", size_data);
  226. if (size_lines.size() == 0) {
  227. if (!eof())
  228. return AK::IterationDecision::Break;
  229. dbgln("Job: Reached end of stream");
  230. finish_up();
  231. return IterationDecision::Break;
  232. } else {
  233. auto chunk = size_lines[0].split_view(';', true);
  234. String size_string = chunk[0];
  235. char* endptr;
  236. auto size = strtoul(size_string.characters(), &endptr, 16);
  237. if (*endptr) {
  238. // invalid number
  239. deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  240. return IterationDecision::Break;
  241. }
  242. if (size == 0) {
  243. // This is the last chunk
  244. // '0' *[; chunk-ext-name = chunk-ext-value]
  245. // We're going to ignore _all_ chunk extensions
  246. read_size = 0;
  247. m_current_chunk_total_size = 0;
  248. m_current_chunk_remaining_size = 0;
  249. dbgln_if(JOB_DEBUG, "Job: Received the last chunk with extensions '{}'", size_string.substring_view(1, size_string.length() - 1));
  250. } else {
  251. m_current_chunk_total_size = size;
  252. m_current_chunk_remaining_size = size;
  253. read_size = size;
  254. dbgln_if(JOB_DEBUG, "Job: Chunk of size '{}' started", size);
  255. }
  256. }
  257. } else {
  258. read_size = remaining;
  259. dbgln_if(JOB_DEBUG, "Job: Resuming chunk with '{}' bytes left over", remaining);
  260. }
  261. } else {
  262. auto transfer_encoding = m_headers.get("Transfer-Encoding");
  263. if (transfer_encoding.has_value()) {
  264. // HTTP/1.1 3.3.3.3:
  265. // If a message is received with both a Transfer-Encoding and a Content-Length header field, the Transfer-Encoding overrides the Content-Length. [...]
  266. // https://httpwg.org/specs/rfc7230.html#message.body.length
  267. m_content_length = {};
  268. // Note: Some servers add extra spaces around 'chunked', see #6302.
  269. auto encoding = transfer_encoding.value().trim_whitespace();
  270. dbgln_if(JOB_DEBUG, "Job: This content has transfer encoding '{}'", encoding);
  271. if (encoding.equals_ignoring_case("chunked")) {
  272. m_current_chunk_remaining_size = -1;
  273. goto read_chunk_size;
  274. } else {
  275. dbgln("Job: Unknown transfer encoding '{}', the result will likely be wrong!", encoding);
  276. }
  277. }
  278. }
  279. dbgln_if(JOB_DEBUG, "Waiting for payload for {}", m_request.url());
  280. auto payload = receive(read_size);
  281. dbgln_if(JOB_DEBUG, "Received {} bytes of payload from {}", payload.size(), m_request.url());
  282. if (payload.is_empty()) {
  283. if (eof()) {
  284. finish_up();
  285. return IterationDecision::Break;
  286. }
  287. if (should_fail_on_empty_payload()) {
  288. deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  289. return IterationDecision::Break;
  290. }
  291. }
  292. bool read_everything = false;
  293. if (m_content_length.has_value()) {
  294. auto length = m_content_length.value();
  295. if (m_received_size + payload.size() >= length) {
  296. payload.resize(length - m_received_size);
  297. read_everything = true;
  298. }
  299. }
  300. m_received_buffers.append(payload);
  301. m_buffered_size += payload.size();
  302. m_received_size += payload.size();
  303. flush_received_buffers();
  304. deferred_invoke([this] { did_progress(m_content_length, m_received_size); });
  305. if (read_everything) {
  306. VERIFY(m_received_size <= m_content_length.value());
  307. finish_up();
  308. return IterationDecision::Break;
  309. }
  310. if (m_current_chunk_remaining_size.has_value()) {
  311. auto size = m_current_chunk_remaining_size.value() - payload.size();
  312. dbgln_if(JOB_DEBUG, "Job: We have {} bytes left over in this chunk", size);
  313. if (size == 0) {
  314. dbgln_if(JOB_DEBUG, "Job: Finished a chunk of {} bytes", m_current_chunk_total_size.value());
  315. if (m_current_chunk_total_size.value() == 0) {
  316. m_state = State::Trailers;
  317. return IterationDecision::Break;
  318. }
  319. // we've read everything, now let's get the next chunk
  320. size = -1;
  321. if (can_read_line()) {
  322. auto line = read_line(PAGE_SIZE);
  323. VERIFY(line.is_empty());
  324. } else {
  325. m_should_read_chunk_ending_line = true;
  326. }
  327. }
  328. m_current_chunk_remaining_size = size;
  329. }
  330. return IterationDecision::Continue;
  331. });
  332. if (!is_established()) {
  333. dbgln_if(JOB_DEBUG, "Connection appears to have closed, finishing up");
  334. finish_up();
  335. }
  336. });
  337. }
  338. void Job::timer_event(Core::TimerEvent& event)
  339. {
  340. event.accept();
  341. finish_up();
  342. if (m_buffered_size == 0)
  343. stop_timer();
  344. }
  345. void Job::finish_up()
  346. {
  347. VERIFY(!m_has_scheduled_finish);
  348. m_state = State::Finished;
  349. if (!m_can_stream_response) {
  350. auto flattened_buffer = ByteBuffer::create_uninitialized(m_buffered_size).release_value(); // FIXME: Handle possible OOM situation.
  351. u8* flat_ptr = flattened_buffer.data();
  352. for (auto& received_buffer : m_received_buffers) {
  353. memcpy(flat_ptr, received_buffer.data(), received_buffer.size());
  354. flat_ptr += received_buffer.size();
  355. }
  356. m_received_buffers.clear();
  357. // For the time being, we cannot stream stuff with content-encoding set to _anything_.
  358. // FIXME: LibCompress exposes a streaming interface, so this can be resolved
  359. auto content_encoding = m_headers.get("Content-Encoding");
  360. if (content_encoding.has_value()) {
  361. if (auto result = handle_content_encoding(flattened_buffer, content_encoding.value()); result.has_value())
  362. flattened_buffer = result.release_value();
  363. else
  364. return did_fail(Core::NetworkJob::Error::TransmissionFailed);
  365. }
  366. m_buffered_size = flattened_buffer.size();
  367. m_received_buffers.append(move(flattened_buffer));
  368. m_can_stream_response = true;
  369. }
  370. flush_received_buffers();
  371. if (m_buffered_size != 0) {
  372. // We have to wait for the client to consume all the downloaded data
  373. // before we can actually call `did_finish`. in a normal flow, this should
  374. // never be hit since the client is reading as we are writing, unless there
  375. // are too many concurrent downloads going on.
  376. dbgln_if(JOB_DEBUG, "Flush finished with {} bytes remaining, will try again later", m_buffered_size);
  377. if (!has_timer())
  378. start_timer(50);
  379. return;
  380. }
  381. m_has_scheduled_finish = true;
  382. auto response = HttpResponse::create(m_code, move(m_headers));
  383. deferred_invoke([this, response = move(response)] {
  384. // If the server responded with "Connection: close", close the connection
  385. // as the server may or may not want to close the socket.
  386. if (auto result = response->headers().get("Connection"sv); result.has_value() && result.value().equals_ignoring_case("close"sv))
  387. shutdown(ShutdownMode::CloseSocket);
  388. did_finish(response);
  389. });
  390. }
  391. }