Socket.cpp 11 KB

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