Socket.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <LibCore/DateTime.h>
  8. #include <LibCore/EventLoop.h>
  9. #include <LibCore/Promise.h>
  10. #include <LibCore/Timer.h>
  11. #include <LibTLS/TLSv12.h>
  12. // Each record can hold at most 18432 bytes, leaving some headroom and rounding down to
  13. // a nice number gives us a maximum of 16 KiB for user-supplied application data,
  14. // which will be sent as a single record containing a single ApplicationData message.
  15. constexpr static size_t MaximumApplicationDataChunkSize = 16 * KiB;
  16. namespace TLS {
  17. ErrorOr<Bytes> TLSv12::read_some(Bytes bytes)
  18. {
  19. m_eof = false;
  20. auto size_to_read = min(bytes.size(), m_context.application_buffer.size());
  21. if (size_to_read == 0) {
  22. m_eof = true;
  23. return Bytes {};
  24. }
  25. m_context.application_buffer.transfer(bytes, size_to_read);
  26. return Bytes { bytes.data(), size_to_read };
  27. }
  28. ErrorOr<size_t> TLSv12::write_some(ReadonlyBytes bytes)
  29. {
  30. if (m_context.connection_status != ConnectionStatus::Established) {
  31. dbgln_if(TLS_DEBUG, "write request while not connected");
  32. return AK::Error::from_string_literal("TLS write request while not connected");
  33. }
  34. for (size_t offset = 0; offset < bytes.size(); offset += MaximumApplicationDataChunkSize) {
  35. PacketBuilder builder { ContentType::APPLICATION_DATA, m_context.options.version, bytes.size() - offset };
  36. builder.append(bytes.slice(offset, min(bytes.size() - offset, MaximumApplicationDataChunkSize)));
  37. auto packet = builder.build();
  38. update_packet(packet);
  39. write_packet(packet);
  40. }
  41. return bytes.size();
  42. }
  43. ErrorOr<NonnullOwnPtr<TLSv12>> TLSv12::connect(ByteString const& host, u16 port, Options options)
  44. {
  45. auto promise = Core::Promise<Empty>::construct();
  46. OwnPtr<Core::Socket> tcp_socket = TRY(Core::TCPSocket::connect(host, port));
  47. TRY(tcp_socket->set_blocking(false));
  48. auto tls_socket = make<TLSv12>(move(tcp_socket), move(options));
  49. tls_socket->set_sni(host);
  50. tls_socket->on_connected = [&] {
  51. promise->resolve({});
  52. };
  53. tls_socket->on_tls_error = [&](auto alert) {
  54. tls_socket->try_disambiguate_error();
  55. promise->reject(AK::Error::from_string_view(enum_to_string(alert)));
  56. };
  57. TRY(promise->await());
  58. tls_socket->on_tls_error = nullptr;
  59. tls_socket->on_connected = nullptr;
  60. tls_socket->m_context.should_expect_successful_read = true;
  61. return tls_socket;
  62. }
  63. ErrorOr<NonnullOwnPtr<TLSv12>> TLSv12::connect(ByteString const& host, Core::Socket& underlying_stream, Options options)
  64. {
  65. auto promise = Core::Promise<Empty>::construct();
  66. TRY(underlying_stream.set_blocking(false));
  67. auto tls_socket = make<TLSv12>(&underlying_stream, move(options));
  68. tls_socket->set_sni(host);
  69. tls_socket->on_connected = [&] {
  70. promise->resolve({});
  71. };
  72. tls_socket->on_tls_error = [&](auto alert) {
  73. tls_socket->try_disambiguate_error();
  74. promise->reject(AK::Error::from_string_view(enum_to_string(alert)));
  75. };
  76. TRY(promise->await());
  77. tls_socket->on_tls_error = nullptr;
  78. tls_socket->on_connected = nullptr;
  79. tls_socket->m_context.should_expect_successful_read = true;
  80. return tls_socket;
  81. }
  82. void TLSv12::setup_connection()
  83. {
  84. Core::deferred_invoke([this] {
  85. auto& stream = underlying_stream();
  86. stream.on_ready_to_read = [this] {
  87. auto result = read_from_socket();
  88. if (result.is_error())
  89. dbgln("Read error: {}", result.error());
  90. };
  91. m_handshake_timeout_timer = Core::Timer::create_single_shot(
  92. m_max_wait_time_for_handshake_in_seconds * 1000, [&] {
  93. dbgln("Handshake timeout :(");
  94. auto timeout_diff = Core::DateTime::now().timestamp() - m_context.handshake_initiation_timestamp;
  95. // If the timeout duration was actually within the max wait time (with a margin of error),
  96. // we're not operating slow, so the server timed out.
  97. // otherwise, it's our fault that the negotiation is taking too long, so extend the timer :P
  98. if (timeout_diff < m_max_wait_time_for_handshake_in_seconds + 1) {
  99. // The server did not respond fast enough,
  100. // time the connection out.
  101. alert(AlertLevel::FATAL, AlertDescription::USER_CANCELED);
  102. m_context.tls_buffer.clear();
  103. m_context.error_code = Error::TimedOut;
  104. m_context.critical_error = (u8)Error::TimedOut;
  105. check_connection_state(false); // Notify the client.
  106. } else {
  107. // Extend the timer, we are too slow.
  108. m_handshake_timeout_timer->restart(m_max_wait_time_for_handshake_in_seconds * 1000);
  109. }
  110. });
  111. auto packet = build_hello();
  112. write_packet(packet);
  113. write_into_socket();
  114. m_handshake_timeout_timer->start();
  115. m_context.handshake_initiation_timestamp = Core::DateTime::now().timestamp();
  116. });
  117. m_has_scheduled_write_flush = true;
  118. }
  119. void TLSv12::notify_client_for_app_data()
  120. {
  121. if (m_context.application_buffer.size() > 0) {
  122. if (on_ready_to_read)
  123. on_ready_to_read();
  124. } else {
  125. if (m_context.connection_finished && !m_context.has_invoked_finish_or_error_callback) {
  126. m_context.has_invoked_finish_or_error_callback = true;
  127. if (on_tls_finished)
  128. on_tls_finished();
  129. }
  130. }
  131. m_has_scheduled_app_data_flush = false;
  132. }
  133. ErrorOr<void> TLSv12::read_from_socket()
  134. {
  135. // If there's anything before we consume stuff, let the client know
  136. // since we won't be consuming things if the connection is terminated.
  137. notify_client_for_app_data();
  138. ScopeGuard notify_guard {
  139. [this] {
  140. // If anything new shows up, tell the client about the event.
  141. notify_client_for_app_data();
  142. }
  143. };
  144. if (!check_connection_state(true))
  145. return {};
  146. u8 buffer[16 * KiB];
  147. Bytes bytes { buffer, array_size(buffer) };
  148. Bytes read_bytes {};
  149. auto& stream = underlying_stream();
  150. do {
  151. auto result = stream.read_some(bytes);
  152. if (result.is_error()) {
  153. if (result.error().is_errno() && result.error().code() != EINTR) {
  154. if (result.error().code() != EAGAIN)
  155. dbgln("TLS Socket read failed, error: {}", result.error());
  156. break;
  157. }
  158. continue;
  159. }
  160. read_bytes = result.release_value();
  161. consume(read_bytes);
  162. } while (!read_bytes.is_empty() && !m_context.critical_error);
  163. if (m_context.should_expect_successful_read && read_bytes.is_empty()) {
  164. // read_some() returned an empty span, this is either an EOF (from improper closure)
  165. // or some sort of weird even that is showing itself as an EOF.
  166. // To guard against servers closing the connection weirdly or just improperly, make sure
  167. // to check the connection state here and send the appropriate notifications.
  168. stream.close();
  169. check_connection_state(true);
  170. }
  171. return {};
  172. }
  173. void TLSv12::write_into_socket()
  174. {
  175. dbgln_if(TLS_DEBUG, "Flushing cached records: {} established? {}", m_context.tls_buffer.size(), is_established());
  176. m_has_scheduled_write_flush = false;
  177. if (!check_connection_state(false))
  178. return;
  179. MUST(flush());
  180. }
  181. bool TLSv12::check_connection_state(bool read)
  182. {
  183. if (m_context.connection_finished)
  184. return false;
  185. if (m_context.close_notify)
  186. m_context.connection_finished = true;
  187. auto& stream = underlying_stream();
  188. if (!stream.is_open()) {
  189. // an abrupt closure (the server is a jerk)
  190. dbgln_if(TLS_DEBUG, "Socket not open, assuming abrupt closure");
  191. m_context.connection_finished = true;
  192. m_context.connection_status = ConnectionStatus::Disconnected;
  193. close();
  194. m_context.has_invoked_finish_or_error_callback = true;
  195. if (on_ready_to_read)
  196. on_ready_to_read(); // Notify the client about the weird event.
  197. if (on_tls_finished)
  198. on_tls_finished();
  199. return false;
  200. }
  201. if (read && stream.is_eof()) {
  202. if (m_context.application_buffer.size() == 0 && m_context.connection_status != ConnectionStatus::Disconnected) {
  203. m_context.has_invoked_finish_or_error_callback = true;
  204. if (on_tls_finished)
  205. on_tls_finished();
  206. }
  207. return false;
  208. }
  209. if (m_context.critical_error) {
  210. dbgln_if(TLS_DEBUG, "CRITICAL ERROR {} :(", m_context.critical_error);
  211. m_context.has_invoked_finish_or_error_callback = true;
  212. if (on_tls_error)
  213. on_tls_error((AlertDescription)m_context.critical_error);
  214. m_context.connection_finished = true;
  215. m_context.connection_status = ConnectionStatus::Disconnected;
  216. close();
  217. return false;
  218. }
  219. if (((read && m_context.application_buffer.size() == 0) || !read) && m_context.connection_finished) {
  220. if (m_context.application_buffer.size() == 0 && m_context.connection_status != ConnectionStatus::Disconnected) {
  221. m_context.has_invoked_finish_or_error_callback = true;
  222. if (on_tls_finished)
  223. on_tls_finished();
  224. }
  225. if (m_context.tls_buffer.size()) {
  226. dbgln_if(TLS_DEBUG, "connection closed without finishing data transfer, {} bytes still in buffer and {} bytes in application buffer",
  227. m_context.tls_buffer.size(),
  228. m_context.application_buffer.size());
  229. }
  230. if (!m_context.application_buffer.size()) {
  231. return false;
  232. }
  233. }
  234. return true;
  235. }
  236. ErrorOr<bool> TLSv12::flush()
  237. {
  238. auto out_bytes = m_context.tls_buffer.bytes();
  239. if (out_bytes.is_empty())
  240. return true;
  241. if constexpr (TLS_DEBUG) {
  242. dbgln("SENDING...");
  243. print_buffer(out_bytes);
  244. }
  245. auto& stream = underlying_stream();
  246. Optional<AK::Error> error;
  247. size_t written;
  248. do {
  249. auto result = stream.write_some(out_bytes);
  250. if (result.is_error()) {
  251. if (result.error().code() != EINTR && result.error().code() != EAGAIN) {
  252. error = result.release_error();
  253. dbgln("TLS Socket write error: {}", *error);
  254. break;
  255. }
  256. continue;
  257. }
  258. written = result.value();
  259. out_bytes = out_bytes.slice(written);
  260. } while (!out_bytes.is_empty());
  261. if (out_bytes.is_empty() && !error.has_value()) {
  262. m_context.tls_buffer.clear();
  263. return true;
  264. }
  265. if (m_context.send_retries++ == 10) {
  266. // drop the records, we can't send
  267. dbgln_if(TLS_DEBUG, "Dropping {} bytes worth of TLS records as max retries has been reached", m_context.tls_buffer.size());
  268. m_context.tls_buffer.clear();
  269. m_context.send_retries = 0;
  270. }
  271. return false;
  272. }
  273. void TLSv12::close()
  274. {
  275. if (underlying_stream().is_open())
  276. alert(AlertLevel::FATAL, AlertDescription::CLOSE_NOTIFY);
  277. // bye bye.
  278. m_context.connection_status = ConnectionStatus::Disconnected;
  279. }
  280. }