Job.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. }
  202. dbgln_if(JOB_DEBUG, "Job: [{}] = '{}'", name, value);
  203. return;
  204. }
  205. VERIFY(m_state == State::InBody);
  206. VERIFY(can_read());
  207. read_while_data_available([&] {
  208. auto read_size = 64 * KiB;
  209. if (m_current_chunk_remaining_size.has_value()) {
  210. read_chunk_size:;
  211. auto remaining = m_current_chunk_remaining_size.value();
  212. if (remaining == -1) {
  213. // read size
  214. auto size_data = read_line(PAGE_SIZE);
  215. if (m_should_read_chunk_ending_line) {
  216. VERIFY(size_data.is_empty());
  217. m_should_read_chunk_ending_line = false;
  218. return IterationDecision::Continue;
  219. }
  220. auto size_lines = size_data.view().lines();
  221. dbgln_if(JOB_DEBUG, "Job: Received a chunk with size '{}'", size_data);
  222. if (size_lines.size() == 0) {
  223. if (!eof())
  224. return AK::IterationDecision::Continue;
  225. dbgln("Job: Reached end of stream");
  226. finish_up();
  227. return IterationDecision::Break;
  228. } else {
  229. auto chunk = size_lines[0].split_view(';', true);
  230. String size_string = chunk[0];
  231. char* endptr;
  232. auto size = strtoul(size_string.characters(), &endptr, 16);
  233. if (*endptr) {
  234. // invalid number
  235. deferred_invoke([this] { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  236. return IterationDecision::Break;
  237. }
  238. if (size == 0) {
  239. // This is the last chunk
  240. // '0' *[; chunk-ext-name = chunk-ext-value]
  241. // We're going to ignore _all_ chunk extensions
  242. read_size = 0;
  243. m_current_chunk_total_size = 0;
  244. m_current_chunk_remaining_size = 0;
  245. dbgln_if(JOB_DEBUG, "Job: Received the last chunk with extensions '{}'", size_string.substring_view(1, size_string.length() - 1));
  246. } else {
  247. m_current_chunk_total_size = size;
  248. m_current_chunk_remaining_size = size;
  249. read_size = size;
  250. dbgln_if(JOB_DEBUG, "Job: Chunk of size '{}' started", size);
  251. }
  252. }
  253. } else {
  254. read_size = remaining;
  255. dbgln_if(JOB_DEBUG, "Job: Resuming chunk with '{}' bytes left over", remaining);
  256. }
  257. } else {
  258. auto transfer_encoding = m_headers.get("Transfer-Encoding");
  259. if (transfer_encoding.has_value()) {
  260. // Note: Some servers add extra spaces around 'chunked', see #6302.
  261. auto encoding = transfer_encoding.value().trim_whitespace();
  262. dbgln_if(JOB_DEBUG, "Job: This content has transfer encoding '{}'", encoding);
  263. if (encoding.equals_ignoring_case("chunked")) {
  264. m_current_chunk_remaining_size = -1;
  265. goto read_chunk_size;
  266. } else {
  267. dbgln("Job: Unknown transfer encoding '{}', the result will likely be wrong!", encoding);
  268. }
  269. }
  270. }
  271. dbgln_if(JOB_DEBUG, "Waiting for payload for {}", m_request.url());
  272. auto payload = receive(read_size);
  273. dbgln_if(JOB_DEBUG, "Received {} bytes of payload from {}", payload.size(), m_request.url());
  274. if (payload.is_empty()) {
  275. if (eof()) {
  276. finish_up();
  277. return IterationDecision::Break;
  278. }
  279. if (should_fail_on_empty_payload()) {
  280. deferred_invoke([this] { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  281. return IterationDecision::Break;
  282. }
  283. }
  284. m_received_buffers.append(payload);
  285. m_buffered_size += payload.size();
  286. m_received_size += payload.size();
  287. flush_received_buffers();
  288. if (m_current_chunk_remaining_size.has_value()) {
  289. auto size = m_current_chunk_remaining_size.value() - payload.size();
  290. dbgln_if(JOB_DEBUG, "Job: We have {} bytes left over in this chunk", size);
  291. if (size == 0) {
  292. dbgln_if(JOB_DEBUG, "Job: Finished a chunk of {} bytes", m_current_chunk_total_size.value());
  293. if (m_current_chunk_total_size.value() == 0) {
  294. m_state = State::Trailers;
  295. return IterationDecision::Break;
  296. }
  297. // we've read everything, now let's get the next chunk
  298. size = -1;
  299. if (can_read_line()) {
  300. auto line = read_line(PAGE_SIZE);
  301. VERIFY(line.is_empty());
  302. } else {
  303. m_should_read_chunk_ending_line = true;
  304. }
  305. }
  306. m_current_chunk_remaining_size = size;
  307. }
  308. auto content_length_header = m_headers.get("Content-Length");
  309. Optional<u32> content_length {};
  310. if (content_length_header.has_value()) {
  311. auto length = content_length_header.value().to_uint();
  312. if (length.has_value())
  313. content_length = length.value();
  314. }
  315. deferred_invoke([this, content_length] { did_progress(content_length, m_received_size); });
  316. if (content_length.has_value()) {
  317. auto length = content_length.value();
  318. if (m_received_size >= length) {
  319. m_received_size = length;
  320. finish_up();
  321. return IterationDecision::Break;
  322. }
  323. }
  324. return IterationDecision::Continue;
  325. });
  326. if (!is_established()) {
  327. dbgln_if(JOB_DEBUG, "Connection appears to have closed, finishing up");
  328. finish_up();
  329. }
  330. });
  331. }
  332. void Job::timer_event(Core::TimerEvent& event)
  333. {
  334. event.accept();
  335. finish_up();
  336. if (m_buffered_size == 0)
  337. stop_timer();
  338. }
  339. void Job::finish_up()
  340. {
  341. VERIFY(!m_has_scheduled_finish);
  342. m_state = State::Finished;
  343. if (!m_can_stream_response) {
  344. auto flattened_buffer = ByteBuffer::create_uninitialized(m_received_size).release_value(); // FIXME: Handle possible OOM situation.
  345. u8* flat_ptr = flattened_buffer.data();
  346. for (auto& received_buffer : m_received_buffers) {
  347. memcpy(flat_ptr, received_buffer.data(), received_buffer.size());
  348. flat_ptr += received_buffer.size();
  349. }
  350. m_received_buffers.clear();
  351. // For the time being, we cannot stream stuff with content-encoding set to _anything_.
  352. // FIXME: LibCompress exposes a streaming interface, so this can be resolved
  353. auto content_encoding = m_headers.get("Content-Encoding");
  354. if (content_encoding.has_value()) {
  355. if (auto result = handle_content_encoding(flattened_buffer, content_encoding.value()); result.has_value())
  356. flattened_buffer = result.release_value();
  357. else
  358. return did_fail(Core::NetworkJob::Error::TransmissionFailed);
  359. }
  360. m_buffered_size = flattened_buffer.size();
  361. m_received_buffers.append(move(flattened_buffer));
  362. m_can_stream_response = true;
  363. }
  364. flush_received_buffers();
  365. if (m_buffered_size != 0) {
  366. // We have to wait for the client to consume all the downloaded data
  367. // before we can actually call `did_finish`. in a normal flow, this should
  368. // never be hit since the client is reading as we are writing, unless there
  369. // are too many concurrent downloads going on.
  370. dbgln_if(JOB_DEBUG, "Flush finished with {} bytes remaining, will try again later", m_buffered_size);
  371. if (!has_timer())
  372. start_timer(50);
  373. return;
  374. }
  375. m_has_scheduled_finish = true;
  376. auto response = HttpResponse::create(m_code, move(m_headers));
  377. deferred_invoke([this, response = move(response)] {
  378. // If the server responded with "Connection: close", close the connection
  379. // as the server may or may not want to close the socket.
  380. if (auto result = response->headers().get("Connection"sv); result.has_value() && result.value().equals_ignoring_case("close"sv))
  381. shutdown(ShutdownMode::CloseSocket);
  382. did_finish(response);
  383. });
  384. }
  385. }