Socket.cpp 11 KB

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