Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(72)

Side by Side Diff: extensions/browser/api/usb/usb_api.cc

Issue 980023002: Move device/usb classes from the FILE thread to UI thread. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Addressed first round of rocket@ feedback. Created 5 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "extensions/browser/api/usb/usb_api.h" 5 #include "extensions/browser/api/usb/usb_api.h"
6 6
7 #include <string> 7 #include <string>
8 #include <vector> 8 #include <vector>
9 9
10 #include "base/barrier_closure.h"
10 #include "base/memory/scoped_ptr.h" 11 #include "base/memory/scoped_ptr.h"
11 #include "base/message_loop/message_loop_proxy.h"
12 #include "device/core/device_client.h" 12 #include "device/core/device_client.h"
13 #include "device/usb/usb_device_handle.h" 13 #include "device/usb/usb_device_handle.h"
14 #include "device/usb/usb_service.h" 14 #include "device/usb/usb_service.h"
15 #include "extensions/browser/api/device_permissions_manager.h" 15 #include "extensions/browser/api/device_permissions_manager.h"
16 #include "extensions/browser/api/device_permissions_prompt.h" 16 #include "extensions/browser/api/device_permissions_prompt.h"
17 #include "extensions/browser/api/extensions_api_client.h" 17 #include "extensions/browser/api/extensions_api_client.h"
18 #include "extensions/browser/api/usb/usb_device_resource.h" 18 #include "extensions/browser/api/usb/usb_device_resource.h"
19 #include "extensions/browser/extension_system.h" 19 #include "extensions/browser/extension_system.h"
20 #include "extensions/common/api/usb.h" 20 #include "extensions/common/api/usb.h"
21 #include "extensions/common/permissions/permissions_data.h" 21 #include "extensions/common/permissions/permissions_data.h"
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
63 using usb::EndpointDescriptor; 63 using usb::EndpointDescriptor;
64 using usb::GenericTransferInfo; 64 using usb::GenericTransferInfo;
65 using usb::InterfaceDescriptor; 65 using usb::InterfaceDescriptor;
66 using usb::IsochronousTransferInfo; 66 using usb::IsochronousTransferInfo;
67 using usb::Recipient; 67 using usb::Recipient;
68 using usb::RequestType; 68 using usb::RequestType;
69 using usb::SynchronizationType; 69 using usb::SynchronizationType;
70 using usb::TransferType; 70 using usb::TransferType;
71 using usb::UsageType; 71 using usb::UsageType;
72 72
73 typedef std::vector<scoped_refptr<UsbDevice> > DeviceVector;
74 typedef scoped_ptr<DeviceVector> ScopedDeviceVector;
75
76 namespace { 73 namespace {
77 74
78 const char kDataKey[] = "data"; 75 const char kDataKey[] = "data";
79 const char kResultCodeKey[] = "resultCode"; 76 const char kResultCodeKey[] = "resultCode";
80 77
81 const char kErrorInitService[] = "Failed to initialize USB service."; 78 const char kErrorInitService[] = "Failed to initialize USB service.";
82 79
83 const char kErrorOpen[] = "Failed to open device."; 80 const char kErrorOpen[] = "Failed to open device.";
84 const char kErrorCancelled[] = "Transfer was cancelled."; 81 const char kErrorCancelled[] = "Transfer was cancelled.";
85 const char kErrorDisconnect[] = "Device disconnected."; 82 const char kErrorDisconnect[] = "Device disconnected.";
86 const char kErrorGeneric[] = "Transfer failed."; 83 const char kErrorGeneric[] = "Transfer failed.";
87 const char kErrorNotSupported[] = "Not supported on this platform."; 84 const char kErrorNotSupported[] = "Not supported on this platform.";
88 const char kErrorNotConfigured[] = "The device is not in a configured state."; 85 const char kErrorNotConfigured[] = "The device is not in a configured state.";
89 const char kErrorOverflow[] = "Inbound transfer overflow."; 86 const char kErrorOverflow[] = "Inbound transfer overflow.";
90 const char kErrorStalled[] = "Transfer stalled."; 87 const char kErrorStalled[] = "Transfer stalled.";
91 const char kErrorTimeout[] = "Transfer timed out."; 88 const char kErrorTimeout[] = "Transfer timed out.";
92 const char kErrorTransferLength[] = "Transfer length is insufficient."; 89 const char kErrorTransferLength[] = "Transfer length is insufficient.";
93 const char kErrorCannotSetConfiguration[] = 90 const char kErrorCannotSetConfiguration[] =
94 "Error setting device configuration."; 91 "Error setting device configuration.";
95 const char kErrorCannotClaimInterface[] = "Error claiming interface."; 92 const char kErrorCannotClaimInterface[] = "Error claiming interface.";
96 const char kErrorCannotReleaseInterface[] = "Error releasing interface."; 93 const char kErrorCannotReleaseInterface[] = "Error releasing interface.";
97 const char kErrorCannotSetInterfaceAlternateSetting[] = 94 const char kErrorCannotSetInterfaceAlternateSetting[] =
98 "Error setting alternate interface setting."; 95 "Error setting alternate interface setting.";
99 const char kErrorConvertDirection[] = "Invalid transfer direction."; 96 const char kErrorConvertDirection[] = "Invalid transfer direction.";
100 const char kErrorConvertRecipient[] = "Invalid transfer recipient."; 97 const char kErrorConvertRecipient[] = "Invalid transfer recipient.";
101 const char kErrorConvertRequestType[] = "Invalid request type."; 98 const char kErrorConvertRequestType[] = "Invalid request type.";
102 const char kErrorMalformedParameters[] = "Error parsing parameters."; 99 const char kErrorMalformedParameters[] = "Error parsing parameters.";
100 const char kErrorNoConnection[] = "No such connection.";
103 const char kErrorNoDevice[] = "No such device."; 101 const char kErrorNoDevice[] = "No such device.";
104 const char kErrorPermissionDenied[] = "Permission to access device was denied"; 102 const char kErrorPermissionDenied[] = "Permission to access device was denied";
105 const char kErrorInvalidTransferLength[] = 103 const char kErrorInvalidTransferLength[] =
106 "Transfer length must be a positive number less than 104,857,600."; 104 "Transfer length must be a positive number less than 104,857,600.";
107 const char kErrorInvalidNumberOfPackets[] = 105 const char kErrorInvalidNumberOfPackets[] =
108 "Number of packets must be a positive number less than 4,194,304."; 106 "Number of packets must be a positive number less than 4,194,304.";
109 const char kErrorInvalidPacketLength[] = 107 const char kErrorInvalidPacketLength[] =
110 "Packet length must be a positive number less than 65,536."; 108 "Packet length must be a positive number less than 65,536.";
111 const char kErrorInvalidTimeout[] = 109 const char kErrorInvalidTimeout[] =
112 "Transfer timeout must be greater than or equal to 0."; 110 "Transfer timeout must be greater than or equal to 0.";
(...skipping 122 matching lines...) Expand 10 before | Expand all | Expand 10 after
235 case device::USB_TRANSFER_OVERFLOW: 233 case device::USB_TRANSFER_OVERFLOW:
236 return kErrorOverflow; 234 return kErrorOverflow;
237 case device::USB_TRANSFER_LENGTH_SHORT: 235 case device::USB_TRANSFER_LENGTH_SHORT:
238 return kErrorTransferLength; 236 return kErrorTransferLength;
239 default: 237 default:
240 NOTREACHED(); 238 NOTREACHED();
241 return ""; 239 return "";
242 } 240 }
243 } 241 }
244 242
245 void RequestUsbDevicesAccessHelper(
246 ScopedDeviceVector devices,
247 std::vector<scoped_refptr<UsbDevice> >::iterator i,
248 int interface_id,
249 const base::Callback<void(ScopedDeviceVector result)>& callback,
250 bool success) {
251 if (success) {
252 ++i;
253 } else {
254 i = devices->erase(i);
255 }
256 if (i == devices->end()) {
257 callback.Run(devices.Pass());
258 return;
259 }
260 (*i)->RequestUsbAccess(interface_id,
261 base::Bind(RequestUsbDevicesAccessHelper,
262 base::Passed(devices.Pass()),
263 i,
264 interface_id,
265 callback));
266 }
267
268 void RequestUsbDevicesAccess(
269 ScopedDeviceVector devices,
270 int interface_id,
271 const base::Callback<void(ScopedDeviceVector result)>& callback) {
272 if (devices->empty()) {
273 callback.Run(devices.Pass());
274 return;
275 }
276 std::vector<scoped_refptr<UsbDevice> >::iterator i = devices->begin();
277 (*i)->RequestUsbAccess(interface_id,
278 base::Bind(RequestUsbDevicesAccessHelper,
279 base::Passed(devices.Pass()),
280 i,
281 interface_id,
282 callback));
283 }
284
285 base::DictionaryValue* CreateTransferInfo(UsbTransferStatus status,
286 scoped_refptr<net::IOBuffer> data,
287 size_t length) {
288 base::DictionaryValue* result = new base::DictionaryValue();
289 result->SetInteger(kResultCodeKey, status);
290 result->Set(kDataKey,
291 base::BinaryValue::CreateWithCopiedBuffer(data->data(), length));
292 return result;
293 }
294
295 base::Value* PopulateConnectionHandle(int handle, 243 base::Value* PopulateConnectionHandle(int handle,
296 int vendor_id, 244 int vendor_id,
297 int product_id) { 245 int product_id) {
298 ConnectionHandle result; 246 ConnectionHandle result;
299 result.handle = handle; 247 result.handle = handle;
300 result.vendor_id = vendor_id; 248 result.vendor_id = vendor_id;
301 result.product_id = product_id; 249 result.product_id = product_id;
302 return result.ToValue().release(); 250 return result.ToValue().release();
303 } 251 }
304 252
(...skipping 122 matching lines...) Expand 10 before | Expand all | Expand 10 after
427 } 375 }
428 if (input.interface_protocol) { 376 if (input.interface_protocol) {
429 output->SetInterfaceProtocol(*input.interface_protocol); 377 output->SetInterfaceProtocol(*input.interface_protocol);
430 } 378 }
431 } 379 }
432 380
433 } // namespace 381 } // namespace
434 382
435 namespace extensions { 383 namespace extensions {
436 384
437 UsbAsyncApiFunction::UsbAsyncApiFunction() : manager_(NULL) { 385 UsbPermissionCheckingFunction::UsbPermissionCheckingFunction()
386 : device_permissions_manager_(nullptr) {
438 } 387 }
439 388
440 UsbAsyncApiFunction::~UsbAsyncApiFunction() { 389 UsbPermissionCheckingFunction::~UsbPermissionCheckingFunction() {
441 } 390 }
442 391
443 bool UsbAsyncApiFunction::PrePrepare() { 392 bool UsbPermissionCheckingFunction::HasDevicePermission(
444 manager_ = ApiResourceManager<UsbDeviceResource>::Get(browser_context()); 393 scoped_refptr<UsbDevice> device) {
445 set_work_thread_id(BrowserThread::FILE); 394 if (!device_permissions_manager_) {
446 return manager_ != NULL; 395 device_permissions_manager_ =
447 } 396 DevicePermissionsManager::Get(browser_context());
397 }
448 398
449 bool UsbAsyncApiFunction::Respond() { 399 DevicePermissions* device_permissions =
450 return error_.empty(); 400 device_permissions_manager_->GetForExtension(extension_id());
451 } 401 DCHECK(device_permissions);
452 402
453 bool UsbAsyncApiFunction::HasDevicePermission(scoped_refptr<UsbDevice> device) { 403 permission_entry_ = device_permissions->FindEntry(device);
454 DCHECK(device_permissions_);
455
456 // Check the DevicePermissionsManager first so that if an entry is found
457 // it can be stored for later. This requires the serial number.
458 base::string16 serial_number;
459 device->GetSerialNumber(&serial_number);
460
461 permission_entry_ = device_permissions_->FindEntry(device, serial_number);
462 if (permission_entry_.get()) { 404 if (permission_entry_.get()) {
463 return true; 405 return true;
464 } 406 }
465 407
466 UsbDevicePermission::CheckParam param( 408 UsbDevicePermission::CheckParam param(
467 device->vendor_id(), 409 device->vendor_id(),
468 device->product_id(), 410 device->product_id(),
469 UsbDevicePermissionData::UNSPECIFIED_INTERFACE); 411 UsbDevicePermissionData::UNSPECIFIED_INTERFACE);
470 if (extension()->permissions_data()->CheckAPIPermissionWithParam( 412 if (extension()->permissions_data()->CheckAPIPermissionWithParam(
471 APIPermission::kUsbDevice, &param)) { 413 APIPermission::kUsbDevice, &param)) {
472 return true; 414 return true;
473 } 415 }
474 416
475 return false; 417 return false;
476 } 418 }
477 419
478 scoped_refptr<UsbDeviceHandle> 420 void UsbPermissionCheckingFunction::RecordDeviceLastUsed() {
479 UsbAsyncApiFunction::GetDeviceHandleOrCompleteWithError( 421 if (permission_entry_.get()) {
480 const ConnectionHandle& input_device_handle) { 422 device_permissions_manager_->UpdateLastUsed(extension_id(),
481 UsbDeviceResource* resource = 423 permission_entry_);
482 manager_->Get(extension_->id(), input_device_handle.handle); 424 }
483 if (!resource) { 425 }
484 CompleteWithError(kErrorNoDevice); 426
485 return NULL; 427 UsbConnectionFunction::UsbConnectionFunction() {
428 }
429
430 UsbConnectionFunction::~UsbConnectionFunction() {
431 }
432
433 scoped_refptr<device::UsbDeviceHandle> UsbConnectionFunction::GetDeviceHandle(
434 const extensions::core_api::usb::ConnectionHandle& handle) {
435 ApiResourceManager<UsbDeviceResource>* manager =
436 ApiResourceManager<UsbDeviceResource>::Get(browser_context());
437 if (!manager) {
438 return nullptr;
486 } 439 }
487 440
488 if (!resource->device().get() || !resource->device()->GetDevice().get()) { 441 UsbDeviceResource* resource = manager->Get(extension_id(), handle.handle);
489 CompleteWithError(kErrorDisconnect); 442 if (!resource) {
490 manager_->Remove(extension_->id(), input_device_handle.handle); 443 return nullptr;
491 return NULL;
492 }
493
494 if (resource->device()->GetDevice()->vendor_id() !=
495 input_device_handle.vendor_id ||
496 resource->device()->GetDevice()->product_id() !=
497 input_device_handle.product_id) {
498 CompleteWithError(kErrorNoDevice);
499 return NULL;
500 } 444 }
501 445
502 return resource->device(); 446 return resource->device();
503 } 447 }
504 448
505 void UsbAsyncApiFunction::RemoveUsbDeviceResource(int api_resource_id) { 449 void UsbConnectionFunction::ReleaseDeviceHandle(
506 manager_->Remove(extension_->id(), api_resource_id); 450 const extensions::core_api::usb::ConnectionHandle& handle) {
451 ApiResourceManager<UsbDeviceResource>* manager =
452 ApiResourceManager<UsbDeviceResource>::Get(browser_context());
453 manager->Remove(extension_id(), handle.handle);
507 } 454 }
508 455
509 void UsbAsyncApiFunction::CompleteWithError(const std::string& error) { 456 UsbTransferFunction::UsbTransferFunction() {
510 SetError(error);
511 AsyncWorkCompleted();
512 } 457 }
513 458
514 UsbAsyncApiTransferFunction::UsbAsyncApiTransferFunction() { 459 UsbTransferFunction::~UsbTransferFunction() {
515 } 460 }
516 461
517 UsbAsyncApiTransferFunction::~UsbAsyncApiTransferFunction() { 462 void UsbTransferFunction::OnCompleted(UsbTransferStatus status,
518 } 463 scoped_refptr<net::IOBuffer> data,
464 size_t length) {
465 scoped_ptr<base::DictionaryValue> transfer_info(new base::DictionaryValue());
466 transfer_info->SetInteger(kResultCodeKey, status);
467 transfer_info->Set(kDataKey, base::BinaryValue::CreateWithCopiedBuffer(
468 data->data(), length));
519 469
520 void UsbAsyncApiTransferFunction::OnCompleted(UsbTransferStatus status, 470 if (status == device::USB_TRANSFER_COMPLETED) {
521 scoped_refptr<net::IOBuffer> data, 471 Respond(OneArgument(transfer_info.release()));
522 size_t length) { 472 } else {
523 if (status != device::USB_TRANSFER_COMPLETED) 473 scoped_ptr<base::ListValue> error_args(new base::ListValue());
524 SetError(ConvertTransferStatusToApi(status)); 474 error_args->Append(transfer_info.release());
525 475 // Returning arguments with an error is wrong but we're stuck with it.
526 SetResult(CreateTransferInfo(status, data, length)); 476 Respond(ErrorWithArguments(error_args.Pass(),
527 AsyncWorkCompleted(); 477 ConvertTransferStatusToApi(status)));
528 } 478 }
529
530 bool UsbAsyncApiTransferFunction::ConvertDirectionSafely(
531 const Direction& input,
532 UsbEndpointDirection* output) {
533 const bool converted = ConvertDirectionFromApi(input, output);
534 if (!converted)
535 SetError(kErrorConvertDirection);
536 return converted;
537 }
538
539 bool UsbAsyncApiTransferFunction::ConvertRequestTypeSafely(
540 const RequestType& input,
541 UsbDeviceHandle::TransferRequestType* output) {
542 const bool converted = ConvertRequestTypeFromApi(input, output);
543 if (!converted)
544 SetError(kErrorConvertRequestType);
545 return converted;
546 }
547
548 bool UsbAsyncApiTransferFunction::ConvertRecipientSafely(
549 const Recipient& input,
550 UsbDeviceHandle::TransferRecipient* output) {
551 const bool converted = ConvertRecipientFromApi(input, output);
552 if (!converted)
553 SetError(kErrorConvertRecipient);
554 return converted;
555 } 479 }
556 480
557 UsbFindDevicesFunction::UsbFindDevicesFunction() { 481 UsbFindDevicesFunction::UsbFindDevicesFunction() {
558 } 482 }
559 483
560 UsbFindDevicesFunction::~UsbFindDevicesFunction() { 484 UsbFindDevicesFunction::~UsbFindDevicesFunction() {
561 } 485 }
562 486
563 bool UsbFindDevicesFunction::Prepare() { 487 ExtensionFunction::ResponseAction UsbFindDevicesFunction::Run() {
564 parameters_ = FindDevices::Params::Create(*args_); 488 scoped_ptr<extensions::core_api::usb::FindDevices::Params> parameters =
565 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 489 FindDevices::Params::Create(*args_);
566 return true; 490 EXTENSION_FUNCTION_VALIDATE(parameters.get());
567 }
568 491
569 void UsbFindDevicesFunction::AsyncWorkStart() { 492 vendor_id_ = parameters->options.vendor_id;
570 scoped_ptr<base::ListValue> result(new base::ListValue()); 493 product_id_ = parameters->options.product_id;
571 const uint16_t vendor_id = parameters_->options.vendor_id; 494 interface_id_ = parameters->options.interface_id.get()
572 const uint16_t product_id = parameters_->options.product_id; 495 ? *parameters->options.interface_id.get()
573 int interface_id = parameters_->options.interface_id.get() 496 : UsbDevicePermissionData::ANY_INTERFACE;
574 ? *parameters_->options.interface_id.get() 497 UsbDevicePermission::CheckParam param(vendor_id_, product_id_, interface_id_);
575 : UsbDevicePermissionData::ANY_INTERFACE;
576 UsbDevicePermission::CheckParam param(vendor_id, product_id, interface_id);
577 if (!extension()->permissions_data()->CheckAPIPermissionWithParam( 498 if (!extension()->permissions_data()->CheckAPIPermissionWithParam(
578 APIPermission::kUsbDevice, &param)) { 499 APIPermission::kUsbDevice, &param)) {
579 LOG(WARNING) << "Insufficient permissions to access device."; 500 return RespondNow(Error(kErrorPermissionDenied));
580 CompleteWithError(kErrorPermissionDenied);
581 return;
582 } 501 }
583 502
584 UsbService* service = device::DeviceClient::Get()->GetUsbService(); 503 UsbService* service = device::DeviceClient::Get()->GetUsbService();
585 if (!service) { 504 if (!service) {
586 CompleteWithError(kErrorInitService); 505 return RespondNow(Error(kErrorInitService));
587 return;
588 } 506 }
589 507
590 ScopedDeviceVector devices(new DeviceVector()); 508 service->GetDevices(
591 service->GetDevices(devices.get()); 509 base::Bind(&UsbFindDevicesFunction::OnGetDevicesComplete, this));
510 return RespondLater();
511 }
592 512
593 for (DeviceVector::iterator it = devices->begin(); it != devices->end();) { 513 void UsbFindDevicesFunction::OnGetDevicesComplete(
594 if ((*it)->vendor_id() != vendor_id || (*it)->product_id() != product_id) { 514 const std::vector<scoped_refptr<UsbDevice>>& devices) {
595 it = devices->erase(it); 515 result_.reset(new base::ListValue());
516 barrier_ = base::BarrierClosure(
517 devices.size(), base::Bind(&UsbFindDevicesFunction::OpenComplete, this));
518
519 for (const scoped_refptr<UsbDevice>& device : devices) {
520 if (device->vendor_id() != vendor_id_ ||
521 device->product_id() != product_id_) {
522 barrier_.Run();
596 } else { 523 } else {
597 ++it; 524 device->RequestUsbAccess(
525 interface_id_,
526 base::Bind(&UsbFindDevicesFunction::OnRequestAccessComplete, this,
527 device));
598 } 528 }
599 } 529 }
600
601 RequestUsbDevicesAccess(
602 devices.Pass(),
603 interface_id,
604 base::Bind(&UsbFindDevicesFunction::OpenDevices, this));
605 } 530 }
606 531
607 void UsbFindDevicesFunction::OpenDevices(ScopedDeviceVector devices) { 532 void UsbFindDevicesFunction::OnRequestAccessComplete(
608 base::ListValue* result = new base::ListValue(); 533 scoped_refptr<UsbDevice> device,
534 bool success) {
535 if (success) {
536 device->Open(base::Bind(&UsbFindDevicesFunction::OnDeviceOpened, this));
537 } else {
538 barrier_.Run();
539 }
540 }
609 541
610 for (size_t i = 0; i < devices->size(); ++i) { 542 void UsbFindDevicesFunction::OnDeviceOpened(
611 scoped_refptr<UsbDeviceHandle> device_handle = devices->at(i)->Open(); 543 scoped_refptr<UsbDeviceHandle> device_handle) {
612 if (device_handle.get()) 544 if (device_handle.get()) {
613 device_handles_.push_back(device_handle); 545 ApiResourceManager<UsbDeviceResource>* manager =
546 ApiResourceManager<UsbDeviceResource>::Get(browser_context());
547 UsbDeviceResource* resource =
548 new UsbDeviceResource(extension_id(), device_handle);
549 scoped_refptr<UsbDevice> device = device_handle->GetDevice();
550 result_->Append(PopulateConnectionHandle(
551 manager->Add(resource), device->vendor_id(), device->product_id()));
614 } 552 }
553 barrier_.Run();
554 }
615 555
616 for (size_t i = 0; i < device_handles_.size(); ++i) { 556 void UsbFindDevicesFunction::OpenComplete() {
617 UsbDeviceHandle* const device_handle = device_handles_[i].get(); 557 Respond(OneArgument(result_.release()));
618 UsbDeviceResource* const resource =
619 new UsbDeviceResource(extension_->id(), device_handle);
620
621 result->Append(PopulateConnectionHandle(manager_->Add(resource),
622 parameters_->options.vendor_id,
623 parameters_->options.product_id));
624 }
625
626 SetResult(result);
627 AsyncWorkCompleted();
628 } 558 }
629 559
630 UsbGetDevicesFunction::UsbGetDevicesFunction() { 560 UsbGetDevicesFunction::UsbGetDevicesFunction() {
631 } 561 }
632 562
633 UsbGetDevicesFunction::~UsbGetDevicesFunction() { 563 UsbGetDevicesFunction::~UsbGetDevicesFunction() {
634 } 564 }
635 565
636 bool UsbGetDevicesFunction::Prepare() { 566 ExtensionFunction::ResponseAction UsbGetDevicesFunction::Run() {
637 parameters_ = GetDevices::Params::Create(*args_); 567 scoped_ptr<extensions::core_api::usb::GetDevices::Params> parameters =
638 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 568 GetDevices::Params::Create(*args_);
639 device_permissions_ = DevicePermissionsManager::Get(browser_context()) 569 EXTENSION_FUNCTION_VALIDATE(parameters.get());
640 ->GetForExtension(extension()->id());
641 return true;
642 }
643 570
644 void UsbGetDevicesFunction::AsyncWorkStart() { 571 if (parameters->options.filters) {
645 std::vector<UsbDeviceFilter> filters; 572 filters_.resize(parameters->options.filters->size());
646 if (parameters_->options.filters) { 573 for (size_t i = 0; i < parameters->options.filters->size(); ++i) {
647 filters.resize(parameters_->options.filters->size()); 574 ConvertDeviceFilter(*parameters->options.filters->at(i).get(),
648 for (size_t i = 0; i < parameters_->options.filters->size(); ++i) { 575 &filters_[i]);
649 ConvertDeviceFilter(*parameters_->options.filters->at(i).get(),
650 &filters[i]);
651 } 576 }
652 } 577 }
653 if (parameters_->options.vendor_id) { 578 if (parameters->options.vendor_id) {
654 filters.resize(filters.size() + 1); 579 filters_.resize(filters_.size() + 1);
655 filters.back().SetVendorId(*parameters_->options.vendor_id); 580 filters_.back().SetVendorId(*parameters->options.vendor_id);
656 if (parameters_->options.product_id) { 581 if (parameters->options.product_id) {
657 filters.back().SetProductId(*parameters_->options.product_id); 582 filters_.back().SetProductId(*parameters->options.product_id);
658 } 583 }
659 } 584 }
660 585
661 UsbService* service = device::DeviceClient::Get()->GetUsbService(); 586 UsbService* service = device::DeviceClient::Get()->GetUsbService();
662 if (!service) { 587 if (!service) {
663 CompleteWithError(kErrorInitService); 588 return RespondNow(Error(kErrorInitService));
664 return;
665 } 589 }
666 590
667 DeviceVector devices; 591 service->GetDevices(
668 service->GetDevices(&devices); 592 base::Bind(&UsbGetDevicesFunction::OnGetDevicesComplete, this));
593 return RespondLater();
594 }
669 595
596 void UsbGetDevicesFunction::OnGetDevicesComplete(
597 const std::vector<scoped_refptr<UsbDevice>>& devices) {
670 scoped_ptr<base::ListValue> result(new base::ListValue()); 598 scoped_ptr<base::ListValue> result(new base::ListValue());
671 for (DeviceVector::iterator it = devices.begin(); it != devices.end(); ++it) { 599 for (const scoped_refptr<UsbDevice>& device : devices) {
672 scoped_refptr<UsbDevice> device = *it; 600 if ((filters_.empty() || UsbDeviceFilter::MatchesAny(device, filters_)) &&
673 if ((filters.empty() || UsbDeviceFilter::MatchesAny(device, filters)) &&
674 HasDevicePermission(device)) { 601 HasDevicePermission(device)) {
675 result->Append(PopulateDevice(it->get())); 602 result->Append(PopulateDevice(device.get()));
676 } 603 }
677 } 604 }
678 605
679 SetResult(result.release()); 606 Respond(OneArgument(result.release()));
680 AsyncWorkCompleted();
681 } 607 }
682 608
683 UsbGetUserSelectedDevicesFunction::UsbGetUserSelectedDevicesFunction() { 609 UsbGetUserSelectedDevicesFunction::UsbGetUserSelectedDevicesFunction() {
684 } 610 }
685 611
686 UsbGetUserSelectedDevicesFunction::~UsbGetUserSelectedDevicesFunction() { 612 UsbGetUserSelectedDevicesFunction::~UsbGetUserSelectedDevicesFunction() {
687 } 613 }
688 614
689 AsyncApiFunction::ResponseAction UsbGetUserSelectedDevicesFunction::Run() { 615 ExtensionFunction::ResponseAction UsbGetUserSelectedDevicesFunction::Run() {
690 scoped_ptr<extensions::core_api::usb::GetUserSelectedDevices::Params> 616 scoped_ptr<extensions::core_api::usb::GetUserSelectedDevices::Params>
691 parameters = GetUserSelectedDevices::Params::Create(*args_); 617 parameters = GetUserSelectedDevices::Params::Create(*args_);
692 EXTENSION_FUNCTION_VALIDATE(parameters.get()); 618 EXTENSION_FUNCTION_VALIDATE(parameters.get());
693 619
694 if (!user_gesture()) { 620 if (!user_gesture()) {
695 return RespondNow(OneArgument(new base::ListValue())); 621 return RespondNow(OneArgument(new base::ListValue()));
696 } 622 }
697 623
698 bool multiple = false; 624 bool multiple = false;
699 if (parameters->options.multiple) { 625 if (parameters->options.multiple) {
(...skipping 21 matching lines...) Expand all
721 return RespondLater(); 647 return RespondLater();
722 } 648 }
723 649
724 void UsbGetUserSelectedDevicesFunction::OnUsbDevicesChosen( 650 void UsbGetUserSelectedDevicesFunction::OnUsbDevicesChosen(
725 const std::vector<scoped_refptr<UsbDevice>>& devices) { 651 const std::vector<scoped_refptr<UsbDevice>>& devices) {
726 scoped_ptr<base::ListValue> result(new base::ListValue()); 652 scoped_ptr<base::ListValue> result(new base::ListValue());
727 for (const auto& device : devices) { 653 for (const auto& device : devices) {
728 result->Append(PopulateDevice(device.get())); 654 result->Append(PopulateDevice(device.get()));
729 } 655 }
730 656
731 SetResult(result.release()); 657 Respond(OneArgument(result.release()));
732 SendResponse(true);
733 Release(); 658 Release();
734 } 659 }
735 660
736 UsbRequestAccessFunction::UsbRequestAccessFunction() { 661 UsbRequestAccessFunction::UsbRequestAccessFunction() {
737 } 662 }
738 663
739 UsbRequestAccessFunction::~UsbRequestAccessFunction() { 664 UsbRequestAccessFunction::~UsbRequestAccessFunction() {
740 } 665 }
741 666
742 bool UsbRequestAccessFunction::Prepare() { 667 ExtensionFunction::ResponseAction UsbRequestAccessFunction::Run() {
743 parameters_ = RequestAccess::Params::Create(*args_); 668 scoped_ptr<extensions::core_api::usb::RequestAccess::Params> parameters =
744 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 669 RequestAccess::Params::Create(*args_);
745 return true; 670 EXTENSION_FUNCTION_VALIDATE(parameters.get());
746 } 671 return RespondNow(OneArgument(new base::FundamentalValue(true)));
747
748 void UsbRequestAccessFunction::AsyncWorkStart() {
749 SetResult(new base::FundamentalValue(true));
750 AsyncWorkCompleted();
751 } 672 }
752 673
753 UsbOpenDeviceFunction::UsbOpenDeviceFunction() { 674 UsbOpenDeviceFunction::UsbOpenDeviceFunction() {
754 } 675 }
755 676
756 UsbOpenDeviceFunction::~UsbOpenDeviceFunction() { 677 UsbOpenDeviceFunction::~UsbOpenDeviceFunction() {
757 } 678 }
758 679
759 bool UsbOpenDeviceFunction::Prepare() { 680 ExtensionFunction::ResponseAction UsbOpenDeviceFunction::Run() {
760 parameters_ = OpenDevice::Params::Create(*args_); 681 scoped_ptr<extensions::core_api::usb::OpenDevice::Params> parameters =
761 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 682 OpenDevice::Params::Create(*args_);
762 device_permissions_manager_ = 683 EXTENSION_FUNCTION_VALIDATE(parameters.get());
763 DevicePermissionsManager::Get(browser_context()); 684
764 device_permissions_ = 685 UsbService* service = device::DeviceClient::Get()->GetUsbService();
765 device_permissions_manager_->GetForExtension(extension()->id()); 686 if (!service) {
766 return true; 687 return RespondNow(Error(kErrorInitService));
688 }
689
690 scoped_refptr<UsbDevice> device =
691 service->GetDeviceById(parameters->device.device);
692 if (!device.get()) {
693 return RespondNow(Error(kErrorNoDevice));
694 }
695
696 if (!HasDevicePermission(device)) {
697 // This function must act as if there is no such device. Otherwise it can be
698 // used to fingerprint unauthorized devices.
699 return RespondNow(Error(kErrorNoDevice));
700 }
701
702 device->RequestUsbAccess(
703 -1, /* any interface, unused by the permission broker */
704 base::Bind(&UsbOpenDeviceFunction::OnRequestAccessComplete, this,
705 device));
706 return RespondLater();
767 } 707 }
768 708
769 void UsbOpenDeviceFunction::AsyncWorkStart() { 709 void UsbOpenDeviceFunction::OnRequestAccessComplete(
770 UsbService* service = device::DeviceClient::Get()->GetUsbService(); 710 scoped_refptr<UsbDevice> device,
771 if (!service) { 711 bool success) {
772 CompleteWithError(kErrorInitService); 712 if (success) {
713 device->Open(base::Bind(&UsbOpenDeviceFunction::OnDeviceOpened, this));
714 } else {
715 Respond(Error(kErrorPermissionDenied));
716 }
717 }
718
719 void UsbOpenDeviceFunction::OnDeviceOpened(
720 scoped_refptr<UsbDeviceHandle> device_handle) {
721 if (!device_handle.get()) {
722 Respond(Error(kErrorOpen));
773 return; 723 return;
774 } 724 }
775 725
776 device_ = service->GetDeviceById(parameters_->device.device); 726 RecordDeviceLastUsed();
777 if (!device_.get()) {
778 CompleteWithError(kErrorNoDevice);
779 return;
780 }
781 727
782 if (!HasDevicePermission(device_)) { 728 ApiResourceManager<UsbDeviceResource>* manager =
783 // This function must act as if there is no such device. Otherwise it can be 729 ApiResourceManager<UsbDeviceResource>::Get(browser_context());
784 // used to fingerprint unauthorized devices. 730 scoped_refptr<UsbDevice> device = device_handle->GetDevice();
785 CompleteWithError(kErrorNoDevice); 731 Respond(OneArgument(PopulateConnectionHandle(
786 return; 732 manager->Add(new UsbDeviceResource(extension_id(), device_handle)),
787 } 733 device->vendor_id(), device->product_id())));
788
789 device_->RequestUsbAccess(
790 -1, /* any interface, unused by the permission broker */
791 base::Bind(&UsbOpenDeviceFunction::OnRequestAccessComplete, this));
792 }
793
794 void UsbOpenDeviceFunction::OnRequestAccessComplete(bool success) {
795 if (!success) {
796 SetError(kErrorPermissionDenied);
797 AsyncWorkCompleted();
798 return;
799 }
800
801 scoped_refptr<UsbDeviceHandle> handle = device_->Open();
802 if (!handle.get()) {
803 SetError(kErrorOpen);
804 AsyncWorkCompleted();
805 return;
806 }
807
808 SetResult(PopulateConnectionHandle(
809 manager_->Add(new UsbDeviceResource(extension_->id(), handle)),
810 device_->vendor_id(), device_->product_id()));
811 AsyncWorkCompleted();
812 }
813
814 bool UsbOpenDeviceFunction::Respond() {
815 if (permission_entry_.get()) {
816 device_permissions_manager_->UpdateLastUsed(extension_->id(),
817 permission_entry_);
818 }
819 return UsbAsyncApiFunction::Respond();
820 } 734 }
821 735
822 UsbSetConfigurationFunction::UsbSetConfigurationFunction() { 736 UsbSetConfigurationFunction::UsbSetConfigurationFunction() {
823 } 737 }
824 738
825 UsbSetConfigurationFunction::~UsbSetConfigurationFunction() { 739 UsbSetConfigurationFunction::~UsbSetConfigurationFunction() {
826 } 740 }
827 741
828 bool UsbSetConfigurationFunction::Prepare() { 742 ExtensionFunction::ResponseAction UsbSetConfigurationFunction::Run() {
829 parameters_ = SetConfiguration::Params::Create(*args_); 743 scoped_ptr<extensions::core_api::usb::SetConfiguration::Params> parameters =
830 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 744 SetConfiguration::Params::Create(*args_);
831 return true; 745 EXTENSION_FUNCTION_VALIDATE(parameters.get());
746
747 scoped_refptr<UsbDeviceHandle> device_handle =
748 GetDeviceHandle(parameters->handle);
749 if (!device_handle.get()) {
750 return RespondNow(Error(kErrorNoConnection));
751 }
752
753 device_handle->SetConfiguration(
754 parameters->configuration_value,
755 base::Bind(&UsbSetConfigurationFunction::OnComplete, this));
756 return RespondLater();
832 } 757 }
833 758
834 void UsbSetConfigurationFunction::AsyncWorkStart() { 759 void UsbSetConfigurationFunction::OnComplete(bool success) {
835 scoped_refptr<UsbDeviceHandle> device_handle = 760 if (success) {
836 GetDeviceHandleOrCompleteWithError(parameters_->handle); 761 Respond(NoArguments());
837 if (!device_handle.get()) { 762 } else {
838 return; 763 Respond(Error(kErrorCannotSetConfiguration));
839 } 764 }
840
841 if (!device_handle->SetConfiguration(parameters_->configuration_value)) {
842 SetError(kErrorCannotSetConfiguration);
843 }
844 AsyncWorkCompleted();
845 } 765 }
846 766
847 UsbGetConfigurationFunction::UsbGetConfigurationFunction() { 767 UsbGetConfigurationFunction::UsbGetConfigurationFunction() {
848 } 768 }
849 769
850 UsbGetConfigurationFunction::~UsbGetConfigurationFunction() { 770 UsbGetConfigurationFunction::~UsbGetConfigurationFunction() {
851 } 771 }
852 772
853 bool UsbGetConfigurationFunction::Prepare() { 773 ExtensionFunction::ResponseAction UsbGetConfigurationFunction::Run() {
854 parameters_ = GetConfiguration::Params::Create(*args_); 774 scoped_ptr<extensions::core_api::usb::GetConfiguration::Params> parameters =
855 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 775 GetConfiguration::Params::Create(*args_);
856 return true; 776 EXTENSION_FUNCTION_VALIDATE(parameters.get());
857 }
858 777
859 void UsbGetConfigurationFunction::AsyncWorkStart() {
860 scoped_refptr<UsbDeviceHandle> device_handle = 778 scoped_refptr<UsbDeviceHandle> device_handle =
861 GetDeviceHandleOrCompleteWithError(parameters_->handle); 779 GetDeviceHandle(parameters->handle);
862 if (!device_handle.get()) { 780 if (!device_handle.get()) {
863 return; 781 return RespondNow(Error(kErrorNoConnection));
864 } 782 }
865 783
866 const UsbConfigDescriptor* config_descriptor = 784 const UsbConfigDescriptor* config_descriptor =
867 device_handle->GetDevice()->GetConfiguration(); 785 device_handle->GetDevice()->GetConfiguration();
868 if (config_descriptor) { 786 if (config_descriptor) {
869 ConfigDescriptor config; 787 ConfigDescriptor config;
870 ConvertConfigDescriptor(*config_descriptor, &config); 788 ConvertConfigDescriptor(*config_descriptor, &config);
871 SetResult(config.ToValue().release()); 789 return RespondNow(OneArgument(config.ToValue().release()));
872 } else { 790 } else {
873 SetError(kErrorNotConfigured); 791 return RespondNow(Error(kErrorNotConfigured));
874 } 792 }
875
876 AsyncWorkCompleted();
877 } 793 }
878 794
879 UsbListInterfacesFunction::UsbListInterfacesFunction() { 795 UsbListInterfacesFunction::UsbListInterfacesFunction() {
880 } 796 }
881 797
882 UsbListInterfacesFunction::~UsbListInterfacesFunction() { 798 UsbListInterfacesFunction::~UsbListInterfacesFunction() {
883 } 799 }
884 800
885 bool UsbListInterfacesFunction::Prepare() { 801 ExtensionFunction::ResponseAction UsbListInterfacesFunction::Run() {
886 parameters_ = ListInterfaces::Params::Create(*args_); 802 scoped_ptr<extensions::core_api::usb::ListInterfaces::Params> parameters =
887 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 803 ListInterfaces::Params::Create(*args_);
888 return true; 804 EXTENSION_FUNCTION_VALIDATE(parameters.get());
889 }
890 805
891 void UsbListInterfacesFunction::AsyncWorkStart() {
892 scoped_refptr<UsbDeviceHandle> device_handle = 806 scoped_refptr<UsbDeviceHandle> device_handle =
893 GetDeviceHandleOrCompleteWithError(parameters_->handle); 807 GetDeviceHandle(parameters->handle);
894 if (!device_handle.get()) { 808 if (!device_handle.get()) {
895 return; 809 return RespondNow(Error(kErrorNoConnection));
896 } 810 }
897 811
898 const UsbConfigDescriptor* config_descriptor = 812 const UsbConfigDescriptor* config_descriptor =
899 device_handle->GetDevice()->GetConfiguration(); 813 device_handle->GetDevice()->GetConfiguration();
900 if (config_descriptor) { 814 if (config_descriptor) {
901 ConfigDescriptor config; 815 ConfigDescriptor config;
902 ConvertConfigDescriptor(*config_descriptor, &config); 816 ConvertConfigDescriptor(*config_descriptor, &config);
903 817
904 scoped_ptr<base::ListValue> result(new base::ListValue); 818 scoped_ptr<base::ListValue> result(new base::ListValue);
905 for (size_t i = 0; i < config.interfaces.size(); ++i) { 819 for (size_t i = 0; i < config.interfaces.size(); ++i) {
906 result->Append(config.interfaces[i]->ToValue().release()); 820 result->Append(config.interfaces[i]->ToValue().release());
907 } 821 }
908 822
909 SetResult(result.release()); 823 return RespondNow(OneArgument(result.release()));
910 } else { 824 } else {
911 SetError(kErrorNotConfigured); 825 return RespondNow(Error(kErrorNotConfigured));
912 } 826 }
913
914 AsyncWorkCompleted();
915 } 827 }
916 828
917 UsbCloseDeviceFunction::UsbCloseDeviceFunction() { 829 UsbCloseDeviceFunction::UsbCloseDeviceFunction() {
918 } 830 }
919 831
920 UsbCloseDeviceFunction::~UsbCloseDeviceFunction() { 832 UsbCloseDeviceFunction::~UsbCloseDeviceFunction() {
921 } 833 }
922 834
923 bool UsbCloseDeviceFunction::Prepare() { 835 ExtensionFunction::ResponseAction UsbCloseDeviceFunction::Run() {
924 parameters_ = CloseDevice::Params::Create(*args_); 836 scoped_ptr<extensions::core_api::usb::CloseDevice::Params> parameters =
925 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 837 CloseDevice::Params::Create(*args_);
926 return true; 838 EXTENSION_FUNCTION_VALIDATE(parameters.get());
927 }
928 839
929 void UsbCloseDeviceFunction::AsyncWorkStart() {
930 scoped_refptr<UsbDeviceHandle> device_handle = 840 scoped_refptr<UsbDeviceHandle> device_handle =
931 GetDeviceHandleOrCompleteWithError(parameters_->handle); 841 GetDeviceHandle(parameters->handle);
932 if (!device_handle.get()) 842 if (!device_handle.get()) {
933 return; 843 return RespondNow(Error(kErrorNoConnection));
844 }
934 845
935 // The device handle is closed when the resource is destroyed. 846 // The device handle is closed when the resource is destroyed.
936 RemoveUsbDeviceResource(parameters_->handle.handle); 847 ReleaseDeviceHandle(parameters->handle);
937 AsyncWorkCompleted(); 848 return RespondNow(NoArguments());
938 } 849 }
939 850
940 UsbClaimInterfaceFunction::UsbClaimInterfaceFunction() { 851 UsbClaimInterfaceFunction::UsbClaimInterfaceFunction() {
941 } 852 }
942 853
943 UsbClaimInterfaceFunction::~UsbClaimInterfaceFunction() { 854 UsbClaimInterfaceFunction::~UsbClaimInterfaceFunction() {
944 } 855 }
945 856
946 bool UsbClaimInterfaceFunction::Prepare() { 857 ExtensionFunction::ResponseAction UsbClaimInterfaceFunction::Run() {
947 parameters_ = ClaimInterface::Params::Create(*args_); 858 scoped_ptr<extensions::core_api::usb::ClaimInterface::Params> parameters =
948 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 859 ClaimInterface::Params::Create(*args_);
949 return true; 860 EXTENSION_FUNCTION_VALIDATE(parameters.get());
861
862 scoped_refptr<UsbDeviceHandle> device_handle =
863 GetDeviceHandle(parameters->handle);
864 if (!device_handle.get()) {
865 return RespondNow(Error(kErrorNoConnection));
866 }
867
868 device_handle->ClaimInterface(
869 parameters->interface_number,
870 base::Bind(&UsbClaimInterfaceFunction::OnComplete, this));
871 return RespondLater();
950 } 872 }
951 873
952 void UsbClaimInterfaceFunction::AsyncWorkStart() { 874 void UsbClaimInterfaceFunction::OnComplete(bool success) {
953 scoped_refptr<UsbDeviceHandle> device_handle = 875 if (success) {
954 GetDeviceHandleOrCompleteWithError(parameters_->handle); 876 Respond(NoArguments());
955 if (!device_handle.get()) 877 } else {
956 return; 878 Respond(Error(kErrorCannotClaimInterface));
957 879 }
958 bool success = device_handle->ClaimInterface(parameters_->interface_number);
959
960 if (!success)
961 SetError(kErrorCannotClaimInterface);
962 AsyncWorkCompleted();
963 } 880 }
964 881
965 UsbReleaseInterfaceFunction::UsbReleaseInterfaceFunction() { 882 UsbReleaseInterfaceFunction::UsbReleaseInterfaceFunction() {
966 } 883 }
967 884
968 UsbReleaseInterfaceFunction::~UsbReleaseInterfaceFunction() { 885 UsbReleaseInterfaceFunction::~UsbReleaseInterfaceFunction() {
969 } 886 }
970 887
971 bool UsbReleaseInterfaceFunction::Prepare() { 888 ExtensionFunction::ResponseAction UsbReleaseInterfaceFunction::Run() {
972 parameters_ = ReleaseInterface::Params::Create(*args_); 889 scoped_ptr<extensions::core_api::usb::ReleaseInterface::Params> parameters =
973 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 890 ReleaseInterface::Params::Create(*args_);
974 return true; 891 EXTENSION_FUNCTION_VALIDATE(parameters.get());
975 }
976 892
977 void UsbReleaseInterfaceFunction::AsyncWorkStart() {
978 scoped_refptr<UsbDeviceHandle> device_handle = 893 scoped_refptr<UsbDeviceHandle> device_handle =
979 GetDeviceHandleOrCompleteWithError(parameters_->handle); 894 GetDeviceHandle(parameters->handle);
980 if (!device_handle.get()) 895 if (!device_handle.get()) {
981 return; 896 return RespondNow(Error(kErrorNoConnection));
897 }
982 898
983 bool success = device_handle->ReleaseInterface(parameters_->interface_number); 899 if (device_handle->ReleaseInterface(parameters->interface_number)) {
984 if (!success) 900 return RespondNow(NoArguments());
985 SetError(kErrorCannotReleaseInterface); 901 } else {
986 AsyncWorkCompleted(); 902 return RespondNow(Error(kErrorCannotReleaseInterface));
903 }
987 } 904 }
988 905
989 UsbSetInterfaceAlternateSettingFunction:: 906 UsbSetInterfaceAlternateSettingFunction::
990 UsbSetInterfaceAlternateSettingFunction() { 907 UsbSetInterfaceAlternateSettingFunction() {
991 } 908 }
992 909
993 UsbSetInterfaceAlternateSettingFunction:: 910 UsbSetInterfaceAlternateSettingFunction::
994 ~UsbSetInterfaceAlternateSettingFunction() { 911 ~UsbSetInterfaceAlternateSettingFunction() {
995 } 912 }
996 913
997 bool UsbSetInterfaceAlternateSettingFunction::Prepare() { 914 ExtensionFunction::ResponseAction
998 parameters_ = SetInterfaceAlternateSetting::Params::Create(*args_); 915 UsbSetInterfaceAlternateSettingFunction::Run() {
999 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 916 scoped_ptr<extensions::core_api::usb::SetInterfaceAlternateSetting::Params>
1000 return true; 917 parameters = SetInterfaceAlternateSetting::Params::Create(*args_);
918 EXTENSION_FUNCTION_VALIDATE(parameters.get());
919
920 scoped_refptr<UsbDeviceHandle> device_handle =
921 GetDeviceHandle(parameters->handle);
922 if (!device_handle.get()) {
923 return RespondNow(Error(kErrorNoConnection));
924 }
925
926 device_handle->SetInterfaceAlternateSetting(
927 parameters->interface_number, parameters->alternate_setting,
928 base::Bind(&UsbSetInterfaceAlternateSettingFunction::OnComplete, this));
929 return RespondLater();
1001 } 930 }
1002 931
1003 void UsbSetInterfaceAlternateSettingFunction::AsyncWorkStart() { 932 void UsbSetInterfaceAlternateSettingFunction::OnComplete(bool success) {
1004 scoped_refptr<UsbDeviceHandle> device_handle = 933 if (success) {
1005 GetDeviceHandleOrCompleteWithError(parameters_->handle); 934 Respond(NoArguments());
1006 if (!device_handle.get()) 935 } else {
1007 return; 936 Respond(Error(kErrorCannotSetInterfaceAlternateSetting));
1008 937 }
1009 bool success = device_handle->SetInterfaceAlternateSetting(
1010 parameters_->interface_number, parameters_->alternate_setting);
1011 if (!success)
1012 SetError(kErrorCannotSetInterfaceAlternateSetting);
1013
1014 AsyncWorkCompleted();
1015 } 938 }
1016 939
1017 UsbControlTransferFunction::UsbControlTransferFunction() { 940 UsbControlTransferFunction::UsbControlTransferFunction() {
1018 } 941 }
1019 942
1020 UsbControlTransferFunction::~UsbControlTransferFunction() { 943 UsbControlTransferFunction::~UsbControlTransferFunction() {
1021 } 944 }
1022 945
1023 bool UsbControlTransferFunction::Prepare() { 946 ExtensionFunction::ResponseAction UsbControlTransferFunction::Run() {
1024 parameters_ = ControlTransfer::Params::Create(*args_); 947 scoped_ptr<extensions::core_api::usb::ControlTransfer::Params> parameters =
1025 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 948 ControlTransfer::Params::Create(*args_);
1026 return true; 949 EXTENSION_FUNCTION_VALIDATE(parameters.get());
1027 }
1028 950
1029 void UsbControlTransferFunction::AsyncWorkStart() {
1030 scoped_refptr<UsbDeviceHandle> device_handle = 951 scoped_refptr<UsbDeviceHandle> device_handle =
1031 GetDeviceHandleOrCompleteWithError(parameters_->handle); 952 GetDeviceHandle(parameters->handle);
1032 if (!device_handle.get()) 953 if (!device_handle.get()) {
1033 return; 954 return RespondNow(Error(kErrorNoConnection));
955 }
1034 956
1035 const ControlTransferInfo& transfer = parameters_->transfer_info; 957 const ControlTransferInfo& transfer = parameters->transfer_info;
1036
1037 UsbEndpointDirection direction; 958 UsbEndpointDirection direction;
1038 UsbDeviceHandle::TransferRequestType request_type; 959 UsbDeviceHandle::TransferRequestType request_type;
1039 UsbDeviceHandle::TransferRecipient recipient; 960 UsbDeviceHandle::TransferRecipient recipient;
1040 size_t size = 0; 961 size_t size = 0;
1041 962
1042 if (!ConvertDirectionSafely(transfer.direction, &direction) || 963 if (!ConvertDirectionFromApi(transfer.direction, &direction)) {
1043 !ConvertRequestTypeSafely(transfer.request_type, &request_type) || 964 return RespondNow(Error(kErrorConvertDirection));
1044 !ConvertRecipientSafely(transfer.recipient, &recipient)) { 965 }
1045 AsyncWorkCompleted(); 966
1046 return; 967 if (!ConvertRequestTypeFromApi(transfer.request_type, &request_type)) {
968 return RespondNow(Error(kErrorConvertRequestType));
969 }
970
971 if (!ConvertRecipientFromApi(transfer.recipient, &recipient)) {
972 return RespondNow(Error(kErrorConvertRecipient));
1047 } 973 }
1048 974
1049 if (!GetTransferSize(transfer, &size)) { 975 if (!GetTransferSize(transfer, &size)) {
1050 CompleteWithError(kErrorInvalidTransferLength); 976 return RespondNow(Error(kErrorInvalidTransferLength));
1051 return;
1052 } 977 }
1053 978
1054 scoped_refptr<net::IOBuffer> buffer = 979 scoped_refptr<net::IOBuffer> buffer =
1055 CreateBufferForTransfer(transfer, direction, size); 980 CreateBufferForTransfer(transfer, direction, size);
1056 if (!buffer.get()) { 981 if (!buffer.get()) {
1057 CompleteWithError(kErrorMalformedParameters); 982 return RespondNow(Error(kErrorMalformedParameters));
1058 return;
1059 } 983 }
1060 984
1061 int timeout = transfer.timeout ? *transfer.timeout : 0; 985 int timeout = transfer.timeout ? *transfer.timeout : 0;
1062 if (timeout < 0) { 986 if (timeout < 0) {
1063 CompleteWithError(kErrorInvalidTimeout); 987 return RespondNow(Error(kErrorInvalidTimeout));
1064 return;
1065 } 988 }
1066 989
1067 device_handle->ControlTransfer( 990 device_handle->ControlTransfer(
1068 direction, request_type, recipient, transfer.request, transfer.value, 991 direction, request_type, recipient, transfer.request, transfer.value,
1069 transfer.index, buffer.get(), size, timeout, 992 transfer.index, buffer.get(), size, timeout,
1070 base::Bind(&UsbControlTransferFunction::OnCompleted, this)); 993 base::Bind(&UsbControlTransferFunction::OnCompleted, this));
994 return RespondLater();
1071 } 995 }
1072 996
1073 UsbBulkTransferFunction::UsbBulkTransferFunction() { 997 UsbBulkTransferFunction::UsbBulkTransferFunction() {
1074 } 998 }
1075 999
1076 UsbBulkTransferFunction::~UsbBulkTransferFunction() { 1000 UsbBulkTransferFunction::~UsbBulkTransferFunction() {
1077 } 1001 }
1078 1002
1079 bool UsbBulkTransferFunction::Prepare() { 1003 ExtensionFunction::ResponseAction UsbBulkTransferFunction::Run() {
1080 parameters_ = BulkTransfer::Params::Create(*args_); 1004 scoped_ptr<extensions::core_api::usb::BulkTransfer::Params> parameters =
1081 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 1005 BulkTransfer::Params::Create(*args_);
1082 return true; 1006 EXTENSION_FUNCTION_VALIDATE(parameters.get());
1083 }
1084 1007
1085 void UsbBulkTransferFunction::AsyncWorkStart() {
1086 scoped_refptr<UsbDeviceHandle> device_handle = 1008 scoped_refptr<UsbDeviceHandle> device_handle =
1087 GetDeviceHandleOrCompleteWithError(parameters_->handle); 1009 GetDeviceHandle(parameters->handle);
1088 if (!device_handle.get()) 1010 if (!device_handle.get()) {
1089 return; 1011 return RespondNow(Error(kErrorNoConnection));
1012 }
1090 1013
1091 const GenericTransferInfo& transfer = parameters_->transfer_info; 1014 const GenericTransferInfo& transfer = parameters->transfer_info;
1092
1093 UsbEndpointDirection direction; 1015 UsbEndpointDirection direction;
1094 size_t size = 0; 1016 size_t size = 0;
1095 1017
1096 if (!ConvertDirectionSafely(transfer.direction, &direction)) { 1018 if (!ConvertDirectionFromApi(transfer.direction, &direction)) {
1097 AsyncWorkCompleted(); 1019 return RespondNow(Error(kErrorConvertDirection));
1098 return;
1099 } 1020 }
1100 1021
1101 if (!GetTransferSize(transfer, &size)) { 1022 if (!GetTransferSize(transfer, &size)) {
1102 CompleteWithError(kErrorInvalidTransferLength); 1023 return RespondNow(Error(kErrorInvalidTransferLength));
1103 return;
1104 } 1024 }
1105 1025
1106 scoped_refptr<net::IOBuffer> buffer = 1026 scoped_refptr<net::IOBuffer> buffer =
1107 CreateBufferForTransfer(transfer, direction, size); 1027 CreateBufferForTransfer(transfer, direction, size);
1108 if (!buffer.get()) { 1028 if (!buffer.get()) {
1109 CompleteWithError(kErrorMalformedParameters); 1029 return RespondNow(Error(kErrorMalformedParameters));
1110 return;
1111 } 1030 }
1112 1031
1113 int timeout = transfer.timeout ? *transfer.timeout : 0; 1032 int timeout = transfer.timeout ? *transfer.timeout : 0;
1114 if (timeout < 0) { 1033 if (timeout < 0) {
1115 CompleteWithError(kErrorInvalidTimeout); 1034 return RespondNow(Error(kErrorInvalidTimeout));
1116 return;
1117 } 1035 }
1118 1036
1119 device_handle->BulkTransfer( 1037 device_handle->BulkTransfer(
1120 direction, transfer.endpoint, buffer.get(), size, timeout, 1038 direction, transfer.endpoint, buffer.get(), size, timeout,
1121 base::Bind(&UsbBulkTransferFunction::OnCompleted, this)); 1039 base::Bind(&UsbBulkTransferFunction::OnCompleted, this));
1040 return RespondLater();
1122 } 1041 }
1123 1042
1124 UsbInterruptTransferFunction::UsbInterruptTransferFunction() { 1043 UsbInterruptTransferFunction::UsbInterruptTransferFunction() {
1125 } 1044 }
1126 1045
1127 UsbInterruptTransferFunction::~UsbInterruptTransferFunction() { 1046 UsbInterruptTransferFunction::~UsbInterruptTransferFunction() {
1128 } 1047 }
1129 1048
1130 bool UsbInterruptTransferFunction::Prepare() { 1049 ExtensionFunction::ResponseAction UsbInterruptTransferFunction::Run() {
1131 parameters_ = InterruptTransfer::Params::Create(*args_); 1050 scoped_ptr<extensions::core_api::usb::InterruptTransfer::Params> parameters =
1132 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 1051 InterruptTransfer::Params::Create(*args_);
1133 return true; 1052 EXTENSION_FUNCTION_VALIDATE(parameters.get());
1134 }
1135 1053
1136 void UsbInterruptTransferFunction::AsyncWorkStart() {
1137 scoped_refptr<UsbDeviceHandle> device_handle = 1054 scoped_refptr<UsbDeviceHandle> device_handle =
1138 GetDeviceHandleOrCompleteWithError(parameters_->handle); 1055 GetDeviceHandle(parameters->handle);
1139 if (!device_handle.get()) 1056 if (!device_handle.get()) {
1140 return; 1057 return RespondNow(Error(kErrorNoConnection));
1058 }
1141 1059
1142 const GenericTransferInfo& transfer = parameters_->transfer_info; 1060 const GenericTransferInfo& transfer = parameters->transfer_info;
1143
1144 UsbEndpointDirection direction; 1061 UsbEndpointDirection direction;
1145 size_t size = 0; 1062 size_t size = 0;
1146 1063
1147 if (!ConvertDirectionSafely(transfer.direction, &direction)) { 1064 if (!ConvertDirectionFromApi(transfer.direction, &direction)) {
1148 AsyncWorkCompleted(); 1065 return RespondNow(Error(kErrorConvertDirection));
1149 return;
1150 } 1066 }
1151 1067
1152 if (!GetTransferSize(transfer, &size)) { 1068 if (!GetTransferSize(transfer, &size)) {
1153 CompleteWithError(kErrorInvalidTransferLength); 1069 return RespondNow(Error(kErrorInvalidTransferLength));
1154 return;
1155 } 1070 }
1156 1071
1157 scoped_refptr<net::IOBuffer> buffer = 1072 scoped_refptr<net::IOBuffer> buffer =
1158 CreateBufferForTransfer(transfer, direction, size); 1073 CreateBufferForTransfer(transfer, direction, size);
1159 if (!buffer.get()) { 1074 if (!buffer.get()) {
1160 CompleteWithError(kErrorMalformedParameters); 1075 return RespondNow(Error(kErrorMalformedParameters));
1161 return;
1162 } 1076 }
1163 1077
1164 int timeout = transfer.timeout ? *transfer.timeout : 0; 1078 int timeout = transfer.timeout ? *transfer.timeout : 0;
1165 if (timeout < 0) { 1079 if (timeout < 0) {
1166 CompleteWithError(kErrorInvalidTimeout); 1080 return RespondNow(Error(kErrorInvalidTimeout));
1167 return;
1168 } 1081 }
1169 1082
1170 device_handle->InterruptTransfer( 1083 device_handle->InterruptTransfer(
1171 direction, transfer.endpoint, buffer.get(), size, timeout, 1084 direction, transfer.endpoint, buffer.get(), size, timeout,
1172 base::Bind(&UsbInterruptTransferFunction::OnCompleted, this)); 1085 base::Bind(&UsbInterruptTransferFunction::OnCompleted, this));
1086 return RespondLater();
1173 } 1087 }
1174 1088
1175 UsbIsochronousTransferFunction::UsbIsochronousTransferFunction() { 1089 UsbIsochronousTransferFunction::UsbIsochronousTransferFunction() {
1176 } 1090 }
1177 1091
1178 UsbIsochronousTransferFunction::~UsbIsochronousTransferFunction() { 1092 UsbIsochronousTransferFunction::~UsbIsochronousTransferFunction() {
1179 } 1093 }
1180 1094
1181 bool UsbIsochronousTransferFunction::Prepare() { 1095 ExtensionFunction::ResponseAction UsbIsochronousTransferFunction::Run() {
1182 parameters_ = IsochronousTransfer::Params::Create(*args_); 1096 scoped_ptr<extensions::core_api::usb::IsochronousTransfer::Params>
1183 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 1097 parameters = IsochronousTransfer::Params::Create(*args_);
1184 return true; 1098 EXTENSION_FUNCTION_VALIDATE(parameters.get());
1185 }
1186 1099
1187 void UsbIsochronousTransferFunction::AsyncWorkStart() {
1188 scoped_refptr<UsbDeviceHandle> device_handle = 1100 scoped_refptr<UsbDeviceHandle> device_handle =
1189 GetDeviceHandleOrCompleteWithError(parameters_->handle); 1101 GetDeviceHandle(parameters->handle);
1190 if (!device_handle.get()) 1102 if (!device_handle.get()) {
1191 return; 1103 return RespondNow(Error(kErrorNoConnection));
1104 }
1192 1105
1193 const IsochronousTransferInfo& transfer = parameters_->transfer_info; 1106 const IsochronousTransferInfo& transfer = parameters->transfer_info;
1194 const GenericTransferInfo& generic_transfer = transfer.transfer_info; 1107 const GenericTransferInfo& generic_transfer = transfer.transfer_info;
1195
1196 size_t size = 0; 1108 size_t size = 0;
1197 UsbEndpointDirection direction; 1109 UsbEndpointDirection direction;
1198 1110
1199 if (!ConvertDirectionSafely(generic_transfer.direction, &direction)) { 1111 if (!ConvertDirectionFromApi(generic_transfer.direction, &direction)) {
1200 AsyncWorkCompleted(); 1112 return RespondNow(Error(kErrorConvertDirection));
1201 return;
1202 } 1113 }
1114
1203 if (!GetTransferSize(generic_transfer, &size)) { 1115 if (!GetTransferSize(generic_transfer, &size)) {
1204 CompleteWithError(kErrorInvalidTransferLength); 1116 return RespondNow(Error(kErrorInvalidTransferLength));
1205 return;
1206 } 1117 }
1118
1207 if (transfer.packets < 0 || transfer.packets >= kMaxPackets) { 1119 if (transfer.packets < 0 || transfer.packets >= kMaxPackets) {
1208 CompleteWithError(kErrorInvalidNumberOfPackets); 1120 return RespondNow(Error(kErrorInvalidNumberOfPackets));
1209 return;
1210 } 1121 }
1122
1211 unsigned int packets = transfer.packets; 1123 unsigned int packets = transfer.packets;
1212 if (transfer.packet_length < 0 || 1124 if (transfer.packet_length < 0 ||
1213 transfer.packet_length >= kMaxPacketLength) { 1125 transfer.packet_length >= kMaxPacketLength) {
1214 CompleteWithError(kErrorInvalidPacketLength); 1126 return RespondNow(Error(kErrorInvalidPacketLength));
1215 return;
1216 } 1127 }
1128
1217 unsigned int packet_length = transfer.packet_length; 1129 unsigned int packet_length = transfer.packet_length;
1218 const uint64 total_length = packets * packet_length; 1130 const uint64 total_length = packets * packet_length;
1219 if (packets > size || total_length > size) { 1131 if (packets > size || total_length > size) {
1220 CompleteWithError(kErrorTransferLength); 1132 return RespondNow(Error(kErrorTransferLength));
1221 return;
1222 } 1133 }
1223 1134
1224 scoped_refptr<net::IOBuffer> buffer = 1135 scoped_refptr<net::IOBuffer> buffer =
1225 CreateBufferForTransfer(generic_transfer, direction, size); 1136 CreateBufferForTransfer(generic_transfer, direction, size);
1226 if (!buffer.get()) { 1137 if (!buffer.get()) {
1227 CompleteWithError(kErrorMalformedParameters); 1138 return RespondNow(Error(kErrorMalformedParameters));
1228 return;
1229 } 1139 }
1230 1140
1231 int timeout = generic_transfer.timeout ? *generic_transfer.timeout : 0; 1141 int timeout = generic_transfer.timeout ? *generic_transfer.timeout : 0;
1232 if (timeout < 0) { 1142 if (timeout < 0) {
1233 CompleteWithError(kErrorInvalidTimeout); 1143 return RespondNow(Error(kErrorInvalidTimeout));
1234 return;
1235 } 1144 }
1236 1145
1237 device_handle->IsochronousTransfer( 1146 device_handle->IsochronousTransfer(
1238 direction, generic_transfer.endpoint, buffer.get(), size, packets, 1147 direction, generic_transfer.endpoint, buffer.get(), size, packets,
1239 packet_length, timeout, 1148 packet_length, timeout,
1240 base::Bind(&UsbIsochronousTransferFunction::OnCompleted, this)); 1149 base::Bind(&UsbIsochronousTransferFunction::OnCompleted, this));
1150 return RespondLater();
1241 } 1151 }
1242 1152
1243 UsbResetDeviceFunction::UsbResetDeviceFunction() { 1153 UsbResetDeviceFunction::UsbResetDeviceFunction() {
1244 } 1154 }
1245 1155
1246 UsbResetDeviceFunction::~UsbResetDeviceFunction() { 1156 UsbResetDeviceFunction::~UsbResetDeviceFunction() {
1247 } 1157 }
1248 1158
1249 bool UsbResetDeviceFunction::Prepare() { 1159 ExtensionFunction::ResponseAction UsbResetDeviceFunction::Run() {
1250 parameters_ = ResetDevice::Params::Create(*args_); 1160 parameters_ = ResetDevice::Params::Create(*args_);
1251 EXTENSION_FUNCTION_VALIDATE(parameters_.get()); 1161 EXTENSION_FUNCTION_VALIDATE(parameters_.get());
1252 return true; 1162
1163 scoped_refptr<UsbDeviceHandle> device_handle =
1164 GetDeviceHandle(parameters_->handle);
1165 if (!device_handle.get()) {
1166 return RespondNow(Error(kErrorNoConnection));
1167 }
1168
1169 device_handle->ResetDevice(
1170 base::Bind(&UsbResetDeviceFunction::OnComplete, this));
1171 return RespondLater();
1253 } 1172 }
1254 1173
1255 void UsbResetDeviceFunction::AsyncWorkStart() { 1174 void UsbResetDeviceFunction::OnComplete(bool success) {
1256 scoped_refptr<UsbDeviceHandle> device_handle = 1175 if (success) {
1257 GetDeviceHandleOrCompleteWithError(parameters_->handle); 1176 Respond(OneArgument(new base::FundamentalValue(true)));
1258 if (!device_handle.get()) 1177 } else {
1259 return; 1178 scoped_refptr<UsbDeviceHandle> device_handle =
1179 GetDeviceHandle(parameters_->handle);
1180 if (device_handle.get()) {
1181 device_handle->Close();
1182 }
1183 ReleaseDeviceHandle(parameters_->handle);
1260 1184
1261 bool success = device_handle->ResetDevice(); 1185 scoped_ptr<base::ListValue> error_args(new base::ListValue());
1262 if (!success) { 1186 error_args->AppendBoolean(false);
1263 device_handle->Close(); 1187 // Returning arguments with an error is wrong but we're stuck with it.
1264 RemoveUsbDeviceResource(parameters_->handle.handle); 1188 Respond(ErrorWithArguments(error_args.Pass(), kErrorResetDevice));
1265 SetResult(new base::FundamentalValue(false));
1266 CompleteWithError(kErrorResetDevice);
1267 return;
1268 } 1189 }
1269
1270 SetResult(new base::FundamentalValue(true));
1271 AsyncWorkCompleted();
1272 } 1190 }
1273 1191
1274 } // namespace extensions 1192 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698