Ignore title parameter for navigator.registerProtocolHandler
[chromium-blink-merge.git] / components / usb_service / usb_device_handle.cc
blobf0f368e86de888e05b37b7f8b2236b11a73f45ac
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 "components/usb_service/usb_device_handle.h"
7 #include <algorithm>
8 #include <vector>
10 #include "base/message_loop/message_loop.h"
11 #include "base/stl_util.h"
12 #include "base/strings/string16.h"
13 #include "base/synchronization/lock.h"
14 #include "components/usb_service/usb_context.h"
15 #include "components/usb_service/usb_device.h"
16 #include "components/usb_service/usb_interface.h"
17 #include "components/usb_service/usb_service.h"
18 #include "content/public/browser/browser_thread.h"
19 #include "third_party/libusb/src/libusb/libusb.h"
21 using content::BrowserThread;
23 namespace usb_service {
25 typedef libusb_device* PlatformUsbDevice;
27 void HandleTransferCompletion(usb_service::PlatformUsbTransferHandle transfer);
29 namespace {
31 static uint8 ConvertTransferDirection(const UsbEndpointDirection direction) {
32 switch (direction) {
33 case USB_DIRECTION_INBOUND:
34 return LIBUSB_ENDPOINT_IN;
35 case USB_DIRECTION_OUTBOUND:
36 return LIBUSB_ENDPOINT_OUT;
37 default:
38 NOTREACHED();
39 return LIBUSB_ENDPOINT_IN;
43 static uint8 CreateRequestType(
44 const UsbEndpointDirection direction,
45 const UsbDeviceHandle::TransferRequestType request_type,
46 const UsbDeviceHandle::TransferRecipient recipient) {
47 uint8 result = ConvertTransferDirection(direction);
49 switch (request_type) {
50 case UsbDeviceHandle::STANDARD:
51 result |= LIBUSB_REQUEST_TYPE_STANDARD;
52 break;
53 case UsbDeviceHandle::CLASS:
54 result |= LIBUSB_REQUEST_TYPE_CLASS;
55 break;
56 case UsbDeviceHandle::VENDOR:
57 result |= LIBUSB_REQUEST_TYPE_VENDOR;
58 break;
59 case UsbDeviceHandle::RESERVED:
60 result |= LIBUSB_REQUEST_TYPE_RESERVED;
61 break;
64 switch (recipient) {
65 case UsbDeviceHandle::DEVICE:
66 result |= LIBUSB_RECIPIENT_DEVICE;
67 break;
68 case UsbDeviceHandle::INTERFACE:
69 result |= LIBUSB_RECIPIENT_INTERFACE;
70 break;
71 case UsbDeviceHandle::ENDPOINT:
72 result |= LIBUSB_RECIPIENT_ENDPOINT;
73 break;
74 case UsbDeviceHandle::OTHER:
75 result |= LIBUSB_RECIPIENT_OTHER;
76 break;
79 return result;
82 static UsbTransferStatus ConvertTransferStatus(
83 const libusb_transfer_status status) {
84 switch (status) {
85 case LIBUSB_TRANSFER_COMPLETED:
86 return USB_TRANSFER_COMPLETED;
87 case LIBUSB_TRANSFER_ERROR:
88 return USB_TRANSFER_ERROR;
89 case LIBUSB_TRANSFER_TIMED_OUT:
90 return USB_TRANSFER_TIMEOUT;
91 case LIBUSB_TRANSFER_STALL:
92 return USB_TRANSFER_STALLED;
93 case LIBUSB_TRANSFER_NO_DEVICE:
94 return USB_TRANSFER_DISCONNECT;
95 case LIBUSB_TRANSFER_OVERFLOW:
96 return USB_TRANSFER_OVERFLOW;
97 case LIBUSB_TRANSFER_CANCELLED:
98 return USB_TRANSFER_CANCELLED;
99 default:
100 NOTREACHED();
101 return USB_TRANSFER_ERROR;
105 static void LIBUSB_CALL
106 PlatformTransferCompletionCallback(PlatformUsbTransferHandle transfer) {
107 BrowserThread::PostTask(BrowserThread::FILE,
108 FROM_HERE,
109 base::Bind(HandleTransferCompletion, transfer));
112 } // namespace
114 void HandleTransferCompletion(PlatformUsbTransferHandle transfer) {
115 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
116 UsbDeviceHandle* const device_handle =
117 reinterpret_cast<UsbDeviceHandle*>(transfer->user_data);
118 CHECK(device_handle) << "Device handle is closed before transfer finishes.";
119 device_handle->TransferComplete(transfer);
120 libusb_free_transfer(transfer);
123 class UsbDeviceHandle::InterfaceClaimer
124 : public base::RefCountedThreadSafe<UsbDeviceHandle::InterfaceClaimer> {
125 public:
126 InterfaceClaimer(const scoped_refptr<UsbDeviceHandle> handle,
127 const int interface_number);
129 bool Claim() const;
131 int alternate_setting() const { return alternate_setting_; }
132 void set_alternate_setting(const int alternate_setting) {
133 alternate_setting_ = alternate_setting;
136 private:
137 friend class UsbDevice;
138 friend class base::RefCountedThreadSafe<InterfaceClaimer>;
139 ~InterfaceClaimer();
141 const scoped_refptr<UsbDeviceHandle> handle_;
142 const int interface_number_;
143 int alternate_setting_;
145 DISALLOW_COPY_AND_ASSIGN(InterfaceClaimer);
148 UsbDeviceHandle::InterfaceClaimer::InterfaceClaimer(
149 const scoped_refptr<UsbDeviceHandle> handle,
150 const int interface_number)
151 : handle_(handle),
152 interface_number_(interface_number),
153 alternate_setting_(0) {
156 UsbDeviceHandle::InterfaceClaimer::~InterfaceClaimer() {
157 libusb_release_interface(handle_->handle(), interface_number_);
160 bool UsbDeviceHandle::InterfaceClaimer::Claim() const {
161 return libusb_claim_interface(handle_->handle(), interface_number_) == 0;
164 struct UsbDeviceHandle::Transfer {
165 Transfer();
166 ~Transfer();
168 UsbTransferType transfer_type;
169 scoped_refptr<net::IOBuffer> buffer;
170 scoped_refptr<UsbDeviceHandle::InterfaceClaimer> claimed_interface;
171 scoped_refptr<base::MessageLoopProxy> message_loop_proxy;
172 size_t length;
173 UsbTransferCallback callback;
176 UsbDeviceHandle::Transfer::Transfer()
177 : transfer_type(USB_TRANSFER_CONTROL), length(0) {
180 UsbDeviceHandle::Transfer::~Transfer() {
183 UsbDeviceHandle::UsbDeviceHandle(scoped_refptr<UsbContext> context,
184 UsbDevice* device,
185 PlatformUsbDeviceHandle handle,
186 scoped_refptr<UsbConfigDescriptor> interfaces)
187 : device_(device),
188 handle_(handle),
189 interfaces_(interfaces),
190 context_(context) {
191 DCHECK(thread_checker_.CalledOnValidThread());
192 DCHECK(handle) << "Cannot create device with NULL handle.";
193 DCHECK(interfaces_) << "Unabled to list interfaces";
196 UsbDeviceHandle::UsbDeviceHandle() : device_(NULL), handle_(NULL) {
199 UsbDeviceHandle::~UsbDeviceHandle() {
200 DCHECK(thread_checker_.CalledOnValidThread());
202 libusb_close(handle_);
203 handle_ = NULL;
206 scoped_refptr<UsbDevice> UsbDeviceHandle::device() const {
207 return device_;
210 void UsbDeviceHandle::Close() {
211 DCHECK(thread_checker_.CalledOnValidThread());
212 if (device_)
213 device_->Close(this);
216 void UsbDeviceHandle::TransferComplete(PlatformUsbTransferHandle handle) {
217 DCHECK(ContainsKey(transfers_, handle)) << "Missing transfer completed";
219 Transfer transfer = transfers_[handle];
220 transfers_.erase(handle);
222 DCHECK_GE(handle->actual_length, 0) << "Negative actual length received";
223 size_t actual_length =
224 static_cast<size_t>(std::max(handle->actual_length, 0));
226 DCHECK(transfer.length >= actual_length)
227 << "data too big for our buffer (libusb failure?)";
229 scoped_refptr<net::IOBuffer> buffer = transfer.buffer;
230 switch (transfer.transfer_type) {
231 case USB_TRANSFER_CONTROL:
232 // If the transfer is a control transfer we do not expose the control
233 // setup header to the caller. This logic strips off the header if
234 // present before invoking the callback provided with the transfer.
235 if (actual_length > 0) {
236 CHECK(transfer.length >= LIBUSB_CONTROL_SETUP_SIZE)
237 << "buffer was not correctly set: too small for the control header";
239 if (transfer.length >= (LIBUSB_CONTROL_SETUP_SIZE + actual_length)) {
240 // If the payload is zero bytes long, pad out the allocated buffer
241 // size to one byte so that an IOBuffer of that size can be allocated.
242 scoped_refptr<net::IOBuffer> resized_buffer =
243 new net::IOBuffer(static_cast<int>(
244 std::max(actual_length, static_cast<size_t>(1))));
245 memcpy(resized_buffer->data(),
246 buffer->data() + LIBUSB_CONTROL_SETUP_SIZE,
247 actual_length);
248 buffer = resized_buffer;
251 break;
253 case USB_TRANSFER_ISOCHRONOUS:
254 // Isochronous replies might carry data in the different isoc packets even
255 // if the transfer actual_data value is zero. Furthermore, not all of the
256 // received packets might contain data, so we need to calculate how many
257 // data bytes we are effectively providing and pack the results.
258 if (actual_length == 0) {
259 size_t packet_buffer_start = 0;
260 for (int i = 0; i < handle->num_iso_packets; ++i) {
261 PlatformUsbIsoPacketDescriptor packet = &handle->iso_packet_desc[i];
262 if (packet->actual_length > 0) {
263 // We don't need to copy as long as all packets until now provide
264 // all the data the packet can hold.
265 if (actual_length < packet_buffer_start) {
266 CHECK(packet_buffer_start + packet->actual_length <=
267 transfer.length);
268 memmove(buffer->data() + actual_length,
269 buffer->data() + packet_buffer_start,
270 packet->actual_length);
272 actual_length += packet->actual_length;
275 packet_buffer_start += packet->length;
278 break;
280 case USB_TRANSFER_BULK:
281 case USB_TRANSFER_INTERRUPT:
282 break;
284 default:
285 NOTREACHED() << "Invalid usb transfer type";
286 break;
289 transfer.message_loop_proxy->PostTask(
290 FROM_HERE,
291 base::Bind(transfer.callback,
292 ConvertTransferStatus(handle->status),
293 buffer,
294 actual_length));
296 // Must release interface first before actually delete this.
297 transfer.claimed_interface = NULL;
300 bool UsbDeviceHandle::ClaimInterface(const int interface_number) {
301 DCHECK(thread_checker_.CalledOnValidThread());
302 if (!device_)
303 return false;
304 if (ContainsKey(claimed_interfaces_, interface_number))
305 return true;
307 scoped_refptr<InterfaceClaimer> claimer =
308 new InterfaceClaimer(this, interface_number);
310 if (claimer->Claim()) {
311 claimed_interfaces_[interface_number] = claimer;
312 RefreshEndpointMap();
313 return true;
315 return false;
318 bool UsbDeviceHandle::ReleaseInterface(const int interface_number) {
319 DCHECK(thread_checker_.CalledOnValidThread());
320 if (!device_)
321 return false;
322 if (!ContainsKey(claimed_interfaces_, interface_number))
323 return false;
325 // Cancel all the transfers on that interface.
326 InterfaceClaimer* interface_claimer =
327 claimed_interfaces_[interface_number].get();
328 for (TransferMap::iterator it = transfers_.begin(); it != transfers_.end();
329 ++it) {
330 if (it->second.claimed_interface.get() == interface_claimer)
331 libusb_cancel_transfer(it->first);
333 claimed_interfaces_.erase(interface_number);
335 RefreshEndpointMap();
336 return true;
339 bool UsbDeviceHandle::SetInterfaceAlternateSetting(
340 const int interface_number,
341 const int alternate_setting) {
342 DCHECK(thread_checker_.CalledOnValidThread());
343 if (!device_)
344 return false;
345 if (!ContainsKey(claimed_interfaces_, interface_number))
346 return false;
347 const int rv = libusb_set_interface_alt_setting(
348 handle_, interface_number, alternate_setting);
349 if (rv == 0) {
350 claimed_interfaces_[interface_number]->set_alternate_setting(
351 alternate_setting);
352 RefreshEndpointMap();
353 return true;
355 return false;
358 bool UsbDeviceHandle::ResetDevice() {
359 DCHECK(thread_checker_.CalledOnValidThread());
360 if (!device_)
361 return false;
363 return libusb_reset_device(handle_) == 0;
366 bool UsbDeviceHandle::GetSerial(base::string16* serial) {
367 DCHECK(thread_checker_.CalledOnValidThread());
368 PlatformUsbDevice device = libusb_get_device(handle_);
369 libusb_device_descriptor desc;
371 if (libusb_get_device_descriptor(device, &desc) != LIBUSB_SUCCESS)
372 return false;
374 if (desc.iSerialNumber == 0)
375 return false;
377 // Getting supported language ID.
378 uint16 langid[128] = {0};
380 int size =
381 libusb_get_string_descriptor(handle_,
384 reinterpret_cast<unsigned char*>(&langid[0]),
385 sizeof(langid));
386 if (size < 0)
387 return false;
389 int language_count = (size - 2) / 2;
391 for (int i = 1; i <= language_count; ++i) {
392 // Get the string using language ID.
393 base::char16 text[256] = {0};
394 size =
395 libusb_get_string_descriptor(handle_,
396 desc.iSerialNumber,
397 langid[i],
398 reinterpret_cast<unsigned char*>(&text[0]),
399 sizeof(text));
400 if (size <= 2)
401 continue;
402 if ((text[0] >> 8) != LIBUSB_DT_STRING)
403 continue;
404 if ((text[0] & 255) > size)
405 continue;
407 size = size / 2 - 1;
408 *serial = base::string16(text + 1, size);
409 return true;
411 return false;
414 void UsbDeviceHandle::ControlTransfer(const UsbEndpointDirection direction,
415 const TransferRequestType request_type,
416 const TransferRecipient recipient,
417 const uint8 request,
418 const uint16 value,
419 const uint16 index,
420 net::IOBuffer* buffer,
421 const size_t length,
422 const unsigned int timeout,
423 const UsbTransferCallback& callback) {
424 if (!device_) {
425 callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
426 return;
429 const size_t resized_length = LIBUSB_CONTROL_SETUP_SIZE + length;
430 scoped_refptr<net::IOBuffer> resized_buffer(
431 new net::IOBufferWithSize(static_cast<int>(resized_length)));
432 if (!resized_buffer) {
433 callback.Run(USB_TRANSFER_ERROR, buffer, 0);
434 return;
436 memcpy(resized_buffer->data() + LIBUSB_CONTROL_SETUP_SIZE,
437 buffer->data(),
438 static_cast<int>(length));
440 PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(0);
441 const uint8 converted_type =
442 CreateRequestType(direction, request_type, recipient);
443 libusb_fill_control_setup(reinterpret_cast<uint8*>(resized_buffer->data()),
444 converted_type,
445 request,
446 value,
447 index,
448 static_cast<int16>(length));
449 libusb_fill_control_transfer(transfer,
450 handle_,
451 reinterpret_cast<uint8*>(resized_buffer->data()),
452 PlatformTransferCompletionCallback,
453 this,
454 timeout);
456 BrowserThread::PostTask(BrowserThread::FILE,
457 FROM_HERE,
458 base::Bind(&UsbDeviceHandle::SubmitTransfer,
459 this,
460 transfer,
461 USB_TRANSFER_CONTROL,
462 resized_buffer,
463 resized_length,
464 base::MessageLoopProxy::current(),
465 callback));
468 void UsbDeviceHandle::BulkTransfer(const UsbEndpointDirection direction,
469 const uint8 endpoint,
470 net::IOBuffer* buffer,
471 const size_t length,
472 const unsigned int timeout,
473 const UsbTransferCallback& callback) {
474 if (!device_) {
475 callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
476 return;
479 PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(0);
480 const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint;
481 libusb_fill_bulk_transfer(transfer,
482 handle_,
483 new_endpoint,
484 reinterpret_cast<uint8*>(buffer->data()),
485 static_cast<int>(length),
486 PlatformTransferCompletionCallback,
487 this,
488 timeout);
490 BrowserThread::PostTask(BrowserThread::FILE,
491 FROM_HERE,
492 base::Bind(&UsbDeviceHandle::SubmitTransfer,
493 this,
494 transfer,
495 USB_TRANSFER_BULK,
496 make_scoped_refptr(buffer),
497 length,
498 base::MessageLoopProxy::current(),
499 callback));
502 void UsbDeviceHandle::InterruptTransfer(const UsbEndpointDirection direction,
503 const uint8 endpoint,
504 net::IOBuffer* buffer,
505 const size_t length,
506 const unsigned int timeout,
507 const UsbTransferCallback& callback) {
508 if (!device_) {
509 callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
510 return;
513 PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(0);
514 const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint;
515 libusb_fill_interrupt_transfer(transfer,
516 handle_,
517 new_endpoint,
518 reinterpret_cast<uint8*>(buffer->data()),
519 static_cast<int>(length),
520 PlatformTransferCompletionCallback,
521 this,
522 timeout);
523 BrowserThread::PostTask(BrowserThread::FILE,
524 FROM_HERE,
525 base::Bind(&UsbDeviceHandle::SubmitTransfer,
526 this,
527 transfer,
528 USB_TRANSFER_INTERRUPT,
529 make_scoped_refptr(buffer),
530 length,
531 base::MessageLoopProxy::current(),
532 callback));
535 void UsbDeviceHandle::IsochronousTransfer(const UsbEndpointDirection direction,
536 const uint8 endpoint,
537 net::IOBuffer* buffer,
538 const size_t length,
539 const unsigned int packets,
540 const unsigned int packet_length,
541 const unsigned int timeout,
542 const UsbTransferCallback& callback) {
543 if (!device_) {
544 callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
545 return;
548 const uint64 total_length = packets * packet_length;
549 CHECK(packets <= length && total_length <= length)
550 << "transfer length is too small";
552 PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(packets);
553 const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint;
554 libusb_fill_iso_transfer(transfer,
555 handle_,
556 new_endpoint,
557 reinterpret_cast<uint8*>(buffer->data()),
558 static_cast<int>(length),
559 packets,
560 PlatformTransferCompletionCallback,
561 this,
562 timeout);
563 libusb_set_iso_packet_lengths(transfer, packet_length);
565 BrowserThread::PostTask(BrowserThread::FILE,
566 FROM_HERE,
567 base::Bind(&UsbDeviceHandle::SubmitTransfer,
568 this,
569 transfer,
570 USB_TRANSFER_ISOCHRONOUS,
571 make_scoped_refptr(buffer),
572 length,
573 base::MessageLoopProxy::current(),
574 callback));
577 void UsbDeviceHandle::RefreshEndpointMap() {
578 DCHECK(thread_checker_.CalledOnValidThread());
579 endpoint_map_.clear();
580 for (ClaimedInterfaceMap::iterator it = claimed_interfaces_.begin();
581 it != claimed_interfaces_.end();
582 ++it) {
583 scoped_refptr<const UsbInterfaceAltSettingDescriptor> interface_desc =
584 interfaces_->GetInterface(it->first)
585 ->GetAltSetting(it->second->alternate_setting());
586 for (size_t i = 0; i < interface_desc->GetNumEndpoints(); i++) {
587 scoped_refptr<const UsbEndpointDescriptor> endpoint =
588 interface_desc->GetEndpoint(i);
589 endpoint_map_[endpoint->GetAddress()] = it->first;
594 scoped_refptr<UsbDeviceHandle::InterfaceClaimer>
595 UsbDeviceHandle::GetClaimedInterfaceForEndpoint(unsigned char endpoint) {
596 unsigned char address = endpoint & LIBUSB_ENDPOINT_ADDRESS_MASK;
597 if (ContainsKey(endpoint_map_, address))
598 return claimed_interfaces_[endpoint_map_[address]];
599 return NULL;
602 void UsbDeviceHandle::SubmitTransfer(
603 PlatformUsbTransferHandle handle,
604 UsbTransferType transfer_type,
605 net::IOBuffer* buffer,
606 const size_t length,
607 scoped_refptr<base::MessageLoopProxy> message_loop_proxy,
608 const UsbTransferCallback& callback) {
609 DCHECK(thread_checker_.CalledOnValidThread());
610 if (!device_) {
611 message_loop_proxy->PostTask(
612 FROM_HERE,
613 base::Bind(
614 callback, USB_TRANSFER_DISCONNECT, make_scoped_refptr(buffer), 0));
617 Transfer transfer;
618 transfer.transfer_type = transfer_type;
619 transfer.buffer = buffer;
620 transfer.length = length;
621 transfer.callback = callback;
622 transfer.message_loop_proxy = message_loop_proxy;
624 // It's OK for this method to return NULL. libusb_submit_transfer will fail if
625 // it requires an interface we didn't claim.
626 transfer.claimed_interface = GetClaimedInterfaceForEndpoint(handle->endpoint);
628 if (libusb_submit_transfer(handle) == LIBUSB_SUCCESS) {
629 transfers_[handle] = transfer;
630 } else {
631 message_loop_proxy->PostTask(
632 FROM_HERE,
633 base::Bind(
634 callback, USB_TRANSFER_ERROR, make_scoped_refptr(buffer), 0));
638 void UsbDeviceHandle::InternalClose() {
639 DCHECK(thread_checker_.CalledOnValidThread());
640 if (!device_)
641 return;
643 // Cancel all the transfers.
644 for (TransferMap::iterator it = transfers_.begin(); it != transfers_.end();
645 ++it) {
646 // The callback will be called some time later.
647 libusb_cancel_transfer(it->first);
650 // Attempt-release all the interfaces.
651 // It will be retained until the transfer cancellation is finished.
652 claimed_interfaces_.clear();
654 // Cannot close device handle here. Need to wait for libusb_cancel_transfer to
655 // finish.
656 device_ = NULL;
659 } // namespace usb_service