TLSv12WebSocketConnectionImpl.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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->on_tls_ready_to_write = [this](auto&) {
  31. on_connected();
  32. };
  33. m_socket->on_tls_finished = [this] {
  34. on_connection_error();
  35. };
  36. m_socket->on_tls_certificate_request = [](auto&) {
  37. // FIXME : Once we handle TLS certificate requests, handle it here as well.
  38. };
  39. bool success = m_socket->connect(connection.url().host(), connection.url().port());
  40. if (!success) {
  41. deferred_invoke([this] {
  42. on_connection_error();
  43. });
  44. }
  45. }
  46. bool TLSv12WebSocketConnectionImpl::send(ReadonlyBytes data)
  47. {
  48. return m_socket->write(data);
  49. }
  50. bool TLSv12WebSocketConnectionImpl::can_read_line()
  51. {
  52. return m_socket->can_read_line();
  53. }
  54. String TLSv12WebSocketConnectionImpl::read_line(size_t size)
  55. {
  56. return m_socket->read_line(size);
  57. }
  58. bool TLSv12WebSocketConnectionImpl::can_read()
  59. {
  60. return m_socket->can_read();
  61. }
  62. ByteBuffer TLSv12WebSocketConnectionImpl::read(int max_size)
  63. {
  64. return m_socket->read(max_size);
  65. }
  66. bool TLSv12WebSocketConnectionImpl::eof()
  67. {
  68. return m_socket->eof();
  69. }
  70. void TLSv12WebSocketConnectionImpl::discard_connection()
  71. {
  72. if (!m_socket)
  73. return;
  74. m_socket->on_tls_connected = nullptr;
  75. m_socket->on_tls_error = nullptr;
  76. m_socket->on_tls_finished = nullptr;
  77. m_socket->on_tls_certificate_request = nullptr;
  78. m_socket->on_ready_to_read = nullptr;
  79. remove_child(*m_socket);
  80. m_socket = nullptr;
  81. }
  82. }