1 // Copyright 2014 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.
5 #ifndef EXTENSIONS_BROWSER_API_CAST_CHANNEL_CAST_SOCKET_H_
6 #define EXTENSIONS_BROWSER_API_CAST_CHANNEL_CAST_SOCKET_H_
11 #include "base/basictypes.h"
12 #include "base/cancelable_callback.h"
13 #include "base/gtest_prod_util.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/threading/thread_checker.h"
16 #include "base/timer/timer.h"
17 #include "extensions/browser/api/api_resource.h"
18 #include "extensions/browser/api/api_resource_manager.h"
19 #include "extensions/browser/api/cast_channel/cast_socket.h"
20 #include "extensions/browser/api/cast_channel/cast_transport.h"
21 #include "extensions/common/api/cast_channel.h"
22 #include "extensions/common/api/cast_channel/logging.pb.h"
23 #include "net/base/completion_callback.h"
24 #include "net/base/io_buffer.h"
25 #include "net/base/ip_endpoint.h"
26 #include "net/base/net_log.h"
31 class SSLClientSocket
;
33 class TCPClientSocket
;
34 class TransportSecurityState
;
37 namespace extensions
{
39 namespace cast_channel
{
45 // Cast device capabilities.
46 enum CastDeviceCapability
{
55 // Public interface of the CastSocket class.
56 class CastSocket
: public ApiResource
{
58 explicit CastSocket(const std::string
& owner_extension_id
);
59 ~CastSocket() override
{}
61 // Used by BrowserContextKeyedAPIFactory.
62 static const char* service_name() { return "CastSocketImplManager"; }
64 // Connects the channel to the peer. If successful, the channel will be in
65 // READY_STATE_OPEN. DO NOT delete the CastSocket object in |callback|.
66 // Instead use Close().
67 // |callback| will be invoked with any ChannelError that occurred, or
68 // CHANNEL_ERROR_NONE if successful.
69 // |delegate| receives message receipt and error events.
70 // Ownership of |delegate| is transferred to this CastSocket.
71 virtual void Connect(scoped_ptr
<CastTransport::Delegate
> delegate
,
72 base::Callback
<void(ChannelError
)> callback
) = 0;
74 // Closes the channel if not already closed. On completion, the channel will
75 // be in READY_STATE_CLOSED.
77 // It is fine to delete this object in |callback|.
78 virtual void Close(const net::CompletionCallback
& callback
) = 0;
80 // The IP endpoint for the destination of the channel.
81 virtual const net::IPEndPoint
& ip_endpoint() const = 0;
83 // Channel id generated by the ApiResourceManager.
84 virtual int id() const = 0;
86 // Sets the channel id generated by ApiResourceManager.
87 virtual void set_id(int id
) = 0;
89 // The authentication level requested for the channel.
90 virtual ChannelAuthType
channel_auth() const = 0;
92 // Returns a cast:// or casts:// URL for the channel endpoint.
93 // For backwards compatibility.
94 virtual std::string
cast_url() const = 0;
96 // The ready state of the channel.
97 virtual ReadyState
ready_state() const = 0;
99 // Returns the last error that occurred on this channel, or
100 // CHANNEL_ERROR_NONE if no error has occurred.
101 virtual ChannelError
error_state() const = 0;
103 // True when keep-alive signaling is handled for this socket.
104 virtual bool keep_alive() const = 0;
106 // Marks a socket as invalid due to an error. Errors close the socket
107 // and any further socket operations will return the error code
108 // net::SOCKET_NOT_CORRECTED.
109 // Setting the error state does not close the socket if it is open.
110 virtual void SetErrorState(ChannelError error_state
) = 0;
112 // Returns a pointer to the socket's message transport layer. Can be used to
113 // send and receive CastMessages over the socket.
114 virtual CastTransport
* transport() const = 0;
117 // This class implements a channel between Chrome and a Cast device using a TCP
118 // socket with SSL. The channel may authenticate that the receiver is a genuine
119 // Cast device. All CastSocketImpl objects must be used only on the IO thread.
121 // NOTE: Not called "CastChannel" to reduce confusion with the generated API
123 class CastSocketImpl
: public CastSocket
{
125 // Creates a new CastSocket that connects to |ip_endpoint| with
126 // |channel_auth|. |owner_extension_id| is the id of the extension that opened
127 // the socket. |channel_auth| must not be CHANNEL_AUTH_NONE.
129 // |owner_extension_id|: ID of the extension calling the API.
130 // |ip_endpoint|: IP address of the remote host.
131 // |channel_auth|: Authentication method used for connecting to a Cast
133 // |net_log|: Log of socket events.
134 // |connect_timeout|: Connection timeout interval.
135 // |logger|: Log of cast channel events.
136 CastSocketImpl(const std::string
& owner_extension_id
,
137 const net::IPEndPoint
& ip_endpoint
,
138 ChannelAuthType channel_auth
,
139 net::NetLog
* net_log
,
140 const base::TimeDelta
& connect_timeout
,
142 const scoped_refptr
<Logger
>& logger
,
143 long device_capabilities
);
145 // Ensures that the socket is closed.
146 ~CastSocketImpl() override
;
148 // CastSocket interface.
149 void Connect(scoped_ptr
<CastTransport::Delegate
> delegate
,
150 base::Callback
<void(ChannelError
)> callback
) override
;
151 CastTransport
* transport() const override
;
152 void Close(const net::CompletionCallback
& callback
) override
;
153 const net::IPEndPoint
& ip_endpoint() const override
;
154 int id() const override
;
155 void set_id(int channel_id
) override
;
156 ChannelAuthType
channel_auth() const override
;
157 std::string
cast_url() const override
;
158 ReadyState
ready_state() const override
;
159 ChannelError
error_state() const override
;
160 bool keep_alive() const override
;
162 // Required by ApiResourceManager.
163 static const char* service_name() { return "CastSocketManager"; }
166 // CastTransport::Delegate methods for receiving handshake messages.
167 class AuthTransportDelegate
: public CastTransport::Delegate
{
169 AuthTransportDelegate(CastSocketImpl
* socket
);
171 // CastTransport::Delegate interface.
172 void OnError(ChannelError error_state
,
173 const LastErrors
& last_errors
) override
;
174 void OnMessage(const CastMessage
& message
) override
;
175 void Start() override
;
178 CastSocketImpl
* socket_
;
181 // Replaces the internally-constructed transport object with one provided
182 // by the caller (e.g. a mock).
183 void SetTransportForTesting(scoped_ptr
<CastTransport
> transport
);
185 // Verifies whether the socket complies with cast channel policy.
186 // Audio only channel policy mandates that a device declaring a video out
187 // capability must not have a certificate with audio only policy.
188 bool VerifyChannelPolicy(const AuthResult
& result
);
190 // Delegate for receiving handshake messages/errors.
191 AuthTransportDelegate auth_delegate_
;
194 FRIEND_TEST_ALL_PREFIXES(CastSocketTest
, TestConnectAuthMessageCorrupted
);
195 FRIEND_TEST_ALL_PREFIXES(CastSocketTest
,
196 TestConnectChallengeReplyReceiveError
);
197 FRIEND_TEST_ALL_PREFIXES(CastSocketTest
,
198 TestConnectChallengeVerificationFails
);
199 friend class AuthTransportDelegate
;
200 friend class ApiResourceManager
<CastSocketImpl
>;
201 friend class CastSocketTest
;
202 friend class TestCastSocket
;
204 void SetErrorState(ChannelError error_state
) override
;
206 // Frees resources and cancels pending callbacks. |ready_state_| will be set
207 // READY_STATE_CLOSED on completion. A no-op if |ready_state_| is already
208 // READY_STATE_CLOSED.
209 void CloseInternal();
211 // Creates an instance of TCPClientSocket.
212 virtual scoped_ptr
<net::TCPClientSocket
> CreateTcpSocket();
213 // Creates an instance of SSLClientSocket with the given underlying |socket|.
214 virtual scoped_ptr
<net::SSLClientSocket
> CreateSslSocket(
215 scoped_ptr
<net::StreamSocket
> socket
);
216 // Extracts peer certificate from SSLClientSocket instance when the socket
217 // is in cert error state.
218 // Returns whether certificate is successfully extracted.
219 virtual bool ExtractPeerCert(std::string
* cert
);
220 // Verifies whether the challenge reply received from the peer is valid:
221 // 1. Signature in the reply is valid.
222 // 2. Certificate is rooted to a trusted CA.
223 virtual bool VerifyChallengeReply();
225 // Invoked by a cancelable closure when connection setup time
226 // exceeds the interval specified at |connect_timeout|.
227 void OnConnectTimeout();
229 /////////////////////////////////////////////////////////////////////////////
230 // Following methods work together to implement the following flow:
231 // 1. Create a new TCP socket and connect to it
232 // 2. Create a new SSL socket and try connecting to it
233 // 3. If connection fails due to invalid cert authority, then extract the
234 // peer certificate from the error.
235 // 4. Whitelist the peer certificate and try #1 and #2 again.
236 // 5. If SSL socket is connected successfully, and if protocol is casts://
237 // then issue an auth challenge request.
238 // 6. Validate the auth challenge response.
240 // Main method that performs connection state transitions.
241 void DoConnectLoop(int result
);
242 // Each of the below Do* method is executed in the corresponding
243 // connection state. For example when connection state is TCP_CONNECT
244 // DoTcpConnect is called, and so on.
246 int DoTcpConnectComplete(int result
);
248 int DoSslConnectComplete(int result
);
249 int DoAuthChallengeSend();
250 int DoAuthChallengeSendComplete(int result
);
251 int DoAuthChallengeReplyComplete(int result
);
252 /////////////////////////////////////////////////////////////////////////////
254 // Schedules asynchrous connection loop processing in the MessageLoop.
255 void PostTaskToStartConnectLoop(int result
);
257 // Runs the external connection callback and resets it.
258 void DoConnectCallback();
260 virtual bool CalledOnValidThread() const;
262 virtual base::Timer
* GetTimer();
264 void SetConnectState(proto::ConnectionState connect_state
);
265 void SetReadyState(ReadyState ready_state
);
267 base::ThreadChecker thread_checker_
;
269 const std::string owner_extension_id_
;
270 // The id of the channel.
272 // The IP endpoint that the the channel is connected to.
273 net::IPEndPoint ip_endpoint_
;
274 // Receiver authentication requested for the channel.
275 ChannelAuthType channel_auth_
;
276 // The NetLog for this service.
277 net::NetLog
* net_log_
;
278 // The NetLog source for this service.
279 net::NetLog::Source net_log_source_
;
280 // True when keep-alive signaling should be handled for this socket.
283 // Shared logging object, used to log CastSocket events for diagnostics.
284 scoped_refptr
<Logger
> logger_
;
286 // CertVerifier is owned by us but should be deleted AFTER SSLClientSocket
287 // since in some cases the destructor of SSLClientSocket may call a method
288 // to cancel a cert verification request.
289 scoped_ptr
<net::CertVerifier
> cert_verifier_
;
290 scoped_ptr
<net::TransportSecurityState
> transport_security_state_
;
292 // Owned ptr to the underlying TCP socket.
293 scoped_ptr
<net::TCPClientSocket
> tcp_socket_
;
295 // Owned ptr to the underlying SSL socket.
296 scoped_ptr
<net::SSLClientSocket
> socket_
;
298 // Certificate of the peer. This field may be empty if the peer
299 // certificate is not yet fetched.
300 std::string peer_cert_
;
302 // Reply received from the receiver to a challenge request.
303 scoped_ptr
<CastMessage
> challenge_reply_
;
305 // Callback invoked when the socket is connected or fails to connect.
306 base::Callback
<void(ChannelError
)> connect_callback_
;
308 // Callback invoked by |connect_timeout_timer_| to cancel the connection.
309 base::CancelableClosure connect_timeout_callback_
;
311 // Duration to wait before timing out.
312 base::TimeDelta connect_timeout_
;
314 // Timer invoked when the connection has timed out.
315 scoped_ptr
<base::Timer
> connect_timeout_timer_
;
317 // Set when a timeout is triggered and the connection process has
321 // Capabilities declared by the cast device.
322 long device_capabilities_
;
324 // Connection flow state machine state.
325 proto::ConnectionState connect_state_
;
327 // Write flow state machine state.
328 proto::WriteState write_state_
;
330 // Read flow state machine state.
331 proto::ReadState read_state_
;
333 // The last error encountered by the channel.
334 ChannelError error_state_
;
336 // The current status of the channel.
337 ReadyState ready_state_
;
339 // Task invoked to (re)start the connect loop. Canceled on entry to the
341 base::CancelableClosure connect_loop_callback_
;
343 // Task invoked to send the auth challenge. Canceled when the auth challenge
345 base::CancelableClosure send_auth_challenge_callback_
;
347 // Cast message formatting and parsing layer.
348 scoped_ptr
<CastTransport
> transport_
;
350 // Caller's message read and error handling delegate.
351 scoped_ptr
<CastTransport::Delegate
> read_delegate_
;
353 DISALLOW_COPY_AND_ASSIGN(CastSocketImpl
);
355 } // namespace cast_channel
356 } // namespace core_api
357 } // namespace extensions
359 #endif // EXTENSIONS_BROWSER_API_CAST_CHANNEL_CAST_SOCKET_H_