summaryrefslogtreecommitdiffstats
path: root/extensions/browser/api/cast_channel/cast_channel_api.cc
blob: b5593f7fb5b2007ee67912bdc2efee77df411f61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/browser/api/cast_channel/cast_channel_api.h"

#include <stddef.h>
#include <stdint.h>

#include <limits>
#include <string>
#include <utility>

#include "base/json/json_writer.h"
#include "base/lazy_instance.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/default_clock.h"
#include "base/values.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/api/cast_channel/cast_auth_ica.h"
#include "extensions/browser/api/cast_channel/cast_message_util.h"
#include "extensions/browser/api/cast_channel/cast_socket.h"
#include "extensions/browser/api/cast_channel/keep_alive_delegate.h"
#include "extensions/browser/api/cast_channel/logger.h"
#include "extensions/browser/event_router.h"
#include "extensions/common/api/cast_channel/cast_channel.pb.h"
#include "extensions/common/api/cast_channel/logging.pb.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"

// Default timeout interval for connection setup.
// Used if not otherwise specified at ConnectInfo::timeout.
const int kDefaultConnectTimeoutMillis = 5000;  // 5 seconds.

namespace extensions {

namespace Close = cast_channel::Close;
namespace OnError = cast_channel::OnError;
namespace OnMessage = cast_channel::OnMessage;
namespace Open = cast_channel::Open;
namespace Send = cast_channel::Send;
using cast_channel::CastDeviceCapability;
using cast_channel::CastMessage;
using cast_channel::CastSocket;
using cast_channel::ChannelAuthType;
using cast_channel::ChannelError;
using cast_channel::ChannelInfo;
using cast_channel::ConnectInfo;
using cast_channel::ErrorInfo;
using cast_channel::LastErrors;
using cast_channel::Logger;
using cast_channel::MessageInfo;
using cast_channel::ReadyState;
using content::BrowserThread;

namespace {

// T is an extension dictionary (MessageInfo or ChannelInfo)
template <class T>
std::string ParamToString(const T& info) {
  scoped_ptr<base::DictionaryValue> dict = info.ToValue();
  std::string out;
  base::JSONWriter::Write(*dict, &out);
  return out;
}

// Fills |channel_info| from the destination and state of |socket|.
void FillChannelInfo(const CastSocket& socket, ChannelInfo* channel_info) {
  DCHECK(channel_info);
  channel_info->channel_id = socket.id();
  const net::IPEndPoint& ip_endpoint = socket.ip_endpoint();
  channel_info->connect_info.ip_address = ip_endpoint.ToStringWithoutPort();
  channel_info->connect_info.port = ip_endpoint.port();
  channel_info->connect_info.auth = socket.channel_auth();
  channel_info->ready_state = socket.ready_state();
  channel_info->error_state = socket.error_state();
  channel_info->keep_alive = socket.keep_alive();
  channel_info->audio_only = socket.audio_only();
}

// Fills |error_info| from |error_state| and |last_errors|.
void FillErrorInfo(ChannelError error_state,
                   const LastErrors& last_errors,
                   ErrorInfo* error_info) {
  error_info->error_state = error_state;
  if (last_errors.event_type != cast_channel::proto::EVENT_TYPE_UNKNOWN)
    error_info->event_type.reset(new int(last_errors.event_type));
  if (last_errors.challenge_reply_error_type !=
      cast_channel::proto::CHALLENGE_REPLY_ERROR_NONE) {
    error_info->challenge_reply_error_type.reset(
        new int(last_errors.challenge_reply_error_type));
  }
  if (last_errors.net_return_value <= 0)
    error_info->net_return_value.reset(new int(last_errors.net_return_value));
}

bool IsValidConnectInfoPort(const ConnectInfo& connect_info) {
  return connect_info.port > 0 && connect_info.port <
    std::numeric_limits<uint16_t>::max();
}

bool IsValidConnectInfoIpAddress(const ConnectInfo& connect_info) {
  net::IPAddressNumber ip_address;
  return net::ParseIPLiteralToNumber(connect_info.ip_address, &ip_address);
}

}  // namespace

CastChannelAPI::CastChannelAPI(content::BrowserContext* context)
    : browser_context_(context),
      logger_(new Logger(make_scoped_ptr<base::Clock>(new base::DefaultClock),
                         base::Time::UnixEpoch())) {
  DCHECK(browser_context_);
}

// static
CastChannelAPI* CastChannelAPI::Get(content::BrowserContext* context) {
  return BrowserContextKeyedAPIFactory<CastChannelAPI>::Get(context);
}

scoped_refptr<Logger> CastChannelAPI::GetLogger() {
  return logger_;
}

void CastChannelAPI::SendEvent(const std::string& extension_id,
                               scoped_ptr<Event> event) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  EventRouter* event_router = EventRouter::Get(GetBrowserContext());
  if (event_router) {
    event_router->DispatchEventToExtension(extension_id, std::move(event));
  }
}

