Job.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 = String::copy(line, Chomp).split(' ');
  94. if (parts.size() < 3) {
  95. fprintf(stderr, "Job: Expected 3-part HTTP status, got '%s'\n", line.data());
  96. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  97. }
  98. bool ok;
  99. m_code = parts[1].to_uint(ok);
  100. if (!ok) {
  101. fprintf(stderr, "Job: Expected numeric HTTP status\n");
  102. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  103. }
  104. m_state = State::InHeaders;
  105. return;
  106. }
  107. if (m_state == State::InHeaders) {
  108. if (!can_read_line())
  109. return;
  110. auto line = read_line(PAGE_SIZE);
  111. if (line.is_null()) {
  112. fprintf(stderr, "Job: Expected HTTP header\n");
  113. return did_fail(Core::NetworkJob::Error::ProtocolFailed);
  114. }
  115. auto chomped_line = String::copy(line, Chomp);
  116. if (chomped_line.is_empty()) {
  117. m_state = State::InBody;
  118. return;
  119. }
  120. auto parts = chomped_line.split(':');
  121. if (parts.is_empty()) {
  122. fprintf(stderr, "Job: Expected HTTP header with key/value\n");
  123. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  124. }
  125. auto name = parts[0];
  126. if (chomped_line.length() < name.length() + 2) {
  127. fprintf(stderr, "Job: Malformed HTTP header: '%s' (%zu)\n", chomped_line.characters(), chomped_line.length());
  128. return deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  129. }
  130. auto value = chomped_line.substring(name.length() + 2, chomped_line.length() - name.length() - 2);
  131. m_headers.set(name, value);
  132. #ifdef JOB_DEBUG
  133. dbg() << "Job: [" << name << "] = '" << value << "'";
  134. #endif
  135. return;
  136. }
  137. ASSERT(m_state == State::InBody);
  138. ASSERT(can_read());
  139. read_while_data_available([&] {
  140. auto payload = receive(64 * KB);
  141. if (!payload) {
  142. if (eof()) {
  143. finish_up();
  144. return IterationDecision::Break;
  145. }
  146. if (should_fail_on_empty_payload()) {
  147. deferred_invoke([this](auto&) { did_fail(Core::NetworkJob::Error::ProtocolFailed); });
  148. return IterationDecision::Break;
  149. }
  150. }
  151. m_received_buffers.append(payload);
  152. m_received_size += payload.size();
  153. auto content_length_header = m_headers.get("Content-Length");
  154. Optional<u32> content_length {};
  155. if (content_length_header.has_value()) {
  156. bool ok;
  157. auto length = content_length_header.value().to_uint(ok);
  158. if (ok)
  159. content_length = length;
  160. }
  161. did_progress(content_length, m_received_size);
  162. if (content_length.has_value()) {
  163. auto length = content_length.value();
  164. if (m_received_size >= length) {
  165. m_received_size = length;
  166. finish_up();
  167. return IterationDecision::Break;
  168. }
  169. }
  170. return IterationDecision::Continue;
  171. });
  172. if (!is_established()) {
  173. #ifdef JOB_DEBUG
  174. dbg() << "Connection appears to have closed, finishing up";
  175. #endif
  176. finish_up();
  177. }
  178. });
  179. }
  180. void Job::finish_up()
  181. {
  182. m_state = State::Finished;
  183. auto flattened_buffer = ByteBuffer::create_uninitialized(m_received_size);
  184. u8* flat_ptr = flattened_buffer.data();
  185. for (auto& received_buffer : m_received_buffers) {
  186. memcpy(flat_ptr, received_buffer.data(), received_buffer.size());
  187. flat_ptr += received_buffer.size();
  188. }
  189. m_received_buffers.clear();
  190. auto content_encoding = m_headers.get("Content-Encoding");
  191. if (content_encoding.has_value()) {
  192. flattened_buffer = handle_content_encoding(flattened_buffer, content_encoding.value());
  193. }
  194. auto response = HttpResponse::create(m_code, move(m_headers), move(flattened_buffer));
  195. deferred_invoke([this, response](auto&) {
  196. did_finish(move(response));
  197. });
  198. }
  199. }