TLSv12WebSocketConnectionImpl.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright (c) 2021, Dex♪ <dexes.ttp@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWebSocket/Impl/TLSv12WebSocketConnectionImpl.h>
  7. namespace WebSocket {
  8. TLSv12WebSocketConnectionImpl::TLSv12WebSocketConnectionImpl(Core::Object* parent)
  9. : AbstractWebSocketImpl(parent)
  10. {
  11. }
  12. TLSv12WebSocketConnectionImpl::~TLSv12WebSocketConnectionImpl()
  13. {
  14. discard_connection();
  15. }
  16. void TLSv12WebSocketConnectionImpl::connect(ConnectionInfo const& connection)
  17. {
  18. VERIFY(!m_socket);
  19. VERIFY(on_connected);
  20. VERIFY(on_connection_error);
  21. VERIFY(on_ready_to_read);
  22. m_socket = TLS::TLSv12::construct(this);
  23. m_socket->set_root_certificates(DefaultRootCACertificates::the().certificates());
  24. m_socket->on_tls_error = [this](TLS::AlertDescription) {
  25. on_connection_error();
  26. };
  27. m_socket->on_tls_ready_to_read = [this](auto&) {
  28. on_ready_to_read();
  29. };
  30. m_socket->set_on_tls_ready_to_write([this](auto& tls) {
  31. tls.set_on_tls_ready_to_write(nullptr);
  32. on_connected();
  33. });
  34. m_socket->on_tls_finished = [this] {
  35. on_connection_error();
  36. };
  37. m_socket->on_tls_certificate_request = [](auto&) {
  38. // FIXME : Once we handle TLS certificate requests, handle it here as well.
  39. };
  40. bool success = m_socket->connect(connection.url().host(), connection.url().port_or_default());
  41. if (!success) {
  42. deferred_invoke([this] {
  43. on_connection_error();
  44. });
  45. }
  46. }
  47. bool TLSv12WebSocketConnectionImpl::send(ReadonlyBytes data)
  48. {
  49. return m_socket->write(data);
  50. }
  51. bool TLSv12WebSocketConnectionImpl::can_read_line()
  52. {
  53. return m_socket->can_read_line();
  54. }
  55. String TLSv12WebSocketConnectionImpl::read_line(size_t size)
  56. {
  57. return m_socket->read_line(size);
  58. }
  59. bool TLSv12WebSocketConnectionImpl::can_read()
  60. {
  61. return m_socket->can_read();
  62. }
  63. ByteBuffer TLSv12WebSocketConnectionImpl::read(int max_size)
  64. {
  65. return m_socket->read(max_size);
  66. }
  67. bool TLSv12WebSocketConnectionImpl::eof()
  68. {
  69. return m_socket->eof();
  70. }
  71. void TLSv12WebSocketConnectionImpl::discard_connection()
  72. {
  73. if (!m_socket)
  74. return;
  75. m_socket->on_tls_connected = nullptr;
  76. m_socket->on_tls_error = nullptr;
  77. m_socket->on_tls_finished = nullptr;
  78. m_socket->on_tls_certificate_request = nullptr;
  79. m_socket->on_ready_to_read = nullptr;
  80. remove_child(*m_socket);
  81. m_socket = nullptr;
  82. }
  83. }