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_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"
29 // Default timeout interval for connection setup.
30 // Used if not otherwise specified at ConnectInfo::timeout.
31 const int kDefaultConnectTimeoutMillis
= 5000; // 5 seconds.
33 namespace extensions
{
35 namespace Close
= cast_channel::Close
;
36 namespace OnError
= cast_channel::OnError
;
37 namespace OnMessage
= cast_channel::OnMessage
;
38 namespace Open
= cast_channel::Open
;
39 namespace Send
= cast_channel::Send
;
40 using cast_channel::CastDeviceCapability
;
41 using cast_channel::CastMessage
;
42 using cast_channel::CastSocket
;
43 using cast_channel::ChannelAuthType
;
44 using cast_channel::ChannelError
;
45 using cast_channel::ChannelInfo
;
46 using cast_channel::ConnectInfo
;
47 using cast_channel::ErrorInfo
;
48 using cast_channel::LastErrors
;
49 using cast_channel::Logger
;
50 using cast_channel::MessageInfo
;
51 using cast_channel::ReadyState
;
52 using content::BrowserThread
;
56 // T is an extension dictionary (MessageInfo or ChannelInfo)
58 std::string
ParamToString(const T
& info
) {
59 scoped_ptr
<base::DictionaryValue
> dict
= info
.ToValue();
61 base::JSONWriter::Write(*dict
, &out
);
65 // Fills |channel_info| from the destination and state of |socket|.
66 void FillChannelInfo(const CastSocket
& socket
, ChannelInfo
* channel_info
) {
68 channel_info
->channel_id
= socket
.id();
69 const net::IPEndPoint
& ip_endpoint
= socket
.ip_endpoint();
70 channel_info
->connect_info
.ip_address
= ip_endpoint
.ToStringWithoutPort();
71 channel_info
->connect_info
.port
= ip_endpoint
.port();
72 channel_info
->connect_info
.auth
= socket
.channel_auth();
73 channel_info
->ready_state
= socket
.ready_state();
74 channel_info
->error_state
= socket
.error_state();
75 channel_info
->keep_alive
= socket
.keep_alive();
78 // Fills |error_info| from |error_state| and |last_errors|.
79 void FillErrorInfo(ChannelError error_state
,
80 const LastErrors
& last_errors
,
81 ErrorInfo
* error_info
) {
82 error_info
->error_state
= error_state
;
83 if (last_errors
.event_type
!= cast_channel::proto::EVENT_TYPE_UNKNOWN
)
84 error_info
->event_type
.reset(new int(last_errors
.event_type
));
85 if (last_errors
.challenge_reply_error_type
!=
86 cast_channel::proto::CHALLENGE_REPLY_ERROR_NONE
) {
87 error_info
->challenge_reply_error_type
.reset(
88 new int(last_errors
.challenge_reply_error_type
));
90 if (last_errors
.net_return_value
<= 0)
91 error_info
->net_return_value
.reset(new int(last_errors
.net_return_value
));
92 if (last_errors
.nss_error_code
< 0)
93 error_info
->nss_error_code
.reset(new int(last_errors
.nss_error_code
));
96 bool IsValidConnectInfoPort(const ConnectInfo
& connect_info
) {
97 return connect_info
.port
> 0 && connect_info
.port
<
98 std::numeric_limits
<uint16_t>::max();
101 bool IsValidConnectInfoIpAddress(const ConnectInfo
& connect_info
) {
102 net::IPAddressNumber ip_address
;
103 return net::ParseIPLiteralToNumber(connect_info
.ip_address
, &ip_address
);
108 CastChannelAPI::CastChannelAPI(content::BrowserContext
* context
)
109 : browser_context_(context
),
110 logger_(new Logger(make_scoped_ptr
<base::Clock
>(new base::DefaultClock
),
111 base::Time::UnixEpoch())) {
112 DCHECK(browser_context_
);
116 CastChannelAPI
* CastChannelAPI::Get(content::BrowserContext
* context
) {
117 return BrowserContextKeyedAPIFactory
<CastChannelAPI
>::Get(context
);
120 scoped_refptr
<Logger
> CastChannelAPI::GetLogger() {
124 void CastChannelAPI::SendEvent(const std::string
& extension_id
,
125 scoped_ptr
<Event
> event
) {
126 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
127 EventRouter
* event_router
= EventRouter::Get(GetBrowserContext());
129 event_router
->DispatchEventToExtension(extension_id
, event
.Pass());
133 static base::LazyInstance
<BrowserContextKeyedAPIFactory
<CastChannelAPI
> >
134 g_factory
= LAZY_INSTANCE_INITIALIZER
;
137 BrowserContextKeyedAPIFactory
<CastChannelAPI
>*
138 CastChannelAPI::GetFactoryInstance() {
139 return g_factory
.Pointer();
142 void CastChannelAPI::SetSocketForTest(scoped_ptr
<CastSocket
> socket_for_test
) {
143 socket_for_test_
= socket_for_test
.Pass();
146 scoped_ptr
<CastSocket
> CastChannelAPI::GetSocketForTest() {
147 return socket_for_test_
.Pass();
150 content::BrowserContext
* CastChannelAPI::GetBrowserContext() const {
151 return browser_context_
;
154 void CastChannelAPI::SetPingTimeoutTimerForTest(scoped_ptr
<base::Timer
> timer
) {
155 injected_timeout_timer_
= timer
.Pass();
158 scoped_ptr
<base::Timer
> CastChannelAPI::GetInjectedTimeoutTimerForTest() {
159 return injected_timeout_timer_
.Pass();
162 CastChannelAPI::~CastChannelAPI() {}
164 CastChannelAsyncApiFunction::CastChannelAsyncApiFunction() {
167 CastChannelAsyncApiFunction::~CastChannelAsyncApiFunction() { }
169 bool CastChannelAsyncApiFunction::PrePrepare() {
170 DCHECK(ApiResourceManager
<CastSocket
>::Get(browser_context()));
171 sockets_
= ApiResourceManager
<CastSocket
>::Get(browser_context())->data_
;
176 bool CastChannelAsyncApiFunction::Respond() {
177 return GetError().empty();
180 CastSocket
* CastChannelAsyncApiFunction::GetSocketOrCompleteWithError(
182 CastSocket
* socket
= GetSocket(channel_id
);
184 SetResultFromError(channel_id
,
185 cast_channel::CHANNEL_ERROR_INVALID_CHANNEL_ID
);
186 AsyncWorkCompleted();
191 int CastChannelAsyncApiFunction::AddSocket(CastSocket
* socket
) {
192 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
194 const int id
= sockets_
->Add(socket
);
199 void CastChannelAsyncApiFunction::RemoveSocket(int channel_id
) {
200 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
201 sockets_
->Remove(extension_
->id(), channel_id
);
204 void CastChannelAsyncApiFunction::SetResultFromSocket(
205 const CastSocket
& socket
) {
206 ChannelInfo channel_info
;
207 FillChannelInfo(socket
, &channel_info
);
208 ChannelError error
= socket
.error_state();
209 if (error
!= cast_channel::CHANNEL_ERROR_NONE
) {
210 SetError("Channel socket error = " + base::IntToString(error
));
212 SetResultFromChannelInfo(channel_info
);
215 void CastChannelAsyncApiFunction::SetResultFromError(int channel_id
,
216 ChannelError error
) {
217 ChannelInfo channel_info
;
218 channel_info
.channel_id
= channel_id
;
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
);
230 return sockets_
->Get(extension_
->id(), channel_id
);
233 void CastChannelAsyncApiFunction::SetResultFromChannelInfo(
234 const ChannelInfo
& channel_info
) {
235 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
236 SetResult(channel_info
.ToValue().release());
239 CastChannelOpenFunction::CastChannelOpenFunction()
240 : new_channel_id_(0) {
243 CastChannelOpenFunction::~CastChannelOpenFunction() { }
245 net::IPEndPoint
* CastChannelOpenFunction::ParseConnectInfo(
246 const ConnectInfo
& connect_info
) {
247 net::IPAddressNumber ip_address
;
248 CHECK(net::ParseIPLiteralToNumber(connect_info
.ip_address
, &ip_address
));
249 return new net::IPEndPoint(ip_address
,
250 static_cast<uint16
>(connect_info
.port
));
253 bool CastChannelOpenFunction::PrePrepare() {
254 api_
= CastChannelAPI::Get(browser_context());
255 return CastChannelAsyncApiFunction::PrePrepare();
258 bool CastChannelOpenFunction::Prepare() {
259 params_
= Open::Params::Create(*args_
);
260 EXTENSION_FUNCTION_VALIDATE(params_
.get());
261 const ConnectInfo
& connect_info
= params_
->connect_info
;
262 if (!IsValidConnectInfoPort(connect_info
)) {
263 SetError("Invalid connect_info (invalid port)");
264 } else if (!IsValidConnectInfoIpAddress(connect_info
)) {
265 SetError("Invalid connect_info (invalid IP address)");
267 // Parse timeout parameters if they are set.
268 if (connect_info
.liveness_timeout
.get()) {
269 liveness_timeout_
= base::TimeDelta::FromMilliseconds(
270 *connect_info
.liveness_timeout
.get());
272 if (connect_info
.ping_interval
.get()) {
274 base::TimeDelta::FromMilliseconds(*connect_info
.ping_interval
.get());
277 // Validate timeout parameters.
278 if (liveness_timeout_
< base::TimeDelta() ||
279 ping_interval_
< base::TimeDelta()) {
280 SetError("livenessTimeout and pingInterval must be greater than 0.");
281 } else if ((liveness_timeout_
> base::TimeDelta()) !=
282 (ping_interval_
> base::TimeDelta())) {
283 SetError("livenessTimeout and pingInterval must be set together.");
284 } else if (liveness_timeout_
< ping_interval_
) {
285 SetError("livenessTimeout must be longer than pingTimeout.");
289 if (!GetError().empty()) {
293 channel_auth_
= connect_info
.auth
;
294 ip_endpoint_
.reset(ParseConnectInfo(connect_info
));
298 void CastChannelOpenFunction::AsyncWorkStart() {
300 DCHECK(ip_endpoint_
.get());
301 const ConnectInfo
& connect_info
= params_
->connect_info
;
303 scoped_ptr
<CastSocket
> test_socket
= api_
->GetSocketForTest();
304 if (test_socket
.get()) {
305 socket
= test_socket
.release();
307 socket
= new cast_channel::CastSocketImpl(
308 extension_
->id(), *ip_endpoint_
, channel_auth_
,
309 ExtensionsBrowserClient::Get()->GetNetLog(),
310 base::TimeDelta::FromMilliseconds(connect_info
.timeout
.get()
311 ? *connect_info
.timeout
.get()
312 : kDefaultConnectTimeoutMillis
),
313 liveness_timeout_
> base::TimeDelta(), api_
->GetLogger(),
314 connect_info
.capabilities
.get() ? *connect_info
.capabilities
.get()
315 : CastDeviceCapability::NONE
);
317 new_channel_id_
= AddSocket(socket
);
318 api_
->GetLogger()->LogNewSocketEvent(*socket
);
320 // Construct read delegates.
321 scoped_ptr
<api::cast_channel::CastTransport::Delegate
> delegate(
322 make_scoped_ptr(new CastMessageHandler(
323 base::Bind(&CastChannelAPI::SendEvent
, api_
->AsWeakPtr()), socket
,
324 api_
->GetLogger())));
325 if (socket
->keep_alive()) {
326 // Wrap read delegate in a KeepAliveDelegate for timeout handling.
327 api::cast_channel::KeepAliveDelegate
* keep_alive
=
328 new api::cast_channel::KeepAliveDelegate(
329 socket
, api_
->GetLogger(), delegate
.Pass(), ping_interval_
,
331 scoped_ptr
<base::Timer
> injected_timer
=
332 api_
->GetInjectedTimeoutTimerForTest();
333 if (injected_timer
) {
334 keep_alive
->SetTimersForTest(
335 make_scoped_ptr(new base::Timer(false, false)),
336 injected_timer
.Pass());
338 delegate
.reset(keep_alive
);
341 api_
->GetLogger()->LogNewSocketEvent(*socket
);
342 socket
->Connect(delegate
.Pass(),
343 base::Bind(&CastChannelOpenFunction::OnOpen
, this));
346 void CastChannelOpenFunction::OnOpen(cast_channel::ChannelError result
) {
347 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
348 VLOG(1) << "Connect finished, OnOpen invoked.";
349 CastSocket
* socket
= GetSocket(new_channel_id_
);
351 SetResultFromError(new_channel_id_
, result
);
353 SetResultFromSocket(*socket
);
355 AsyncWorkCompleted();
358 CastChannelSendFunction::CastChannelSendFunction() { }
360 CastChannelSendFunction::~CastChannelSendFunction() { }
362 bool CastChannelSendFunction::Prepare() {
363 params_
= Send::Params::Create(*args_
);
364 EXTENSION_FUNCTION_VALIDATE(params_
.get());
365 if (params_
->message
.namespace_
.empty()) {
366 SetError("message_info.namespace_ is required");
369 if (params_
->message
.source_id
.empty()) {
370 SetError("message_info.source_id is required");
373 if (params_
->message
.destination_id
.empty()) {
374 SetError("message_info.destination_id is required");
377 switch (params_
->message
.data
->GetType()) {
378 case base::Value::TYPE_STRING
:
379 case base::Value::TYPE_BINARY
:
382 SetError("Invalid type of message_info.data");
388 void CastChannelSendFunction::AsyncWorkStart() {
389 CastSocket
* socket
= GetSocket(params_
->channel
.channel_id
);
391 SetResultFromError(params_
->channel
.channel_id
,
392 cast_channel::CHANNEL_ERROR_INVALID_CHANNEL_ID
);
393 AsyncWorkCompleted();
396 CastMessage message_to_send
;
397 if (!MessageInfoToCastMessage(params_
->message
, &message_to_send
)) {
398 SetResultFromError(params_
->channel
.channel_id
,
399 cast_channel::CHANNEL_ERROR_INVALID_MESSAGE
);
400 AsyncWorkCompleted();
403 socket
->transport()->SendMessage(
404 message_to_send
, base::Bind(&CastChannelSendFunction::OnSend
, this));
407 void CastChannelSendFunction::OnSend(int result
) {
408 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
409 int channel_id
= params_
->channel
.channel_id
;
410 CastSocket
* socket
= GetSocket(channel_id
);
411 if (result
< 0 || !socket
) {
412 SetResultFromError(channel_id
,
413 cast_channel::CHANNEL_ERROR_SOCKET_ERROR
);
415 SetResultFromSocket(*socket
);
417 AsyncWorkCompleted();
420 CastChannelCloseFunction::CastChannelCloseFunction() { }
422 CastChannelCloseFunction::~CastChannelCloseFunction() { }
424 bool CastChannelCloseFunction::Prepare() {
425 params_
= Close::Params::Create(*args_
);
426 EXTENSION_FUNCTION_VALIDATE(params_
.get());
430 void CastChannelCloseFunction::AsyncWorkStart() {
431 CastSocket
* socket
= GetSocket(params_
->channel
.channel_id
);
433 SetResultFromError(params_
->channel
.channel_id
,
434 cast_channel::CHANNEL_ERROR_INVALID_CHANNEL_ID
);
435 AsyncWorkCompleted();
437 socket
->Close(base::Bind(&CastChannelCloseFunction::OnClose
, this));
441 void CastChannelCloseFunction::OnClose(int result
) {
442 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
443 VLOG(1) << "CastChannelCloseFunction::OnClose result = " << result
;
444 int channel_id
= params_
->channel
.channel_id
;
445 CastSocket
* socket
= GetSocket(channel_id
);
446 if (result
< 0 || !socket
) {
447 SetResultFromError(channel_id
,
448 cast_channel::CHANNEL_ERROR_SOCKET_ERROR
);
450 SetResultFromSocket(*socket
);
451 // This will delete |socket|.
452 RemoveSocket(channel_id
);
454 AsyncWorkCompleted();
457 CastChannelGetLogsFunction::CastChannelGetLogsFunction() {
460 CastChannelGetLogsFunction::~CastChannelGetLogsFunction() {
463 bool CastChannelGetLogsFunction::PrePrepare() {
464 api_
= CastChannelAPI::Get(browser_context());
465 return CastChannelAsyncApiFunction::PrePrepare();
468 bool CastChannelGetLogsFunction::Prepare() {
472 void CastChannelGetLogsFunction::AsyncWorkStart() {
476 scoped_ptr
<char[]> out
= api_
->GetLogger()->GetLogs(&length
);
478 SetResult(new base::BinaryValue(out
.Pass(), length
));
480 SetError("Unable to get logs.");
483 api_
->GetLogger()->Reset();
485 AsyncWorkCompleted();
488 CastChannelOpenFunction::CastMessageHandler::CastMessageHandler(
489 const EventDispatchCallback
& ui_dispatch_cb
,
490 cast_channel::CastSocket
* socket
,
491 scoped_refptr
<Logger
> logger
)
492 : ui_dispatch_cb_(ui_dispatch_cb
), socket_(socket
), logger_(logger
) {
497 CastChannelOpenFunction::CastMessageHandler::~CastMessageHandler() {
500 void CastChannelOpenFunction::CastMessageHandler::OnError(
501 cast_channel::ChannelError error_state
) {
502 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
504 ChannelInfo channel_info
;
505 FillChannelInfo(*socket_
, &channel_info
);
506 channel_info
.error_state
= error_state
;
507 ErrorInfo error_info
;
508 FillErrorInfo(error_state
, logger_
->GetLastErrors(socket_
->id()),
511 scoped_ptr
<base::ListValue
> results
=
512 OnError::Create(channel_info
, error_info
);
513 scoped_ptr
<Event
> event(new Event(events::CAST_CHANNEL_ON_ERROR
,
514 OnError::kEventName
, results
.Pass()));
515 BrowserThread::PostTask(
516 BrowserThread::UI
, FROM_HERE
,
517 base::Bind(ui_dispatch_cb_
, socket_
->owner_extension_id(),
518 base::Passed(event
.Pass())));
521 void CastChannelOpenFunction::CastMessageHandler::OnMessage(
522 const CastMessage
& message
) {
523 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
525 MessageInfo message_info
;
526 cast_channel::CastMessageToMessageInfo(message
, &message_info
);
527 ChannelInfo channel_info
;
528 FillChannelInfo(*socket_
, &channel_info
);
529 VLOG(1) << "Received message " << ParamToString(message_info
)
530 << " on channel " << ParamToString(channel_info
);
532 scoped_ptr
<base::ListValue
> results
=
533 OnMessage::Create(channel_info
, message_info
);
534 scoped_ptr
<Event
> event(new Event(events::CAST_CHANNEL_ON_MESSAGE
,
535 OnMessage::kEventName
, results
.Pass()));
536 BrowserThread::PostTask(
537 BrowserThread::UI
, FROM_HERE
,
538 base::Bind(ui_dispatch_cb_
, socket_
->owner_extension_id(),
539 base::Passed(event
.Pass())));
542 void CastChannelOpenFunction::CastMessageHandler::Start() {
545 CastChannelSetAuthorityKeysFunction::CastChannelSetAuthorityKeysFunction() {
548 CastChannelSetAuthorityKeysFunction::~CastChannelSetAuthorityKeysFunction() {
551 bool CastChannelSetAuthorityKeysFunction::Prepare() {
552 params_
= cast_channel::SetAuthorityKeys::Params::Create(*args_
);
553 EXTENSION_FUNCTION_VALIDATE(params_
.get());
557 void CastChannelSetAuthorityKeysFunction::AsyncWorkStart() {
558 std::string
& keys
= params_
->keys
;
559 std::string
& signature
= params_
->signature
;
560 if (signature
.empty() || keys
.empty() ||
561 !cast_channel::SetTrustedCertificateAuthorities(keys
, signature
)) {
562 SetError("Unable to set authority keys.");
565 AsyncWorkCompleted();
568 } // namespace extensions