Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / extensions / api / cast_channel / cast_socket.cc
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.
4
5 #include "chrome/browser/extensions/api/cast_channel/cast_socket.h"
6
7 #include <string.h>
8
9 #include "base/bind.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"
31
32 // Assumes |url_| of type GURL is available in the current scope.
33 #define VLOG_WITH_URL(level) VLOG(level) << "[" + url_.spec() + "] "
34
35 namespace {
36
37 // Allowed schemes for Cast device URLs.
38 const char kCastInsecureScheme[] = "cast";
39 const char kCastSecureScheme[] = "casts";
40
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;
46
47 }  // namespace
48
49 namespace extensions {
50
51 static base::LazyInstance<
52   ProfileKeyedAPIFactory<ApiResourceManager<api::cast_channel::CastSocket> > >
53     g_factory = LAZY_INSTANCE_INITIALIZER;
54
55 // static
56 template <>
57 ProfileKeyedAPIFactory<ApiResourceManager<api::cast_channel::CastSocket> >*
58 ApiResourceManager<api::cast_channel::CastSocket>::GetFactoryInstance() {
59   return g_factory.Pointer();
60 }
61
62 namespace api {
63 namespace cast_channel {
64
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);
69
70 CastSocket::CastSocket(const std::string& owner_extension_id,
71                        const GURL& url,
72                        CastSocket::Delegate* delegate,
73                        net::NetLog* net_log) :
74     ApiResource(owner_extension_id),
75     channel_id_(0),
76     url_(url),
77     delegate_(delegate),
78     auth_required_(false),
79     current_message_size_(0),
80     current_message_(new CastMessage()),
81     net_log_(net_log),
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) {
87   DCHECK(net_log_);
88   net_log_source_.type = net::NetLog::SOURCE_SOCKET;
89   net_log_source_.id = net_log_->NextID();
90
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_;
97 }
98
99 CastSocket::~CastSocket() { }
100
101 const GURL& CastSocket::url() const {
102   return url_;
103 }
104
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.
112 }
113
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);
124   }
125
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
130   // context object.
131   context.cert_verifier = cert_verifier_.get();
132   context.transport_security_state = transport_security_state_.get();
133
134   scoped_ptr<net::ClientSocketHandle> connection(new net::ClientSocketHandle);
135   connection->SetSocket(socket.Pass());
136   net::HostPortPair host_and_port = net::HostPortPair::FromIPEndPoint(
137       ip_endpoint_);
138
139   return net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket(
140       connection.Pass(), host_and_port, ssl_config, context);
141 }
142
143 bool CastSocket::ExtractPeerCert(std::string* cert) {
144   DCHECK(cert);
145   DCHECK(peer_cert_.empty());
146   net::SSLInfo ssl_info;
147   if (!socket_->GetSSLInfo(&ssl_info) || !ssl_info.cert.get())
148     return false;
149   bool result = net::X509Certificate::GetDEREncoded(
150      ssl_info.cert->os_cert_handle(), cert);
151   if (result)
152     VLOG_WITH_URL(1) << "Successfully extracted peer certificate: " << *cert;
153   return result;
154 }
155
156 bool CastSocket::VerifyChallengeReply() {
157   return AuthenticateChallengeReply(*challenge_reply_.get(), peer_cert_);
158 }
159
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);
165     return;
166   }
167   if (!ParseChannelUrl(url_)) {
168     callback.Run(net::ERR_CONNECTION_FAILED);
169     return;
170   }
171
172   ready_state_ = READY_STATE_CONNECTING;
173   connect_callback_ = callback;
174   connect_state_ = CONN_STATE_TCP_CONNECT;
175   DoConnectLoop(net::OK);
176 }
177
178 void CastSocket::PostTaskToStartConnectLoop(int result) {
179   DCHECK(CalledOnValidThread());
180   base::MessageLoop::current()->PostTask(
181       FROM_HERE,
182       base::Bind(&CastSocket::DoConnectLoop, AsWeakPtr(), result));
183 }
184
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
193   // synchronously.
194   int rv = result;
195   do {
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;
200     switch (state) {
201       case CONN_STATE_TCP_CONNECT:
202         rv = DoTcpConnect();
203         break;
204       case CONN_STATE_TCP_CONNECT_COMPLETE:
205         rv = DoTcpConnectComplete(rv);
206         break;
207       case CONN_STATE_SSL_CONNECT:
208         DCHECK_EQ(net::OK, rv);
209         rv = DoSslConnect();
210         break;
211       case CONN_STATE_SSL_CONNECT_COMPLETE:
212         rv = DoSslConnectComplete(rv);
213         break;
214       case CONN_STATE_AUTH_CHALLENGE_SEND:
215         rv = DoAuthChallengeSend();
216         break;
217       case CONN_STATE_AUTH_CHALLENGE_SEND_COMPLETE:
218         rv = DoAuthChallengeSendComplete(rv);
219         break;
220       case CONN_STATE_AUTH_CHALLENGE_REPLY_COMPLETE:
221         rv = DoAuthChallengeReplyComplete(rv);
222         break;
223       default:
224         NOTREACHED() << "BUG in connect flow. Unknown state: " << state;
225         break;
226     }
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
231
232   // Connect loop is finished: if there is no pending IO invoke the callback.
233   if (rv != net::ERR_IO_PENDING)
234     DoConnectCallback(rv);
235 }
236
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()));
243 }
244
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;
252   }
253   return result;
254 }
255
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()));
262 }
263
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;
272   }
273   return result;
274 }
275
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(
287       FROM_HERE,
288       base::Bind(&CastSocket::SendCastMessageInternal, AsWeakPtr(),
289                  challenge_message,
290                  base::Bind(&CastSocket::DoConnectLoop, AsWeakPtr())));
291   // Always return IO_PENDING since the result is always asynchronous.
292   return net::ERR_IO_PENDING;
293 }
294
295 int CastSocket::DoAuthChallengeSendComplete(int result) {
296   VLOG_WITH_URL(1) << "DoAuthChallengeSendComplete: " << result;
297   if (result < 0)
298     return 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;
306 }
307
308 int CastSocket::DoAuthChallengeReplyComplete(int result) {
309   VLOG_WITH_URL(1) << "DoAuthChallengeReplyComplete: " << result;
310   if (result < 0)
311     return result;
312   if (!VerifyChallengeReply())
313     return net::ERR_FAILED;
314   VLOG_WITH_URL(1) << "Auth challenge verification succeeded";
315   return net::OK;
316 }
317
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);
325 }
326
327 void CastSocket::Close(const net::CompletionCallback& callback) {
328   DCHECK(CalledOnValidThread());
329   VLOG_WITH_URL(1) << "Close ReadyState = " << ready_state_;
330   tcp_socket_.reset();
331   socket_.reset();
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|
337 }
338
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);
344     return;
345   }
346   CastMessage message_proto;
347   if (!MessageInfoToCastMessage(message, &message_proto)) {
348     callback.Run(net::ERR_FAILED);
349     return;
350   }
351
352   SendCastMessageInternal(message_proto, callback);
353 }
354
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);
361     return;
362   }
363
364   write_queue_.push(write_request);
365   if (write_state_ == WRITE_STATE_NONE) {
366     write_state_ = WRITE_STATE_WRITE;
367     DoWriteLoop(net::OK);
368   }
369 }
370
371 void CastSocket::DoWriteLoop(int result) {
372   DCHECK(CalledOnValidThread());
373   VLOG_WITH_URL(1) << "DoWriteLoop queue size: " << write_queue_.size();
374
375   if (write_queue_.empty()) {
376     write_state_ = WRITE_STATE_NONE;
377     return;
378   }
379
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
383   // synchronously.
384   int rv = result;
385   do {
386     WriteState state = write_state_;
387     write_state_ = WRITE_STATE_NONE;
388     switch (state) {
389       case WRITE_STATE_WRITE:
390         rv = DoWrite();
391         break;
392       case WRITE_STATE_WRITE_COMPLETE:
393         rv = DoWriteComplete(rv);
394         break;
395       case WRITE_STATE_DO_CALLBACK:
396         rv = DoWriteCallback();
397         break;
398       case WRITE_STATE_ERROR:
399         rv = DoWriteError(rv);
400         break;
401       default:
402         NOTREACHED() << "BUG in write flow. Unknown state: " << state;
403         break;
404     }
405   } while (!write_queue_.empty() &&
406            rv != net::ERR_IO_PENDING &&
407            write_state_ != WRITE_STATE_NONE);
408
409   // If write loop is done because the queue is empty then set write
410   // state to NONE
411   if (write_queue_.empty())
412     write_state_ = WRITE_STATE_NONE;
413
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_);
417 }
418
419 int CastSocket::DoWrite() {
420   DCHECK(!write_queue_.empty());
421   WriteRequest& request = write_queue_.front();
422
423   VLOG_WITH_URL(2) << "WriteData byte_count = " << request.io_buffer->size()
424                    << " bytes_written " << request.io_buffer->BytesConsumed();
425
426   write_state_ = WRITE_STATE_WRITE_COMPLETE;
427
428   return socket_->Write(
429       request.io_buffer.get(),
430       request.io_buffer->BytesRemaining(),
431       base::Bind(&CastSocket::DoWriteLoop, AsWeakPtr()));
432 }
433
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;
440   }
441
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;
448   else
449     write_state_ = WRITE_STATE_WRITE;
450
451   return net::OK;
452 }
453
454 int CastSocket::DoWriteCallback() {
455   DCHECK(!write_queue_.empty());
456   WriteRequest& request = write_queue_.front();
457   int bytes_consumed = request.io_buffer->BytesConsumed();
458
459   // If inside connection flow, then there should be exaclty one item in
460   // the write queue.
461   if (ready_state_ == READY_STATE_CONNECTING) {
462     write_queue_.pop();
463     DCHECK(write_queue_.empty());
464     PostTaskToStartConnectLoop(bytes_consumed);
465   } else {
466     WriteRequest& request = write_queue_.front();
467     request.callback.Run(bytes_consumed);
468     write_queue_.pop();
469   }
470   write_state_ = WRITE_STATE_WRITE;
471   return net::OK;
472 }
473
474 int CastSocket::DoWriteError(int result) {
475   DCHECK(!write_queue_.empty());
476   DCHECK_LT(result, 0);
477
478   // If inside connection flow, then there should be exactly one item in
479   // the write queue.
480   if (ready_state_ == READY_STATE_CONNECTING) {
481     write_queue_.pop();
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.
486     return net::OK;
487   }
488
489   while (!write_queue_.empty()) {
490     WriteRequest& request = write_queue_.front();
491     request.callback.Run(result);
492     write_queue_.pop();
493   }
494   return net::ERR_FAILED;
495 }
496
497 void CastSocket::PostTaskToStartReadLoop() {
498   DCHECK(CalledOnValidThread());
499   base::MessageLoop::current()->PostTask(
500       FROM_HERE,
501       base::Bind(&CastSocket::StartReadLoop, AsWeakPtr()));
502 }
503
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;
508     DoReadLoop(net::OK);
509   }
510 }
511
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
517   // synchronously.
518   int rv = result;
519   do {
520     ReadState state = read_state_;
521     read_state_ = READ_STATE_NONE;
522
523     switch (state) {
524       case READ_STATE_READ:
525         rv = DoRead();
526         break;
527       case READ_STATE_READ_COMPLETE:
528         rv = DoReadComplete(rv);
529         break;
530       case READ_STATE_DO_CALLBACK:
531         rv = DoReadCallback();
532         break;
533       case READ_STATE_ERROR:
534         rv = DoReadError(rv);
535         break;
536       default:
537         NOTREACHED() << "BUG in read flow. Unknown state: " << state;
538         break;
539     }
540   } while (rv != net::ERR_IO_PENDING && read_state_ != READ_STATE_NONE);
541
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_);
545 }
546
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);
555   } else {
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);
560   }
561   DCHECK_GT(num_bytes_to_read, 0U);
562
563   // Read up to num_bytes_to_read into |current_read_buffer_|.
564   return socket_->Read(
565       current_read_buffer_.get(),
566       num_bytes_to_read,
567       base::Bind(&CastSocket::DoReadLoop, AsWeakPtr()));
568 }
569
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;
579   }
580
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;
586
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;
593     }
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.
598     if (ProcessBody()) {
599       read_state_ = READ_STATE_DO_CALLBACK;
600     } else {
601       error_state_ = cast_channel::CHANNEL_ERROR_INVALID_MESSAGE;
602       read_state_ = READ_STATE_ERROR;
603     }
604   }
605
606   return net::OK;
607 }
608
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);
617     } else {
618       read_state_ = READ_STATE_ERROR;
619     }
620   } else if (delegate_) {
621     MessageInfo message_info;
622     if (CastMessageToMessageInfo(message, &message_info))
623       delegate_->OnMessage(this, message_info);
624     else
625       read_state_ = READ_STATE_ERROR;
626   }
627   current_message_->Clear();
628   return net::OK;
629 }
630
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.
637     return net::OK;
638   }
639   return net::ERR_FAILED;
640 }
641
642 bool CastSocket::ProcessHeader() {
643   DCHECK_EQ(static_cast<uint32>(header_read_buffer_->offset()),
644             kMessageHeaderSize);
645   MessageHeader header;
646   MessageHeader::ReadFromIOBuffer(header_read_buffer_.get(), &header);
647   if (header.message_size > kMaxMessageSize)
648     return false;
649
650   VLOG_WITH_URL(2) << "Parsed header { message_size: "
651                    << header.message_size << " }";
652   current_message_size_ = header.message_size;
653   return true;
654 }
655
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_)) {
661     return false;
662   }
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_;
667   return true;
668 }
669
670 // static
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();
678     return false;
679   }
680   CastSocket::MessageHeader header;
681   header.SetMessageSize(message_size);
682   header.PrependToString(message_data);
683   return true;
684 };
685
686 void CastSocket::CloseWithError(ChannelError error) {
687   DCHECK(CalledOnValidThread());
688   socket_.reset(NULL);
689   ready_state_ = READY_STATE_CLOSED;
690   error_state_ = error;
691   if (delegate_)
692     delegate_->OnError(this, error);
693 }
694
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;
701   } else {
702     return false;
703   }
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) {
711     return false;
712   }
713   if (path.find("//") != 0) {
714     return false;
715   }
716   size_t colon = path.find_last_of(':');
717   if (colon == std::string::npos || colon < 3 || colon > path.size() - 2) {
718     return false;
719   }
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;
723   int port;
724   if (!base::StringToInt(port_str, &port))
725     return false;
726   net::IPAddressNumber ip_address;
727   if (!net::ParseIPLiteralToNumber(ip_address_str, &ip_address))
728     return false;
729   ip_endpoint_ = net::IPEndPoint(ip_address, port);
730   return true;
731 };
732
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_;
738 }
739
740 bool CastSocket::CalledOnValidThread() const {
741   return thread_checker_.CalledOnValidThread();
742 }
743
744 CastSocket::MessageHeader::MessageHeader() : message_size(0) { }
745
746 void CastSocket::MessageHeader::SetMessageSize(size_t size) {
747   DCHECK(size < static_cast<size_t>(kuint32max));
748   DCHECK(size > 0);
749   message_size = static_cast<size_t>(size);
750 }
751
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));
758 }
759
760 void CastSocket::MessageHeader::ReadFromIOBuffer(
761     net::GrowableIOBuffer* buffer, MessageHeader* header) {
762   uint32 message_size;
763   memcpy(&message_size, buffer->StartOfBuffer(), kMessageHeaderSize);
764   header->message_size = base::NetToHost32(message_size);
765 }
766
767 std::string CastSocket::MessageHeader::ToString() {
768   return "{message_size: " + base::UintToString(message_size) + "}";
769 }
770
771 CastSocket::WriteRequest::WriteRequest(const net::CompletionCallback& callback)
772   : callback(callback) { }
773
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))
778     return false;
779   io_buffer = new net::DrainableIOBuffer(new net::StringIOBuffer(message_data),
780                                          message_data.size());
781   return true;
782 }
783
784 CastSocket::WriteRequest::~WriteRequest() { }
785
786 }  // namespace cast_channel
787 }  // namespace api
788 }  // namespace extensions
789
790 #undef VLOG_WITH_URL