Socket.cpp 10 KB

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