Job.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 <LibCore/Gzip.h>
  28. #include <LibCore/TCPSocket.h>
  29. #include <LibHTTP/HttpResponse.h>
  30. #include <LibHTTP/Job.h>
  31. #include <stdio.h>
  32. #include <unistd.h>
  33. namespace HTTP {
  34. static ByteBuffer handle_content_encoding(const ByteBuffer& buf, const String& content_encoding)
  35. {
  36. dbgln<debug_job>("Job::handle_content_encoding: buf has content_encoding={}", content_encoding);
  37. if (content_encoding == "gzip") {
  38. if (!Core::Gzip::is_compressed(buf)) {
  39. dbgln("Job::handle_content_encoding: buf is not gzip compressed!");
  40. }
  41. dbgln<debug_job>("Job::handle_content_encoding: buf is gzip compressed!");
  42. auto uncompressed = Core::Gzip::decompress(buf);
  43. if (!uncompressed.has_value()) {
  44. dbgln("Job::handle_content_encoding: Gzip::decompress() failed. Returning original buffer.");
  45. return buf;
  46. }
  47. if constexpr (debug_job) {
  48. dbgln("Job::handle_content_encoding: Gzip::decompress() successful.");
  49. dbgln(" Input size: {}", buf.size());
  50. dbgln(" Output size: {}", uncompressed.value().size());
  51. }
  52. return uncompressed.value();
  53. }
  54. return buf;
  55. }
  56. Job::Job(const HttpRequest& request, OutputStream& output_stream)
  57. : Core::NetworkJob(output_stream)
  58. , m_request(request)
  59. {
  60. }
  61. Job::~Job()
  62. {
  63. }
  64. void Job::flush_received_buffers()
  65. {
  66. if (!m_can_stream_response || m_buffered_size == 0)
  67. return;
  68. dbgln<debug_job>("Job: Flushing received buffers: have {} bytes in {} buffers", m_buffered_size, m_received_buffers.size());
  69. for (size_t i = 0; i < m_received_buffers.size(); ++i) {
  70. auto& payload = m_received_buffers[i];
  71. auto written = do_write(payload);
  72. m_buffered_size -= written;
  73. if (written == payload.size()) {
  74. // FIXME: Make this a take-first-friendly object?
  75. m_received_buffers.take_first();
  76. --i;
  77. continue;
  78. }
  79. ASSERT(written < payload.size());
  80. payload = payload.slice(written, payload.size() - written);
  81. break;
  82. }
  83. dbgln<debug_job>("Job: Flushing received buffers done: have {} bytes in {} buffers", m_buffered_size, m_received_buffers.size());
  84. }
  85. void Job::on_socket_connected()
  86. {
  87. register_on_ready_to_write([&] {
  88. if (m_sent_data)
  89. return;
  90. m_sent_data = true;
  91. auto raw_request = m_request.to_raw_request();
  92. if constexpr (debug_job) {
  93. dbgln("Job: raw_request:");
  94. dbgln("{}", String::copy(raw_request));
  95. }
  96. bool success = write(raw_request);
  97. if (!success)
  98. deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  99. });
  100. register_on_ready_to_read([&] {
  101. if (is_cancelled())
  102. return;
  103. if (m_state == State::Finished) {
  104. // This is probably just a EOF notification, which means we should receive nothing
  105. // and then get eof() == true.
  106. [[maybe_unused]] auto payload = receive(64);
  107. // These assertions are only correct if "Connection: close".
  108. ASSERT(payload.is_empty());
  109. ASSERT(eof());
  110. return;
  111. }
  112. if (m_state == State::InStatus) {
  113. if (!can_read_line())
  114. return;
  115. auto line = read_line(PAGE_SIZE);
  116. if (line.is_null()) {
  117. fprintf(stderr, "Job: Expected HTTP status\n");
  118. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  119. }
  120. auto parts = line.split_view(' ');
  121. if (parts.size() < 3) {
  122. warnln("Job: Expected 3-part HTTP status, got '{}'", line);
  123. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  124. }
  125. auto code = parts[1].to_uint();
  126. if (!code.has_value()) {
  127. fprintf(stderr, "Job: Expected numeric HTTP status\n");
  128. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  129. }
  130. m_code = code.value();
  131. m_state = State::InHeaders;
  132. return;
  133. }
  134. if (m_state == State::InHeaders || m_state == State::Trailers) {
  135. if (!can_read_line())
  136. return;
  137. auto line = read_line(PAGE_SIZE);
  138. if (line.is_null()) {
  139. if (m_state == State::Trailers) {
  140. // Some servers like to send two ending chunks
  141. // use this fact as an excuse to ignore anything after the last chunk
  142. // that is not a valid trailing header.
  143. return finish_up();
  144. }
  145. fprintf(stderr, "Job: Expected HTTP header\n");
  146. return did_fail(Core::NetworkJob::Error::ProtocolFailed);
  147. }
  148. if (line.is_empty()) {
  149. if (m_state == State::Trailers) {
  150. return finish_up();
  151. } else {
  152. if (on_headers_received)
  153. on_headers_received(m_headers, m_code > 0 ? m_code : Optional<u32> {});
  154. m_state = State::InBody;
  155. }
  156. return;
  157. }
  158. auto parts = line.split_view(':');
  159. if (parts.is_empty()) {
  160. if (m_state == State::Trailers) {
  161. // Some servers like to send two ending chunks
  162. // use this fact as an excuse to ignore anything after the last chunk
  163. // that is not a valid trailing header.
  164. return finish_up();
  165. }
  166. fprintf(stderr, "Job: Expected HTTP header with key/value\n");
  167. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  168. }
  169. auto name = parts[0];
  170. if (line.length() < name.length() + 2) {
  171. if (m_state == State::Trailers) {
  172. // Some servers like to send two ending chunks
  173. // use this fact as an excuse to ignore anything after the last chunk
  174. // that is not a valid trailing header.
  175. return finish_up();
  176. }
  177. warnln("Job: Malformed HTTP header: '{}' ({})", line, line.length());
  178. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  179. }
  180. auto value = line.substring(name.length() + 2, line.length() - name.length() - 2);
  181. m_headers.set(name, value);
  182. if (name.equals_ignoring_case("Content-Encoding")) {
  183. // Assume that any content-encoding means that we can't decode it as a stream :(
  184. dbgln<debug_job>("Content-Encoding {} detected, cannot stream output :(", value);
  185. m_can_stream_response = false;
  186. }
  187. dbgln<debug_job>("Job: [{}] = '{}'", name, value);
  188. return;
  189. }
  190. ASSERT(m_state == State::InBody);
  191. ASSERT(can_read());
  192. read_while_data_available([&] {
  193. auto read_size = 64 * KiB;
  194. if (m_current_chunk_remaining_size.has_value()) {
  195. read_chunk_size:;
  196. auto remaining = m_current_chunk_remaining_size.value();
  197. if (remaining == -1) {
  198. // read size
  199. auto size_data = read_line(PAGE_SIZE);
  200. auto size_lines = size_data.view().lines();
  201. dbgln<debug_job>("Job: Received a chunk with size '{}'", size_data);
  202. if (size_lines.size() == 0) {
  203. dbgln("Job: Reached end of stream");
  204. finish_up();
  205. return IterationDecision::Break;
  206. } else {
  207. auto chunk = size_lines[0].split_view(';', true);
  208. String size_string = chunk[0];
  209. char* endptr;
  210. auto size = strtoul(size_string.characters(), &endptr, 16);
  211. if (*endptr) {
  212. // invalid number
  213. deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::TransmissionFailed); });
  214. return IterationDecision::Break;
  215. }
  216. if (size == 0) {
  217. // This is the last chunk
  218. // '0' *[; chunk-ext-name = chunk-ext-value]
  219. // We're going to ignore _all_ chunk extensions
  220. read_size = 0;
  221. m_current_chunk_total_size = 0;
  222. m_current_chunk_remaining_size = 0;
  223. dbgln<debug_job>("Job: Received the last chunk with extensions '{}'", size_string.substring_view(1, size_string.length() - 1));
  224. } else {
  225. m_current_chunk_total_size = size;
  226. m_current_chunk_remaining_size = size;
  227. read_size = size;
  228. dbgln<debug_job>("Job: Chunk of size '{}' started", size);
  229. }
  230. }
  231. } else {
  232. read_size = remaining;
  233. dbgln<debug_job>("Job: Resuming chunk with '{}' bytes left over", remaining);
  234. }
  235. } else {
  236. auto transfer_encoding = m_headers.get("Transfer-Encoding");
  237. if (transfer_encoding.has_value()) {
  238. auto encoding = transfer_encoding.value();
  239. dbgln<debug_job>("Job: This content has transfer encoding '{}'", encoding);
  240. if (encoding.equals_ignoring_case("chunked")) {
  241. m_current_chunk_remaining_size = -1;
  242. goto read_chunk_size;
  243. } else {
  244. dbgln("Job: Unknown transfer encoding '{}', the result will likely be wrong!", encoding);
  245. }
  246. }
  247. }
  248. auto payload = receive(read_size);
  249. if (!payload) {
  250. if (eof()) {
  251. finish_up();
  252. return IterationDecision::Break;
  253. }
  254. if (should_fail_on_empty_payload()) {
  255. deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  256. return IterationDecision::Break;
  257. }
  258. }
  259. m_received_buffers.append(payload);
  260. m_buffered_size += payload.size();
  261. m_received_size += payload.size();
  262. flush_received_buffers();
  263. if (m_current_chunk_remaining_size.has_value()) {
  264. auto size = m_current_chunk_remaining_size.value() - payload.size();
  265. dbgln<debug_job>("Job: We have {} bytes left over in this chunk", size);
  266. if (size == 0) {
  267. dbgln<debug_job>("Job: Finished a chunk of {} bytes", m_current_chunk_total_size.value());
  268. if (m_current_chunk_total_size.value() == 0) {
  269. m_state = State::Trailers;
  270. return IterationDecision::Break;
  271. }
  272. // we've read everything, now let's get the next chunk
  273. size = -1;
  274. [[maybe_unused]] auto line = read_line(PAGE_SIZE);
  275. if constexpr (debug_job)
  276. dbgln("Line following (should be empty): '{}'", line);
  277. }
  278. m_current_chunk_remaining_size = size;
  279. }
  280. auto content_length_header = m_headers.get("Content-Length");
  281. Optional<u32> content_length {};
  282. if (content_length_header.has_value()) {
  283. auto length = content_length_header.value().to_uint();
  284. if (length.has_value())
  285. content_length = length.value();
  286. }
  287. deferred_invoke([this, content_length](auto&) { did_progress(content_length, m_received_size); });
  288. if (content_length.has_value()) {
  289. auto length = content_length.value();
  290. if (m_received_size >= length) {
  291. m_received_size = length;
  292. finish_up();
  293. return IterationDecision::Break;
  294. }
  295. }
  296. return IterationDecision::Continue;
  297. });
  298. if (!is_established()) {
  299. #ifdef JOB_DEBUG
  300. dbgln("Connection appears to have closed, finishing up");
  301. #endif
  302. finish_up();
  303. }
  304. });
  305. }
  306. void Job::finish_up()
  307. {
  308. m_state = State::Finished;
  309. if (!m_can_stream_response) {
  310. auto flattened_buffer = ByteBuffer::create_uninitialized(m_received_size);
  311. u8* flat_ptr = flattened_buffer.data();
  312. for (auto& received_buffer : m_received_buffers) {
  313. memcpy(flat_ptr, received_buffer.data(), received_buffer.size());
  314. flat_ptr += received_buffer.size();
  315. }
  316. m_received_buffers.clear();
  317. // For the time being, we cannot stream stuff with content-encoding set to _anything_.
  318. auto content_encoding = m_headers.get("Content-Encoding");
  319. if (content_encoding.has_value()) {
  320. flattened_buffer = handle_content_encoding(flattened_buffer, content_encoding.value());
  321. }
  322. m_buffered_size = flattened_buffer.size();
  323. m_received_buffers.append(move(flattened_buffer));
  324. m_can_stream_response = true;
  325. }
  326. flush_received_buffers();
  327. if (m_buffered_size != 0) {
  328. // We have to wait for the client to consume all the downloaded data
  329. // before we can actually call `did_finish`. in a normal flow, this should
  330. // never be hit since the client is reading as we are writing, unless there
  331. // are too many concurrent downloads going on.
  332. deferred_invoke([this](auto&) {
  333. finish_up();
  334. });
  335. return;
  336. }
  337. auto response = HttpResponse::create(m_code, move(m_headers));
  338. deferred_invoke([this, response](auto&) {
  339. did_finish(move(response));
  340. });
  341. }
  342. }