static base::LazyInstance<BrowserContextKeyedAPIFactory<CastChannelAPI> >
    g_factory = LAZY_INSTANCE_INITIALIZER;

// static
BrowserContextKeyedAPIFactory<CastChannelAPI>*
CastChannelAPI::GetFactoryInstance() {
  return g_factory.Pointer();
}

void CastChannelAPI::SetSocketForTest(scoped_ptr<CastSocket> socket_for_test) {
  socket_for_test_ = std::move(socket_for_test);
}

scoped_ptr<CastSocket> CastChannelAPI::GetSocketForTest() {
  return std::move(socket_for_test_);
}

content::BrowserContext* CastChannelAPI::GetBrowserContext() const {
  return browser_context_;
}

void CastChannelAPI::SetPingTimeoutTimerForTest(scoped_ptr<base::Timer> timer) {
  injected_timeout_timer_ = std::move(timer);
}

scoped_ptr<base::Timer> CastChannelAPI::GetInjectedTimeoutTimerForTest() {
  return std::move(injected_timeout_timer_);
}

CastChannelAPI::~CastChannelAPI() {}

CastChannelAsyncApiFunction::CastChannelAsyncApiFunction() {
}

CastChannelAsyncApiFunction::~CastChannelAsyncApiFunction() { }

bool CastChannelAsyncApiFunction::PrePrepare() {
  DCHECK(ApiResourceManager<CastSocket>::Get(browser_context()));
  sockets_ = ApiResourceManager<CastSocket>::Get(browser_context())->data_;
  DCHECK(sockets_);
  return true;
}

bool CastChannelAsyncApiFunction::Respond() {
  return GetError().empty();
}

CastSocket* CastChannelAsyncApiFunction::GetSocketOrCompleteWithError(
    int channel_id) {
  CastSocket* socket = GetSocket(channel_id);
  if (!socket) {
    SetResultFromError(channel_id,
                       cast_channel::CHANNEL_ERROR_INVALID_CHANNEL_ID);
    AsyncWorkCompleted();
  }
  return socket;
}

int CastChannelAsyncApiFunction::AddSocket(CastSocket* socket) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  DCHECK(socket);
  const int id = sockets_->Add(socket);
  socket->set_id(id);
  return id;
}

void CastChannelAsyncApiFunction::RemoveSocket(int channel_id) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  sockets_->Remove(extension_->id(), channel_id);
}

void CastChannelAsyncApiFunction::SetResultFromSocket(
    const CastSocket& socket) {
  ChannelInfo channel_info;
  FillChannelInfo(socket, &channel_info);
  ChannelError error = socket.error_state();
  if (error != cast_channel::CHANNEL_ERROR_NONE) {
    SetError("Channel socket error = " + base::IntToString(error));
  }
  SetResultFromChannelInfo(channel_info);
}

void CastChannelAsyncApiFunction::SetResultFromError(int channel_id,
                                                     ChannelError error) {
  ChannelInfo channel_info;
  channel_info.channel_id = channel_id;
  channel_info.ready_state = cast_channel::READY_STATE_CLOSED;
  channel_info.error_state = error;
  channel_info.connect_info.ip_address = "";
  channel_info.connect_info.port = 0;
  channel_info.connect_info.auth = cast_channel::CHANNEL_AUTH_TYPE_SSL;
  SetResultFromChannelInfo(channel_info);
  SetError("Channel error = " + base::IntToString(error));
}

