Socket.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. namespace TLS {
  12. Optional<ByteBuffer> TLSv12::read()
  13. {
  14. if (m_context.application_buffer.size()) {
  15. auto buf = move(m_context.application_buffer);
  16. return { move(buf) };
  17. }
  18. return {};
  19. }
  20. ByteBuffer TLSv12::read(size_t max_size)
  21. {
  22. if (m_context.application_buffer.size()) {
  23. auto length = min(m_context.application_buffer.size(), max_size);
  24. auto buf = m_context.application_buffer.slice(0, length);
  25. m_context.application_buffer = m_context.application_buffer.slice(length, m_context.application_buffer.size() - length);
  26. return buf;
  27. }
  28. return {};
  29. }
  30. String TLSv12::read_line(size_t max_size)
  31. {
  32. if (!can_read_line())
  33. return {};
  34. auto* start = m_context.application_buffer.data();
  35. auto* newline = (u8*)memchr(m_context.application_buffer.data(), '\n', m_context.application_buffer.size());
  36. VERIFY(newline);
  37. size_t offset = newline - start;
  38. if (offset > max_size)
  39. return {};
  40. auto buffer_result = ByteBuffer::copy(start, offset);
  41. if (!buffer_result.has_value()) {
  42. dbgln("TLS: Failed to read line, not enough memory");
  43. dbgln("max_size < offset: {} < {} (size = {})", max_size, offset, m_context.application_buffer.size());
  44. dbgln("-> {:32hex-dump}", ReadonlyBytes { start, offset });
  45. return {};
  46. }
  47. String line { bit_cast<char const*>(start), offset, Chomp };
  48. m_context.application_buffer = m_context.application_buffer.slice(offset + 1, m_context.application_buffer.size() - offset - 1);
  49. return line;
  50. }
  51. bool TLSv12::write(ReadonlyBytes buffer)
  52. {
  53. if (m_context.connection_status != ConnectionStatus::Established) {
  54. dbgln_if(TLS_DEBUG, "write request while not connected");
  55. return false;
  56. }
  57. PacketBuilder builder { MessageType::ApplicationData, m_context.options.version, buffer.size() };
  58. builder.append(buffer);
  59. auto packet = builder.build();
  60. update_packet(packet);
  61. write_packet(packet);
  62. return true;
  63. }
  64. bool TLSv12::connect(const String& hostname, int port)
  65. {
  66. set_sni(hostname);
  67. return Core::Socket::connect(hostname, port);
  68. }
  69. bool TLSv12::common_connect(const struct sockaddr* saddr, socklen_t length)
  70. {
  71. if (m_context.critical_error)
  72. return false;
  73. if (Core::Socket::is_connected()) {
  74. if (is_established()) {
  75. VERIFY_NOT_REACHED();
  76. } else {
  77. Core::Socket::close(); // reuse?
  78. }
  79. }
  80. Core::Socket::on_connected = [this] {
  81. Core::Socket::on_ready_to_read = [this] {
  82. read_from_socket();
  83. };
  84. auto packet = build_hello();
  85. write_packet(packet);
  86. deferred_invoke([&] {
  87. m_handshake_timeout_timer = Core::Timer::create_single_shot(
  88. m_max_wait_time_for_handshake_in_seconds * 1000, [&] {
  89. auto timeout_diff = Core::DateTime::now().timestamp() - m_context.handshake_initiation_timestamp;
  90. // If the timeout duration was actually within the max wait time (with a margin of error),
  91. // we're not operating slow, so the server timed out.
  92. // otherwise, it's our fault that the negotiation is taking too long, so extend the timer :P
  93. if (timeout_diff < m_max_wait_time_for_handshake_in_seconds + 1) {
  94. // The server did not respond fast enough,
  95. // time the connection out.
  96. alert(AlertLevel::Critical, AlertDescription::UserCanceled);
  97. m_context.connection_finished = true;
  98. m_context.tls_buffer.clear();
  99. m_context.error_code = Error::TimedOut;
  100. m_context.critical_error = (u8)Error::TimedOut;
  101. check_connection_state(false); // Notify the client.
  102. } else {
  103. // Extend the timer, we are too slow.
  104. m_handshake_timeout_timer->restart(m_max_wait_time_for_handshake_in_seconds * 1000);
  105. }
  106. },
  107. this);
  108. write_into_socket();
  109. m_handshake_timeout_timer->start();
  110. m_context.handshake_initiation_timestamp = Core::DateTime::now().timestamp();
  111. });
  112. m_has_scheduled_write_flush = true;
  113. if (on_tls_connected)
  114. on_tls_connected();
  115. };
  116. bool success = Core::Socket::common_connect(saddr, length);
  117. if (!success)
  118. return false;
  119. return true;
  120. }
  121. void TLSv12::read_from_socket()
  122. {
  123. auto did_schedule_read = false;
  124. auto notify_client_for_app_data = [&] {
  125. if (m_context.application_buffer.size() > 0) {
  126. if (!did_schedule_read) {
  127. deferred_invoke([&] { read_from_socket(); });
  128. did_schedule_read = true;
  129. }
  130. if (on_tls_ready_to_read)
  131. on_tls_ready_to_read(*this);
  132. }
  133. };
  134. // If there's anything before we consume stuff, let the client know
  135. // since we won't be consuming things if the connection is terminated.
  136. notify_client_for_app_data();
  137. if (!check_connection_state(true))
  138. return;
  139. consume(Core::Socket::read(4096));
  140. // If anything new shows up, tell the client about the event.
  141. notify_client_for_app_data();
  142. }
  143. void TLSv12::write_into_socket()
  144. {
  145. dbgln_if(TLS_DEBUG, "Flushing cached records: {} established? {}", m_context.tls_buffer.size(), is_established());
  146. m_has_scheduled_write_flush = false;
  147. if (!check_connection_state(false))
  148. return;
  149. flush();
  150. if (!is_established())
  151. return;
  152. if (!m_context.application_buffer.size()) // hey client, you still have stuff to read...
  153. if (on_tls_ready_to_write)
  154. on_tls_ready_to_write(*this);
  155. }
  156. bool TLSv12::check_connection_state(bool read)
  157. {
  158. if (!Core::Socket::is_open() || !Core::Socket::is_connected() || Core::Socket::eof()) {
  159. // an abrupt closure (the server is a jerk)
  160. dbgln_if(TLS_DEBUG, "Socket not open, assuming abrupt closure");
  161. m_context.connection_finished = true;
  162. }
  163. if (m_context.critical_error) {
  164. dbgln_if(TLS_DEBUG, "CRITICAL ERROR {} :(", m_context.critical_error);
  165. if (on_tls_error)
  166. on_tls_error((AlertDescription)m_context.critical_error);
  167. return false;
  168. }
  169. if (((read && m_context.application_buffer.size() == 0) || !read) && m_context.connection_finished) {
  170. if (m_context.application_buffer.size() == 0 && m_context.connection_status != ConnectionStatus::Disconnected) {
  171. if (on_tls_finished)
  172. on_tls_finished();
  173. }
  174. if (m_context.tls_buffer.size()) {
  175. dbgln_if(TLS_DEBUG, "connection closed without finishing data transfer, {} bytes still in buffer and {} bytes in application buffer",
  176. m_context.tls_buffer.size(),
  177. m_context.application_buffer.size());
  178. } else {
  179. m_context.connection_finished = false;
  180. dbgln_if(TLS_DEBUG, "FINISHED");
  181. }
  182. if (!m_context.application_buffer.size()) {
  183. m_context.connection_status = ConnectionStatus::Disconnected;
  184. return false;
  185. }
  186. }
  187. return true;
  188. }
  189. bool TLSv12::flush()
  190. {
  191. auto out_buffer = write_buffer().data();
  192. size_t out_buffer_index { 0 };
  193. size_t out_buffer_length = write_buffer().size();
  194. if (out_buffer_length == 0)
  195. return true;
  196. if constexpr (TLS_DEBUG) {
  197. dbgln("SENDING...");
  198. print_buffer(out_buffer, out_buffer_length);
  199. }
  200. if (Core::Socket::write(&out_buffer[out_buffer_index], out_buffer_length)) {
  201. write_buffer().clear();
  202. return true;
  203. }
  204. if (m_context.send_retries++ == 10) {
  205. // drop the records, we can't send
  206. dbgln_if(TLS_DEBUG, "Dropping {} bytes worth of TLS records as max retries has been reached", write_buffer().size());
  207. write_buffer().clear();
  208. m_context.send_retries = 0;
  209. }
  210. return false;
  211. }
  212. }