Job.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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 (m_state == State::InStatus) {
  115. if (!can_read_line()) {
  116. dbgln_if(JOB_DEBUG, "Job {} cannot read line", m_request.url());
  117. return;
  118. }
  119. auto line = read_line(PAGE_SIZE);
  120. dbgln_if(JOB_DEBUG, "Job {} read line of length {}", m_request.url(), line.length());
  121. if (line.is_null()) {
  122. dbgln("Job: Expected HTTP status");
  123. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  124. }
  125. auto parts = line.split_view(' ');
  126. if (parts.size() < 3) {
  127. dbgln("Job: Expected 3-part HTTP status, got '{}'", line);
  128. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  129. }
  130. auto code = parts[1].to_uint();
  131. if (!code.has_value()) {
  132. dbgln("Job: Expected numeric HTTP status");
  133. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  134. }
  135. m_code = code.value();
  136. m_state = State::InHeaders;
  137. return;
  138. }
  139. if (m_state == State::InHeaders || m_state == State::Trailers) {
  140. if (!can_read_line())
  141. return;
  142. auto line = read_line(PAGE_SIZE);
  143. if (line.is_null()) {
  144. if (m_state == State::Trailers) {
  145. // Some servers like to send two ending chunks
  146. // use this fact as an excuse to ignore anything after the last chunk
  147. // that is not a valid trailing header.
  148. return finish_up();
  149. }
  150. dbgln("Job: Expected HTTP header");
  151. return did_fail(Core::NetworkJob::Error::ProtocolFailed);
  152. }
  153. if (line.is_empty()) {
  154. if (m_state == State::Trailers) {
  155. return finish_up();
  156. } else {
  157. if (on_headers_received)
  158. on_headers_received(m_headers, m_code > 0 ? m_code : Optional<u32> {});
  159. m_state = State::InBody;
  160. }
  161. // We've reached the end of the headers, there's a possibility that the server
  162. // responds with nothing (content-length = 0 with normal encoding); if that's the case,
  163. // quit early as we won't be reading anything anyway.
  164. if (auto result = m_headers.get("Content-Length"sv).value_or(""sv).to_uint(); result.has_value()) {
  165. if (result.value() == 0 && !m_headers.get("Transfer-Encoding"sv).value_or(""sv).view().trim_whitespace().equals_ignoring_case("chunked"sv))
  166. return finish_up();
  167. }
  168. return;
  169. }
  170. auto parts = line.split_view(':');
  171. if (parts.is_empty()) {
  172. if (m_state == State::Trailers) {
  173. // Some servers like to send two ending chunks
  174. // use this fact as an excuse to ignore anything after the last chunk
  175. // that is not a valid trailing header.
  176. return finish_up();
  177. }
  178. dbgln("Job: Expected HTTP header with key/value");
  179. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  180. }
  181. auto name = parts[0];
  182. if (line.length() < name.length() + 2) {
  183. if (m_state == State::Trailers) {
  184. // Some servers like to send two ending chunks
  185. // use this fact as an excuse to ignore anything after the last chunk
  186. // that is not a valid trailing header.
  187. return finish_up();
  188. }
  189. dbgln("Job: Malformed HTTP header: '{}' ({})", line, line.length());
  190. return deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  191. }
  192. auto value = line.substring(name.length() + 2, line.length() - name.length() - 2);
  193. m_headers.set(name, value);
  194. if (name.equals_ignoring_case("Content-Encoding")) {
  195. // Assume that any content-encoding means that we can't decode it as a stream :(
  196. dbgln_if(JOB_DEBUG, "Content-Encoding {} detected, cannot stream output :(", value);
  197. m_can_stream_response = false;
  198. }
  199. dbgln_if(JOB_DEBUG, "Job: [{}] = '{}'", name, value);
  200. return;
  201. }
  202. VERIFY(m_state == State::InBody);
  203. VERIFY(can_read());
  204. read_while_data_available([&] {
  205. auto read_size = 64 * KiB;
  206. if (m_current_chunk_remaining_size.has_value()) {
  207. read_chunk_size:;
  208. auto remaining = m_current_chunk_remaining_size.value();
  209. if (remaining == -1) {
  210. // read size
  211. auto size_data = read_line(PAGE_SIZE);
  212. if (m_should_read_chunk_ending_line) {
  213. VERIFY(size_data.is_empty());
  214. m_should_read_chunk_ending_line = false;
  215. return IterationDecision::Continue;
  216. }
  217. auto size_lines = size_data.view().lines();
  218. dbgln_if(JOB_DEBUG, "Job: Received a chunk with size '{}'", size_data);
  219. if (size_lines.size() == 0) {
  220. if (!eof())
  221. return AK::IterationDecision::Continue;
  222. dbgln("Job: Reached end of stream");
  223. finish_up();
  224. return IterationDecision::Break;
  225. } else {
  226. auto chunk = size_lines[0].split_view(';', true);
  227. String size_string = chunk[0];
  228. char* endptr;
  229. auto size = strtoul(size_string.characters(), &endptr, 16);
  230. if (*endptr) {
  231. // invalid number
  232. deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  233. return IterationDecision::Break;
  234. }
  235. if (size == 0) {
  236. // This is the last chunk
  237. // '0' *[; chunk-ext-name = chunk-ext-value]
  238. // We're going to ignore _all_ chunk extensions
  239. read_size = 0;
  240. m_current_chunk_total_size = 0;
  241. m_current_chunk_remaining_size = 0;
  242. dbgln_if(JOB_DEBUG, "Job: Received the last chunk with extensions '{}'", size_string.substring_view(1, size_string.length() - 1));
  243. } else {
  244. m_current_chunk_total_size = size;
  245. m_current_chunk_remaining_size = size;
  246. read_size = size;
  247. dbgln_if(JOB_DEBUG, "Job: Chunk of size '{}' started", size);
  248. }
  249. }
  250. } else {
  251. read_size = remaining;
  252. dbgln_if(JOB_DEBUG, "Job: Resuming chunk with '{}' bytes left over", remaining);
  253. }
  254. } else {
  255. auto transfer_encoding = m_headers.get("Transfer-Encoding");
  256. if (transfer_encoding.has_value()) {
  257. // Note: Some servers add extra spaces around 'chunked', see #6302.
  258. auto encoding = transfer_encoding.value().trim_whitespace();
  259. dbgln_if(JOB_DEBUG, "Job: This content has transfer encoding '{}'", encoding);
  260. if (encoding.equals_ignoring_case("chunked")) {
  261. m_current_chunk_remaining_size = -1;
  262. goto read_chunk_size;
  263. } else {
  264. dbgln("Job: Unknown transfer encoding '{}', the result will likely be wrong!", encoding);
  265. }
  266. }
  267. }
  268. dbgln_if(JOB_DEBUG, "Waiting for payload for {}", m_request.url());
  269. auto payload = receive(read_size);
  270. dbgln_if(JOB_DEBUG, "Received {} bytes of payload from {}", payload.size(), m_request.url());
  271. if (payload.is_empty()) {
  272. if (eof()) {
  273. finish_up();
  274. return IterationDecision::Break;
  275. }
  276. if (should_fail_on_empty_payload()) {
  277. deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  278. return IterationDecision::Break;
  279. }
  280. }
  281. m_received_buffers.append(payload);
  282. m_buffered_size += payload.size();
  283. m_received_size += payload.size();
  284. flush_received_buffers();
  285. if (m_current_chunk_remaining_size.has_value()) {
  286. auto size = m_current_chunk_remaining_size.value() - payload.size();
  287. dbgln_if(JOB_DEBUG, "Job: We have {} bytes left over in this chunk", size);
  288. if (size == 0) {
  289. dbgln_if(JOB_DEBUG, "Job: Finished a chunk of {} bytes", m_current_chunk_total_size.value());
  290. if (m_current_chunk_total_size.value() == 0) {
  291. m_state = State::Trailers;
  292. return IterationDecision::Break;
  293. }
  294. // we've read everything, now let's get the next chunk
  295. size = -1;
  296. if (can_read_line()) {
  297. auto line = read_line(PAGE_SIZE);
  298. VERIFY(line.is_empty());
  299. } else {
  300. m_should_read_chunk_ending_line = true;
  301. }
  302. }
  303. m_current_chunk_remaining_size = size;
  304. }
  305. auto content_length_header = m_headers.get("Content-Length");
  306. Optional<u32> content_length {};
  307. if (content_length_header.has_value()) {
  308. auto length = content_length_header.value().to_uint();
  309. if (length.has_value())
  310. content_length = length.value();
  311. }
  312. deferred_invoke([this, content_length] { did_progress(content_length, m_received_size); });
  313. if (content_length.has_value()) {
  314. auto length = content_length.value();
  315. if (m_received_size >= length) {
  316. m_received_size = length;
  317. finish_up();
  318. return IterationDecision::Break;
  319. }
  320. }
  321. return IterationDecision::Continue;
  322. });
  323. if (!is_established()) {
  324. dbgln_if(JOB_DEBUG, "Connection appears to have closed, finishing up");
  325. finish_up();
  326. }
  327. });
  328. }
  329. void Job::timer_event(Core::TimerEvent& event)
  330. {
  331. event.accept();
  332. finish_up();
  333. if (m_buffered_size == 0)
  334. stop_timer();
  335. }
  336. void Job::finish_up()
  337. {
  338. VERIFY(!m_has_scheduled_finish);
  339. m_state = State::Finished;
  340. if (!m_can_stream_response) {
  341. auto flattened_buffer = ByteBuffer::create_uninitialized(m_received_size).release_value(); // FIXME: Handle possible OOM situation.
  342. u8* flat_ptr = flattened_buffer.data();
  343. for (auto& received_buffer : m_received_buffers) {
  344. memcpy(flat_ptr, received_buffer.data(), received_buffer.size());
  345. flat_ptr += received_buffer.size();
  346. }
  347. m_received_buffers.clear();
  348. // For the time being, we cannot stream stuff with content-encoding set to _anything_.
  349. // FIXME: LibCompress exposes a streaming interface, so this can be resolved
  350. auto content_encoding = m_headers.get("Content-Encoding");
  351. if (content_encoding.has_value()) {
  352. if (auto result = handle_content_encoding(flattened_buffer, content_encoding.value()); result.has_value())
  353. flattened_buffer = result.release_value();
  354. else
  355. return did_fail(Core::NetworkJob::Error::TransmissionFailed);
  356. }
  357. m_buffered_size = flattened_buffer.size();
  358. m_received_buffers.append(move(flattened_buffer));
  359. m_can_stream_response = true;
  360. }
  361. flush_received_buffers();
  362. if (m_buffered_size != 0) {
  363. // We have to wait for the client to consume all the downloaded data
  364. // before we can actually call `did_finish`. in a normal flow, this should
  365. // never be hit since the client is reading as we are writing, unless there
  366. // are too many concurrent downloads going on.
  367. dbgln_if(JOB_DEBUG, "Flush finished with {} bytes remaining, will try again later", m_buffered_size);
  368. if (!has_timer())
  369. start_timer(50);
  370. return;
  371. }
  372. m_has_scheduled_finish = true;
  373. auto response = HttpResponse::create(m_code, move(m_headers));
  374. deferred_invoke([this, response = move(response)] {
  375. // If the server responded with "Connection: close", close the connection
  376. // as the server may or may not want to close the socket.
  377. if (auto result = response->headers().get("Connection"sv); result.has_value() && result.value().equals_ignoring_case("close"sv))
  378. shutdown(ShutdownMode::CloseSocket);
  379. did_finish(response);
  380. });
  381. }
  382. }