Job.cpp 17 KB

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