Job.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Debug.h>
  27. #include <LibCompress/Gzip.h>
  28. #include <LibCompress/Zlib.h>
  29. #include <LibCore/TCPSocket.h>
  30. #include <LibHTTP/HttpResponse.h>
  31. #include <LibHTTP/Job.h>
  32. #include <stdio.h>
  33. #include <unistd.h>
  34. namespace HTTP {
  35. static ByteBuffer handle_content_encoding(const ByteBuffer& buf, const String& content_encoding)
  36. {
  37. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: buf has content_encoding={}", content_encoding);
  38. if (content_encoding == "gzip") {
  39. if (!Compress::GzipDecompressor::is_likely_compressed(buf)) {
  40. dbgln("Job::handle_content_encoding: buf is not gzip compressed!");
  41. }
  42. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: buf is gzip compressed!");
  43. auto uncompressed = Compress::GzipDecompressor::decompress_all(buf);
  44. if (!uncompressed.has_value()) {
  45. dbgln("Job::handle_content_encoding: Gzip::decompress() failed. Returning original buffer.");
  46. return buf;
  47. }
  48. if constexpr (JOB_DEBUG) {
  49. dbgln("Job::handle_content_encoding: Gzip::decompress() successful.");
  50. dbgln(" Input size: {}", buf.size());
  51. dbgln(" Output size: {}", uncompressed.value().size());
  52. }
  53. return uncompressed.value();
  54. } else if (content_encoding == "deflate") {
  55. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: buf is deflate compressed!");
  56. // Even though the content encoding is "deflate", it's actually deflate with the zlib wrapper.
  57. // https://tools.ietf.org/html/rfc7230#section-4.2.2
  58. auto uncompressed = Compress::Zlib::decompress_all(buf);
  59. if (!uncompressed.has_value()) {
  60. // From the RFC:
  61. // "Note: Some non-conformant implementations send the "deflate"
  62. // compressed data without the zlib wrapper."
  63. dbgln_if(JOB_DEBUG, "Job::handle_content_encoding: Zlib::decompress_all() failed. Trying DeflateDecompressor::decompress_all()");
  64. uncompressed = Compress::DeflateDecompressor::decompress_all(buf);
  65. if (!uncompressed.has_value()) {
  66. dbgln("Job::handle_content_encoding: DeflateDecompressor::decompress_all() failed, returning original buffer.");
  67. return buf;
  68. }
  69. }
  70. if constexpr (JOB_DEBUG) {
  71. dbgln("Job::handle_content_encoding: Deflate decompression successful.");
  72. dbgln(" Input size: {}", buf.size());
  73. dbgln(" Output size: {}", uncompressed.value().size());
  74. }
  75. return uncompressed.value();
  76. }
  77. return buf;
  78. }
  79. Job::Job(const HttpRequest& request, OutputStream& output_stream)
  80. : Core::NetworkJob(output_stream)
  81. , m_request(request)
  82. {
  83. }
  84. Job::~Job()
  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", m_buffered_size, m_received_buffers.size());
  92. for (size_t i = 0; i < m_received_buffers.size(); ++i) {
  93. auto& payload = m_received_buffers[i];
  94. auto written = do_write(payload);
  95. m_buffered_size -= written;
  96. if (written == payload.size()) {
  97. // FIXME: Make this a take-first-friendly object?
  98. m_received_buffers.take_first();
  99. --i;
  100. continue;
  101. }
  102. VERIFY(written < payload.size());
  103. payload = payload.slice(written, payload.size() - written);
  104. break;
  105. }
  106. dbgln_if(JOB_DEBUG, "Job: Flushing received buffers done: have {} bytes in {} buffers", m_buffered_size, m_received_buffers.size());
  107. }
  108. void Job::on_socket_connected()
  109. {
  110. register_on_ready_to_write([&] {
  111. if (m_sent_data)
  112. return;
  113. m_sent_data = true;
  114. auto raw_request = m_request.to_raw_request();
  115. if constexpr (JOB_DEBUG) {
  116. dbgln("Job: raw_request:");
  117. dbgln("{}", String::copy(raw_request));
  118. }
  119. bool success = write(raw_request);
  120. if (!success)
  121. deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  122. });
  123. register_on_ready_to_read([&] {
  124. if (is_cancelled())
  125. return;
  126. if (m_state == State::Finished) {
  127. // This is probably just a EOF notification, which means we should receive nothing
  128. // and then get eof() == true.
  129. [[maybe_unused]] auto payload = receive(64);
  130. // These assertions are only correct if "Connection: close".
  131. VERIFY(payload.is_empty());
  132. VERIFY(eof());
  133. return;
  134. }
  135. if (m_state == State::InStatus) {
  136. if (!can_read_line())
  137. return;
  138. auto line = read_line(PAGE_SIZE);
  139. if (line.is_null()) {
  140. fprintf(stderr, "Job: Expected HTTP status\n");
  141. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  142. }
  143. auto parts = line.split_view(' ');
  144. if (parts.size() < 3) {
  145. warnln("Job: Expected 3-part HTTP status, got '{}'", line);
  146. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  147. }
  148. auto code = parts[1].to_uint();
  149. if (!code.has_value()) {
  150. fprintf(stderr, "Job: Expected numeric HTTP status\n");
  151. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  152. }
  153. m_code = code.value();
  154. m_state = State::InHeaders;
  155. return;
  156. }
  157. if (m_state == State::InHeaders || m_state == State::Trailers) {
  158. if (!can_read_line())
  159. return;
  160. auto line = read_line(PAGE_SIZE);
  161. if (line.is_null()) {
  162. if (m_state == State::Trailers) {
  163. // Some servers like to send two ending chunks
  164. // use this fact as an excuse to ignore anything after the last chunk
  165. // that is not a valid trailing header.
  166. return finish_up();
  167. }
  168. fprintf(stderr, "Job: Expected HTTP header\n");
  169. return did_fail(Core::NetworkJob::Error::ProtocolFailed);
  170. }
  171. if (line.is_empty()) {
  172. if (m_state == State::Trailers) {
  173. return finish_up();
  174. } else {
  175. if (on_headers_received)
  176. on_headers_received(m_headers, m_code > 0 ? m_code : Optional<u32> {});
  177. m_state = State::InBody;
  178. }
  179. return;
  180. }
  181. auto parts = line.split_view(':');
  182. if (parts.is_empty()) {
  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. fprintf(stderr, "Job: Expected HTTP header with key/value\n");
  190. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  191. }
  192. auto name = parts[0];
  193. if (line.length() < name.length() + 2) {
  194. if (m_state == State::Trailers) {
  195. // Some servers like to send two ending chunks
  196. // use this fact as an excuse to ignore anything after the last chunk
  197. // that is not a valid trailing header.
  198. return finish_up();
  199. }
  200. warnln("Job: Malformed HTTP header: '{}' ({})", line, line.length());
  201. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  202. }
  203. auto value = line.substring(name.length() + 2, line.length() - name.length() - 2);
  204. m_headers.set(name, value);
  205. if (name.equals_ignoring_case("Content-Encoding")) {
  206. // Assume that any content-encoding means that we can't decode it as a stream :(
  207. dbgln_if(JOB_DEBUG, "Content-Encoding {} detected, cannot stream output :(", value);
  208. m_can_stream_response = false;
  209. }
  210. dbgln_if(JOB_DEBUG, "Job: [{}] = '{}'", name, value);
  211. return;
  212. }
  213. VERIFY(m_state == State::InBody);
  214. VERIFY(can_read());
  215. read_while_data_available([&] {
  216. auto read_size = 64 * KiB;
  217. if (m_current_chunk_remaining_size.has_value()) {
  218. read_chunk_size:;
  219. auto remaining = m_current_chunk_remaining_size.value();
  220. if (remaining == -1) {
  221. // read size
  222. auto size_data = read_line(PAGE_SIZE);
  223. if (m_should_read_chunk_ending_line) {
  224. VERIFY(size_data.is_empty());
  225. m_should_read_chunk_ending_line = false;
  226. return IterationDecision::Continue;
  227. }
  228. auto size_lines = size_data.view().lines();
  229. dbgln_if(JOB_DEBUG, "Job: Received a chunk with size '{}'", size_data);
  230. if (size_lines.size() == 0) {
  231. dbgln("Job: Reached end of stream");
  232. finish_up();
  233. return IterationDecision::Break;
  234. } else {
  235. auto chunk = size_lines[0].split_view(';', true);
  236. String size_string = chunk[0];
  237. char* endptr;
  238. auto size = strtoul(size_string.characters(), &endptr, 16);
  239. if (*endptr) {
  240. // invalid number
  241. deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  242. return IterationDecision::Break;
  243. }
  244. if (size == 0) {
  245. // This is the last chunk
  246. // '0' *[; chunk-ext-name = chunk-ext-value]
  247. // We're going to ignore _all_ chunk extensions
  248. read_size = 0;
  249. m_current_chunk_total_size = 0;
  250. m_current_chunk_remaining_size = 0;
  251. dbgln_if(JOB_DEBUG, "Job: Received the last chunk with extensions '{}'", size_string.substring_view(1, size_string.length() - 1));
  252. } else {
  253. m_current_chunk_total_size = size;
  254. m_current_chunk_remaining_size = size;
  255. read_size = size;
  256. dbgln_if(JOB_DEBUG, "Job: Chunk of size '{}' started", size);
  257. }
  258. }
  259. } else {
  260. read_size = remaining;
  261. dbgln_if(JOB_DEBUG, "Job: Resuming chunk with '{}' bytes left over", remaining);
  262. }
  263. } else {
  264. auto transfer_encoding = m_headers.get("Transfer-Encoding");
  265. if (transfer_encoding.has_value()) {
  266. auto encoding = transfer_encoding.value();
  267. dbgln_if(JOB_DEBUG, "Job: This content has transfer encoding '{}'", encoding);
  268. if (encoding.equals_ignoring_case("chunked")) {
  269. m_current_chunk_remaining_size = -1;
  270. goto read_chunk_size;
  271. } else {
  272. dbgln("Job: Unknown transfer encoding '{}', the result will likely be wrong!", encoding);
  273. }
  274. }
  275. }
  276. auto payload = receive(read_size);
  277. if (!payload) {
  278. if (eof()) {
  279. finish_up();
  280. return IterationDecision::Break;
  281. }
  282. if (should_fail_on_empty_payload()) {
  283. deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  284. return IterationDecision::Break;
  285. }
  286. }
  287. m_received_buffers.append(payload);
  288. m_buffered_size += payload.size();
  289. m_received_size += payload.size();
  290. flush_received_buffers();
  291. if (m_current_chunk_remaining_size.has_value()) {
  292. auto size = m_current_chunk_remaining_size.value() - payload.size();
  293. dbgln_if(JOB_DEBUG, "Job: We have {} bytes left over in this chunk", size);
  294. if (size == 0) {
  295. dbgln_if(JOB_DEBUG, "Job: Finished a chunk of {} bytes", m_current_chunk_total_size.value());
  296. if (m_current_chunk_total_size.value() == 0) {
  297. m_state = State::Trailers;
  298. return IterationDecision::Break;
  299. }
  300. // we've read everything, now let's get the next chunk
  301. size = -1;
  302. if (can_read_line()) {
  303. auto line = read_line(PAGE_SIZE);
  304. VERIFY(line.is_empty());
  305. } else {
  306. m_should_read_chunk_ending_line = true;
  307. }
  308. }
  309. m_current_chunk_remaining_size = size;
  310. }
  311. auto content_length_header = m_headers.get("Content-Length");
  312. Optional<u32> content_length {};
  313. if (content_length_header.has_value()) {
  314. auto length = content_length_header.value().to_uint();
  315. if (length.has_value())
  316. content_length = length.value();
  317. }
  318. deferred_invoke([this, content_length](auto&) { did_progress(content_length, m_received_size); });
  319. if (content_length.has_value()) {
  320. auto length = content_length.value();
  321. if (m_received_size >= length) {
  322. m_received_size = length;
  323. finish_up();
  324. return IterationDecision::Break;
  325. }
  326. }
  327. return IterationDecision::Continue;
  328. });
  329. if (!is_established()) {
  330. #if JOB_DEBUG
  331. dbgln("Connection appears to have closed, finishing up");
  332. #endif
  333. finish_up();
  334. }
  335. });
  336. }
  337. void Job::finish_up()
  338. {
  339. m_state = State::Finished;
  340. if (!m_can_stream_response) {
  341. auto flattened_buffer = ByteBuffer::create_uninitialized(m_received_size);
  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. flattened_buffer = handle_content_encoding(flattened_buffer, content_encoding.value());
  353. }
  354. m_buffered_size = flattened_buffer.size();
  355. m_received_buffers.append(move(flattened_buffer));
  356. m_can_stream_response = true;
  357. }
  358. flush_received_buffers();
  359. if (m_buffered_size != 0) {
  360. // We have to wait for the client to consume all the downloaded data
  361. // before we can actually call `did_finish`. in a normal flow, this should
  362. // never be hit since the client is reading as we are writing, unless there
  363. // are too many concurrent downloads going on.
  364. deferred_invoke([this](auto&) {
  365. finish_up();
  366. });
  367. return;
  368. }
  369. auto response = HttpResponse::create(m_code, move(m_headers));
  370. deferred_invoke([this, response](auto&) {
  371. did_finish(move(response));
  372. });
  373. }
  374. }