Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(159)

Side by Side Diff: chrome/browser/extensions/api/cast_channel/cast_socket.cc

Issue 79673003: Refactor CastSocket code for the following: (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: Created 7 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright 2013 The Chromium Authors. All rights reserved. 1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/extensions/api/cast_channel/cast_socket.h" 5 #include "chrome/browser/extensions/api/cast_channel/cast_socket.h"
6 6
7 #include <string.h> 7 #include <string.h>
8 8
9 #include "base/bind.h" 9 #include "base/bind.h"
10 #include "base/callback_helpers.h" 10 #include "base/callback_helpers.h"
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after
57 template <> 57 template <>
58 ProfileKeyedAPIFactory<ApiResourceManager<api::cast_channel::CastSocket> >* 58 ProfileKeyedAPIFactory<ApiResourceManager<api::cast_channel::CastSocket> >*
59 ApiResourceManager<api::cast_channel::CastSocket>::GetFactoryInstance() { 59 ApiResourceManager<api::cast_channel::CastSocket>::GetFactoryInstance() {
60 return &g_factory.Get(); 60 return &g_factory.Get();
61 } 61 }
62 62
63 namespace api { 63 namespace api {
64 namespace cast_channel { 64 namespace cast_channel {
65 65
66 const uint32 kMaxMessageSize = 65536; 66 const uint32 kMaxMessageSize = 65536;
67 // Don't use sizeof(MessageHeader) because of alignment; instead, sum the
68 // sizeof() for the fields.
69 const uint32 kMessageHeaderSize = sizeof(uint32);
67 70
68 CastSocket::CastSocket(const std::string& owner_extension_id, 71 CastSocket::CastSocket(const std::string& owner_extension_id,
69 const GURL& url, 72 const GURL& url,
70 CastSocket::Delegate* delegate, 73 CastSocket::Delegate* delegate,
71 net::NetLog* net_log) : 74 net::NetLog* net_log) :
72 ApiResource(owner_extension_id), 75 ApiResource(owner_extension_id),
73 channel_id_(0), 76 channel_id_(0),
74 url_(url), 77 url_(url),
75 delegate_(delegate), 78 delegate_(delegate),
76 auth_required_(false), 79 auth_required_(false),
77 error_state_(CHANNEL_ERROR_NONE),
78 ready_state_(READY_STATE_NONE),
79 write_callback_pending_(false),
80 read_callback_pending_(false),
81 current_message_size_(0), 80 current_message_size_(0),
82 net_log_(net_log), 81 net_log_(net_log),
83 next_state_(CONN_STATE_NONE), 82 connect_state_(CONN_STATE_NONE),
84 in_connect_loop_(false) { 83 write_state_(WRITE_STATE_NONE),
84 read_state_(READ_STATE_NONE),
85 error_state_(CHANNEL_ERROR_NONE),
86 ready_state_(READY_STATE_NONE) {
85 DCHECK(net_log_); 87 DCHECK(net_log_);
86 net_log_source_.type = net::NetLog::SOURCE_SOCKET; 88 net_log_source_.type = net::NetLog::SOURCE_SOCKET;
87 net_log_source_.id = net_log_->NextID(); 89 net_log_source_.id = net_log_->NextID();
88 90
89 // We reuse these buffers for each message. 91 // Reuse these buffers for each message.
90 header_read_buffer_ = new net::GrowableIOBuffer(); 92 header_read_buffer_ = new net::GrowableIOBuffer();
91 header_read_buffer_->SetCapacity(kMessageHeaderSize); 93 header_read_buffer_->SetCapacity(kMessageHeaderSize);
92 body_read_buffer_ = new net::GrowableIOBuffer(); 94 body_read_buffer_ = new net::GrowableIOBuffer();
93 body_read_buffer_->SetCapacity(kMaxMessageSize); 95 body_read_buffer_->SetCapacity(kMaxMessageSize);
94 current_read_buffer_ = header_read_buffer_; 96 current_read_buffer_ = header_read_buffer_;
95 } 97 }
96 98
97 CastSocket::~CastSocket() { } 99 CastSocket::~CastSocket() { }
98 100
99 const GURL& CastSocket::url() const { 101 const GURL& CastSocket::url() const {
100 return url_; 102 return url_;
101 } 103 }
102 104
103 scoped_ptr<net::TCPClientSocket> CastSocket::CreateTcpSocket() { 105 scoped_ptr<net::TCPClientSocket> CastSocket::CreateTcpSocket() {
104 net::AddressList addresses(ip_endpoint_); 106 net::AddressList addresses(ip_endpoint_);
105 scoped_ptr<net::TCPClientSocket> tcp_socket( 107 return scoped_ptr<net::TCPClientSocket>(
106 new net::TCPClientSocket(addresses, net_log_, net_log_source_)); 108 new net::TCPClientSocket(addresses, net_log_, net_log_source_));
107 // Options cannot be set on the TCPClientSocket yet, because the 109 // Options cannot be set on the TCPClientSocket yet, because the
108 // underlying platform socket will not be created until we Bind() 110 // underlying platform socket will not be created until Bind()
109 // or Connect() it. 111 // or Connect() is called.
110 return tcp_socket.Pass();
111 } 112 }
112 113
113 scoped_ptr<net::SSLClientSocket> CastSocket::CreateSslSocket() { 114 scoped_ptr<net::SSLClientSocket> CastSocket::CreateSslSocket(
115 scoped_ptr<net::StreamSocket> socket) {
114 net::SSLConfig ssl_config; 116 net::SSLConfig ssl_config;
115 // If a peer cert was extracted in a previous attempt to connect, then 117 // If a peer cert was extracted in a previous attempt to connect, then
116 // whitelist that cert. 118 // whitelist that cert.
117 if (!peer_cert_.empty()) { 119 if (!peer_cert_.empty()) {
118 net::SSLConfig::CertAndStatus cert_and_status; 120 net::SSLConfig::CertAndStatus cert_and_status;
119 cert_and_status.cert_status = net::CERT_STATUS_AUTHORITY_INVALID; 121 cert_and_status.cert_status = net::CERT_STATUS_AUTHORITY_INVALID;
120 cert_and_status.der_cert = peer_cert_; 122 cert_and_status.der_cert = peer_cert_;
121 ssl_config.allowed_bad_certs.push_back(cert_and_status); 123 ssl_config.allowed_bad_certs.push_back(cert_and_status);
122 } 124 }
123 125
124 cert_verifier_.reset(net::CertVerifier::CreateDefault()); 126 cert_verifier_.reset(net::CertVerifier::CreateDefault());
125 transport_security_state_.reset(new net::TransportSecurityState); 127 transport_security_state_.reset(new net::TransportSecurityState);
126 net::SSLClientSocketContext context; 128 net::SSLClientSocketContext context;
127 // CertVerifier and TransportSecurityState are owned by us, not the 129 // CertVerifier and TransportSecurityState are owned by us, not the
128 // context object. 130 // context object.
129 context.cert_verifier = cert_verifier_.get(); 131 context.cert_verifier = cert_verifier_.get();
130 context.transport_security_state = transport_security_state_.get(); 132 context.transport_security_state = transport_security_state_.get();
131 133
132 scoped_ptr<net::ClientSocketHandle> connection(new net::ClientSocketHandle); 134 scoped_ptr<net::ClientSocketHandle> connection(new net::ClientSocketHandle);
133 connection->SetSocket(tcp_socket_.PassAs<net::StreamSocket>()); 135 connection->SetSocket(socket.Pass());
134 net::HostPortPair host_and_port = net::HostPortPair::FromIPEndPoint( 136 net::HostPortPair host_and_port = net::HostPortPair::FromIPEndPoint(
135 ip_endpoint_); 137 ip_endpoint_);
136 138
137 return net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket( 139 return net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket(
138 connection.Pass(), host_and_port, ssl_config, context); 140 connection.Pass(), host_and_port, ssl_config, context);
139 } 141 }
140 142
141 bool CastSocket::ExtractPeerCert(std::string* cert) { 143 bool CastSocket::ExtractPeerCert(std::string* cert) {
142 DCHECK(cert); 144 DCHECK(cert);
143 DCHECK(peer_cert_.empty()); 145 DCHECK(peer_cert_.empty());
144 net::SSLInfo ssl_info; 146 net::SSLInfo ssl_info;
145 if (!socket_->GetSSLInfo(&ssl_info) || !ssl_info.cert.get()) 147 if (!socket_->GetSSLInfo(&ssl_info) || !ssl_info.cert.get())
146 return false; 148 return false;
147 bool result = net::X509Certificate::GetDEREncoded( 149 bool result = net::X509Certificate::GetDEREncoded(
148 ssl_info.cert->os_cert_handle(), cert); 150 ssl_info.cert->os_cert_handle(), cert);
149 if (result) 151 if (result)
150 VLOG(1) << "Successfully extracted peer certificate: " << *cert; 152 VLOG(1) << "Successfully extracted peer certificate: " << *cert;
151 return result; 153 return result;
152 } 154 }
153 155
154 int CastSocket::SendAuthChallenge() { 156 bool CastSocket::VerifyChallengeReply() {
155 CastMessage challenge_message; 157 return AuthenticateChallengeReply(*challenge_reply_.get(), peer_cert_);
156 CreateAuthChallengeMessage(&challenge_message);
157 VLOG(1) << "Sending challenge: " << CastMessageToString(challenge_message);
158 int result = SendMessageInternal(
159 challenge_message,
160 base::Bind(&CastSocket::OnChallengeEvent, AsWeakPtr()));
161 return (result < 0) ? result : net::OK;
162 }
163
164 int CastSocket::ReadAuthChallengeReply() {
165 int result = ReadData();
166 return (result < 0) ? result : net::OK;
167 }
168
169 void CastSocket::OnConnectComplete(int result) {
170 int rv = DoConnectLoop(result);
171 if (rv != net::ERR_IO_PENDING)
172 DoConnectCallback(rv);
173 }
174
175 void CastSocket::OnChallengeEvent(int result) {
176 // result >= 0 means read or write succeeded synchronously.
177 int rv = DoConnectLoop(result >= 0 ? net::OK : result);
178 if (rv != net::ERR_IO_PENDING)
179 DoConnectCallback(rv);
180 } 158 }
181 159
182 void CastSocket::Connect(const net::CompletionCallback& callback) { 160 void CastSocket::Connect(const net::CompletionCallback& callback) {
183 DCHECK(CalledOnValidThread()); 161 DCHECK(CalledOnValidThread());
184 int result = net::ERR_CONNECTION_FAILED;
185 VLOG(1) << "Connect readyState = " << ready_state_; 162 VLOG(1) << "Connect readyState = " << ready_state_;
186 if (ready_state_ != READY_STATE_NONE) { 163 if (ready_state_ != READY_STATE_NONE) {
187 callback.Run(result); 164 callback.Run(net::ERR_CONNECTION_FAILED);
188 return; 165 return;
189 } 166 }
190 if (!ParseChannelUrl(url_)) { 167 if (!ParseChannelUrl(url_)) {
191 CloseWithError(cast_channel::CHANNEL_ERROR_CONNECT_ERROR); 168 callback.Run(net::ERR_CONNECTION_FAILED);
192 callback.Run(result);
193 return; 169 return;
194 } 170 }
171
172 ready_state_ = READY_STATE_CONNECTING;
195 connect_callback_ = callback; 173 connect_callback_ = callback;
196 next_state_ = CONN_STATE_TCP_CONNECT; 174 connect_state_ = CONN_STATE_TCP_CONNECT;
197 int rv = DoConnectLoop(net::OK); 175 DoConnectLoop(net::OK);
198 if (rv != net::ERR_IO_PENDING) 176 }
199 DoConnectCallback(rv); 177
178 void CastSocket::PostTaskToStartConnectLoop(int result) {
179 DCHECK(CalledOnValidThread());
180 base::MessageLoop::current()->PostTask(
181 FROM_HERE,
182 base::Bind(&CastSocket::DoConnectLoop, AsWeakPtr(), result));
200 } 183 }
201 184
202 // This method performs the state machine transitions for connection flow. 185 // This method performs the state machine transitions for connection flow.
203 // There are two entry points to this method: 186 // There are two entry points to this method:
204 // 1. public Connect method: this starts the flow 187 // 1. Connect method: this starts the flow
205 // 2. OnConnectComplete: callback method called when an async operation 188 // 2. Callback from network operations that finish asynchronously
206 // is done. OnConnectComplete calls this method to continue the state 189 void CastSocket::DoConnectLoop(int result) {
207 // machine transitions.
208 int CastSocket::DoConnectLoop(int result) {
209 // Avoid re-entrancy as a result of synchronous completion.
210 if (in_connect_loop_)
211 return net::ERR_IO_PENDING;
212 in_connect_loop_ = true;
213
214 // Network operations can either finish synchronously or asynchronously. 190 // Network operations can either finish synchronously or asynchronously.
215 // This method executes the state machine transitions in a loop so that 191 // This method executes the state machine transitions in a loop so that
216 // correct state transitions happen even when network operations finish 192 // correct state transitions happen even when network operations finish
217 // synchronously. 193 // synchronously.
218 int rv = result; 194 int rv = result;
219 do { 195 do {
220 ConnectionState state = next_state_; 196 ConnectionState state = connect_state_;
221 // All the Do* methods do not set next_state_ in case of an 197 // Default to CONN_STATE_NONE, which breaks the processing loop if any
222 // error. So set next_state_ to NONE to figure out if the Do* 198 // handler fails to transition to another state to continue processing.
223 // method changed state or not. 199 connect_state_ = CONN_STATE_NONE;
224 next_state_ = CONN_STATE_NONE;
225 switch (state) { 200 switch (state) {
226 case CONN_STATE_TCP_CONNECT: 201 case CONN_STATE_TCP_CONNECT:
227 rv = DoTcpConnect(); 202 rv = DoTcpConnect();
228 break; 203 break;
229 case CONN_STATE_TCP_CONNECT_COMPLETE: 204 case CONN_STATE_TCP_CONNECT_COMPLETE:
230 rv = DoTcpConnectComplete(rv); 205 rv = DoTcpConnectComplete(rv);
231 break; 206 break;
232 case CONN_STATE_SSL_CONNECT: 207 case CONN_STATE_SSL_CONNECT:
233 DCHECK_EQ(net::OK, rv); 208 DCHECK_EQ(net::OK, rv);
234 rv = DoSslConnect(); 209 rv = DoSslConnect();
235 break; 210 break;
236 case CONN_STATE_SSL_CONNECT_COMPLETE: 211 case CONN_STATE_SSL_CONNECT_COMPLETE:
237 rv = DoSslConnectComplete(rv); 212 rv = DoSslConnectComplete(rv);
238 break; 213 break;
239 case CONN_STATE_AUTH_CHALLENGE_SEND: 214 case CONN_STATE_AUTH_CHALLENGE_SEND:
240 rv = DoAuthChallengeSend(); 215 rv = DoAuthChallengeSend();
241 break; 216 break;
242 case CONN_STATE_AUTH_CHALLENGE_SEND_COMPLETE: 217 case CONN_STATE_AUTH_CHALLENGE_SEND_COMPLETE:
243 rv = DoAuthChallengeSendComplete(rv); 218 rv = DoAuthChallengeSendComplete(rv);
244 break; 219 break;
245 case CONN_STATE_AUTH_CHALLENGE_REPLY_COMPLETE: 220 case CONN_STATE_AUTH_CHALLENGE_REPLY_COMPLETE:
246 rv = DoAuthChallengeReplyComplete(rv); 221 rv = DoAuthChallengeReplyComplete(rv);
247 break; 222 break;
248
249 default: 223 default:
250 NOTREACHED() << "BUG in CastSocket state machine code"; 224 NOTREACHED() << "BUG in connect flow. Unknown state: " << state;
251 break; 225 break;
252 } 226 }
253 } while (rv != net::ERR_IO_PENDING && next_state_ != CONN_STATE_NONE); 227 } while (rv != net::ERR_IO_PENDING && connect_state_ != CONN_STATE_NONE);
254 // Get out of the loop either when: 228 // Get out of the loop either when:
255 // a. A network operation is pending, OR 229 // a. A network operation is pending, OR
256 // b. The Do* method called did not change state 230 // b. The Do* method called did not change state
257 231
258 in_connect_loop_ = false; 232 // Connect loop is finished: if there is no pending IO invoke the callback.
259 233 if (rv != net::ERR_IO_PENDING)
260 return rv; 234 DoConnectCallback(rv);
261 } 235 }
262 236
263 int CastSocket::DoTcpConnect() { 237 int CastSocket::DoTcpConnect() {
264 VLOG(1) << "DoTcpConnect"; 238 VLOG(1) << "DoTcpConnect";
265 next_state_ = CONN_STATE_TCP_CONNECT_COMPLETE; 239 connect_state_ = CONN_STATE_TCP_CONNECT_COMPLETE;
266 tcp_socket_ = CreateTcpSocket(); 240 tcp_socket_ = CreateTcpSocket();
267 return tcp_socket_->Connect( 241 return tcp_socket_->Connect(
268 base::Bind(&CastSocket::OnConnectComplete, AsWeakPtr())); 242 base::Bind(&CastSocket::DoConnectLoop, AsWeakPtr()));
269 } 243 }
270 244
271 int CastSocket::DoTcpConnectComplete(int result) { 245 int CastSocket::DoTcpConnectComplete(int result) {
272 VLOG(1) << "DoTcpConnectComplete: " << result; 246 VLOG(1) << "DoTcpConnectComplete: " << result;
273 if (result == net::OK) { 247 if (result == net::OK) {
274 // Enable TCP protocol-level keep-alive. 248 // Enable TCP protocol-level keep-alive.
275 bool result = tcp_socket_->SetKeepAlive(true, kTcpKeepAliveDelaySecs); 249 bool result = tcp_socket_->SetKeepAlive(true, kTcpKeepAliveDelaySecs);
276 LOG_IF(WARNING, !result) << "Failed to SetKeepAlive."; 250 LOG_IF(WARNING, !result) << "Failed to SetKeepAlive.";
277 next_state_ = CONN_STATE_SSL_CONNECT; 251 connect_state_ = CONN_STATE_SSL_CONNECT;
278 } 252 }
279 return result; 253 return result;
280 } 254 }
281 255
282 int CastSocket::DoSslConnect() { 256 int CastSocket::DoSslConnect() {
283 VLOG(1) << "DoSslConnect"; 257 VLOG(1) << "DoSslConnect";
284 next_state_ = CONN_STATE_SSL_CONNECT_COMPLETE; 258 connect_state_ = CONN_STATE_SSL_CONNECT_COMPLETE;
285 socket_ = CreateSslSocket(); 259 socket_ = CreateSslSocket(tcp_socket_.PassAs<net::StreamSocket>());
286 return socket_->Connect( 260 return socket_->Connect(
287 base::Bind(&CastSocket::OnConnectComplete, AsWeakPtr())); 261 base::Bind(&CastSocket::DoConnectLoop, AsWeakPtr()));
288 } 262 }
289 263
290 int CastSocket::DoSslConnectComplete(int result) { 264 int CastSocket::DoSslConnectComplete(int result) {
291 VLOG(1) << "DoSslConnectComplete: " << result; 265 VLOG(1) << "DoSslConnectComplete: " << result;
292 if (result == net::ERR_CERT_AUTHORITY_INVALID && 266 if (result == net::ERR_CERT_AUTHORITY_INVALID &&
293 peer_cert_.empty() && 267 peer_cert_.empty() &&
294 ExtractPeerCert(&peer_cert_)) { 268 ExtractPeerCert(&peer_cert_)) {
295 next_state_ = CONN_STATE_TCP_CONNECT; 269 connect_state_ = CONN_STATE_TCP_CONNECT;
296 } else if (result == net::OK && auth_required_) { 270 } else if (result == net::OK && auth_required_) {
297 next_state_ = CONN_STATE_AUTH_CHALLENGE_SEND; 271 connect_state_ = CONN_STATE_AUTH_CHALLENGE_SEND;
298 } 272 }
299 return result; 273 return result;
300 } 274 }
301 275
302 int CastSocket::DoAuthChallengeSend() { 276 int CastSocket::DoAuthChallengeSend() {
303 VLOG(1) << "DoAuthChallengeSend"; 277 VLOG(1) << "DoAuthChallengeSend";
304 next_state_ = CONN_STATE_AUTH_CHALLENGE_SEND_COMPLETE; 278 connect_state_ = CONN_STATE_AUTH_CHALLENGE_SEND_COMPLETE;
305 return SendAuthChallenge(); 279 CastMessage challenge_message;
280 CreateAuthChallengeMessage(&challenge_message);
281 VLOG(1) << "Sending challenge: " << CastMessageToString(challenge_message);
282 // Post a task to send auth challenge so that DoWriteLoop is not nested inside
283 // DoConnectLoop. This is not strictly necessary but keeps the write loop
284 // code decoupled from connect loop code.
285 base::MessageLoop::current()->PostTask(
286 FROM_HERE,
287 base::Bind(&CastSocket::SendCastMessageInternal, AsWeakPtr(),
288 challenge_message,
289 base::Bind(&CastSocket::DoConnectLoop, AsWeakPtr())));
290 // Always return IO_PENDING since the result is always asynchronous.
291 return net::ERR_IO_PENDING;
306 } 292 }
307 293
308 int CastSocket::DoAuthChallengeSendComplete(int result) { 294 int CastSocket::DoAuthChallengeSendComplete(int result) {
309 VLOG(1) << "DoAuthChallengeSendComplete: " << result; 295 VLOG(1) << "DoAuthChallengeSendComplete: " << result;
310 if (result != net::OK) 296 if (result < 0)
311 return result; 297 return result;
312 next_state_ = CONN_STATE_AUTH_CHALLENGE_REPLY_COMPLETE; 298 connect_state_ = CONN_STATE_AUTH_CHALLENGE_REPLY_COMPLETE;
313 return ReadAuthChallengeReply(); 299 // Post a task to start read loop so that DoReadLoop is not nested inside
300 // DoConnectLoop. This is not strictly necessary but keeps the read loop
301 // code decoupled from connect loop code.
302 PostTaskToStartReadLoop();
303 // Always return IO_PENDING since the result is always asynchronous.
304 return net::ERR_IO_PENDING;
314 } 305 }
315 306
316 int CastSocket::DoAuthChallengeReplyComplete(int result) { 307 int CastSocket::DoAuthChallengeReplyComplete(int result) {
317 VLOG(1) << "DoAuthChallengeReplyComplete: " << result; 308 VLOG(1) << "DoAuthChallengeReplyComplete: " << result;
318 if (result != net::OK) 309 if (result < 0)
319 return result; 310 return result;
320 if (!VerifyChallengeReply()) 311 if (!VerifyChallengeReply())
321 return net::ERR_FAILED; 312 return net::ERR_FAILED;
322 VLOG(1) << "Auth challenge verification succeeded"; 313 VLOG(1) << "Auth challenge verification succeeded";
323 return net::OK; 314 return net::OK;
324 } 315 }
325 316
326 bool CastSocket::VerifyChallengeReply() {
327 return AuthenticateChallengeReply(*challenge_reply_.get(), peer_cert_);
328 }
329
330 void CastSocket::DoConnectCallback(int result) { 317 void CastSocket::DoConnectCallback(int result) {
331 ready_state_ = (result == net::OK) ? READY_STATE_OPEN : READY_STATE_CLOSED; 318 ready_state_ = (result == net::OK) ? READY_STATE_OPEN : READY_STATE_CLOSED;
332 error_state_ = (result == net::OK) ? 319 error_state_ = (result == net::OK) ?
333 CHANNEL_ERROR_NONE : CHANNEL_ERROR_CONNECT_ERROR; 320 CHANNEL_ERROR_NONE : CHANNEL_ERROR_CONNECT_ERROR;
321 if (result == net::OK) // Start the read loop
322 PostTaskToStartReadLoop();
334 base::ResetAndReturn(&connect_callback_).Run(result); 323 base::ResetAndReturn(&connect_callback_).Run(result);
335 // Start the ReadData loop if not already started.
336 // If auth_required_ is true we would've started a ReadData loop already.
337 // TODO(munjal): This is a bit ugly. Refactor read and write code.
338 if (result == net::OK && !auth_required_)
339 ReadData();
340 } 324 }
341 325
342 void CastSocket::Close(const net::CompletionCallback& callback) { 326 void CastSocket::Close(const net::CompletionCallback& callback) {
343 DCHECK(CalledOnValidThread()); 327 DCHECK(CalledOnValidThread());
344 VLOG(1) << "Close ReadyState = " << ready_state_; 328 VLOG(1) << "Close ReadyState = " << ready_state_;
345 tcp_socket_.reset(NULL); 329 tcp_socket_.reset();
346 socket_.reset(NULL); 330 socket_.reset();
347 cert_verifier_.reset(NULL); 331 cert_verifier_.reset();
348 transport_security_state_.reset(NULL); 332 transport_security_state_.reset();
349 ready_state_ = READY_STATE_CLOSED; 333 ready_state_ = READY_STATE_CLOSED;
350 callback.Run(net::OK); 334 callback.Run(net::OK);
335 // |callback| can delete |this|
351 } 336 }
352 337
353 void CastSocket::SendMessage(const MessageInfo& message, 338 void CastSocket::SendMessage(const MessageInfo& message,
354 const net::CompletionCallback& callback) { 339 const net::CompletionCallback& callback) {
355 DCHECK(CalledOnValidThread()); 340 DCHECK(CalledOnValidThread());
356 VLOG(1) << "Send ReadyState " << ready_state_;
357 int result = net::ERR_FAILED;
358 if (ready_state_ != READY_STATE_OPEN) { 341 if (ready_state_ != READY_STATE_OPEN) {
359 callback.Run(result); 342 callback.Run(net::ERR_FAILED);
360 return; 343 return;
361 } 344 }
362 CastMessage message_proto; 345 CastMessage message_proto;
363 if (!MessageInfoToCastMessage(message, &message_proto)) { 346 if (!MessageInfoToCastMessage(message, &message_proto)) {
364 CloseWithError(cast_channel::CHANNEL_ERROR_INVALID_MESSAGE); 347 callback.Run(net::ERR_FAILED);
365 // TODO(mfoltz): Do a better job of signaling cast_channel errors to the 348 return;
366 // caller. 349 }
367 callback.Run(net::OK); 350
368 return; 351 SendCastMessageInternal(message_proto, callback);
369 } 352 }
370 SendMessageInternal(message_proto, callback); 353
371 } 354 void CastSocket::SendCastMessageInternal(
372 355 const CastMessage& message,
373 int CastSocket::SendMessageInternal(const CastMessage& message_proto, 356 const net::CompletionCallback& callback) {
374 const net::CompletionCallback& callback) {
375 WriteRequest write_request(callback); 357 WriteRequest write_request(callback);
376 if (!write_request.SetContent(message_proto)) 358 if (!write_request.SetContent(message)) {
377 return net::ERR_FAILED; 359 callback.Run(net::ERR_FAILED);
360 return;
361 }
362
378 write_queue_.push(write_request); 363 write_queue_.push(write_request);
379 return WriteData(); 364 if (write_state_ == WRITE_STATE_NONE) {
380 } 365 write_state_ = WRITE_STATE_WRITE;
381 366 DoWriteLoop(net::OK);
382 int CastSocket::WriteData() { 367 }
368 }
369
370 void CastSocket::DoWriteLoop(int result) {
383 DCHECK(CalledOnValidThread()); 371 DCHECK(CalledOnValidThread());
384 VLOG(1) << "WriteData q = " << write_queue_.size(); 372 VLOG(1) << "WriteData q = " << write_queue_.size();
385 if (write_queue_.empty() || write_callback_pending_) 373
386 return net::ERR_FAILED; 374 if (write_queue_.empty()) {
387 375 write_state_ = WRITE_STATE_NONE;
376 return;
377 }
378
379 // Network operations can either finish synchronously or asynchronously.
380 // This method executes the state machine transitions in a loop so that
381 // write state transitions happen even when network operations finish
382 // synchronously.
383 int rv = result;
384 do {
385 WriteState state = write_state_;
386 write_state_ = WRITE_STATE_NONE;
387 switch (state) {
388 case WRITE_STATE_WRITE:
389 rv = DoWrite();
390 break;
391 case WRITE_STATE_WRITE_COMPLETE:
392 rv = DoWriteComplete(rv);
393 break;
394 case WRITE_STATE_DO_CALLBACK:
395 rv = DoWriteCallback();
396 break;
397 case WRITE_STATE_ERROR:
398 rv = DoWriteError(rv);
399 break;
400 default:
401 NOTREACHED() << "BUG in write flow. Unknown state: " << state;
402 break;
403 }
404 } while (!write_queue_.empty() &&
405 rv != net::ERR_IO_PENDING &&
406 write_state_ != WRITE_STATE_NONE);
407
408 // If write loop is done because the queue is empty then set write
409 // state to NONE
410 if (write_queue_.empty())
411 write_state_ = WRITE_STATE_NONE;
412
413 // Write loop is done - if the result is ERR_FAILED then close with error.
414 if (rv == net::ERR_FAILED)
415 CloseWithError(error_state_);
416 }
417
418 int CastSocket::DoWrite() {
419 DCHECK(!write_queue_.empty());
388 WriteRequest& request = write_queue_.front(); 420 WriteRequest& request = write_queue_.front();
389 421
390 VLOG(1) << "WriteData byte_count = " << request.io_buffer->size() 422 VLOG(1) << "WriteData byte_count = " << request.io_buffer->size()
391 << " bytes_written " << request.io_buffer->BytesConsumed(); 423 << " bytes_written " << request.io_buffer->BytesConsumed();
392 424
393 write_callback_pending_ = true; 425 write_state_ = WRITE_STATE_WRITE_COMPLETE;
394 int result = socket_->Write( 426
427 return socket_->Write(
395 request.io_buffer.get(), 428 request.io_buffer.get(),
396 request.io_buffer->BytesRemaining(), 429 request.io_buffer->BytesRemaining(),
397 base::Bind(&CastSocket::OnWriteData, AsWeakPtr())); 430 base::Bind(&CastSocket::DoWriteLoop, AsWeakPtr()));
398 431 }
399 if (result != net::ERR_IO_PENDING) 432
400 OnWriteData(result); 433 int CastSocket::DoWriteComplete(int result) {
401 434 DCHECK(!write_queue_.empty());
402 return result; 435 if (result <= 0) { // NOTE that 0 also indicates an error
403 } 436 error_state_ = CHANNEL_ERROR_SOCKET_ERROR;
404 437 write_state_ = WRITE_STATE_ERROR;
405 void CastSocket::OnWriteData(int result) { 438 return result == 0 ? net::ERR_FAILED : result;
406 DCHECK(CalledOnValidThread()); 439 }
407 VLOG(1) << "OnWriteComplete result = " << result; 440
408 DCHECK(write_callback_pending_); 441 // Some bytes were successfully written
409 DCHECK(!write_queue_.empty());
410 write_callback_pending_ = false;
411 WriteRequest& request = write_queue_.front(); 442 WriteRequest& request = write_queue_.front();
412 scoped_refptr<net::DrainableIOBuffer> io_buffer = request.io_buffer; 443 scoped_refptr<net::DrainableIOBuffer> io_buffer = request.io_buffer;
413 444 io_buffer->DidConsume(result);
414 if (result >= 0) { 445 if (io_buffer->BytesRemaining() == 0) // Message fully sent
415 io_buffer->DidConsume(result); 446 write_state_ = WRITE_STATE_DO_CALLBACK;
416 if (io_buffer->BytesRemaining() > 0) { 447 else
417 VLOG(1) << "OnWriteComplete size = " << io_buffer->size() 448 write_state_ = WRITE_STATE_WRITE;
418 << " consumed " << io_buffer->BytesConsumed() 449
419 << " remaining " << io_buffer->BytesRemaining() 450 return net::OK;
420 << " # requests " << write_queue_.size(); 451 }
421 WriteData(); 452
422 return; 453 int CastSocket::DoWriteCallback() {
454 DCHECK(!write_queue_.empty());
455 WriteRequest& request = write_queue_.front();
456 int bytes_consumed = request.io_buffer->BytesConsumed();
457
458 // If inside connection flow, then there should be exaclty one item in
459 // the write queue.
460 if (ready_state_ == READY_STATE_CONNECTING) {
461 write_queue_.pop();
462 DCHECK(write_queue_.empty());
463 PostTaskToStartConnectLoop(bytes_consumed);
464 } else {
465 WriteRequest& request = write_queue_.front();
466 request.callback.Run(bytes_consumed);
467 write_queue_.pop();
468 }
469 write_state_ = WRITE_STATE_WRITE;
470 return net::OK;
471 }
472
473 int CastSocket::DoWriteError(int result) {
474 DCHECK(!write_queue_.empty());
475 DCHECK_LT(result, 0);
476
477 // If inside connection flow, then there should be exactly one item in
478 // the write queue.
479 if (ready_state_ == READY_STATE_CONNECTING) {
480 write_queue_.pop();
481 DCHECK(write_queue_.empty());
482 PostTaskToStartConnectLoop(result);
483 // Connect loop will handle the error. Return net::OK so that write flow
484 // does not try to report error also.
485 return net::OK;
486 }
487
488 while (!write_queue_.empty()) {
489 WriteRequest& request = write_queue_.front();
490 request.callback.Run(result);
491 write_queue_.pop();
492 }
493 return net::ERR_FAILED;
494 }
495
496 void CastSocket::PostTaskToStartReadLoop() {
497 DCHECK(CalledOnValidThread());
498 base::MessageLoop::current()->PostTask(
499 FROM_HERE,
500 base::Bind(&CastSocket::StartReadLoop, AsWeakPtr()));
501 }
502
503 void CastSocket::StartReadLoop() {
504 // Read loop would have already been started if read state is not NONE
505 if (read_state_ == READ_STATE_NONE) {
506 read_state_ = READ_STATE_READ;
507 DoReadLoop(net::OK);
508 }
509 }
510
511 void CastSocket::DoReadLoop(int result) {
512 DCHECK(CalledOnValidThread());
513 // Network operations can either finish synchronously or asynchronously.
514 // This method executes the state machine transitions in a loop so that
515 // write state transitions happen even when network operations finish
516 // synchronously.
517 int rv = result;
518 do {
519 ReadState state = read_state_;
520 read_state_ = READ_STATE_NONE;
521
522 switch (state) {
523 case READ_STATE_READ:
524 rv = DoRead();
525 break;
526 case READ_STATE_READ_COMPLETE:
527 rv = DoReadComplete(rv);
528 break;
529 case READ_STATE_DO_CALLBACK:
530 rv = DoReadCallback();
531 break;
532 case READ_STATE_ERROR:
533 rv = DoReadError(rv);
534 break;
535 default:
536 NOTREACHED() << "BUG in read flow. Unknown state: " << state;
537 break;
423 } 538 }
424 DCHECK_EQ(io_buffer->BytesConsumed(), io_buffer->size()); 539 } while (rv != net::ERR_IO_PENDING && read_state_ != READ_STATE_NONE);
425 DCHECK_EQ(io_buffer->BytesRemaining(), 0); 540
426 result = io_buffer->BytesConsumed(); 541 // Read loop is done - If the result is ERR_FAILED then close with error.
427 } 542 if (rv == net::ERR_FAILED)
428 543 CloseWithError(error_state_);
429 request.callback.Run(result); 544 }
430 write_queue_.pop(); 545
431 546 int CastSocket::DoRead() {
432 VLOG(1) << "OnWriteComplete size = " << io_buffer->size() 547 read_state_ = READ_STATE_READ_COMPLETE;
433 << " consumed " << io_buffer->BytesConsumed() 548 // Figure out whether to read header or body, and the remaining bytes.
434 << " remaining " << io_buffer->BytesRemaining()
435 << " # requests " << write_queue_.size();
436
437 if (result < 0) {
438 CloseWithError(CHANNEL_ERROR_SOCKET_ERROR);
439 return;
440 }
441
442 if (!write_queue_.empty())
443 WriteData();
444 }
445
446 int CastSocket::ReadData() {
447 DCHECK(CalledOnValidThread());
448 if (!socket_.get())
449 return net::ERR_FAILED;
450 DCHECK(!read_callback_pending_);
451 read_callback_pending_ = true;
452 // Figure out if we are reading the header or body, and the remaining bytes.
453 uint32 num_bytes_to_read = 0; 549 uint32 num_bytes_to_read = 0;
454 if (header_read_buffer_->RemainingCapacity() > 0) { 550 if (header_read_buffer_->RemainingCapacity() > 0) {
455 current_read_buffer_ = header_read_buffer_; 551 current_read_buffer_ = header_read_buffer_;
456 num_bytes_to_read = header_read_buffer_->RemainingCapacity(); 552 num_bytes_to_read = header_read_buffer_->RemainingCapacity();
457 DCHECK_LE(num_bytes_to_read, kMessageHeaderSize); 553 DCHECK_LE(num_bytes_to_read, kMessageHeaderSize);
458 } else { 554 } else {
459 DCHECK_GT(current_message_size_, 0U); 555 DCHECK_GT(current_message_size_, 0U);
460 num_bytes_to_read = current_message_size_ - body_read_buffer_->offset(); 556 num_bytes_to_read = current_message_size_ - body_read_buffer_->offset();
461 current_read_buffer_ = body_read_buffer_; 557 current_read_buffer_ = body_read_buffer_;
462 DCHECK_LE(num_bytes_to_read, kMaxMessageSize); 558 DCHECK_LE(num_bytes_to_read, kMaxMessageSize);
463 } 559 }
464 DCHECK_GT(num_bytes_to_read, 0U); 560 DCHECK_GT(num_bytes_to_read, 0U);
465 // We read up to num_bytes_to_read into |current_read_buffer_|. 561
466 int result = socket_->Read( 562 // Read up to num_bytes_to_read into |current_read_buffer_|.
563 return socket_->Read(
467 current_read_buffer_.get(), 564 current_read_buffer_.get(),
468 num_bytes_to_read, 565 num_bytes_to_read,
469 base::Bind(&CastSocket::OnReadData, AsWeakPtr())); 566 base::Bind(&CastSocket::DoReadLoop, AsWeakPtr()));
470 VLOG(1) << "ReadData result = " << result;
471 if (result > 0) {
472 OnReadData(result);
473 } else if (result != net::ERR_IO_PENDING) {
474 CloseWithError(CHANNEL_ERROR_SOCKET_ERROR);
475 }
476 return result;
477 } 567 }
478 568
479 void CastSocket::OnReadData(int result) { 569 int CastSocket::DoReadComplete(int result) {
480 DCHECK(CalledOnValidThread()); 570 VLOG(1) << "DoReadDataComplete result = " << result
481 VLOG(1) << "OnReadData result = " << result
482 << " header offset = " << header_read_buffer_->offset() 571 << " header offset = " << header_read_buffer_->offset()
483 << " body offset = " << body_read_buffer_->offset(); 572 << " body offset = " << body_read_buffer_->offset();
484 read_callback_pending_ = false; 573 if (result <= 0) { // 0 means EOF: the peer closed the socket
485 if (result <= 0) { 574 error_state_ = CHANNEL_ERROR_SOCKET_ERROR;
486 CloseWithError(CHANNEL_ERROR_SOCKET_ERROR); 575 read_state_ = READ_STATE_ERROR;
487 return; 576 return result == 0 ? net::ERR_FAILED : result;
488 } 577 }
489 // We read some data. Move the offset in the current buffer forward. 578
579 // Some data was read. Move the offset in the current buffer forward.
490 DCHECK_LE(current_read_buffer_->offset() + result, 580 DCHECK_LE(current_read_buffer_->offset() + result,
491 current_read_buffer_->capacity()); 581 current_read_buffer_->capacity());
492 current_read_buffer_->set_offset(current_read_buffer_->offset() + result); 582 current_read_buffer_->set_offset(current_read_buffer_->offset() + result);
583 read_state_ = READ_STATE_READ;
493 584
494 bool should_continue = true;
495 if (current_read_buffer_.get() == header_read_buffer_.get() && 585 if (current_read_buffer_.get() == header_read_buffer_.get() &&
496 current_read_buffer_->RemainingCapacity() == 0) { 586 current_read_buffer_->RemainingCapacity() == 0) {
497 // If we have read a full header, process the contents. 587 // A full header is read, process the contents.
498 should_continue = ProcessHeader(); 588 if (!ProcessHeader()) {
589 error_state_ = cast_channel::CHANNEL_ERROR_INVALID_MESSAGE;
590 read_state_ = READ_STATE_ERROR;
591 }
499 } else if (current_read_buffer_.get() == body_read_buffer_.get() && 592 } else if (current_read_buffer_.get() == body_read_buffer_.get() &&
500 static_cast<uint32>(current_read_buffer_->offset()) == 593 static_cast<uint32>(current_read_buffer_->offset()) ==
501 current_message_size_) { 594 current_message_size_) {
502 // If we have read a full body, process the contents. 595 // Full body is read, process the contents.
503 should_continue = ProcessBody(); 596 if (ProcessBody()) {
597 read_state_ = READ_STATE_DO_CALLBACK;
598 } else {
599 error_state_ = cast_channel::CHANNEL_ERROR_INVALID_MESSAGE;
600 read_state_ = READ_STATE_ERROR;
601 }
504 } 602 }
505 if (should_continue) 603
506 ReadData(); 604 return net::OK;
605 }
606
607 int CastSocket::DoReadCallback() {
608 read_state_ = READ_STATE_READ;
609 if (IsAuthMessage(current_message_)) {
610 // An auth message is received, check that connect flow is running.
611 if (ready_state_ == READY_STATE_CONNECTING) {
612 challenge_reply_.reset(new CastMessage(current_message_));
613 PostTaskToStartConnectLoop(net::OK);
614 } else {
615 read_state_ = READ_STATE_ERROR;
616 }
617 } else if (delegate_) {
618 MessageInfo message;
619 if (CastMessageToMessageInfo(current_message_, &message))
620 delegate_->OnMessage(this, message);
621 else
622 read_state_ = READ_STATE_ERROR;
623 }
624 current_message_.Clear();
625 return net::OK;
626 }
627
628 int CastSocket::DoReadError(int result) {
629 DCHECK_LE(result, 0);
630 // If inside connection flow, then get back to connect loop.
631 if (ready_state_ == READY_STATE_CONNECTING) {
632 PostTaskToStartConnectLoop(result);
633 // does not try to report error also.
634 return net::OK;
635 }
636 return net::ERR_FAILED;
507 } 637 }
508 638
509 bool CastSocket::ProcessHeader() { 639 bool CastSocket::ProcessHeader() {
510 DCHECK_EQ(static_cast<uint32>(header_read_buffer_->offset()), 640 DCHECK_EQ(static_cast<uint32>(header_read_buffer_->offset()),
511 kMessageHeaderSize); 641 kMessageHeaderSize);
512 MessageHeader header; 642 MessageHeader header;
513 MessageHeader::ReadFromIOBuffer(header_read_buffer_.get(), &header); 643 MessageHeader::ReadFromIOBuffer(header_read_buffer_.get(), &header);
514 if (header.message_size > kMaxMessageSize) { 644 if (header.message_size > kMaxMessageSize)
515 CloseWithError(cast_channel::CHANNEL_ERROR_INVALID_MESSAGE);
516 return false; 645 return false;
517 } 646
518 VLOG(1) << "Parsed header { message_size: " << header.message_size << " }"; 647 VLOG(1) << "Parsed header { message_size: " << header.message_size << " }";
519 current_message_size_ = header.message_size; 648 current_message_size_ = header.message_size;
520 return true; 649 return true;
521 } 650 }
522 651
523 bool CastSocket::ProcessBody() { 652 bool CastSocket::ProcessBody() {
524 DCHECK_EQ(static_cast<uint32>(body_read_buffer_->offset()), 653 DCHECK_EQ(static_cast<uint32>(body_read_buffer_->offset()),
525 current_message_size_); 654 current_message_size_);
526 if (!ParseMessageFromBody()) { 655 if (!current_message_.ParseFromArray(
527 CloseWithError(cast_channel::CHANNEL_ERROR_INVALID_MESSAGE); 656 body_read_buffer_->StartOfBuffer(), current_message_size_)) {
528 return false; 657 return false;
529 } 658 }
530 current_message_size_ = 0; 659 current_message_size_ = 0;
531 header_read_buffer_->set_offset(0); 660 header_read_buffer_->set_offset(0);
532 body_read_buffer_->set_offset(0); 661 body_read_buffer_->set_offset(0);
533 current_read_buffer_ = header_read_buffer_; 662 current_read_buffer_ = header_read_buffer_;
534 return true; 663 return true;
535 } 664 }
536 665
537 bool CastSocket::ParseMessageFromBody() {
538 DCHECK(CalledOnValidThread());
539 DCHECK_EQ(static_cast<uint32>(body_read_buffer_->offset()),
540 current_message_size_);
541 CastMessage message_proto;
542 if (!message_proto.ParseFromArray(
543 body_read_buffer_->StartOfBuffer(),
544 current_message_size_))
545 return false;
546 VLOG(1) << "Parsed message " << CastMessageToString(message_proto);
547 // If the message is an auth message then we handle it internally.
548 if (IsAuthMessage(message_proto)) {
549 challenge_reply_.reset(new CastMessage(message_proto));
550 OnChallengeEvent(net::OK);
551 } else if (delegate_) {
552 MessageInfo message;
553 if (!CastMessageToMessageInfo(message_proto, &message))
554 return false;
555 delegate_->OnMessage(this, message);
556 }
557 return true;
558 }
559
560 // static 666 // static
561 bool CastSocket::Serialize(const CastMessage& message_proto, 667 bool CastSocket::Serialize(const CastMessage& message_proto,
562 std::string* message_data) { 668 std::string* message_data) {
563 DCHECK(message_data); 669 DCHECK(message_data);
564 message_proto.SerializeToString(message_data); 670 message_proto.SerializeToString(message_data);
565 size_t message_size = message_data->size(); 671 size_t message_size = message_data->size();
566 if (message_size > kMaxMessageSize) { 672 if (message_size > kMaxMessageSize) {
567 message_data->clear(); 673 message_data->clear();
568 return false; 674 return false;
569 } 675 }
(...skipping 44 matching lines...) Expand 10 before | Expand all | Expand 10 after
614 if (!base::StringToInt(port_str, &port)) 720 if (!base::StringToInt(port_str, &port))
615 return false; 721 return false;
616 net::IPAddressNumber ip_address; 722 net::IPAddressNumber ip_address;
617 if (!net::ParseIPLiteralToNumber(ip_address_str, &ip_address)) 723 if (!net::ParseIPLiteralToNumber(ip_address_str, &ip_address))
618 return false; 724 return false;
619 ip_endpoint_ = net::IPEndPoint(ip_address, port); 725 ip_endpoint_ = net::IPEndPoint(ip_address, port);
620 return true; 726 return true;
621 }; 727 };
622 728
623 void CastSocket::FillChannelInfo(ChannelInfo* channel_info) const { 729 void CastSocket::FillChannelInfo(ChannelInfo* channel_info) const {
624 DCHECK(CalledOnValidThread());
625 channel_info->channel_id = channel_id_; 730 channel_info->channel_id = channel_id_;
626 channel_info->url = url_.spec(); 731 channel_info->url = url_.spec();
627 channel_info->ready_state = ready_state_; 732 channel_info->ready_state = ready_state_;
628 channel_info->error_state = error_state_; 733 channel_info->error_state = error_state_;
629 } 734 }
630 735
631 bool CastSocket::CalledOnValidThread() const { 736 bool CastSocket::CalledOnValidThread() const {
632 return thread_checker_.CalledOnValidThread(); 737 return thread_checker_.CalledOnValidThread();
633 } 738 }
634 739
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
670 io_buffer = new net::DrainableIOBuffer(new net::StringIOBuffer(message_data), 775 io_buffer = new net::DrainableIOBuffer(new net::StringIOBuffer(message_data),
671 message_data.size()); 776 message_data.size());
672 return true; 777 return true;
673 } 778 }
674 779
675 CastSocket::WriteRequest::~WriteRequest() { } 780 CastSocket::WriteRequest::~WriteRequest() { }
676 781
677 } // namespace cast_channel 782 } // namespace cast_channel
678 } // namespace api 783 } // namespace api
679 } // namespace extensions 784 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698