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