CastSocket* CastChannelAsyncApiFunction::GetSocket(int channel_id) const {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  return sockets_->Get(extension_->id(), channel_id);
}

void CastChannelAsyncApiFunction::SetResultFromChannelInfo(
    const ChannelInfo& channel_info) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  SetResult(channel_info.ToValue().release());
}

CastChannelOpenFunction::CastChannelOpenFunction()
    : new_channel_id_(0) {
}

CastChannelOpenFunction::~CastChannelOpenFunction() { }

net::IPEndPoint* CastChannelOpenFunction::ParseConnectInfo(
    const ConnectInfo& connect_info) {
  net::IPAddressNumber ip_address;
  CHECK(net::ParseIPLiteralToNumber(connect_info.ip_address, &ip_address));
  return new net::IPEndPoint(ip_address,
                             static_cast<uint16_t>(connect_info.port));
}

bool CastChannelOpenFunction::PrePrepare() {
  api_ = CastChannelAPI::Get(browser_context());
  return CastChannelAsyncApiFunction::PrePrepare();
}

bool CastChannelOpenFunction::Prepare() {
  params_ = Open::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());
  const ConnectInfo& connect_info = params_->connect_info;
  if (!IsValidConnectInfoPort(connect_info)) {
    SetError("Invalid connect_info (invalid port)");
  } else if (!IsValidConnectInfoIpAddress(connect_info)) {
    SetError("Invalid connect_info (invalid IP address)");
  } else {
    // Parse timeout parameters if they are set.
    if (connect_info.liveness_timeout.get()) {
      liveness_timeout_ = base::TimeDelta::FromMilliseconds(
          *connect_info.liveness_timeout.get());
    }
    if (connect_info.ping_interval.get()) {
      ping_interval_ =
          base::TimeDelta::FromMilliseconds(*connect_info.ping_interval.get());
    }

    // Validate timeout parameters.
    if (liveness_timeout_ < base::TimeDelta() ||
        ping_interval_ < base::TimeDelta()) {
      SetError("livenessTimeout and pingInterval must be greater than 0.");
    } else if ((liveness_timeout_ > base::TimeDelta()) !=
               (ping_interval_ > base::TimeDelta())) {
      SetError("livenessTimeout and pingInterval must be set together.");
    } else if (liveness_timeout_ < ping_interval_) {
      SetError("livenessTimeout must be longer than pingTimeout.");
    }
  }

  if (!GetError().empty()) {
    return false;
  }

  channel_auth_ = connect_info.auth;
  ip_endpoint_.reset(ParseConnectInfo(connect_info));
  return true;
}

void CastChannelOpenFunction::AsyncWorkStart() {
  DCHECK(api_);
  DCHECK(ip_endpoint_.get());
  const ConnectInfo& connect_info = params_->connect_info;
  CastSocket* socket;
  scoped_ptr<CastSocket> test_socket = api_->GetSocketForTest();
  if (test_socket.get()) {
    socket = test_socket.release();
  } else {
    socket = new cast_channel::CastSocketImpl(
        extension_->id(), *ip_endpoint_, channel_auth_,
        ExtensionsBrowserClient::Get()->GetNetLog(),
        base::TimeDelta::FromMilliseconds(connect_info.timeout.get()
                                              ? *connect_info.timeout.get()
                                              : kDefaultConnectTimeoutMillis),
        liveness_timeout_ > base::TimeDelta(), api_->GetLogger(),
        connect_info.capabilities.get() ? *connect_info.capabilities.get()
                                        : CastDeviceCapability::NONE);
  }
  new_channel_id_ = AddSocket(socket);
  api_->GetLogger()->LogNewSocketEvent(*socket);

  // Construct read delegates.
  scoped_ptr<api::cast_channel::CastTransport::Delegate> delegate(
      make_scoped_ptr(new CastMessageHandler(
          base::Bind(&CastChannelAPI::SendEvent, api_->AsWeakPtr()), socket,
          api_->GetLogger())));
  if (socket->keep_alive()) {
    // Wrap read delegate in a KeepAliveDelegate for timeout handling.
    api::cast_channel::KeepAliveDelegate* keep_alive =
        new api::cast_channel::KeepAliveDelegate(
            socket, api_->GetLogger(), std::move(delegate), ping_interval_,
            liveness_timeout_);
    scoped_ptr<base::Timer> injected_timer =
        api_->GetInjectedTimeoutTimerForTest();
    if (injected_timer) {
      keep_alive->SetTimersForTest(
          make_scoped_ptr(new base::Timer(false, false)),
          std::move(injected_timer));
    }
    delegate.reset(keep_alive);
  }

  api_->GetLogger()->LogNewSocketEvent(*socket);
  socket->Connect(std::move(delegate),
                  base::Bind(&CastChannelOpenFunction::OnOpen, this));
}

