Socket.cpp 11 KB

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