Socket.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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/Timer.h>
  27. #include <LibCrypto/ASN1/DER.h>
  28. #include <LibCrypto/PK/Code/EMSA_PSS.h>
  29. #include <LibTLS/TLSv12.h>
  30. namespace TLS {
  31. Optional<ByteBuffer> TLSv12::read()
  32. {
  33. if (m_context.application_buffer.size()) {
  34. auto buf = m_context.application_buffer.slice(0, m_context.application_buffer.size());
  35. m_context.application_buffer.clear();
  36. return buf;
  37. }
  38. return {};
  39. }
  40. ByteBuffer TLSv12::read(size_t max_size)
  41. {
  42. if (m_context.application_buffer.size()) {
  43. auto length = min(m_context.application_buffer.size(), max_size);
  44. auto buf = m_context.application_buffer.slice(0, length);
  45. m_context.application_buffer = m_context.application_buffer.slice(length, m_context.application_buffer.size() - length);
  46. return buf;
  47. }
  48. return {};
  49. }
  50. ByteBuffer TLSv12::read_line(size_t max_size)
  51. {
  52. if (!can_read_line())
  53. return {};
  54. auto* start = m_context.application_buffer.data();
  55. auto* newline = (u8*)memchr(m_context.application_buffer.data(), '\n', m_context.application_buffer.size());
  56. ASSERT(newline);
  57. size_t offset = newline - start;
  58. if (offset > max_size)
  59. return {};
  60. auto buffer = ByteBuffer::copy(start, offset);
  61. m_context.application_buffer = m_context.application_buffer.slice(offset + 1, m_context.application_buffer.size() - offset - 1);
  62. return buffer;
  63. }
  64. bool TLSv12::write(const ByteBuffer& buffer)
  65. {
  66. if (m_context.connection_status != ConnectionStatus::Established) {
  67. #ifdef TLS_DEBUG
  68. dbg() << "write request while not connected";
  69. #endif
  70. return false;
  71. }
  72. PacketBuilder builder { MessageType::ApplicationData, m_context.version, buffer.size() };
  73. builder.append(buffer);
  74. auto packet = builder.build();
  75. update_packet(packet);
  76. write_packet(packet);
  77. return true;
  78. }
  79. bool TLSv12::connect(const String& hostname, int port)
  80. {
  81. set_sni(hostname);
  82. return Core::Socket::connect(hostname, port);
  83. }
  84. bool TLSv12::common_connect(const struct sockaddr* saddr, socklen_t length)
  85. {
  86. if (m_context.critical_error)
  87. return false;
  88. if (Core::Socket::is_connected()) {
  89. if (is_established()) {
  90. ASSERT_NOT_REACHED();
  91. } else {
  92. Core::Socket::close(); // reuse?
  93. }
  94. }
  95. auto packet = build_hello();
  96. write_packet(packet);
  97. Core::Socket::on_connected = [this] {
  98. Core::Socket::on_ready_to_read = [this] {
  99. read_from_socket();
  100. };
  101. write_into_socket();
  102. if (on_tls_connected)
  103. on_tls_connected();
  104. };
  105. bool success = Core::Socket::common_connect(saddr, length);
  106. if (!success)
  107. return false;
  108. return true;
  109. }
  110. void TLSv12::read_from_socket()
  111. {
  112. if (m_context.application_buffer.size() > 0) {
  113. deferred_invoke([&](auto&) { read_from_socket(); });
  114. if (on_tls_ready_to_read)
  115. on_tls_ready_to_read(*this);
  116. }
  117. if (!check_connection_state(true))
  118. return;
  119. flush();
  120. consume(Core::Socket::read(4096));
  121. }
  122. void TLSv12::write_into_socket()
  123. {
  124. #ifdef TLS_DEBUG
  125. dbg() << "Flushing cached records: " << m_context.tls_buffer.size() << " established? " << is_established();
  126. #endif
  127. m_has_scheduled_write_flush = false;
  128. if (!check_connection_state(false))
  129. return;
  130. flush();
  131. if (!is_established()) {
  132. deferred_invoke([this](auto&) { write_into_socket(); });
  133. m_has_scheduled_write_flush = true;
  134. return;
  135. }
  136. if (is_established() && !m_context.application_buffer.size()) // hey client, you still have stuff to read...
  137. if (on_tls_ready_to_write)
  138. on_tls_ready_to_write(*this);
  139. }
  140. bool TLSv12::check_connection_state(bool read)
  141. {
  142. if (!Core::Socket::is_open() || !Core::Socket::is_connected() || Core::Socket::eof()) {
  143. // an abrupt closure (the server is a jerk)
  144. #ifdef TLS_DEBUG
  145. dbg() << "Socket not open, assuming abrupt closure";
  146. #endif
  147. m_context.connection_finished = true;
  148. }
  149. if (m_context.critical_error) {
  150. #ifdef TLS_DEBUG
  151. dbg() << "CRITICAL ERROR " << m_context.critical_error << " :(";
  152. #endif
  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. #ifdef TLS_DEBUG
  164. 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";
  165. #endif
  166. } else {
  167. m_context.connection_finished = false;
  168. #ifdef TLS_DEBUG
  169. dbg() << "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. #ifdef TLS_DEBUG
  187. dbg() << "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. #ifdef TLS_DEBUG
  197. dbg() << "Dropping " << write_buffer().size() << " bytes worth of TLS records as max retries has been reached";
  198. #endif
  199. write_buffer().clear();
  200. m_context.send_retries = 0;
  201. }
  202. return false;
  203. }
  204. }