Socket.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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/Timer.h>
  9. #include <LibCrypto/PK/Code/EMSA_PSS.h>
  10. #include <LibTLS/TLSv12.h>
  11. // Each record can hold at most 18432 bytes, leaving some headroom and rounding down to
  12. // a nice number gives us a maximum of 16 KiB for user-supplied application data,
  13. // which will be sent as a single record containing a single ApplicationData message.
  14. constexpr static size_t MaximumApplicationDataChunkSize = 16 * KiB;
  15. namespace TLS {
  16. Optional<ByteBuffer> TLSv12::read()
  17. {
  18. if (m_context.application_buffer.size()) {
  19. auto buf = move(m_context.application_buffer);
  20. return { move(buf) };
  21. }
  22. return {};
  23. }
  24. ByteBuffer TLSv12::read(size_t max_size)
  25. {
  26. if (m_context.application_buffer.size()) {
  27. auto length = min(m_context.application_buffer.size(), max_size);
  28. auto buf = m_context.application_buffer.slice(0, length);
  29. m_context.application_buffer = m_context.application_buffer.slice(length, m_context.application_buffer.size() - length);
  30. return buf;
  31. }
  32. return {};
  33. }
  34. String TLSv12::read_line(size_t max_size)
  35. {
  36. if (!can_read_line())
  37. return {};
  38. auto* start = m_context.application_buffer.data();
  39. auto* newline = (u8*)memchr(m_context.application_buffer.data(), '\n', m_context.application_buffer.size());
  40. VERIFY(newline);
  41. size_t offset = newline - start;
  42. if (offset > max_size)
  43. return {};
  44. String line { bit_cast<char const*>(start), offset, Chomp };
  45. m_context.application_buffer = m_context.application_buffer.slice(offset + 1, m_context.application_buffer.size() - offset - 1);
  46. return line;
  47. }
  48. bool TLSv12::write(ReadonlyBytes buffer)
  49. {
  50. if (m_context.connection_status != ConnectionStatus::Established) {
  51. dbgln_if(TLS_DEBUG, "write request while not connected");
  52. return false;
  53. }
  54. for (size_t offset = 0; offset < buffer.size(); offset += MaximumApplicationDataChunkSize) {
  55. PacketBuilder builder { MessageType::ApplicationData, m_context.options.version, buffer.size() - offset };
  56. builder.append(buffer.slice(offset, min(buffer.size() - offset, MaximumApplicationDataChunkSize)));
  57. auto packet = builder.build();
  58. update_packet(packet);
  59. write_packet(packet);
  60. }
  61. return true;
  62. }
  63. bool TLSv12::connect(const String& hostname, int port)
  64. {
  65. set_sni(hostname);
  66. return Core::Socket::connect(hostname, port);
  67. }
  68. bool TLSv12::common_connect(const struct sockaddr* saddr, socklen_t length)
  69. {
  70. if (m_context.critical_error)
  71. return false;
  72. if (Core::Socket::is_connected()) {
  73. if (is_established()) {
  74. VERIFY_NOT_REACHED();
  75. } else {
  76. Core::Socket::close(); // reuse?
  77. }
  78. }
  79. Core::Socket::on_connected = [this] {
  80. Core::Socket::on_ready_to_read = [this] {
  81. read_from_socket();
  82. };
  83. auto packet = build_hello();
  84. write_packet(packet);
  85. deferred_invoke([&] {
  86. m_handshake_timeout_timer = Core::Timer::create_single_shot(
  87. m_max_wait_time_for_handshake_in_seconds * 1000, [&] {
  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::Critical, AlertDescription::UserCanceled);
  96. m_context.connection_finished = true;
  97. m_context.tls_buffer.clear();
  98. m_context.error_code = Error::TimedOut;
  99. m_context.critical_error = (u8)Error::TimedOut;
  100. check_connection_state(false); // Notify the client.
  101. } else {
  102. // Extend the timer, we are too slow.
  103. m_handshake_timeout_timer->restart(m_max_wait_time_for_handshake_in_seconds * 1000);
  104. }
  105. },
  106. this);
  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. if (on_tls_connected)
  113. on_tls_connected();
  114. };
  115. bool success = Core::Socket::common_connect(saddr, length);
  116. if (!success)
  117. return false;
  118. return true;
  119. }
  120. void TLSv12::notify_client_for_app_data()
  121. {
  122. if (m_context.application_buffer.size() > 0) {
  123. if (!m_has_scheduled_app_data_flush) {
  124. deferred_invoke([this] { notify_client_for_app_data(); });
  125. m_has_scheduled_app_data_flush = true;
  126. }
  127. if (on_tls_ready_to_read)
  128. on_tls_ready_to_read(*this);
  129. } else {
  130. if (m_context.connection_finished && !m_context.has_invoked_finish_or_error_callback) {
  131. m_context.has_invoked_finish_or_error_callback = true;
  132. if (on_tls_finished)
  133. on_tls_finished();
  134. }
  135. }
  136. m_has_scheduled_app_data_flush = false;
  137. }
  138. void TLSv12::read_from_socket()
  139. {
  140. // If there's anything before we consume stuff, let the client know
  141. // since we won't be consuming things if the connection is terminated.
  142. notify_client_for_app_data();
  143. ScopeGuard notify_guard {
  144. [this] {
  145. // If anything new shows up, tell the client about the event.
  146. notify_client_for_app_data();
  147. }
  148. };
  149. if (!check_connection_state(true))
  150. return;
  151. consume(Core::Socket::read(4 * MiB));
  152. }
  153. void TLSv12::write_into_socket()
  154. {
  155. dbgln_if(TLS_DEBUG, "Flushing cached records: {} established? {}", m_context.tls_buffer.size(), is_established());
  156. m_has_scheduled_write_flush = false;
  157. if (!check_connection_state(false))
  158. return;
  159. flush();
  160. if (!is_established())
  161. return;
  162. if (!m_context.application_buffer.size()) // hey client, you still have stuff to read...
  163. if (on_tls_ready_to_write)
  164. on_tls_ready_to_write(*this);
  165. }
  166. bool TLSv12::check_connection_state(bool read)
  167. {
  168. if (m_context.connection_finished)
  169. return false;
  170. if (!Core::Socket::is_open() || !Core::Socket::is_connected()) {
  171. // an abrupt closure (the server is a jerk)
  172. dbgln_if(TLS_DEBUG, "Socket not open, assuming abrupt closure");
  173. m_context.connection_finished = true;
  174. m_context.connection_status = ConnectionStatus::Disconnected;
  175. Core::Socket::close();
  176. return false;
  177. }
  178. if (read && Core::Socket::eof()) {
  179. if (m_context.application_buffer.size() == 0 && m_context.connection_status != ConnectionStatus::Disconnected) {
  180. m_context.has_invoked_finish_or_error_callback = true;
  181. if (on_tls_finished)
  182. on_tls_finished();
  183. }
  184. return false;
  185. }
  186. if (m_context.critical_error) {
  187. dbgln_if(TLS_DEBUG, "CRITICAL ERROR {} :(", m_context.critical_error);
  188. m_context.has_invoked_finish_or_error_callback = true;
  189. if (on_tls_error)
  190. on_tls_error((AlertDescription)m_context.critical_error);
  191. m_context.connection_finished = true;
  192. m_context.connection_status = ConnectionStatus::Disconnected;
  193. Core::Socket::close();
  194. return false;
  195. }
  196. if (((read && m_context.application_buffer.size() == 0) || !read) && m_context.connection_finished) {
  197. if (m_context.application_buffer.size() == 0 && m_context.connection_status != ConnectionStatus::Disconnected) {
  198. m_context.has_invoked_finish_or_error_callback = true;
  199. if (on_tls_finished)
  200. on_tls_finished();
  201. }
  202. if (m_context.tls_buffer.size()) {
  203. dbgln_if(TLS_DEBUG, "connection closed without finishing data transfer, {} bytes still in buffer and {} bytes in application buffer",
  204. m_context.tls_buffer.size(),
  205. m_context.application_buffer.size());
  206. }
  207. if (!m_context.application_buffer.size()) {
  208. return false;
  209. }
  210. }
  211. return true;
  212. }
  213. bool TLSv12::flush()
  214. {
  215. auto out_buffer = write_buffer().data();
  216. size_t out_buffer_index { 0 };
  217. size_t out_buffer_length = write_buffer().size();
  218. if (out_buffer_length == 0)
  219. return true;
  220. if constexpr (TLS_DEBUG) {
  221. dbgln("SENDING...");
  222. print_buffer(out_buffer, out_buffer_length);
  223. }
  224. if (Core::Socket::write(&out_buffer[out_buffer_index], out_buffer_length)) {
  225. write_buffer().clear();
  226. return true;
  227. }
  228. if (m_context.send_retries++ == 10) {
  229. // drop the records, we can't send
  230. dbgln_if(TLS_DEBUG, "Dropping {} bytes worth of TLS records as max retries has been reached", write_buffer().size());
  231. write_buffer().clear();
  232. m_context.send_retries = 0;
  233. }
  234. return false;
  235. }
  236. }