Socket.cpp 7.9 KB

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