TLSv12WebSocketConnectionImpl.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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::connect(connection.url().host(), connection.url().port_or_default()).release_value_but_fixme_should_propagate_errors();
  23. m_socket->on_tls_error = [this](TLS::AlertDescription) {
  24. on_connection_error();
  25. };
  26. m_socket->on_ready_to_read = [this] {
  27. on_ready_to_read();
  28. };
  29. m_socket->on_tls_finished = [this] {
  30. on_connection_error();
  31. };
  32. m_socket->on_tls_certificate_request = [](auto&) {
  33. // FIXME : Once we handle TLS certificate requests, handle it here as well.
  34. };
  35. on_connected();
  36. }
  37. bool TLSv12WebSocketConnectionImpl::send(ReadonlyBytes data)
  38. {
  39. return m_socket->write_or_error(data);
  40. }
  41. bool TLSv12WebSocketConnectionImpl::can_read_line()
  42. {
  43. return m_socket->can_read_line();
  44. }
  45. String TLSv12WebSocketConnectionImpl::read_line(size_t size)
  46. {
  47. return m_socket->read_line(size);
  48. }
  49. bool TLSv12WebSocketConnectionImpl::can_read()
  50. {
  51. return m_socket->can_read();
  52. }
  53. ByteBuffer TLSv12WebSocketConnectionImpl::read(int max_size)
  54. {
  55. auto buffer = ByteBuffer::create_uninitialized(max_size).release_value_but_fixme_should_propagate_errors();
  56. auto nread = m_socket->read(buffer).release_value_but_fixme_should_propagate_errors();
  57. return buffer.slice(0, nread);
  58. }
  59. bool TLSv12WebSocketConnectionImpl::eof()
  60. {
  61. return m_socket->is_eof();
  62. }
  63. void TLSv12WebSocketConnectionImpl::discard_connection()
  64. {
  65. if (!m_socket)
  66. return;
  67. m_socket->on_tls_error = nullptr;
  68. m_socket->on_tls_finished = nullptr;
  69. m_socket->on_tls_certificate_request = nullptr;
  70. m_socket->on_ready_to_read = nullptr;
  71. m_socket = nullptr;
  72. }
  73. }