1 // Copyright 2019 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef CAST_COMMON_PUBLIC_CAST_SOCKET_H_
6 #define CAST_COMMON_PUBLIC_CAST_SOCKET_H_
7
8 #include <array>
9 #include <memory>
10 #include <vector>
11
12 #include "platform/api/tls_connection.h"
13 #include "util/weak_ptr.h"
14
15 namespace cast {
16 namespace channel {
17 class CastMessage;
18 } // namespace channel
19 } // namespace cast
20
21 namespace openscreen {
22 namespace cast {
23
24 // Represents a simple message-oriented socket for communicating with the Cast
25 // V2 protocol. It isn't thread-safe, so it should only be used on the same
26 // TaskRunner thread as its TlsConnection.
27 class CastSocket : public TlsConnection::Client {
28 public:
29 class Client {
30 public:
31
32 // Called when a terminal error on |socket| has occurred.
33 virtual void OnError(CastSocket* socket, Error error) = 0;
34
35 virtual void OnMessage(CastSocket* socket,
36 ::cast::channel::CastMessage message) = 0;
37
38 protected:
39 virtual ~Client();
40 };
41
42 CastSocket(std::unique_ptr<TlsConnection> connection, Client* client);
43 ~CastSocket();
44
45 // Sends |message| immediately unless the underlying TLS connection is
46 // write-blocked, in which case |message| will be queued. An error will be
47 // returned if |message| cannot be serialized for any reason, even while
48 // write-blocked.
49 [[nodiscard]] Error Send(const ::cast::channel::CastMessage& message);
50
51 void SetClient(Client* client);
52
53 std::array<uint8_t, 2> GetSanitizedIpAddress();
54
socket_id()55 int socket_id() const { return socket_id_; }
56
set_audio_only(bool audio_only)57 void set_audio_only(bool audio_only) { audio_only_ = audio_only; }
audio_only()58 bool audio_only() const { return audio_only_; }
59
60 // TlsConnection::Client overrides.
61 void OnError(TlsConnection* connection, Error error) override;
62 void OnRead(TlsConnection* connection, std::vector<uint8_t> block) override;
63
GetWeakPtr()64 WeakPtr<CastSocket> GetWeakPtr() const { return weak_factory_.GetWeakPtr(); }
65
66 private:
67 enum class State : bool {
68 kOpen = true,
69 kError = false,
70 };
71
72 static int g_next_socket_id_;
73
74 const std::unique_ptr<TlsConnection> connection_;
75 Client* client_; // May never be null.
76 const int socket_id_;
77 bool audio_only_ = false;
78 std::vector<uint8_t> read_buffer_;
79 State state_ = State::kOpen;
80
81 WeakPtrFactory<CastSocket> weak_factory_{this};
82 };
83
84 // Returns socket->socket_id() if |socket| is not null, otherwise 0.
ToCastSocketId(CastSocket * socket)85 constexpr int ToCastSocketId(CastSocket* socket) {
86 return socket ? socket->socket_id() : 0;
87 }
88
89 } // namespace cast
90 } // namespace openscreen
91
92 #endif // CAST_COMMON_PUBLIC_CAST_SOCKET_H_
93