Job.cpp 13 KB

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