Socket.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /*
  2. * Copyright (c) 2020, Ali Mohammad Pur <ali.mpfard@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <LibCore/DateTime.h>
  27. #include <LibCore/Timer.h>
  28. #include <LibCrypto/ASN1/DER.h>
  29. #include <LibCrypto/PK/Code/EMSA_PSS.h>
  30. #include <LibTLS/TLSv12.h>
  31. namespace TLS {
  32. Optional<ByteBuffer> TLSv12::read()
  33. {
  34. if (m_context.application_buffer.size()) {
  35. auto buf = m_context.application_buffer.slice(0, m_context.application_buffer.size());
  36. m_context.application_buffer.clear();
  37. return buf;
  38. }
  39. return {};
  40. }
  41. ByteBuffer TLSv12::read(size_t max_size)
  42. {
  43. if (m_context.application_buffer.size()) {
  44. auto length = min(m_context.application_buffer.size(), max_size);
  45. auto buf = m_context.application_buffer.slice(0, length);
  46. m_context.application_buffer = m_context.application_buffer.slice(length, m_context.application_buffer.size() - length);
  47. return buf;
  48. }
  49. return {};
  50. }
  51. ByteBuffer TLSv12::read_line(size_t max_size)
  52. {
  53. if (!can_read_line())
  54. return {};
  55. auto* start = m_context.application_buffer.data();
  56. auto* newline = (u8*)memchr(m_context.application_buffer.data(), '\n', m_context.application_buffer.size());
  57. ASSERT(newline);
  58. size_t offset = newline - start;
  59. if (offset > max_size)
  60. return {};
  61. auto buffer = ByteBuffer::copy(start, offset);
  62. m_context.application_buffer = m_context.application_buffer.slice(offset + 1, m_context.application_buffer.size() - offset - 1);
  63. return buffer;
  64. }
  65. bool TLSv12::write(const ByteBuffer& buffer)
  66. {
  67. if (m_context.connection_status != ConnectionStatus::Established) {
  68. #ifdef TLS_DEBUG
  69. dbg() << "write request while not connected";
  70. #endif
  71. return false;
  72. }
  73. PacketBuilder builder { MessageType::ApplicationData, m_context.version, buffer.size() };
  74. builder.append(buffer);
  75. auto packet = builder.build();
  76. update_packet(packet);
  77. write_packet(packet);
  78. return true;
  79. }
  80. bool TLSv12::connect(const String& hostname, int port)
  81. {
  82. set_sni(hostname);
  83. return Core::Socket::connect(hostname, port);
  84. }
  85. bool TLSv12::common_connect(const struct sockaddr* saddr, socklen_t length)
  86. {
  87. if (m_context.critical_error)
  88. return false;
  89. if (Core::Socket::is_connected()) {
  90. if (is_established()) {
  91. ASSERT_NOT_REACHED();
  92. } else {
  93. Core::Socket::close(); // reuse?
  94. }
  95. }
  96. Core::Socket::on_connected = [this] {
  97. Core::Socket::on_ready_to_read = [this] {
  98. read_from_socket();
  99. };
  100. auto packet = build_hello();
  101. write_packet(packet);
  102. deferred_invoke([&](auto&) {
  103. m_handshake_timeout_timer = Core::Timer::create_single_shot(
  104. m_max_wait_time_for_handshake_in_seconds * 1000, [&] {
  105. // The server did not respond fast enough,
  106. // time the connection out.
  107. alert(AlertLevel::Critical, AlertDescription::UserCanceled);
  108. m_context.connection_finished = true;
  109. m_context.tls_buffer.clear();
  110. m_context.error_code = Error::TimedOut;
  111. m_context.critical_error = (u8)Error::TimedOut;
  112. check_connection_state(false); // Notify the client.
  113. },
  114. this);
  115. write_into_socket();
  116. m_handshake_timeout_timer->start();
  117. });
  118. m_has_scheduled_write_flush = true;
  119. if (on_tls_connected)
  120. on_tls_connected();
  121. };
  122. bool success = Core::Socket::common_connect(saddr, length);
  123. if (!success)
  124. return false;
  125. return true;
  126. }
  127. void TLSv12::read_from_socket()
  128. {
  129. if (m_context.application_buffer.size() > 0) {
  130. deferred_invoke([&](auto&) { read_from_socket(); });
  131. if (on_tls_ready_to_read)
  132. on_tls_ready_to_read(*this);
  133. }
  134. if (!check_connection_state(true))
  135. return;
  136. consume(Core::Socket::read(4096));
  137. }
  138. void TLSv12::write_into_socket()
  139. {
  140. #ifdef TLS_DEBUG
  141. dbg() << "Flushing cached records: " << m_context.tls_buffer.size() << " established? " << is_established();
  142. #endif
  143. m_has_scheduled_write_flush = false;
  144. if (!check_connection_state(false))
  145. return;
  146. flush();
  147. if (!is_established())
  148. return;
  149. if (!m_context.application_buffer.size()) // hey client, you still have stuff to read...
  150. if (on_tls_ready_to_write)
  151. on_tls_ready_to_write(*this);
  152. }
  153. bool TLSv12::check_connection_state(bool read)
  154. {
  155. if (!Core::Socket::is_open() || !Core::Socket::is_connected() || Core::Socket::eof()) {
  156. // an abrupt closure (the server is a jerk)
  157. #ifdef TLS_DEBUG
  158. dbg() << "Socket not open, assuming abrupt closure";
  159. #endif
  160. m_context.connection_finished = true;
  161. }
  162. if (m_context.critical_error) {
  163. #ifdef TLS_DEBUG
  164. dbg() << "CRITICAL ERROR " << m_context.critical_error << " :(";
  165. #endif
  166. if (on_tls_error)
  167. on_tls_error((AlertDescription)m_context.critical_error);
  168. return false;
  169. }
  170. if (((read && m_context.application_buffer.size() == 0) || !read) && m_context.connection_finished) {
  171. if (m_context.application_buffer.size() == 0) {
  172. if (on_tls_finished)
  173. on_tls_finished();
  174. }
  175. if (m_context.tls_buffer.size()) {
  176. #ifdef TLS_DEBUG
  177. dbg() << "connection closed without finishing data transfer, " << m_context.tls_buffer.size() << " bytes still in buffer & " << m_context.application_buffer.size() << " bytes in application buffer";
  178. #endif
  179. } else {
  180. m_context.connection_finished = false;
  181. #ifdef TLS_DEBUG
  182. dbg() << "FINISHED";
  183. #endif
  184. }
  185. if (!m_context.application_buffer.size()) {
  186. m_context.connection_status = ConnectionStatus::Disconnected;
  187. return false;
  188. }
  189. }
  190. return true;
  191. }
  192. bool TLSv12::flush()
  193. {
  194. auto out_buffer = write_buffer().data();
  195. size_t out_buffer_index { 0 };
  196. size_t out_buffer_length = write_buffer().size();
  197. if (out_buffer_length == 0)
  198. return true;
  199. #ifdef TLS_DEBUG
  200. dbg() << "SENDING...";
  201. print_buffer(out_buffer, out_buffer_length);
  202. #endif
  203. if (Core::Socket::write(&out_buffer[out_buffer_index], out_buffer_length)) {
  204. write_buffer().clear();
  205. return true;
  206. }
  207. if (m_context.send_retries++ == 10) {
  208. // drop the records, we can't send
  209. #ifdef TLS_DEBUG
  210. dbg() << "Dropping " << write_buffer().size() << " bytes worth of TLS records as max retries has been reached";
  211. #endif
  212. write_buffer().clear();
  213. m_context.send_retries = 0;
  214. }
  215. return false;
  216. }
  217. }