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
3 // found in the LICENSE file.
5 #include "chrome/browser/extensions/api/cast_channel/cast_socket.h"
10 #include "base/callback_helpers.h"
11 #include "base/lazy_instance.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/sys_byteorder.h"
14 #include "chrome/browser/extensions/api/cast_channel/cast_auth_util.h"
15 #include "chrome/browser/extensions/api/cast_channel/cast_channel.pb.h"
16 #include "chrome/browser/extensions/api/cast_channel/cast_message_util.h"
17 #include "net/base/address_list.h"
18 #include "net/base/host_port_pair.h"
19 #include "net/base/net_errors.h"
20 #include "net/base/net_util.h"
21 #include "net/cert/cert_verifier.h"
22 #include "net/cert/x509_certificate.h"
23 #include "net/http/transport_security_state.h"
24 #include "net/socket/client_socket_factory.h"
25 #include "net/socket/client_socket_handle.h"
26 #include "net/socket/ssl_client_socket.h"
27 #include "net/socket/stream_socket.h"
28 #include "net/socket/tcp_client_socket.h"
29 #include "net/ssl/ssl_config_service.h"
30 #include "net/ssl/ssl_info.h"
32 // Assumes |url_| of type GURL is available in the current scope.
33 #define VLOG_WITH_URL(level) VLOG(level) << "[" + url_.spec() + "] "
37 // Allowed schemes for Cast device URLs.
38 const char kCastInsecureScheme[] = "cast";
39 const char kCastSecureScheme[] = "casts";
41 // The default keepalive delay. On Linux, keepalives probes will be sent after
42 // the socket is idle for this length of time, and the socket will be closed
43 // after 9 failed probes. So the total idle time before close is 10 *
44 // kTcpKeepAliveDelaySecs.
45 const int kTcpKeepAliveDelaySecs = 10;
49 namespace extensions {
51 static base::LazyInstance<
52 ProfileKeyedAPIFactory<ApiResourceManager<api::cast_channel::CastSocket> > >
53 g_factory = LAZY_INSTANCE_INITIALIZER;
57 ProfileKeyedAPIFactory<ApiResourceManager<api::cast_channel::CastSocket> >*
58 ApiResourceManager<api::cast_channel::CastSocket>::GetFactoryInstance() {
59 return g_factory.Pointer();
63 namespace cast_channel {
65 const uint32 kMaxMessageSize = 65536;
66 // Don't use sizeof(MessageHeader) because of alignment; instead, sum the
67 // sizeof() for the fields.
68 const uint32 kMessageHeaderSize = sizeof(uint32);
70 CastSocket::CastSocket(const std::string& owner_extension_id,
72 CastSocket::Delegate* delegate,
73 net::NetLog* net_log) :
74 ApiResource(owner_extension_id),
78 auth_required_(false),
79 current_message_size_(0),
80 current_message_(new CastMessage()),
82 connect_state_(CONN_STATE_NONE),
83 write_state_(WRITE_STATE_NONE),
84 read_state_(READ_STATE_NONE),
85 error_state_(CHANNEL_ERROR_NONE),
86 ready_state_(READY_STATE_NONE) {
88 net_log_source_.type = net::NetLog::SOURCE_SOCKET;
89 net_log_source_.id = net_log_->NextID();
91 // Reuse these buffers for each message.
92 header_read_buffer_ = new net::GrowableIOBuffer();
93 header_read_buffer_->SetCapacity(kMessageHeaderSize);
94 body_read_buffer_ = new net::GrowableIOBuffer();
95 body_read_buffer_->SetCapacity(kMaxMessageSize);
96 current_read_buffer_ = header_read_buffer_;
99 CastSocket::~CastSocket() { }
101 const GURL& CastSocket::url() const {
105 scoped_ptr<net::TCPClientSocket> CastSocket::CreateTcpSocket() {
106 net::AddressList addresses(ip_endpoint_);
107 return scoped_ptr<net::TCPClientSocket>(
108 new net::TCPClientSocket(addresses, net_log_, net_log_source_));
109 // Options cannot be set on the TCPClientSocket yet, because the
110 // underlying platform socket will not be created until Bind()
111 // or Connect() is called.
114 scoped_ptr<net::SSLClientSocket> CastSocket::CreateSslSocket(
115 scoped_ptr<net::StreamSocket> socket) {
116 net::SSLConfig ssl_config;
117 // If a peer cert was extracted in a previous attempt to connect, then
118 // whitelist that cert.
119 if (!peer_cert_.empty()) {
120 net::SSLConfig::CertAndStatus cert_and_status;
121 cert_and_status.cert_status = net::CERT_STATUS_AUTHORITY_INVALID;
122 cert_and_status.der_cert = peer_cert_;
123 ssl_config.allowed_bad_certs.push_back(cert_and_status);
126 cert_verifier_.reset(net::CertVerifier::CreateDefault());
127 transport_security_state_.reset(new net::TransportSecurityState);
128 net::SSLClientSocketContext context;
129 // CertVerifier and TransportSecurityState are owned by us, not the
131 context.cert_verifier = cert_verifier_.get();
132 context.transport_security_state = transport_security_state_.get();
134 scoped_ptr<net::ClientSocketHandle> connection(new net::ClientSocketHandle);
135 connection->SetSocket(socket.Pass());
136 net::HostPortPair host_and_port = net::HostPortPair::FromIPEndPoint(
139 return net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket(
140 connection.Pass(), host_and_port, ssl_config, context);
143 bool CastSocket::ExtractPeerCert(std::string* cert) {
145 DCHECK(peer_cert_.empty());
146 net::SSLInfo ssl_info;
147 if (!socket_->GetSSLInfo(&ssl_info) || !ssl_info.cert.get())
149 bool result = net::X509Certificate::GetDEREncoded(
150 ssl_info.cert->os_cert_handle(), cert);
152 VLOG_WITH_URL(1) << "Successfully extracted peer certificate: " << *cert;
156 bool CastSocket::VerifyChallengeReply() {
157 return AuthenticateChallengeReply(*challenge_reply_.get(), peer_cert_);
160 void CastSocket::Connect(const net::CompletionCallback& callback) {
161 DCHECK(CalledOnValidThread());
162 VLOG_WITH_URL(1) << "Connect readyState = " << ready_state_;
163 if (ready_state_ != READY_STATE_NONE) {
164 callback.Run(net::ERR_CONNECTION_FAILED);
167 if (!ParseChannelUrl(url_)) {
168 callback.Run(net::ERR_CONNECTION_FAILED);
172 ready_state_ = READY_STATE_CONNECTING;
173 connect_callback_ = callback;
174 connect_state_ = CONN_STATE_TCP_CONNECT;
175 DoConnectLoop(net::OK);
178 void CastSocket::PostTaskToStartConnectLoop(int result) {
179 DCHECK(CalledOnValidThread());
180 base::MessageLoop::current()->PostTask(
182 base::Bind(&CastSocket::DoConnectLoop, AsWeakPtr(), result));
185 // This method performs the state machine transitions for connection flow.
186 // There are two entry points to this method:
187 // 1. Connect method: this starts the flow
188 // 2. Callback from network operations that finish asynchronously
189 void CastSocket::DoConnectLoop(int result) {
190 // Network operations can either finish synchronously or asynchronously.
191 // This method executes the state machine transitions in a loop so that
192 // correct state transitions happen even when network operations finish
196 ConnectionState state = connect_state_;
197 // Default to CONN_STATE_NONE, which breaks the processing loop if any
198 // handler fails to transition to another state to continue processing.
199 connect_state_ = CONN_STATE_NONE;
201 case CONN_STATE_TCP_CONNECT:
204 case CONN_STATE_TCP_CONNECT_COMPLETE:
205 rv = DoTcpConnectComplete(rv);
207 case CONN_STATE_SSL_CONNECT:
208 DCHECK_EQ(net::OK, rv);
211 case CONN_STATE_SSL_CONNECT_COMPLETE:
212 rv = DoSslConnectComplete(rv);
214 case CONN_STATE_AUTH_CHALLENGE_SEND:
215 rv = DoAuthChallengeSend();
217 case CONN_STATE_AUTH_CHALLENGE_SEND_COMPLETE:
218 rv = DoAuthChallengeSendComplete(rv);
220 case CONN_STATE_AUTH_CHALLENGE_REPLY_COMPLETE:
221 rv = DoAuthChallengeReplyComplete(rv);
224 NOTREACHED() << "BUG in connect flow. Unknown state: " << state;
227 } while (rv != net::ERR_IO_PENDING && connect_state_ != CONN_STATE_NONE);
228 // Get out of the loop either when:
229 // a. A network operation is pending, OR
230 // b. The Do* method called did not change state
232 // Connect loop is finished: if there is no pending IO invoke the callback.
233 if (rv != net::ERR_IO_PENDING)
234 DoConnectCallback(rv);
237 int CastSocket::DoTcpConnect() {
238 VLOG_WITH_URL(1) << "DoTcpConnect";
239 connect_state_ = CONN_STATE_TCP_CONNECT_COMPLETE;
240 tcp_socket_ = CreateTcpSocket();
241 return tcp_socket_->Connect(
242 base::Bind(&CastSocket::DoConnectLoop, AsWeakPtr()));
245 int CastSocket::DoTcpConnectComplete(int result) {
246 VLOG_WITH_URL(1) << "DoTcpConnectComplete: " << result;
247 if (result == net::OK) {
248 // Enable TCP protocol-level keep-alive.
249 bool result = tcp_socket_->SetKeepAlive(true, kTcpKeepAliveDelaySecs);
250 LOG_IF(WARNING, !result) << "Failed to SetKeepAlive.";
251 connect_state_ = CONN_STATE_SSL_CONNECT;
256 int CastSocket::DoSslConnect() {
257 VLOG_WITH_URL(1) << "DoSslConnect";
258 connect_state_ = CONN_STATE_SSL_CONNECT_COMPLETE;
259 socket_ = CreateSslSocket(tcp_socket_.PassAs<net::StreamSocket>());
260 return socket_->Connect(
261 base::Bind(&CastSocket::DoConnectLoop, AsWeakPtr()));
264 int CastSocket::DoSslConnectComplete(int result) {
265 VLOG_WITH_URL(1) << "DoSslConnectComplete: " << result;
266 if (result == net::ERR_CERT_AUTHORITY_INVALID &&
267 peer_cert_.empty() &&
268 ExtractPeerCert(&peer_cert_)) {
269 connect_state_ = CONN_STATE_TCP_CONNECT;
270 } else if (result == net::OK && auth_required_) {
271 connect_state_ = CONN_STATE_AUTH_CHALLENGE_SEND;
276 int CastSocket::DoAuthChallengeSend() {
277 VLOG_WITH_URL(1) << "DoAuthChallengeSend";
278 connect_state_ = CONN_STATE_AUTH_CHALLENGE_SEND_COMPLETE;
279 CastMessage challenge_message;
280 CreateAuthChallengeMessage(&challenge_message);
281 VLOG_WITH_URL(1) << "Sending challenge: "
282 << CastMessageToString(challenge_message);
283 // Post a task to send auth challenge so that DoWriteLoop is not nested inside
284 // DoConnectLoop. This is not strictly necessary but keeps the write loop
285 // code decoupled from connect loop code.
286 base::MessageLoop::current()->PostTask(
288 base::Bind(&CastSocket::SendCastMessageInternal, AsWeakPtr(),
290 base::Bind(&CastSocket::DoConnectLoop, AsWeakPtr())));
291 // Always return IO_PENDING since the result is always asynchronous.
292 return net::ERR_IO_PENDING;
295 int CastSocket::DoAuthChallengeSendComplete(int result) {
296 VLOG_WITH_URL(1) << "DoAuthChallengeSendComplete: " << result;
299 connect_state_ = CONN_STATE_AUTH_CHALLENGE_REPLY_COMPLETE;
300 // Post a task to start read loop so that DoReadLoop is not nested inside
301 // DoConnectLoop. This is not strictly necessary but keeps the read loop
302 // code decoupled from connect loop code.
303 PostTaskToStartReadLoop();
304 // Always return IO_PENDING since the result is always asynchronous.
305 return net::ERR_IO_PENDING;
308 int CastSocket::DoAuthChallengeReplyComplete(int result) {
309 VLOG_WITH_URL(1) << "DoAuthChallengeReplyComplete: " << result;
312 if (!VerifyChallengeReply())
313 return net::ERR_FAILED;
314 VLOG_WITH_URL(1) << "Auth challenge verification succeeded";
318 void CastSocket::DoConnectCallback(int result) {
319 ready_state_ = (result == net::OK) ? READY_STATE_OPEN : READY_STATE_CLOSED;
320 error_state_ = (result == net::OK) ?
321 CHANNEL_ERROR_NONE : CHANNEL_ERROR_CONNECT_ERROR;
322 if (result == net::OK) // Start the read loop
323 PostTaskToStartReadLoop();
324 base::ResetAndReturn(&connect_callback_).Run(result);
327 void CastSocket::Close(const net::CompletionCallback& callback) {
328 DCHECK(CalledOnValidThread());
329 VLOG_WITH_URL(1) << "Close ReadyState = " << ready_state_;
332 cert_verifier_.reset();
333 transport_security_state_.reset();
334 ready_state_ = READY_STATE_CLOSED;
335 callback.Run(net::OK);
336 // |callback| can delete |this|
339 void CastSocket::SendMessage(const MessageInfo& message,
340 const net::CompletionCallback& callback) {
341 DCHECK(CalledOnValidThread());
342 if (ready_state_ != READY_STATE_OPEN) {
343 callback.Run(net::ERR_FAILED);
346 CastMessage message_proto;
347 if (!MessageInfoToCastMessage(message, &message_proto)) {
348 callback.Run(net::ERR_FAILED);
352 SendCastMessageInternal(message_proto, callback);
355 void CastSocket::SendCastMessageInternal(
356 const CastMessage& message,
357 const net::CompletionCallback& callback) {
358 WriteRequest write_request(callback);
359 if (!write_request.SetContent(message)) {
360 callback.Run(net::ERR_FAILED);
364 write_queue_.push(write_request);
365 if (write_state_ == WRITE_STATE_NONE) {
366 write_state_ = WRITE_STATE_WRITE;
367 DoWriteLoop(net::OK);
371 void CastSocket::DoWriteLoop(int result) {
372 DCHECK(CalledOnValidThread());
373 VLOG_WITH_URL(1) << "DoWriteLoop queue size: " << write_queue_.size();
375 if (write_queue_.empty()) {
376 write_state_ = WRITE_STATE_NONE;
380 // Network operations can either finish synchronously or asynchronously.
381 // This method executes the state machine transitions in a loop so that
382 // write state transitions happen even when network operations finish
386 WriteState state = write_state_;
387 write_state_ = WRITE_STATE_NONE;
389 case WRITE_STATE_WRITE:
392 case WRITE_STATE_WRITE_COMPLETE:
393 rv = DoWriteComplete(rv);
395 case WRITE_STATE_DO_CALLBACK:
396 rv = DoWriteCallback();
398 case WRITE_STATE_ERROR:
399 rv = DoWriteError(rv);
402 NOTREACHED() << "BUG in write flow. Unknown state: " << state;
405 } while (!write_queue_.empty() &&
406 rv != net::ERR_IO_PENDING &&
407 write_state_ != WRITE_STATE_NONE);
409 // If write loop is done because the queue is empty then set write
411 if (write_queue_.empty())
412 write_state_ = WRITE_STATE_NONE;
414 // Write loop is done - if the result is ERR_FAILED then close with error.
415 if (rv == net::ERR_FAILED)
416 CloseWithError(error_state_);
419 int CastSocket::DoWrite() {
420 DCHECK(!write_queue_.empty());
421 WriteRequest& request = write_queue_.front();
423 VLOG_WITH_URL(2) << "WriteData byte_count = " << request.io_buffer->size()
424 << " bytes_written " << request.io_buffer->BytesConsumed();
426 write_state_ = WRITE_STATE_WRITE_COMPLETE;
428 return socket_->Write(
429 request.io_buffer.get(),
430 request.io_buffer->BytesRemaining(),
431 base::Bind(&CastSocket::DoWriteLoop, AsWeakPtr()));
434 int CastSocket::DoWriteComplete(int result) {
435 DCHECK(!write_queue_.empty());
436 if (result <= 0) { // NOTE that 0 also indicates an error
437 error_state_ = CHANNEL_ERROR_SOCKET_ERROR;
438 write_state_ = WRITE_STATE_ERROR;
439 return result == 0 ? net::ERR_FAILED : result;
442 // Some bytes were successfully written
443 WriteRequest& request = write_queue_.front();
444 scoped_refptr<net::DrainableIOBuffer> io_buffer = request.io_buffer;
445 io_buffer->DidConsume(result);
446 if (io_buffer->BytesRemaining() == 0) // Message fully sent
447 write_state_ = WRITE_STATE_DO_CALLBACK;
449 write_state_ = WRITE_STATE_WRITE;
454 int CastSocket::DoWriteCallback() {
455 DCHECK(!write_queue_.empty());
456 WriteRequest& request = write_queue_.front();
457 int bytes_consumed = request.io_buffer->BytesConsumed();
459 // If inside connection flow, then there should be exaclty one item in
461 if (ready_state_ == READY_STATE_CONNECTING) {
463 DCHECK(write_queue_.empty());
464 PostTaskToStartConnectLoop(bytes_consumed);
466 WriteRequest& request = write_queue_.front();
467 request.callback.Run(bytes_consumed);
470 write_state_ = WRITE_STATE_WRITE;
474 int CastSocket::DoWriteError(int result) {
475 DCHECK(!write_queue_.empty());
476 DCHECK_LT(result, 0);
478 // If inside connection flow, then there should be exactly one item in
480 if (ready_state_ == READY_STATE_CONNECTING) {
482 DCHECK(write_queue_.empty());
483 PostTaskToStartConnectLoop(result);
484 // Connect loop will handle the error. Return net::OK so that write flow
485 // does not try to report error also.
489 while (!write_queue_.empty()) {
490 WriteRequest& request = write_queue_.front();
491 request.callback.Run(result);
494 return net::ERR_FAILED;
497 void CastSocket::PostTaskToStartReadLoop() {
498 DCHECK(CalledOnValidThread());
499 base::MessageLoop::current()->PostTask(
501 base::Bind(&CastSocket::StartReadLoop, AsWeakPtr()));
504 void CastSocket::StartReadLoop() {
505 // Read loop would have already been started if read state is not NONE
506 if (read_state_ == READ_STATE_NONE) {
507 read_state_ = READ_STATE_READ;
512 void CastSocket::DoReadLoop(int result) {
513 DCHECK(CalledOnValidThread());
514 // Network operations can either finish synchronously or asynchronously.
515 // This method executes the state machine transitions in a loop so that
516 // write state transitions happen even when network operations finish
520 ReadState state = read_state_;
521 read_state_ = READ_STATE_NONE;
524 case READ_STATE_READ:
527 case READ_STATE_READ_COMPLETE:
528 rv = DoReadComplete(rv);
530 case READ_STATE_DO_CALLBACK:
531 rv = DoReadCallback();
533 case READ_STATE_ERROR:
534 rv = DoReadError(rv);
537 NOTREACHED() << "BUG in read flow. Unknown state: " << state;
540 } while (rv != net::ERR_IO_PENDING && read_state_ != READ_STATE_NONE);
542 // Read loop is done - If the result is ERR_FAILED then close with error.
543 if (rv == net::ERR_FAILED)
544 CloseWithError(error_state_);
547 int CastSocket::DoRead() {
548 read_state_ = READ_STATE_READ_COMPLETE;
549 // Figure out whether to read header or body, and the remaining bytes.
550 uint32 num_bytes_to_read = 0;
551 if (header_read_buffer_->RemainingCapacity() > 0) {
552 current_read_buffer_ = header_read_buffer_;
553 num_bytes_to_read = header_read_buffer_->RemainingCapacity();
554 DCHECK_LE(num_bytes_to_read, kMessageHeaderSize);
556 DCHECK_GT(current_message_size_, 0U);
557 num_bytes_to_read = current_message_size_ - body_read_buffer_->offset();
558 current_read_buffer_ = body_read_buffer_;
559 DCHECK_LE(num_bytes_to_read, kMaxMessageSize);
561 DCHECK_GT(num_bytes_to_read, 0U);
563 // Read up to num_bytes_to_read into |current_read_buffer_|.
564 return socket_->Read(
565 current_read_buffer_.get(),
567 base::Bind(&CastSocket::DoReadLoop, AsWeakPtr()));
570 int CastSocket::DoReadComplete(int result) {
571 VLOG_WITH_URL(2) << "DoReadComplete result = " << result
572 << " header offset = " << header_read_buffer_->offset()
573 << " body offset = " << body_read_buffer_->offset();
574 if (result <= 0) { // 0 means EOF: the peer closed the socket
575 VLOG_WITH_URL(1) << "Read error, peer closed the socket";
576 error_state_ = CHANNEL_ERROR_SOCKET_ERROR;
577 read_state_ = READ_STATE_ERROR;
578 return result == 0 ? net::ERR_FAILED : result;
581 // Some data was read. Move the offset in the current buffer forward.
582 DCHECK_LE(current_read_buffer_->offset() + result,
583 current_read_buffer_->capacity());
584 current_read_buffer_->set_offset(current_read_buffer_->offset() + result);
585 read_state_ = READ_STATE_READ;
587 if (current_read_buffer_.get() == header_read_buffer_.get() &&
588 current_read_buffer_->RemainingCapacity() == 0) {
589 // A full header is read, process the contents.
590 if (!ProcessHeader()) {
591 error_state_ = cast_channel::CHANNEL_ERROR_INVALID_MESSAGE;
592 read_state_ = READ_STATE_ERROR;
594 } else if (current_read_buffer_.get() == body_read_buffer_.get() &&
595 static_cast<uint32>(current_read_buffer_->offset()) ==
596 current_message_size_) {
597 // Full body is read, process the contents.
599 read_state_ = READ_STATE_DO_CALLBACK;
601 error_state_ = cast_channel::CHANNEL_ERROR_INVALID_MESSAGE;
602 read_state_ = READ_STATE_ERROR;
609 int CastSocket::DoReadCallback() {
610 read_state_ = READ_STATE_READ;
611 const CastMessage& message = *(current_message_.get());
612 if (IsAuthMessage(message)) {
613 // An auth message is received, check that connect flow is running.
614 if (ready_state_ == READY_STATE_CONNECTING) {
615 challenge_reply_.reset(new CastMessage(message));
616 PostTaskToStartConnectLoop(net::OK);
618 read_state_ = READ_STATE_ERROR;
620 } else if (delegate_) {
621 MessageInfo message_info;
622 if (CastMessageToMessageInfo(message, &message_info))
623 delegate_->OnMessage(this, message_info);
625 read_state_ = READ_STATE_ERROR;
627 current_message_->Clear();
631 int CastSocket::DoReadError(int result) {
632 DCHECK_LE(result, 0);
633 // If inside connection flow, then get back to connect loop.
634 if (ready_state_ == READY_STATE_CONNECTING) {
635 PostTaskToStartConnectLoop(result);
636 // does not try to report error also.
639 return net::ERR_FAILED;
642 bool CastSocket::ProcessHeader() {
643 DCHECK_EQ(static_cast<uint32>(header_read_buffer_->offset()),
645 MessageHeader header;
646 MessageHeader::ReadFromIOBuffer(header_read_buffer_.get(), &header);
647 if (header.message_size > kMaxMessageSize)
650 VLOG_WITH_URL(2) << "Parsed header { message_size: "
651 << header.message_size << " }";
652 current_message_size_ = header.message_size;
656 bool CastSocket::ProcessBody() {
657 DCHECK_EQ(static_cast<uint32>(body_read_buffer_->offset()),
658 current_message_size_);
659 if (!current_message_->ParseFromArray(
660 body_read_buffer_->StartOfBuffer(), current_message_size_)) {
663 current_message_size_ = 0;
664 header_read_buffer_->set_offset(0);
665 body_read_buffer_->set_offset(0);
666 current_read_buffer_ = header_read_buffer_;
671 bool CastSocket::Serialize(const CastMessage& message_proto,
672 std::string* message_data) {
673 DCHECK(message_data);
674 message_proto.SerializeToString(message_data);
675 size_t message_size = message_data->size();
676 if (message_size > kMaxMessageSize) {
677 message_data->clear();
680 CastSocket::MessageHeader header;
681 header.SetMessageSize(message_size);
682 header.PrependToString(message_data);
686 void CastSocket::CloseWithError(ChannelError error) {
687 DCHECK(CalledOnValidThread());
689 ready_state_ = READY_STATE_CLOSED;
690 error_state_ = error;
692 delegate_->OnError(this, error);
695 bool CastSocket::ParseChannelUrl(const GURL& url) {
696 VLOG_WITH_URL(2) << "ParseChannelUrl";
697 if (url.SchemeIs(kCastInsecureScheme)) {
698 auth_required_ = false;
699 } else if (url.SchemeIs(kCastSecureScheme)) {
700 auth_required_ = true;
704 // TODO(mfoltz): Manual parsing, yech. Register cast[s] as standard schemes?
705 // TODO(mfoltz): Test for IPv6 addresses. Brackets or no brackets?
706 // TODO(mfoltz): Maybe enforce restriction to IPv4 private and IPv6
707 // link-local networks
708 const std::string& path = url.path();
709 // Shortest possible: //A:B
710 if (path.size() < 5) {
713 if (path.find("//") != 0) {
716 size_t colon = path.find_last_of(':');
717 if (colon == std::string::npos || colon < 3 || colon > path.size() - 2) {
720 const std::string& ip_address_str = path.substr(2, colon - 2);
721 const std::string& port_str = path.substr(colon + 1);
722 VLOG_WITH_URL(2) << "IP: " << ip_address_str << " Port: " << port_str;
724 if (!base::StringToInt(port_str, &port))
726 net::IPAddressNumber ip_address;
727 if (!net::ParseIPLiteralToNumber(ip_address_str, &ip_address))
729 ip_endpoint_ = net::IPEndPoint(ip_address, port);
733 void CastSocket::FillChannelInfo(ChannelInfo* channel_info) const {
734 channel_info->channel_id = channel_id_;
735 channel_info->url = url_.spec();
736 channel_info->ready_state = ready_state_;
737 channel_info->error_state = error_state_;
740 bool CastSocket::CalledOnValidThread() const {
741 return thread_checker_.CalledOnValidThread();
744 CastSocket::MessageHeader::MessageHeader() : message_size(0) { }
746 void CastSocket::MessageHeader::SetMessageSize(size_t size) {
747 DCHECK(size < static_cast<size_t>(kuint32max));
749 message_size = static_cast<size_t>(size);
752 void CastSocket::MessageHeader::PrependToString(std::string* str) {
753 MessageHeader output = *this;
754 output.message_size = base::HostToNet32(message_size);
755 char char_array[kMessageHeaderSize];
756 memcpy(&char_array, &output, arraysize(char_array));
757 str->insert(0, char_array, arraysize(char_array));
760 void CastSocket::MessageHeader::ReadFromIOBuffer(
761 net::GrowableIOBuffer* buffer, MessageHeader* header) {
763 memcpy(&message_size, buffer->StartOfBuffer(), kMessageHeaderSize);
764 header->message_size = base::NetToHost32(message_size);
767 std::string CastSocket::MessageHeader::ToString() {
768 return "{message_size: " + base::UintToString(message_size) + "}";
771 CastSocket::WriteRequest::WriteRequest(const net::CompletionCallback& callback)
772 : callback(callback) { }
774 bool CastSocket::WriteRequest::SetContent(const CastMessage& message_proto) {
775 DCHECK(!io_buffer.get());
776 std::string message_data;
777 if (!Serialize(message_proto, &message_data))
779 io_buffer = new net::DrainableIOBuffer(new net::StringIOBuffer(message_data),
780 message_data.size());
784 CastSocket::WriteRequest::~WriteRequest() { }
786 } // namespace cast_channel
788 } // namespace extensions