Socket.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 <LibCrypto/PK/Code/EMSA_PSS.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. Core::EventLoop loop;
  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. loop.quit(0);
  52. };
  53. tls_socket->on_tls_error = [&](auto alert) {
  54. loop.quit(256 - to_underlying(alert));
  55. };
  56. auto result = loop.exec();
  57. if (result == 0)
  58. return tls_socket;
  59. tls_socket->try_disambiguate_error();
  60. // FIXME: Should return richer information here.
  61. return AK::Error::from_string_view(enum_to_string(static_cast<AlertDescription>(256 - result)));
  62. }
  63. ErrorOr<NonnullOwnPtr<TLSv12>> TLSv12::connect(ByteString const& host, Core::Socket& underlying_stream, Options options)
  64. {
  65. TRY(underlying_stream.set_blocking(false));
  66. auto tls_socket = make<TLSv12>(&underlying_stream, move(options));
  67. tls_socket->set_sni(host);
  68. Core::EventLoop loop;
  69. tls_socket->on_connected = [&] {
  70. loop.quit(0);
  71. };
  72. tls_socket->on_tls_error = [&](auto alert) {
  73. loop.quit(256 - to_underlying(alert));
  74. };
  75. auto result = loop.exec();
  76. if (result == 0)
  77. return tls_socket;
  78. tls_socket->try_disambiguate_error();
  79. // FIXME: Should return richer information here.
  80. return AK::Error::from_string_view(enum_to_string(static_cast<AlertDescription>(256 - result)));
  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. }).release_value_but_fixme_should_propagate_errors();
  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. return {};
  164. }
  165. void TLSv12::write_into_socket()
  166. {
  167. dbgln_if(TLS_DEBUG, "Flushing cached records: {} established? {}", m_context.tls_buffer.size(), is_established());
  168. m_has_scheduled_write_flush = false;
  169. if (!check_connection_state(false))
  170. return;
  171. MUST(flush());
  172. }
  173. bool TLSv12::check_connection_state(bool read)
  174. {
  175. if (m_context.connection_finished)
  176. return false;
  177. if (m_context.close_notify)
  178. m_context.connection_finished = true;
  179. auto& stream = underlying_stream();
  180. if (!stream.is_open()) {
  181. // an abrupt closure (the server is a jerk)
  182. dbgln_if(TLS_DEBUG, "Socket not open, assuming abrupt closure");
  183. m_context.connection_finished = true;
  184. m_context.connection_status = ConnectionStatus::Disconnected;
  185. close();
  186. return false;
  187. }
  188. if (read && stream.is_eof()) {
  189. if (m_context.application_buffer.size() == 0 && m_context.connection_status != ConnectionStatus::Disconnected) {
  190. m_context.has_invoked_finish_or_error_callback = true;
  191. if (on_tls_finished)
  192. on_tls_finished();
  193. }
  194. return false;
  195. }
  196. if (m_context.critical_error) {
  197. dbgln_if(TLS_DEBUG, "CRITICAL ERROR {} :(", m_context.critical_error);
  198. m_context.has_invoked_finish_or_error_callback = true;
  199. if (on_tls_error)
  200. on_tls_error((AlertDescription)m_context.critical_error);
  201. m_context.connection_finished = true;
  202. m_context.connection_status = ConnectionStatus::Disconnected;
  203. close();
  204. return false;
  205. }
  206. if (((read && m_context.application_buffer.size() == 0) || !read) && m_context.connection_finished) {
  207. if (m_context.application_buffer.size() == 0 && m_context.connection_status != ConnectionStatus::Disconnected) {
  208. m_context.has_invoked_finish_or_error_callback = true;
  209. if (on_tls_finished)
  210. on_tls_finished();
  211. }
  212. if (m_context.tls_buffer.size()) {
  213. dbgln_if(TLS_DEBUG, "connection closed without finishing data transfer, {} bytes still in buffer and {} bytes in application buffer",
  214. m_context.tls_buffer.size(),
  215. m_context.application_buffer.size());
  216. }
  217. if (!m_context.application_buffer.size()) {
  218. return false;
  219. }
  220. }
  221. return true;
  222. }
  223. ErrorOr<bool> TLSv12::flush()
  224. {
  225. auto out_bytes = m_context.tls_buffer.bytes();
  226. if (out_bytes.is_empty())
  227. return true;
  228. if constexpr (TLS_DEBUG) {
  229. dbgln("SENDING...");
  230. print_buffer(out_bytes);
  231. }
  232. auto& stream = underlying_stream();
  233. Optional<AK::Error> error;
  234. size_t written;
  235. do {
  236. auto result = stream.write_some(out_bytes);
  237. if (result.is_error()) {
  238. if (result.error().code() != EINTR && result.error().code() != EAGAIN) {
  239. error = result.release_error();
  240. dbgln("TLS Socket write error: {}", *error);
  241. break;
  242. }
  243. continue;
  244. }
  245. written = result.value();
  246. out_bytes = out_bytes.slice(written);
  247. } while (!out_bytes.is_empty());
  248. if (out_bytes.is_empty() && !error.has_value()) {
  249. m_context.tls_buffer.clear();
  250. return true;
  251. }
  252. if (m_context.send_retries++ == 10) {
  253. // drop the records, we can't send
  254. dbgln_if(TLS_DEBUG, "Dropping {} bytes worth of TLS records as max retries has been reached", m_context.tls_buffer.size());
  255. m_context.tls_buffer.clear();
  256. m_context.send_retries = 0;
  257. }
  258. return false;
  259. }
  260. void TLSv12::close()
  261. {
  262. alert(AlertLevel::FATAL, AlertDescription::CLOSE_NOTIFY);
  263. // bye bye.
  264. m_context.connection_status = ConnectionStatus::Disconnected;
  265. }
  266. }