HttpJob.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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/HttpJob.h>
  28. #include <LibCore/HttpResponse.h>
  29. #include <LibCore/TCPSocket.h>
  30. #include <stdio.h>
  31. #include <unistd.h>
  32. //#define CHTTPJOB_DEBUG
  33. namespace Core {
  34. static ByteBuffer handle_content_encoding(const ByteBuffer& buf, const String& content_encoding)
  35. {
  36. #ifdef CHTTPJOB_DEBUG
  37. dbg() << "CHttpJob::handle_content_encoding: buf has content_encoding = " << content_encoding;
  38. #endif
  39. if (content_encoding == "gzip") {
  40. if (!CGzip::is_compressed(buf)) {
  41. dbg() << "CHttpJob::handle_content_encoding: buf is not gzip compressed!";
  42. }
  43. #ifdef CHTTPJOB_DEBUG
  44. dbg() << "CHttpJob::handle_content_encoding: buf is gzip compressed!";
  45. #endif
  46. auto uncompressed = CGzip::decompress(buf);
  47. if (!uncompressed.has_value()) {
  48. dbg() << "CHttpJob::handle_content_encoding: Gzip::decompress() failed. Returning original buffer.";
  49. return buf;
  50. }
  51. #ifdef CHTTPJOB_DEBUG
  52. dbg() << "CHttpJob::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. HttpJob::HttpJob(const HttpRequest& request)
  61. : m_request(request)
  62. {
  63. }
  64. HttpJob::~HttpJob()
  65. {
  66. }
  67. void HttpJob::on_socket_connected()
  68. {
  69. auto raw_request = m_request.to_raw_request();
  70. #if 0
  71. dbg() << "CHttpJob: raw_request:";
  72. dbg() << String::copy(raw_request).characters();
  73. #endif
  74. bool success = m_socket->send(raw_request);
  75. if (!success)
  76. return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::TransmissionFailed); });
  77. m_socket->on_ready_to_read = [&] {
  78. if (is_cancelled())
  79. return;
  80. if (m_state == State::InStatus) {
  81. if (!m_socket->can_read_line())
  82. return;
  83. auto line = m_socket->read_line(PAGE_SIZE);
  84. if (line.is_null()) {
  85. fprintf(stderr, "CHttpJob: Expected HTTP status\n");
  86. return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::TransmissionFailed); });
  87. }
  88. auto parts = String::copy(line, Chomp).split(' ');
  89. if (parts.size() < 3) {
  90. fprintf(stderr, "CHttpJob: Expected 3-part HTTP status, got '%s'\n", line.data());
  91. return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::ProtocolFailed); });
  92. }
  93. bool ok;
  94. m_code = parts[1].to_uint(ok);
  95. if (!ok) {
  96. fprintf(stderr, "CHttpJob: Expected numeric HTTP status\n");
  97. return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::ProtocolFailed); });
  98. }
  99. m_state = State::InHeaders;
  100. return;
  101. }
  102. if (m_state == State::InHeaders) {
  103. if (!m_socket->can_read_line())
  104. return;
  105. auto line = m_socket->read_line(PAGE_SIZE);
  106. if (line.is_null()) {
  107. fprintf(stderr, "CHttpJob: Expected HTTP header\n");
  108. return did_fail(NetworkJob::Error::ProtocolFailed);
  109. }
  110. auto chomped_line = String::copy(line, Chomp);
  111. if (chomped_line.is_empty()) {
  112. m_state = State::InBody;
  113. return;
  114. }
  115. auto parts = chomped_line.split(':');
  116. if (parts.is_empty()) {
  117. fprintf(stderr, "CHttpJob: Expected HTTP header with key/value\n");
  118. return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::ProtocolFailed); });
  119. }
  120. auto name = parts[0];
  121. if (chomped_line.length() < name.length() + 2) {
  122. fprintf(stderr, "CHttpJob: Malformed HTTP header: '%s' (%zu)\n", chomped_line.characters(), chomped_line.length());
  123. return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::ProtocolFailed); });
  124. }
  125. auto value = chomped_line.substring(name.length() + 2, chomped_line.length() - name.length() - 2);
  126. m_headers.set(name, value);
  127. #ifdef CHTTPJOB_DEBUG
  128. dbg() << "CHttpJob: [" << name << "] = '" << value << "'";
  129. #endif
  130. return;
  131. }
  132. ASSERT(m_state == State::InBody);
  133. ASSERT(m_socket->can_read());
  134. auto payload = m_socket->receive(64 * KB);
  135. if (!payload) {
  136. if (m_socket->eof())
  137. return finish_up();
  138. return deferred_invoke([this](auto&) { did_fail(NetworkJob::Error::ProtocolFailed); });
  139. }
  140. m_received_buffers.append(payload);
  141. m_received_size += payload.size();
  142. auto content_length_header = m_headers.get("Content-Length");
  143. if (content_length_header.has_value()) {
  144. bool ok;
  145. if (m_received_size >= content_length_header.value().to_uint(ok) && ok)
  146. return finish_up();
  147. }
  148. };
  149. }
  150. void HttpJob::finish_up()
  151. {
  152. m_state = State::Finished;
  153. auto flattened_buffer = ByteBuffer::create_uninitialized(m_received_size);
  154. u8* flat_ptr = flattened_buffer.data();
  155. for (auto& received_buffer : m_received_buffers) {
  156. memcpy(flat_ptr, received_buffer.data(), received_buffer.size());
  157. flat_ptr += received_buffer.size();
  158. }
  159. m_received_buffers.clear();
  160. auto content_encoding = m_headers.get("Content-Encoding");
  161. if (content_encoding.has_value()) {
  162. flattened_buffer = handle_content_encoding(flattened_buffer, content_encoding.value());
  163. }
  164. auto response = HttpResponse::create(m_code, move(m_headers), move(flattened_buffer));
  165. deferred_invoke([this, response](auto&) {
  166. did_finish(move(response));
  167. });
  168. }
  169. void HttpJob::start()
  170. {
  171. ASSERT(!m_socket);
  172. m_socket = TCPSocket::construct(this);
  173. m_socket->on_connected = [this] {
  174. #ifdef CHTTPJOB_DEBUG
  175. dbg() << "CHttpJob: on_connected callback";
  176. #endif
  177. on_socket_connected();
  178. };
  179. bool success = m_socket->connect(m_request.url().host(), m_request.url().port());
  180. if (!success) {
  181. deferred_invoke([this](auto&) {
  182. return did_fail(NetworkJob::Error::ConnectionFailed);
  183. });
  184. }
  185. }
  186. void HttpJob::shutdown()
  187. {
  188. if (!m_socket)
  189. return;
  190. m_socket->on_ready_to_read = nullptr;
  191. m_socket->on_connected = nullptr;
  192. remove_child(*m_socket);
  193. m_socket = nullptr;
  194. }
  195. }