Socket.cpp 7.9 KB

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