Explicitly add python-numpy dependency to install-build-deps.
[chromium-blink-merge.git] / extensions / browser / api / cast_channel / cast_socket.h
blobb96fd8d4553e789dd39e969db971931166279104
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_
8 #include <queue>
9 #include <string>
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"
28 namespace net {
29 class AddressList;
30 class CertVerifier;
31 class SSLClientSocket;
32 class StreamSocket;
33 class TCPClientSocket;
34 class TransportSecurityState;
37 namespace extensions {
38 namespace core_api {
39 namespace cast_channel {
40 class CastMessage;
41 class Logger;
42 struct LastErrors;
43 class MessageFramer;
45 // Public interface of the CastSocket class.
46 class CastSocket : public ApiResource {
47 public:
48 explicit CastSocket(const std::string& owner_extension_id);
49 virtual ~CastSocket() {}
51 // Used by BrowserContextKeyedAPIFactory.
52 static const char* service_name() { return "CastSocketImplManager"; }
54 // Connects the channel to the peer. If successful, the channel will be in
55 // READY_STATE_OPEN. DO NOT delete the CastSocketImpl object in |callback|.
56 // Instead use Close().
57 // |callback| will be invoked with any ChannelError that occurred, or
58 // CHANNEL_ERROR_NONE if successful.
59 // |delegate| receives message receipt and error events.
60 // Ownership of |delegate| is transferred to this CastSocket.
61 virtual void Connect(scoped_ptr<CastTransport::Delegate> delegate,
62 base::Callback<void(ChannelError)> callback) = 0;
64 // Closes the channel if not already closed. On completion, the channel will
65 // be in READY_STATE_CLOSED.
67 // It is fine to delete this object in |callback|.
68 virtual void Close(const net::CompletionCallback& callback) = 0;
70 // The IP endpoint for the destination of the channel.
71 virtual const net::IPEndPoint& ip_endpoint() const = 0;
73 // Channel id generated by the ApiResourceManager.
74 virtual int id() const = 0;
76 // Sets the channel id generated by ApiResourceManager.
77 virtual void set_id(int id) = 0;
79 // The authentication level requested for the channel.
80 virtual ChannelAuthType channel_auth() const = 0;
82 // Returns a cast:// or casts:// URL for the channel endpoint.
83 // For backwards compatibility.
84 virtual std::string cast_url() const = 0;
86 // The ready state of the channel.
87 virtual ReadyState ready_state() const = 0;
89 // Returns the last error that occurred on this channel, or
90 // CHANNEL_ERROR_NONE if no error has occurred.
91 virtual ChannelError error_state() const = 0;
93 // Marks a socket as invalid due to an error. Errors close the socket
94 // and any further socket operations will return the error code
95 // net::SOCKET_NOT_CORRECTED.
96 // Setting the error state does not close the socket if it is open.
97 virtual void SetErrorState(ChannelError error_state) = 0;
99 // Returns a pointer to the socket's message transport layer. Can be used to
100 // send and receive CastMessages over the socket.
101 virtual CastTransport* transport() const = 0;
104 // This class implements a channel between Chrome and a Cast device using a TCP
105 // socket with SSL. The channel may authenticate that the receiver is a genuine
106 // Cast device. All CastSocketImpl objects must be used only on the IO thread.
108 // NOTE: Not called "CastChannel" to reduce confusion with the generated API
109 // code.
110 class CastSocketImpl : public CastSocket {
111 public:
112 // Creates a new CastSocket that connects to |ip_endpoint| with
113 // |channel_auth|. |owner_extension_id| is the id of the extension that opened
114 // the socket. |channel_auth| must not be CHANNEL_AUTH_NONE.
115 // Parameters:
116 // |owner_extension_id|: ID of the extension calling the API.
117 // |ip_endpoint|: IP address of the remote host.
118 // |channel_auth|: Authentication method used for connecting to a Cast
119 // receiver.
120 // |net_log|: Log of socket events.
121 // |connect_timeout|: Connection timeout interval.
122 // |logger|: Log of cast channel events.
123 CastSocketImpl(const std::string& owner_extension_id,
124 const net::IPEndPoint& ip_endpoint,
125 ChannelAuthType channel_auth,
126 net::NetLog* net_log,
127 const base::TimeDelta& connect_timeout,
128 const scoped_refptr<Logger>& logger);
130 // Ensures that the socket is closed.
131 virtual ~CastSocketImpl();
133 // CastSocket interface.
134 virtual void Connect(scoped_ptr<CastTransport::Delegate> delegate,
135 base::Callback<void(ChannelError)> callback) override;
136 virtual CastTransport* transport() const override;
137 virtual void Close(const net::CompletionCallback& callback) override;
138 const virtual net::IPEndPoint& ip_endpoint() const override;
139 virtual int id() const override;
140 virtual void set_id(int channel_id) override;
141 virtual ChannelAuthType channel_auth() const override;
142 virtual std::string cast_url() const override;
143 virtual ReadyState ready_state() const override;
144 virtual ChannelError error_state() const override;
146 // Required by ApiResourceManager.
147 static const char* service_name() { return "CastSocketManager"; }
149 protected:
150 // CastTransport::Delegate methods for receiving handshake messages.
151 class AuthTransportDelegate : public CastTransport::Delegate {
152 public:
153 AuthTransportDelegate(CastSocketImpl* socket);
155 // CastTransport::Delegate interface.
156 virtual void OnError(ChannelError error_state,
157 const LastErrors& last_errors) override;
158 virtual void OnMessage(const CastMessage& message) override;
160 private:
161 CastSocketImpl* socket_;
164 // Replaces the internally-constructed transport object with one provided
165 // by the caller (e.g. a mock).
166 void SetTransportForTesting(scoped_ptr<CastTransport> transport);
168 // Delegate for receiving handshake messages/errors.
169 AuthTransportDelegate auth_delegate_;
171 private:
172 FRIEND_TEST_ALL_PREFIXES(CastSocketTest, TestConnectAuthMessageCorrupted);
173 FRIEND_TEST_ALL_PREFIXES(CastSocketTest,
174 TestConnectChallengeReplyReceiveError);
175 FRIEND_TEST_ALL_PREFIXES(CastSocketTest,
176 TestConnectChallengeVerificationFails);
177 friend class AuthTransportDelegate;
178 friend class ApiResourceManager<CastSocketImpl>;
179 friend class CastSocketTest;
180 friend class TestCastSocket;
182 virtual void SetErrorState(ChannelError error_state) override;
184 // Frees resources and cancels pending callbacks. |ready_state_| will be set
185 // READY_STATE_CLOSED on completion. A no-op if |ready_state_| is already
186 // READY_STATE_CLOSED.
187 void CloseInternal();
189 // Creates an instance of TCPClientSocket.
190 virtual scoped_ptr<net::TCPClientSocket> CreateTcpSocket();
191 // Creates an instance of SSLClientSocket with the given underlying |socket|.
192 virtual scoped_ptr<net::SSLClientSocket> CreateSslSocket(
193 scoped_ptr<net::StreamSocket> socket);
194 // Extracts peer certificate from SSLClientSocket instance when the socket
195 // is in cert error state.
196 // Returns whether certificate is successfully extracted.
197 virtual bool ExtractPeerCert(std::string* cert);
198 // Verifies whether the challenge reply received from the peer is valid:
199 // 1. Signature in the reply is valid.
200 // 2. Certificate is rooted to a trusted CA.
201 virtual bool VerifyChallengeReply();
203 // Invoked by a cancelable closure when connection setup time
204 // exceeds the interval specified at |connect_timeout|.
205 void OnConnectTimeout();
207 /////////////////////////////////////////////////////////////////////////////
208 // Following methods work together to implement the following flow:
209 // 1. Create a new TCP socket and connect to it
210 // 2. Create a new SSL socket and try connecting to it
211 // 3. If connection fails due to invalid cert authority, then extract the
212 // peer certificate from the error.
213 // 4. Whitelist the peer certificate and try #1 and #2 again.
214 // 5. If SSL socket is connected successfully, and if protocol is casts://
215 // then issue an auth challenge request.
216 // 6. Validate the auth challenge response.
218 // Main method that performs connection state transitions.
219 void DoConnectLoop(int result);
220 // Each of the below Do* method is executed in the corresponding
221 // connection state. For example when connection state is TCP_CONNECT
222 // DoTcpConnect is called, and so on.
223 int DoTcpConnect();
224 int DoTcpConnectComplete(int result);
225 int DoSslConnect();
226 int DoSslConnectComplete(int result);
227 int DoAuthChallengeSend();
228 int DoAuthChallengeSendComplete(int result);
229 int DoAuthChallengeReplyComplete(int result);
230 /////////////////////////////////////////////////////////////////////////////
232 // Schedules asynchrous connection loop processing in the MessageLoop.
233 void PostTaskToStartConnectLoop(int result);
235 // Runs the external connection callback and resets it.
236 void DoConnectCallback();
238 virtual bool CalledOnValidThread() const;
240 virtual base::Timer* GetTimer();
242 void SetConnectState(proto::ConnectionState connect_state);
243 void SetReadyState(ReadyState ready_state);
245 base::ThreadChecker thread_checker_;
247 const std::string owner_extension_id_;
248 // The id of the channel.
249 int channel_id_;
250 // The IP endpoint that the the channel is connected to.
251 net::IPEndPoint ip_endpoint_;
252 // Receiver authentication requested for the channel.
253 ChannelAuthType channel_auth_;
254 // The NetLog for this service.
255 net::NetLog* net_log_;
256 // The NetLog source for this service.
257 net::NetLog::Source net_log_source_;
259 // Shared logging object, used to log CastSocket events for diagnostics.
260 scoped_refptr<Logger> logger_;
262 // CertVerifier is owned by us but should be deleted AFTER SSLClientSocket
263 // since in some cases the destructor of SSLClientSocket may call a method
264 // to cancel a cert verification request.
265 scoped_ptr<net::CertVerifier> cert_verifier_;
266 scoped_ptr<net::TransportSecurityState> transport_security_state_;
268 // Owned ptr to the underlying TCP socket.
269 scoped_ptr<net::TCPClientSocket> tcp_socket_;
271 // Owned ptr to the underlying SSL socket.
272 scoped_ptr<net::SSLClientSocket> socket_;
274 // Certificate of the peer. This field may be empty if the peer
275 // certificate is not yet fetched.
276 std::string peer_cert_;
278 // Reply received from the receiver to a challenge request.
279 scoped_ptr<CastMessage> challenge_reply_;
281 // Callback invoked when the socket is connected or fails to connect.
282 base::Callback<void(ChannelError)> connect_callback_;
284 // Callback invoked by |connect_timeout_timer_| to cancel the connection.
285 base::CancelableClosure connect_timeout_callback_;
287 // Duration to wait before timing out.
288 base::TimeDelta connect_timeout_;
290 // Timer invoked when the connection has timed out.
291 scoped_ptr<base::Timer> connect_timeout_timer_;
293 // Set when a timeout is triggered and the connection process has
294 // canceled.
295 bool is_canceled_;
297 // Connection flow state machine state.
298 proto::ConnectionState connect_state_;
300 // Write flow state machine state.
301 proto::WriteState write_state_;
303 // Read flow state machine state.
304 proto::ReadState read_state_;
306 // The last error encountered by the channel.
307 ChannelError error_state_;
309 // The current status of the channel.
310 ReadyState ready_state_;
312 // Task invoked to (re)start the connect loop. Canceled on entry to the
313 // connect loop.
314 base::CancelableClosure connect_loop_callback_;
316 // Task invoked to send the auth challenge. Canceled when the auth challenge
317 // has been sent.
318 base::CancelableClosure send_auth_challenge_callback_;
320 // Cast message formatting and parsing layer.
321 scoped_ptr<CastTransport> transport_;
323 // Caller's message read and error handling delegate.
324 scoped_ptr<CastTransport::Delegate> read_delegate_;
326 DISALLOW_COPY_AND_ASSIGN(CastSocketImpl);
328 } // namespace cast_channel
329 } // namespace core_api
330 } // namespace extensions
332 #endif // EXTENSIONS_BROWSER_API_CAST_CHANNEL_CAST_SOCKET_H_