HttpsJob.cpp 8.5 KB

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