void CastChannelOpenFunction::OnOpen(cast_channel::ChannelError result) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  VLOG(1) << "Connect finished, OnOpen invoked.";
  CastSocket* socket = GetSocket(new_channel_id_);
  if (!socket) {
    SetResultFromError(new_channel_id_, result);
  } else {
    SetResultFromSocket(*socket);
  }
  AsyncWorkCompleted();
}

CastChannelSendFunction::CastChannelSendFunction() { }

CastChannelSendFunction::~CastChannelSendFunction() { }

bool CastChannelSendFunction::Prepare() {
  params_ = Send::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());
  if (params_->message.namespace_.empty()) {
    SetError("message_info.namespace_ is required");
    return false;
  }
  if (params_->message.source_id.empty()) {
    SetError("message_info.source_id is required");
    return false;
  }
  if (params_->message.destination_id.empty()) {
    SetError("message_info.destination_id is required");
    return false;
  }
  switch (params_->message.data->GetType()) {
    case base::Value::TYPE_STRING:
    case base::Value::TYPE_BINARY:
      break;
    default:
      SetError("Invalid type of message_info.data");
      return false;
  }
  return true;
}

void CastChannelSendFunction::AsyncWorkStart() {
  CastSocket* socket = GetSocket(params_->channel.channel_id);
  if (!socket) {
    SetResultFromError(params_->channel.channel_id,
                       cast_channel::CHANNEL_ERROR_INVALID_CHANNEL_ID);
    AsyncWorkCompleted();
    return;
  }
  CastMessage message_to_send;
  if (!MessageInfoToCastMessage(params_->message, &message_to_send)) {
    SetResultFromError(params_->channel.channel_id,
                       cast_channel::CHANNEL_ERROR_INVALID_MESSAGE);
    AsyncWorkCompleted();
    return;
  }
  socket->transport()->SendMessage(
      message_to_send, base::Bind(&CastChannelSendFunction::OnSend, this));
}

void CastChannelSendFunction::OnSend(int result) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  int channel_id = params_->channel.channel_id;
  CastSocket* socket = GetSocket(channel_id);
  if (result < 0 || !socket) {
    SetResultFromError(channel_id,
                       cast_channel::CHANNEL_ERROR_SOCKET_ERROR);
  } else {
    SetResultFromSocket(*socket);
  }
  AsyncWorkCompleted();
}

CastChannelCloseFunction::CastChannelCloseFunction() { }

CastChannelCloseFunction::~CastChannelCloseFunction() { }

bool CastChannelCloseFunction::Prepare() {
  params_ = Close::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());
  return true;
}

void CastChannelCloseFunction::AsyncWorkStart() {
  CastSocket* socket = GetSocket(params_->channel.channel_id);
  if (!socket) {
    SetResultFromError(params_->channel.channel_id,
                       cast_channel::CHANNEL_ERROR_INVALID_CHANNEL_ID);
    AsyncWorkCompleted();
  } else {
    socket->Close(base::Bind(&CastChannelCloseFunction::OnClose, this));
  }
}

