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 "chrome/browser/extensions/api/bluetooth_socket/bluetooth_socket_api.h"
9 #include "chrome/browser/extensions/api/bluetooth_socket/bluetooth_api_socket.h"
10 #include "chrome/browser/extensions/api/bluetooth_socket/bluetooth_socket_event_dispatcher.h"
11 #include "chrome/common/extensions/api/bluetooth/bluetooth_manifest_data.h"
12 #include "content/public/browser/browser_context.h"
13 #include "content/public/browser/browser_thread.h"
14 #include "device/bluetooth/bluetooth_adapter.h"
15 #include "device/bluetooth/bluetooth_adapter_factory.h"
16 #include "device/bluetooth/bluetooth_device.h"
17 #include "device/bluetooth/bluetooth_socket.h"
18 #include "extensions/common/permissions/permissions_data.h"
19 #include "net/base/io_buffer.h"
21 using content::BrowserThread
;
22 using extensions::BluetoothApiSocket
;
23 using extensions::api::bluetooth_socket::ListenOptions
;
24 using extensions::api::bluetooth_socket::SocketInfo
;
25 using extensions::api::bluetooth_socket::SocketProperties
;
29 const char kDeviceNotFoundError
[] = "Device not found";
30 const char kInvalidPsmError
[] = "Invalid PSM";
31 const char kInvalidUuidError
[] = "Invalid UUID";
32 const char kPermissionDeniedError
[] = "Permission denied";
33 const char kSocketNotFoundError
[] = "Socket not found";
35 linked_ptr
<SocketInfo
> CreateSocketInfo(int socket_id
,
36 BluetoothApiSocket
* socket
) {
37 DCHECK(BrowserThread::CurrentlyOn(BluetoothApiSocket::kThreadId
));
38 linked_ptr
<SocketInfo
> socket_info(new SocketInfo());
39 // This represents what we know about the socket, and does not call through
41 socket_info
->socket_id
= socket_id
;
43 socket_info
->name
.reset(new std::string(*socket
->name()));
45 socket_info
->persistent
= socket
->persistent();
46 if (socket
->buffer_size() > 0) {
47 socket_info
->buffer_size
.reset(new int(socket
->buffer_size()));
49 socket_info
->paused
= socket
->paused();
50 socket_info
->connected
= socket
->IsConnected();
52 if (socket
->IsConnected())
53 socket_info
->address
.reset(new std::string(socket
->device_address()));
54 socket_info
->uuid
.reset(new std::string(socket
->uuid().canonical_value()));
59 void SetSocketProperties(BluetoothApiSocket
* socket
,
60 SocketProperties
* properties
) {
61 if (properties
->name
.get()) {
62 socket
->set_name(*properties
->name
.get());
64 if (properties
->persistent
.get()) {
65 socket
->set_persistent(*properties
->persistent
.get());
67 if (properties
->buffer_size
.get()) {
68 // buffer size is validated when issuing the actual Recv operation
70 socket
->set_buffer_size(*properties
->buffer_size
.get());
74 extensions::api::BluetoothSocketEventDispatcher
* GetSocketEventDispatcher(
75 content::BrowserContext
* browser_context
) {
76 extensions::api::BluetoothSocketEventDispatcher
* socket_event_dispatcher
=
77 extensions::api::BluetoothSocketEventDispatcher::Get(browser_context
);
78 DCHECK(socket_event_dispatcher
)
79 << "There is no socket event dispatcher. "
80 "If this assertion is failing during a test, then it is likely that "
81 "TestExtensionSystem is failing to provide an instance of "
82 "BluetoothSocketEventDispatcher.";
83 return socket_event_dispatcher
;
86 // Returns |true| if |psm| is a valid PSM.
87 // Per the Bluetooth specification, the PSM field must be at least two octets in
88 // length, with least significant bit of the least significant octet equal to
89 // '1' and the least significant bit of the most significant octet equal to '0'.
90 bool IsValidPsm(int psm
) {
94 std::vector
<int16_t> octets
;
96 octets
.push_back(psm
& 0xFF);
100 if (octets
.size() < 2U)
103 // The least significant bit of the least significant octet must be '1'.
104 if ((octets
.front() & 0x01) != 1)
107 // The least significant bit of the most significant octet must be '0'.
108 if ((octets
.back() & 0x01) != 0)
116 namespace extensions
{
119 BluetoothSocketAsyncApiFunction::BluetoothSocketAsyncApiFunction() {}
121 BluetoothSocketAsyncApiFunction::~BluetoothSocketAsyncApiFunction() {}
123 bool BluetoothSocketAsyncApiFunction::RunAsync() {
124 if (!PrePrepare() || !Prepare()) {
131 bool BluetoothSocketAsyncApiFunction::PrePrepare() {
132 if (!BluetoothManifestData::CheckSocketPermitted(GetExtension())) {
133 error_
= kPermissionDeniedError
;
137 manager_
= ApiResourceManager
<BluetoothApiSocket
>::Get(browser_context());
139 << "There is no socket manager. "
140 "If this assertion is failing during a test, then it is likely that "
141 "TestExtensionSystem is failing to provide an instance of "
142 "ApiResourceManager<BluetoothApiSocket>.";
143 return manager_
!= NULL
;
146 bool BluetoothSocketAsyncApiFunction::Respond() { return error_
.empty(); }
148 void BluetoothSocketAsyncApiFunction::AsyncWorkCompleted() {
149 SendResponse(Respond());
152 void BluetoothSocketAsyncApiFunction::Work() {}
154 void BluetoothSocketAsyncApiFunction::AsyncWorkStart() {
156 AsyncWorkCompleted();
159 int BluetoothSocketAsyncApiFunction::AddSocket(BluetoothApiSocket
* socket
) {
160 return manager_
->Add(socket
);
163 content::BrowserThread::ID
164 BluetoothSocketAsyncApiFunction::work_thread_id() const {
165 return BluetoothApiSocket::kThreadId
;
168 BluetoothApiSocket
* BluetoothSocketAsyncApiFunction::GetSocket(
169 int api_resource_id
) {
170 return manager_
->Get(extension_id(), api_resource_id
);
173 void BluetoothSocketAsyncApiFunction::RemoveSocket(int api_resource_id
) {
174 manager_
->Remove(extension_id(), api_resource_id
);
177 base::hash_set
<int>* BluetoothSocketAsyncApiFunction::GetSocketIds() {
178 return manager_
->GetResourceIds(extension_id());
181 BluetoothSocketCreateFunction::BluetoothSocketCreateFunction() {}
183 BluetoothSocketCreateFunction::~BluetoothSocketCreateFunction() {}
185 bool BluetoothSocketCreateFunction::Prepare() {
186 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
188 params_
= bluetooth_socket::Create::Params::Create(*args_
);
189 EXTENSION_FUNCTION_VALIDATE(params_
.get());
193 void BluetoothSocketCreateFunction::Work() {
194 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
196 BluetoothApiSocket
* socket
= new BluetoothApiSocket(extension_id());
198 bluetooth_socket::SocketProperties
* properties
=
199 params_
.get()->properties
.get();
201 SetSocketProperties(socket
, properties
);
204 bluetooth_socket::CreateInfo create_info
;
205 create_info
.socket_id
= AddSocket(socket
);
206 results_
= bluetooth_socket::Create::Results::Create(create_info
);
207 AsyncWorkCompleted();
210 BluetoothSocketUpdateFunction::BluetoothSocketUpdateFunction() {}
212 BluetoothSocketUpdateFunction::~BluetoothSocketUpdateFunction() {}
214 bool BluetoothSocketUpdateFunction::Prepare() {
215 params_
= bluetooth_socket::Update::Params::Create(*args_
);
216 EXTENSION_FUNCTION_VALIDATE(params_
.get());
220 void BluetoothSocketUpdateFunction::Work() {
221 BluetoothApiSocket
* socket
= GetSocket(params_
->socket_id
);
223 error_
= kSocketNotFoundError
;
227 SetSocketProperties(socket
, ¶ms_
.get()->properties
);
228 results_
= bluetooth_socket::Update::Results::Create();
231 BluetoothSocketSetPausedFunction::BluetoothSocketSetPausedFunction()
232 : socket_event_dispatcher_(NULL
) {}
234 BluetoothSocketSetPausedFunction::~BluetoothSocketSetPausedFunction() {}
236 bool BluetoothSocketSetPausedFunction::Prepare() {
237 params_
= bluetooth_socket::SetPaused::Params::Create(*args_
);
238 EXTENSION_FUNCTION_VALIDATE(params_
.get());
240 socket_event_dispatcher_
= GetSocketEventDispatcher(browser_context());
241 return socket_event_dispatcher_
!= NULL
;
244 void BluetoothSocketSetPausedFunction::Work() {
245 BluetoothApiSocket
* socket
= GetSocket(params_
->socket_id
);
247 error_
= kSocketNotFoundError
;
251 if (socket
->paused() != params_
->paused
) {
252 socket
->set_paused(params_
->paused
);
253 if (!params_
->paused
) {
254 socket_event_dispatcher_
->OnSocketResume(extension_id(),
259 results_
= bluetooth_socket::SetPaused::Results::Create();
262 BluetoothSocketListenFunction::BluetoothSocketListenFunction() {}
264 BluetoothSocketListenFunction::~BluetoothSocketListenFunction() {}
266 bool BluetoothSocketListenFunction::Prepare() {
267 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
270 socket_event_dispatcher_
= GetSocketEventDispatcher(browser_context());
271 return socket_event_dispatcher_
!= NULL
;
274 void BluetoothSocketListenFunction::AsyncWorkStart() {
275 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
276 device::BluetoothAdapterFactory::GetAdapter(
277 base::Bind(&BluetoothSocketListenFunction::OnGetAdapter
, this));
280 void BluetoothSocketListenFunction::OnGetAdapter(
281 scoped_refptr
<device::BluetoothAdapter
> adapter
) {
282 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
283 BluetoothApiSocket
* socket
= GetSocket(socket_id());
285 error_
= kSocketNotFoundError
;
286 AsyncWorkCompleted();
290 device::BluetoothUUID
bluetooth_uuid(uuid());
291 if (!bluetooth_uuid
.IsValid()) {
292 error_
= kInvalidUuidError
;
293 AsyncWorkCompleted();
297 BluetoothPermissionRequest
param(uuid());
298 if (!BluetoothManifestData::CheckRequest(GetExtension(), param
)) {
299 error_
= kPermissionDeniedError
;
300 AsyncWorkCompleted();
304 scoped_ptr
<std::string
> name
;
306 name
.reset(new std::string(*socket
->name()));
312 base::Bind(&BluetoothSocketListenFunction::OnCreateService
, this),
313 base::Bind(&BluetoothSocketListenFunction::OnCreateServiceError
, this));
317 void BluetoothSocketListenFunction::OnCreateService(
318 scoped_refptr
<device::BluetoothSocket
> socket
) {
319 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
321 // Fetch the socket again since this is not a reference-counted object, and
322 // it may have gone away in the meantime (we check earlier to avoid making
323 // a connection in the case of an obvious programming error).
324 BluetoothApiSocket
* api_socket
= GetSocket(socket_id());
326 error_
= kSocketNotFoundError
;
327 AsyncWorkCompleted();
331 api_socket
->AdoptListeningSocket(socket
,
332 device::BluetoothUUID(uuid()));
333 socket_event_dispatcher_
->OnSocketListen(extension_id(), socket_id());
336 AsyncWorkCompleted();
339 void BluetoothSocketListenFunction::OnCreateServiceError(
340 const std::string
& message
) {
341 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
343 AsyncWorkCompleted();
346 BluetoothSocketListenUsingRfcommFunction::
347 BluetoothSocketListenUsingRfcommFunction() {}
349 BluetoothSocketListenUsingRfcommFunction::
350 ~BluetoothSocketListenUsingRfcommFunction() {}
352 int BluetoothSocketListenUsingRfcommFunction::socket_id() const {
353 return params_
->socket_id
;
356 const std::string
& BluetoothSocketListenUsingRfcommFunction::uuid() const {
357 return params_
->uuid
;
360 bool BluetoothSocketListenUsingRfcommFunction::CreateParams() {
361 params_
= bluetooth_socket::ListenUsingRfcomm::Params::Create(*args_
);
362 EXTENSION_FUNCTION_VALIDATE(params_
.get());
366 void BluetoothSocketListenUsingRfcommFunction::CreateService(
367 scoped_refptr
<device::BluetoothAdapter
> adapter
,
368 const device::BluetoothUUID
& uuid
,
369 scoped_ptr
<std::string
> name
,
370 const device::BluetoothAdapter::CreateServiceCallback
& callback
,
371 const device::BluetoothAdapter::CreateServiceErrorCallback
&
373 device::BluetoothAdapter::ServiceOptions service_options
;
374 service_options
.name
= name
.Pass();
376 ListenOptions
* options
= params_
->options
.get();
378 if (options
->channel
.get())
379 service_options
.channel
.reset(new int(*(options
->channel
)));
382 adapter
->CreateRfcommService(uuid
, service_options
, callback
, error_callback
);
385 void BluetoothSocketListenUsingRfcommFunction::CreateResults() {
386 results_
= bluetooth_socket::ListenUsingRfcomm::Results::Create();
389 BluetoothSocketListenUsingL2capFunction::
390 BluetoothSocketListenUsingL2capFunction() {}
392 BluetoothSocketListenUsingL2capFunction::
393 ~BluetoothSocketListenUsingL2capFunction() {}
395 int BluetoothSocketListenUsingL2capFunction::socket_id() const {
396 return params_
->socket_id
;
399 const std::string
& BluetoothSocketListenUsingL2capFunction::uuid() const {
400 return params_
->uuid
;
403 bool BluetoothSocketListenUsingL2capFunction::CreateParams() {
404 params_
= bluetooth_socket::ListenUsingL2cap::Params::Create(*args_
);
405 EXTENSION_FUNCTION_VALIDATE(params_
.get());
409 void BluetoothSocketListenUsingL2capFunction::CreateService(
410 scoped_refptr
<device::BluetoothAdapter
> adapter
,
411 const device::BluetoothUUID
& uuid
,
412 scoped_ptr
<std::string
> name
,
413 const device::BluetoothAdapter::CreateServiceCallback
& callback
,
414 const device::BluetoothAdapter::CreateServiceErrorCallback
&
416 device::BluetoothAdapter::ServiceOptions service_options
;
417 service_options
.name
= name
.Pass();
419 ListenOptions
* options
= params_
->options
.get();
422 int psm
= *options
->psm
;
423 if (!IsValidPsm(psm
)) {
424 error_callback
.Run(kInvalidPsmError
);
428 service_options
.psm
.reset(new int(psm
));
432 adapter
->CreateL2capService(uuid
, service_options
, callback
, error_callback
);
435 void BluetoothSocketListenUsingL2capFunction::CreateResults() {
436 results_
= bluetooth_socket::ListenUsingL2cap::Results::Create();
439 BluetoothSocketConnectFunction::BluetoothSocketConnectFunction() {}
441 BluetoothSocketConnectFunction::~BluetoothSocketConnectFunction() {}
443 bool BluetoothSocketConnectFunction::Prepare() {
444 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
445 params_
= bluetooth_socket::Connect::Params::Create(*args_
);
446 EXTENSION_FUNCTION_VALIDATE(params_
.get());
448 socket_event_dispatcher_
= GetSocketEventDispatcher(browser_context());
449 return socket_event_dispatcher_
!= NULL
;
452 void BluetoothSocketConnectFunction::AsyncWorkStart() {
453 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
454 device::BluetoothAdapterFactory::GetAdapter(
455 base::Bind(&BluetoothSocketConnectFunction::OnGetAdapter
, this));
458 void BluetoothSocketConnectFunction::OnGetAdapter(
459 scoped_refptr
<device::BluetoothAdapter
> adapter
) {
460 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
461 BluetoothApiSocket
* socket
= GetSocket(params_
->socket_id
);
463 error_
= kSocketNotFoundError
;
464 AsyncWorkCompleted();
468 device::BluetoothDevice
* device
= adapter
->GetDevice(params_
->address
);
470 error_
= kDeviceNotFoundError
;
471 AsyncWorkCompleted();
475 device::BluetoothUUID
uuid(params_
->uuid
);
476 if (!uuid
.IsValid()) {
477 error_
= kInvalidUuidError
;
478 AsyncWorkCompleted();
482 BluetoothPermissionRequest
param(params_
->uuid
);
483 if (!BluetoothManifestData::CheckRequest(GetExtension(), param
)) {
484 error_
= kPermissionDeniedError
;
485 AsyncWorkCompleted();
489 device
->ConnectToService(
491 base::Bind(&BluetoothSocketConnectFunction::OnConnect
, this),
492 base::Bind(&BluetoothSocketConnectFunction::OnConnectError
, this));
495 void BluetoothSocketConnectFunction::OnConnect(
496 scoped_refptr
<device::BluetoothSocket
> socket
) {
497 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
499 // Fetch the socket again since this is not a reference-counted object, and
500 // it may have gone away in the meantime (we check earlier to avoid making
501 // a connection in the case of an obvious programming error).
502 BluetoothApiSocket
* api_socket
= GetSocket(params_
->socket_id
);
504 error_
= kSocketNotFoundError
;
505 AsyncWorkCompleted();
509 api_socket
->AdoptConnectedSocket(socket
,
511 device::BluetoothUUID(params_
->uuid
));
512 socket_event_dispatcher_
->OnSocketConnect(extension_id(),
515 results_
= bluetooth_socket::Connect::Results::Create();
516 AsyncWorkCompleted();
519 void BluetoothSocketConnectFunction::OnConnectError(
520 const std::string
& message
) {
521 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
523 AsyncWorkCompleted();
526 BluetoothSocketDisconnectFunction::BluetoothSocketDisconnectFunction() {}
528 BluetoothSocketDisconnectFunction::~BluetoothSocketDisconnectFunction() {}
530 bool BluetoothSocketDisconnectFunction::Prepare() {
531 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
532 params_
= bluetooth_socket::Disconnect::Params::Create(*args_
);
533 EXTENSION_FUNCTION_VALIDATE(params_
.get());
537 void BluetoothSocketDisconnectFunction::AsyncWorkStart() {
538 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
539 BluetoothApiSocket
* socket
= GetSocket(params_
->socket_id
);
541 error_
= kSocketNotFoundError
;
542 AsyncWorkCompleted();
546 socket
->Disconnect(base::Bind(&BluetoothSocketDisconnectFunction::OnSuccess
,
550 void BluetoothSocketDisconnectFunction::OnSuccess() {
551 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
552 results_
= bluetooth_socket::Disconnect::Results::Create();
553 AsyncWorkCompleted();
556 BluetoothSocketCloseFunction::BluetoothSocketCloseFunction() {}
558 BluetoothSocketCloseFunction::~BluetoothSocketCloseFunction() {}
560 bool BluetoothSocketCloseFunction::Prepare() {
561 params_
= bluetooth_socket::Close::Params::Create(*args_
);
562 EXTENSION_FUNCTION_VALIDATE(params_
.get());
566 void BluetoothSocketCloseFunction::Work() {
567 BluetoothApiSocket
* socket
= GetSocket(params_
->socket_id
);
569 error_
= kSocketNotFoundError
;
573 RemoveSocket(params_
->socket_id
);
574 results_
= bluetooth_socket::Close::Results::Create();
577 BluetoothSocketSendFunction::BluetoothSocketSendFunction()
578 : io_buffer_size_(0) {}
580 BluetoothSocketSendFunction::~BluetoothSocketSendFunction() {}
582 bool BluetoothSocketSendFunction::Prepare() {
583 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
584 params_
= bluetooth_socket::Send::Params::Create(*args_
);
585 EXTENSION_FUNCTION_VALIDATE(params_
.get());
587 io_buffer_size_
= params_
->data
.size();
588 io_buffer_
= new net::WrappedIOBuffer(params_
->data
.data());
592 void BluetoothSocketSendFunction::AsyncWorkStart() {
593 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
594 BluetoothApiSocket
* socket
= GetSocket(params_
->socket_id
);
596 error_
= kSocketNotFoundError
;
600 socket
->Send(io_buffer_
,
602 base::Bind(&BluetoothSocketSendFunction::OnSuccess
, this),
603 base::Bind(&BluetoothSocketSendFunction::OnError
, this));
606 void BluetoothSocketSendFunction::OnSuccess(int bytes_sent
) {
607 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
608 results_
= bluetooth_socket::Send::Results::Create(bytes_sent
);
609 AsyncWorkCompleted();
612 void BluetoothSocketSendFunction::OnError(
613 BluetoothApiSocket::ErrorReason reason
,
614 const std::string
& message
) {
615 DCHECK(BrowserThread::CurrentlyOn(work_thread_id()));
617 AsyncWorkCompleted();
620 BluetoothSocketGetInfoFunction::BluetoothSocketGetInfoFunction() {}
622 BluetoothSocketGetInfoFunction::~BluetoothSocketGetInfoFunction() {}
624 bool BluetoothSocketGetInfoFunction::Prepare() {
625 params_
= bluetooth_socket::GetInfo::Params::Create(*args_
);
626 EXTENSION_FUNCTION_VALIDATE(params_
.get());
630 void BluetoothSocketGetInfoFunction::Work() {
631 BluetoothApiSocket
* socket
= GetSocket(params_
->socket_id
);
633 error_
= kSocketNotFoundError
;
637 linked_ptr
<bluetooth_socket::SocketInfo
> socket_info
=
638 CreateSocketInfo(params_
->socket_id
, socket
);
639 results_
= bluetooth_socket::GetInfo::Results::Create(*socket_info
);
642 BluetoothSocketGetSocketsFunction::BluetoothSocketGetSocketsFunction() {}
644 BluetoothSocketGetSocketsFunction::~BluetoothSocketGetSocketsFunction() {}
646 bool BluetoothSocketGetSocketsFunction::Prepare() { return true; }
648 void BluetoothSocketGetSocketsFunction::Work() {
649 std::vector
<linked_ptr
<bluetooth_socket::SocketInfo
> > socket_infos
;
650 base::hash_set
<int>* resource_ids
= GetSocketIds();
651 if (resource_ids
!= NULL
) {
652 for (base::hash_set
<int>::iterator it
= resource_ids
->begin();
653 it
!= resource_ids
->end();
656 BluetoothApiSocket
* socket
= GetSocket(socket_id
);
658 socket_infos
.push_back(CreateSocketInfo(socket_id
, socket
));
662 results_
= bluetooth_socket::GetSockets::Results::Create(socket_infos
);
666 } // namespace extensions