Socket.cpp 7.4 KB

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