void CastChannelCloseFunction::OnClose(int result) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  VLOG(1) << "CastChannelCloseFunction::OnClose result = " << result;
  int channel_id = params_->channel.channel_id;
  CastSocket* socket = GetSocket(channel_id);
  if (result < 0 || !socket) {
    SetResultFromError(channel_id,
                       cast_channel::CHANNEL_ERROR_SOCKET_ERROR);
  } else {
    SetResultFromSocket(*socket);
    // This will delete |socket|.
    RemoveSocket(channel_id);
  }
  AsyncWorkCompleted();
}

CastChannelGetLogsFunction::CastChannelGetLogsFunction() {
}

CastChannelGetLogsFunction::~CastChannelGetLogsFunction() {
}

bool CastChannelGetLogsFunction::PrePrepare() {
  api_ = CastChannelAPI::Get(browser_context());
  return CastChannelAsyncApiFunction::PrePrepare();
}

bool CastChannelGetLogsFunction::Prepare() {
  return true;
}

void CastChannelGetLogsFunction::AsyncWorkStart() {
  DCHECK(api_);

  size_t length = 0;
  scoped_ptr<char[]> out = api_->GetLogger()->GetLogs(&length);
  if (out.get()) {
    SetResult(new base::BinaryValue(std::move(out), length));
  } else {
    SetError("Unable to get logs.");
  }

  api_->GetLogger()->Reset();

  AsyncWorkCompleted();
}

CastChannelOpenFunction::CastMessageHandler::CastMessageHandler(
    const EventDispatchCallback& ui_dispatch_cb,
    cast_channel::CastSocket* socket,
    scoped_refptr<Logger> logger)
    : ui_dispatch_cb_(ui_dispatch_cb), socket_(socket), logger_(logger) {
  DCHECK(socket_);
  DCHECK(logger_);
}

CastChannelOpenFunction::CastMessageHandler::~CastMessageHandler() {
}

void CastChannelOpenFunction::CastMessageHandler::OnError(
    cast_channel::ChannelError error_state) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  ChannelInfo channel_info;
  FillChannelInfo(*socket_, &channel_info);
  channel_info.error_state = error_state;
  ErrorInfo error_info;
  FillErrorInfo(error_state, logger_->GetLastErrors(socket_->id()),
                &error_info);

  scoped_ptr<base::ListValue> results =
      OnError::Create(channel_info, error_info);
  scoped_ptr<Event> event(new Event(events::CAST_CHANNEL_ON_ERROR,
                                    OnError::kEventName, std::move(results)));
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(ui_dispatch_cb_, socket_->owner_extension_id(),
                 base::Passed(std::move(event))));
}

void CastChannelOpenFunction::CastMessageHandler::OnMessage(
    const CastMessage& message) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  MessageInfo message_info;
  cast_channel::CastMessageToMessageInfo(message, &message_info);
  ChannelInfo channel_info;
  FillChannelInfo(*socket_, &channel_info);
  VLOG(1) << "Received message " << ParamToString(message_info)
          << " on channel " << ParamToString(channel_info);

  scoped_ptr<base::ListValue> results =
      OnMessage::Create(channel_info, message_info);
  scoped_ptr<Event> event(new Event(events::CAST_CHANNEL_ON_MESSAGE,
                                    OnMessage::kEventName, std::move(results)));
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(ui_dispatch_cb_, socket_->owner_extension_id(),
                 base::Passed(std::move(event))));
}

void CastChannelOpenFunction::CastMessageHandler::Start() {
}

CastChannelSetAuthorityKeysFunction::CastChannelSetAuthorityKeysFunction() {
}

CastChannelSetAuthorityKeysFunction::~CastChannelSetAuthorityKeysFunction() {
}

bool CastChannelSetAuthorityKeysFunction::Prepare() {
  params_ = cast_channel::SetAuthorityKeys::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());
  return true;
}

void CastChannelSetAuthorityKeysFunction::AsyncWorkStart() {
  std::string& keys = params_->keys;
  std::string& signature = params_->signature;
  if (signature.empty() || keys.empty() ||
      !cast_channel::SetTrustedCertificateAuthorities(keys, signature)) {
    SetError("Unable to set authority keys.");
  }

  AsyncWorkCompleted();
}

}  // namespace extensions