1 // Copyright 2014 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 "extensions/browser/api/cast_channel/cast_channel_api.h"
10 #include "base/json/json_writer.h"
11 #include "base/lazy_instance.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/time/default_tick_clock.h"
15 #include "base/values.h"
16 #include "content/public/browser/browser_thread.h"
17 #include "extensions/browser/api/cast_channel/cast_auth_ica.h"
18 #include "extensions/browser/api/cast_channel/cast_message_util.h"
19 #include "extensions/browser/api/cast_channel/cast_socket.h"
20 #include "extensions/browser/api/cast_channel/keep_alive_delegate.h"
21 #include "extensions/browser/api/cast_channel/logger.h"
22 #include "extensions/browser/event_router.h"
23 #include "extensions/common/api/cast_channel/cast_channel.pb.h"
24 #include "extensions/common/api/cast_channel/logging.pb.h"
25 #include "net/base/ip_endpoint.h"
26 #include "net/base/net_errors.h"
27 #include "net/base/net_util.h"
30 // Default timeout interval for connection setup.
31 // Used if not otherwise specified at ConnectInfo::timeout.
32 const int kDefaultConnectTimeoutMillis
= 5000; // 5 seconds.
34 namespace extensions
{
36 namespace Close
= cast_channel::Close
;
37 namespace OnError
= cast_channel::OnError
;
38 namespace OnMessage
= cast_channel::OnMessage
;
39 namespace Open
= cast_channel::Open
;
40 namespace Send
= cast_channel::Send
;
41 using cast_channel::CastDeviceCapability
;
42 using cast_channel::CastMessage
;
43 using cast_channel::CastSocket
;
44 using cast_channel::ChannelAuthType
;
45 using cast_channel::ChannelError
;
46 using cast_channel::ChannelInfo
;
47 using cast_channel::ConnectInfo
;
48 using cast_channel::ErrorInfo
;
49 using cast_channel::LastErrors
;
50 using cast_channel::Logger
;
51 using cast_channel::MessageInfo
;
52 using cast_channel::ReadyState
;
53 using content::BrowserThread
;
57 // T is an extension dictionary (MessageInfo or ChannelInfo)
59 std::string
ParamToString(const T
& info
) {
60 scoped_ptr
<base::DictionaryValue
> dict
= info
.ToValue();
62 base::JSONWriter::Write(dict
.get(), &out
);
66 // Fills |channel_info| from the destination and state of |socket|.
67 void FillChannelInfo(const CastSocket
& socket
, ChannelInfo
* channel_info
) {
69 channel_info
->channel_id
= socket
.id();
70 channel_info
->url
= socket
.cast_url();
71 const net::IPEndPoint
& ip_endpoint
= socket
.ip_endpoint();
72 channel_info
->connect_info
.ip_address
= ip_endpoint
.ToStringWithoutPort();
73 channel_info
->connect_info
.port
= ip_endpoint
.port();
74 channel_info
->connect_info
.auth
= socket
.channel_auth();
75 channel_info
->ready_state
= socket
.ready_state();
76 channel_info
->error_state
= socket
.error_state();
77 channel_info
->keep_alive
= socket
.keep_alive();
80 // Fills |error_info| from |error_state| and |last_errors|.
81 void FillErrorInfo(ChannelError error_state
,
82 const LastErrors
& last_errors
,
83 ErrorInfo
* error_info
) {
84 error_info
->error_state
= error_state
;
85 if (last_errors
.event_type
!= cast_channel::proto::EVENT_TYPE_UNKNOWN
)
86 error_info
->event_type
.reset(new int(last_errors
.event_type
));
87 if (last_errors
.challenge_reply_error_type
!=
88 cast_channel::proto::CHALLENGE_REPLY_ERROR_NONE
) {
89 error_info
->challenge_reply_error_type
.reset(
90 new int(last_errors
.challenge_reply_error_type
));
92 if (last_errors
.net_return_value
<= 0)
93 error_info
->net_return_value
.reset(new int(last_errors
.net_return_value
));
94 if (last_errors
.nss_error_code
< 0)
95 error_info
->nss_error_code
.reset(new int(last_errors
.nss_error_code
));
98 bool IsValidConnectInfoPort(const ConnectInfo
& connect_info
) {
99 return connect_info
.port
> 0 && connect_info
.port
<
100 std::numeric_limits
<uint16_t>::max();
103 bool IsValidConnectInfoAuth(const ConnectInfo
& connect_info
) {
104 return connect_info
.auth
== cast_channel::CHANNEL_AUTH_TYPE_SSL_VERIFIED
||
105 connect_info
.auth
== cast_channel::CHANNEL_AUTH_TYPE_SSL
;
108 bool IsValidConnectInfoIpAddress(const ConnectInfo
& connect_info
) {
109 net::IPAddressNumber ip_address
;
110 return net::ParseIPLiteralToNumber(connect_info
.ip_address
, &ip_address
);
115 CastChannelAPI::CastChannelAPI(content::BrowserContext
* context
)
116 : browser_context_(context
),
118 new Logger(scoped_ptr
<base::TickClock
>(new base::DefaultTickClock
),
119 base::TimeTicks::UnixEpoch())) {
120 DCHECK(browser_context_
);
124 CastChannelAPI
* CastChannelAPI::Get(content::BrowserContext
* context
) {
125 return BrowserContextKeyedAPIFactory
<CastChannelAPI
>::Get(context
);
128 scoped_refptr
<Logger
> CastChannelAPI::GetLogger() {
132 static base::LazyInstance
<BrowserContextKeyedAPIFactory
<CastChannelAPI
> >
133 g_factory
= LAZY_INSTANCE_INITIALIZER
;
136 BrowserContextKeyedAPIFactory
<CastChannelAPI
>*
137 CastChannelAPI::GetFactoryInstance() {
138 return g_factory
.Pointer();
141 void CastChannelAPI::SetSocketForTest(scoped_ptr
<CastSocket
> socket_for_test
) {
142 socket_for_test_
= socket_for_test
.Pass();
145 scoped_ptr
<CastSocket
> CastChannelAPI::GetSocketForTest() {
146 return socket_for_test_
.Pass();
149 content::BrowserContext
* CastChannelAPI::GetBrowserContext() const {
150 return browser_context_
;
153 void CastChannelAPI::SetPingTimeoutTimerForTest(scoped_ptr
<base::Timer
> timer
) {
154 injected_timeout_timer_
= timer
.Pass();
157 scoped_ptr
<base::Timer
> CastChannelAPI::GetInjectedTimeoutTimerForTest() {
158 return injected_timeout_timer_
.Pass();
161 CastChannelAPI::~CastChannelAPI() {}
163 CastChannelAsyncApiFunction::CastChannelAsyncApiFunction() : manager_(NULL
) {
166 CastChannelAsyncApiFunction::~CastChannelAsyncApiFunction() { }
168 bool CastChannelAsyncApiFunction::PrePrepare() {
169 manager_
= ApiResourceManager
<CastSocket
>::Get(browser_context());
173 bool CastChannelAsyncApiFunction::Respond() {
174 return GetError().empty();
177 CastSocket
* CastChannelAsyncApiFunction::GetSocketOrCompleteWithError(
179 CastSocket
* socket
= GetSocket(channel_id
);
181 SetResultFromError(channel_id
,
182 cast_channel::CHANNEL_ERROR_INVALID_CHANNEL_ID
);
183 AsyncWorkCompleted();
188 int CastChannelAsyncApiFunction::AddSocket(CastSocket
* socket
) {
189 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
192 const int id
= manager_
->Add(socket
);
197 void CastChannelAsyncApiFunction::RemoveSocket(int channel_id
) {
198 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
200 manager_
->Remove(extension_
->id(), channel_id
);
203 void CastChannelAsyncApiFunction::SetResultFromSocket(
204 const CastSocket
& socket
) {
205 ChannelInfo channel_info
;
206 FillChannelInfo(socket
, &channel_info
);
207 ChannelError error
= socket
.error_state();
208 if (error
!= cast_channel::CHANNEL_ERROR_NONE
) {
209 SetError("Channel socket error = " + base::IntToString(error
));
211 SetResultFromChannelInfo(channel_info
);
214 void CastChannelAsyncApiFunction::SetResultFromError(int channel_id
,
215 ChannelError error
) {
216 ChannelInfo channel_info
;
217 channel_info
.channel_id
= channel_id
;
218 channel_info
.url
= "";
219 channel_info
.ready_state
= cast_channel::READY_STATE_CLOSED
;
220 channel_info
.error_state
= error
;
221 channel_info
.connect_info
.ip_address
= "";
222 channel_info
.connect_info
.port
= 0;
223 channel_info
.connect_info
.auth
= cast_channel::CHANNEL_AUTH_TYPE_SSL
;
224 SetResultFromChannelInfo(channel_info
);
225 SetError("Channel error = " + base::IntToString(error
));
228 CastSocket
* CastChannelAsyncApiFunction::GetSocket(int channel_id
) const {
229 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
231 return manager_
->Get(extension_
->id(), channel_id
);
234 void CastChannelAsyncApiFunction::SetResultFromChannelInfo(
235 const ChannelInfo
& channel_info
) {
236 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
237 SetResult(channel_info
.ToValue().release());
240 CastChannelOpenFunction::CastChannelOpenFunction()
241 : new_channel_id_(0) { }
243 CastChannelOpenFunction::~CastChannelOpenFunction() { }
245 // TODO(mfoltz): Remove URL parsing when clients have converted to use
248 // Allowed schemes for Cast device URLs.
249 const char kCastInsecureScheme
[] = "cast";
250 const char kCastSecureScheme
[] = "casts";
252 bool CastChannelOpenFunction::ParseChannelUrl(const GURL
& url
,
253 ConnectInfo
* connect_info
) {
254 DCHECK(connect_info
);
255 VLOG(2) << "ParseChannelUrl";
256 bool auth_required
= false;
257 if (url
.SchemeIs(kCastSecureScheme
)) {
258 auth_required
= true;
259 } else if (!url
.SchemeIs(kCastInsecureScheme
)) {
262 // TODO(mfoltz): Test for IPv6 addresses. Brackets or no brackets?
263 // TODO(mfoltz): Maybe enforce restriction to IPv4 private and IPv6
264 // link-local networks
265 const std::string
& path
= url
.path();
266 // Shortest possible: //A:B
267 if (path
.size() < 5) {
270 if (path
.find("//") != 0) {
273 size_t colon
= path
.find_last_of(':');
274 if (colon
== std::string::npos
|| colon
< 3 || colon
> path
.size() - 2) {
277 const std::string
& ip_address_str
= path
.substr(2, colon
- 2);
278 const std::string
& port_str
= path
.substr(colon
+ 1);
279 VLOG(2) << "IP: " << ip_address_str
<< " Port: " << port_str
;
281 if (!base::StringToInt(port_str
, &port
))
283 connect_info
->ip_address
= ip_address_str
;
284 connect_info
->port
= port
;
285 connect_info
->auth
= auth_required
?
286 cast_channel::CHANNEL_AUTH_TYPE_SSL_VERIFIED
:
287 cast_channel::CHANNEL_AUTH_TYPE_SSL
;
291 net::IPEndPoint
* CastChannelOpenFunction::ParseConnectInfo(
292 const ConnectInfo
& connect_info
) {
293 net::IPAddressNumber ip_address
;
294 CHECK(net::ParseIPLiteralToNumber(connect_info
.ip_address
, &ip_address
));
295 return new net::IPEndPoint(ip_address
,
296 static_cast<uint16
>(connect_info
.port
));
299 bool CastChannelOpenFunction::PrePrepare() {
300 api_
= CastChannelAPI::Get(browser_context());
301 return CastChannelAsyncApiFunction::PrePrepare();
304 bool CastChannelOpenFunction::Prepare() {
305 params_
= Open::Params::Create(*args_
);
306 EXTENSION_FUNCTION_VALIDATE(params_
.get());
307 // The connect_info parameter may be a string URL like cast:// or casts:// or
308 // a ConnectInfo object.
309 std::string cast_url
;
310 switch (params_
->connect_info
->GetType()) {
311 case base::Value::TYPE_STRING
:
312 CHECK(params_
->connect_info
->GetAsString(&cast_url
));
313 connect_info_
.reset(new ConnectInfo
);
314 if (!ParseChannelUrl(GURL(cast_url
), connect_info_
.get())) {
315 connect_info_
.reset();
316 SetError("Invalid connect_info (invalid Cast URL " + cast_url
+ ")");
319 case base::Value::TYPE_DICTIONARY
:
320 connect_info_
= ConnectInfo::FromValue(*(params_
->connect_info
));
321 if (!connect_info_
.get()) {
322 SetError("connect_info.auth is required");
326 SetError("Invalid connect_info (unknown type)");
329 if (!connect_info_
.get()) {
332 if (!IsValidConnectInfoPort(*connect_info_
)) {
333 SetError("Invalid connect_info (invalid port)");
334 } else if (!IsValidConnectInfoAuth(*connect_info_
)) {
335 SetError("Invalid connect_info (invalid auth)");
336 } else if (!IsValidConnectInfoIpAddress(*connect_info_
)) {
337 SetError("Invalid connect_info (invalid IP address)");
339 // Parse timeout parameters if they are set.
340 if (connect_info_
->liveness_timeout
) {
342 base::TimeDelta::FromMilliseconds(*connect_info_
->liveness_timeout
);
344 if (connect_info_
->ping_interval
) {
346 base::TimeDelta::FromMilliseconds(*connect_info_
->ping_interval
);
349 // Validate timeout parameters.
350 if (liveness_timeout_
< base::TimeDelta() ||
351 ping_interval_
< base::TimeDelta()) {
352 SetError("livenessTimeout and pingInterval must be greater than 0.");
353 } else if ((liveness_timeout_
> base::TimeDelta()) !=
354 (ping_interval_
> base::TimeDelta())) {
355 SetError("livenessTimeout and pingInterval must be set together.");
356 } else if (liveness_timeout_
< ping_interval_
) {
357 SetError("livenessTimeout must be longer than pingTimeout.");
361 if (!GetError().empty()) {
365 channel_auth_
= connect_info_
->auth
;
366 ip_endpoint_
.reset(ParseConnectInfo(*connect_info_
));
370 void CastChannelOpenFunction::AsyncWorkStart() {
372 DCHECK(ip_endpoint_
.get());
374 scoped_ptr
<CastSocket
> test_socket
= api_
->GetSocketForTest();
375 if (test_socket
.get()) {
376 socket
= test_socket
.release();
378 socket
= new cast_channel::CastSocketImpl(
379 extension_
->id(), *ip_endpoint_
, channel_auth_
,
380 ExtensionsBrowserClient::Get()->GetNetLog(),
381 base::TimeDelta::FromMilliseconds(connect_info_
->timeout
.get()
382 ? *connect_info_
->timeout
383 : kDefaultConnectTimeoutMillis
),
384 liveness_timeout_
> base::TimeDelta(), api_
->GetLogger(),
385 connect_info_
->capabilities
? *connect_info_
->capabilities
386 : CastDeviceCapability::NONE
);
388 new_channel_id_
= AddSocket(socket
);
389 api_
->GetLogger()->LogNewSocketEvent(*socket
);
391 // Construct read delegates.
392 scoped_ptr
<core_api::cast_channel::CastTransport::Delegate
> delegate(
393 make_scoped_ptr(new CastMessageHandler(api_
, socket
)));
394 if (socket
->keep_alive()) {
395 // Wrap read delegate in a KeepAliveDelegate for timeout handling.
396 core_api::cast_channel::KeepAliveDelegate
* keep_alive
=
397 new core_api::cast_channel::KeepAliveDelegate(
398 socket
, delegate
.Pass(), ping_interval_
, liveness_timeout_
);
399 scoped_ptr
<base::Timer
> injected_timer
=
400 api_
->GetInjectedTimeoutTimerForTest();
401 if (injected_timer
) {
402 keep_alive
->SetTimersForTest(
403 make_scoped_ptr(new base::Timer(false, false)),
404 injected_timer
.Pass());
406 delegate
.reset(keep_alive
);
409 api_
->GetLogger()->LogNewSocketEvent(*socket
);
410 socket
->Connect(delegate
.Pass(),
411 base::Bind(&CastChannelOpenFunction::OnOpen
, this));
414 void CastChannelOpenFunction::OnOpen(cast_channel::ChannelError result
) {
415 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
416 VLOG(1) << "Connect finished, OnOpen invoked.";
417 CastSocket
* socket
= GetSocket(new_channel_id_
);
419 SetResultFromError(new_channel_id_
, result
);
421 SetResultFromSocket(*socket
);
423 AsyncWorkCompleted();
426 CastChannelSendFunction::CastChannelSendFunction() { }
428 CastChannelSendFunction::~CastChannelSendFunction() { }
430 bool CastChannelSendFunction::Prepare() {
431 params_
= Send::Params::Create(*args_
);
432 EXTENSION_FUNCTION_VALIDATE(params_
.get());
433 if (params_
->message
.namespace_
.empty()) {
434 SetError("message_info.namespace_ is required");
437 if (params_
->message
.source_id
.empty()) {
438 SetError("message_info.source_id is required");
441 if (params_
->message
.destination_id
.empty()) {
442 SetError("message_info.destination_id is required");
445 switch (params_
->message
.data
->GetType()) {
446 case base::Value::TYPE_STRING
:
447 case base::Value::TYPE_BINARY
:
450 SetError("Invalid type of message_info.data");
456 void CastChannelSendFunction::AsyncWorkStart() {
457 CastSocket
* socket
= GetSocket(params_
->channel
.channel_id
);
459 SetResultFromError(params_
->channel
.channel_id
,
460 cast_channel::CHANNEL_ERROR_INVALID_CHANNEL_ID
);
461 AsyncWorkCompleted();
464 CastMessage message_to_send
;
465 if (!MessageInfoToCastMessage(params_
->message
, &message_to_send
)) {
466 SetResultFromError(params_
->channel
.channel_id
,
467 cast_channel::CHANNEL_ERROR_INVALID_MESSAGE
);
468 AsyncWorkCompleted();
471 socket
->transport()->SendMessage(
472 message_to_send
, base::Bind(&CastChannelSendFunction::OnSend
, this));
475 void CastChannelSendFunction::OnSend(int result
) {
476 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
477 int channel_id
= params_
->channel
.channel_id
;
478 CastSocket
* socket
= GetSocket(channel_id
);
479 if (result
< 0 || !socket
) {
480 SetResultFromError(channel_id
,
481 cast_channel::CHANNEL_ERROR_SOCKET_ERROR
);
483 SetResultFromSocket(*socket
);
485 AsyncWorkCompleted();
488 CastChannelCloseFunction::CastChannelCloseFunction() { }
490 CastChannelCloseFunction::~CastChannelCloseFunction() { }
492 bool CastChannelCloseFunction::Prepare() {
493 params_
= Close::Params::Create(*args_
);
494 EXTENSION_FUNCTION_VALIDATE(params_
.get());
498 void CastChannelCloseFunction::AsyncWorkStart() {
499 CastSocket
* socket
= GetSocket(params_
->channel
.channel_id
);
501 SetResultFromError(params_
->channel
.channel_id
,
502 cast_channel::CHANNEL_ERROR_INVALID_CHANNEL_ID
);
503 AsyncWorkCompleted();
505 socket
->Close(base::Bind(&CastChannelCloseFunction::OnClose
, this));
509 void CastChannelCloseFunction::OnClose(int result
) {
510 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
511 VLOG(1) << "CastChannelCloseFunction::OnClose result = " << result
;
512 int channel_id
= params_
->channel
.channel_id
;
513 CastSocket
* socket
= GetSocket(channel_id
);
514 if (result
< 0 || !socket
) {
515 SetResultFromError(channel_id
,
516 cast_channel::CHANNEL_ERROR_SOCKET_ERROR
);
518 SetResultFromSocket(*socket
);
519 // This will delete |socket|.
520 RemoveSocket(channel_id
);
522 AsyncWorkCompleted();
525 CastChannelGetLogsFunction::CastChannelGetLogsFunction() {
528 CastChannelGetLogsFunction::~CastChannelGetLogsFunction() {
531 bool CastChannelGetLogsFunction::PrePrepare() {
532 api_
= CastChannelAPI::Get(browser_context());
533 return CastChannelAsyncApiFunction::PrePrepare();
536 bool CastChannelGetLogsFunction::Prepare() {
540 void CastChannelGetLogsFunction::AsyncWorkStart() {
544 scoped_ptr
<char[]> out
= api_
->GetLogger()->GetLogs(&length
);
546 SetResult(new base::BinaryValue(out
.Pass(), length
));
548 SetError("Unable to get logs.");
551 api_
->GetLogger()->Reset();
553 AsyncWorkCompleted();
556 CastChannelOpenFunction::CastMessageHandler::CastMessageHandler(
558 cast_channel::CastSocket
* socket
)
559 : api(api
), socket(socket
) {
564 CastChannelOpenFunction::CastMessageHandler::~CastMessageHandler() {
567 void CastChannelOpenFunction::CastMessageHandler::OnError(
568 cast_channel::ChannelError error_state
,
569 const cast_channel::LastErrors
& last_errors
) {
570 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
572 ChannelInfo channel_info
;
573 FillChannelInfo(*socket
, &channel_info
);
574 channel_info
.error_state
= error_state
;
575 ErrorInfo error_info
;
576 FillErrorInfo(error_state
, last_errors
, &error_info
);
578 scoped_ptr
<base::ListValue
> results
=
579 OnError::Create(channel_info
, error_info
);
580 scoped_ptr
<Event
> event(new Event(OnError::kEventName
, results
.Pass()));
581 extensions::EventRouter::Get(api
->GetBrowserContext())
582 ->DispatchEventToExtension(socket
->owner_extension_id(), event
.Pass());
585 void CastChannelOpenFunction::CastMessageHandler::OnMessage(
586 const CastMessage
& message
) {
587 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
589 MessageInfo message_info
;
590 cast_channel::CastMessageToMessageInfo(message
, &message_info
);
591 ChannelInfo channel_info
;
592 FillChannelInfo(*socket
, &channel_info
);
593 VLOG(1) << "Received message " << ParamToString(message_info
)
594 << " on channel " << ParamToString(channel_info
);
596 scoped_ptr
<base::ListValue
> results
=
597 OnMessage::Create(channel_info
, message_info
);
598 scoped_ptr
<Event
> event(new Event(OnMessage::kEventName
, results
.Pass()));
599 extensions::EventRouter::Get(api
->GetBrowserContext())
600 ->DispatchEventToExtension(socket
->owner_extension_id(), event
.Pass());
603 void CastChannelOpenFunction::CastMessageHandler::Start() {
606 CastChannelSetAuthorityKeysFunction::CastChannelSetAuthorityKeysFunction() {
609 CastChannelSetAuthorityKeysFunction::~CastChannelSetAuthorityKeysFunction() {
612 bool CastChannelSetAuthorityKeysFunction::Prepare() {
613 params_
= cast_channel::SetAuthorityKeys::Params::Create(*args_
);
614 EXTENSION_FUNCTION_VALIDATE(params_
.get());
618 void CastChannelSetAuthorityKeysFunction::AsyncWorkStart() {
619 std::string
& keys
= params_
->keys
;
620 std::string
& signature
= params_
->signature
;
621 if (signature
.empty() || keys
.empty() ||
622 !cast_channel::SetTrustedCertificateAuthorities(keys
, signature
)) {
623 SetError("Unable to set authority keys.");
626 AsyncWorkCompleted();
629 } // namespace extensions