Socket.cpp 10 KB

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