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

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

Powered by Google App Engine
This is Rietveld 408576698