Disable firewall check. It takes signifficant time, need to be on FILE thread.
[chromium-blink-merge.git] / components / usb_service / usb_device_handle.cc
blobb341368955649560207665ce7148cdee61ff9fb9
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 void HandleTransferCompletion(usb_service::PlatformUsbTransferHandle transfer);
27 namespace {
29 static uint8 ConvertTransferDirection(const UsbEndpointDirection direction) {
30 switch (direction) {
31 case USB_DIRECTION_INBOUND:
32 return LIBUSB_ENDPOINT_IN;
33 case USB_DIRECTION_OUTBOUND:
34 return LIBUSB_ENDPOINT_OUT;
35 default:
36 NOTREACHED();
37 return LIBUSB_ENDPOINT_IN;
41 static uint8 CreateRequestType(
42 const UsbEndpointDirection direction,
43 const UsbDeviceHandle::TransferRequestType request_type,
44 const UsbDeviceHandle::TransferRecipient recipient) {
45 uint8 result = ConvertTransferDirection(direction);
47 switch (request_type) {
48 case UsbDeviceHandle::STANDARD:
49 result |= LIBUSB_REQUEST_TYPE_STANDARD;
50 break;
51 case UsbDeviceHandle::CLASS:
52 result |= LIBUSB_REQUEST_TYPE_CLASS;
53 break;
54 case UsbDeviceHandle::VENDOR:
55 result |= LIBUSB_REQUEST_TYPE_VENDOR;
56 break;
57 case UsbDeviceHandle::RESERVED:
58 result |= LIBUSB_REQUEST_TYPE_RESERVED;
59 break;
62 switch (recipient) {
63 case UsbDeviceHandle::DEVICE:
64 result |= LIBUSB_RECIPIENT_DEVICE;
65 break;
66 case UsbDeviceHandle::INTERFACE:
67 result |= LIBUSB_RECIPIENT_INTERFACE;
68 break;
69 case UsbDeviceHandle::ENDPOINT:
70 result |= LIBUSB_RECIPIENT_ENDPOINT;
71 break;
72 case UsbDeviceHandle::OTHER:
73 result |= LIBUSB_RECIPIENT_OTHER;
74 break;
77 return result;
80 static UsbTransferStatus ConvertTransferStatus(
81 const libusb_transfer_status status) {
82 switch (status) {
83 case LIBUSB_TRANSFER_COMPLETED:
84 return USB_TRANSFER_COMPLETED;
85 case LIBUSB_TRANSFER_ERROR:
86 return USB_TRANSFER_ERROR;
87 case LIBUSB_TRANSFER_TIMED_OUT:
88 return USB_TRANSFER_TIMEOUT;
89 case LIBUSB_TRANSFER_STALL:
90 return USB_TRANSFER_STALLED;
91 case LIBUSB_TRANSFER_NO_DEVICE:
92 return USB_TRANSFER_DISCONNECT;
93 case LIBUSB_TRANSFER_OVERFLOW:
94 return USB_TRANSFER_OVERFLOW;
95 case LIBUSB_TRANSFER_CANCELLED:
96 return USB_TRANSFER_CANCELLED;
97 default:
98 NOTREACHED();
99 return USB_TRANSFER_ERROR;
103 static void LIBUSB_CALL
104 PlatformTransferCompletionCallback(PlatformUsbTransferHandle transfer) {
105 BrowserThread::PostTask(BrowserThread::FILE,
106 FROM_HERE,
107 base::Bind(HandleTransferCompletion, transfer));
110 } // namespace
112 void HandleTransferCompletion(PlatformUsbTransferHandle transfer) {
113 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
114 UsbDeviceHandle* const device_handle =
115 reinterpret_cast<UsbDeviceHandle*>(transfer->user_data);
116 CHECK(device_handle) << "Device handle is closed before transfer finishes.";
117 device_handle->TransferComplete(transfer);
118 libusb_free_transfer(transfer);
121 class UsbDeviceHandle::InterfaceClaimer
122 : public base::RefCountedThreadSafe<UsbDeviceHandle::InterfaceClaimer> {
123 public:
124 InterfaceClaimer(const scoped_refptr<UsbDeviceHandle> handle,
125 const int interface_number);
127 bool Claim() const;
129 int alternate_setting() const { return alternate_setting_; }
130 void set_alternate_setting(const int alternate_setting) {
131 alternate_setting_ = alternate_setting;
134 private:
135 friend class UsbDevice;
136 friend class base::RefCountedThreadSafe<InterfaceClaimer>;
137 ~InterfaceClaimer();
139 const scoped_refptr<UsbDeviceHandle> handle_;
140 const int interface_number_;
141 int alternate_setting_;
143 DISALLOW_COPY_AND_ASSIGN(InterfaceClaimer);
146 UsbDeviceHandle::InterfaceClaimer::InterfaceClaimer(
147 const scoped_refptr<UsbDeviceHandle> handle,
148 const int interface_number)
149 : handle_(handle),
150 interface_number_(interface_number),
151 alternate_setting_(0) {
154 UsbDeviceHandle::InterfaceClaimer::~InterfaceClaimer() {
155 libusb_release_interface(handle_->handle(), interface_number_);
158 bool UsbDeviceHandle::InterfaceClaimer::Claim() const {
159 return libusb_claim_interface(handle_->handle(), interface_number_) == 0;
162 struct UsbDeviceHandle::Transfer {
163 Transfer();
164 ~Transfer();
166 UsbTransferType transfer_type;
167 scoped_refptr<net::IOBuffer> buffer;
168 scoped_refptr<UsbDeviceHandle::InterfaceClaimer> claimed_interface;
169 scoped_refptr<base::MessageLoopProxy> message_loop_proxy;
170 size_t length;
171 UsbTransferCallback callback;
174 UsbDeviceHandle::Transfer::Transfer()
175 : transfer_type(USB_TRANSFER_CONTROL), length(0) {
178 UsbDeviceHandle::Transfer::~Transfer() {
181 UsbDeviceHandle::UsbDeviceHandle(scoped_refptr<UsbContext> context,
182 UsbDevice* device,
183 PlatformUsbDeviceHandle handle,
184 scoped_refptr<UsbConfigDescriptor> interfaces)
185 : device_(device),
186 handle_(handle),
187 interfaces_(interfaces),
188 context_(context) {
189 DCHECK(thread_checker_.CalledOnValidThread());
190 DCHECK(handle) << "Cannot create device with NULL handle.";
191 DCHECK(interfaces_) << "Unabled to list interfaces";
194 UsbDeviceHandle::UsbDeviceHandle() : device_(NULL), handle_(NULL) {
197 UsbDeviceHandle::~UsbDeviceHandle() {
198 DCHECK(thread_checker_.CalledOnValidThread());
200 libusb_close(handle_);
201 handle_ = NULL;
204 scoped_refptr<UsbDevice> UsbDeviceHandle::device() const {
205 return device_;
208 void UsbDeviceHandle::Close() {
209 DCHECK(thread_checker_.CalledOnValidThread());
210 if (device_)
211 device_->Close(this);
214 void UsbDeviceHandle::TransferComplete(PlatformUsbTransferHandle handle) {
215 DCHECK(ContainsKey(transfers_, handle)) << "Missing transfer completed";
217 Transfer transfer = transfers_[handle];
218 transfers_.erase(handle);
220 DCHECK_GE(handle->actual_length, 0) << "Negative actual length received";
221 size_t actual_length =
222 static_cast<size_t>(std::max(handle->actual_length, 0));
224 DCHECK(transfer.length >= actual_length)
225 << "data too big for our buffer (libusb failure?)";
227 scoped_refptr<net::IOBuffer> buffer = transfer.buffer;
228 switch (transfer.transfer_type) {
229 case USB_TRANSFER_CONTROL:
230 // If the transfer is a control transfer we do not expose the control
231 // setup header to the caller. This logic strips off the header if
232 // present before invoking the callback provided with the transfer.
233 if (actual_length > 0) {
234 CHECK(transfer.length >= LIBUSB_CONTROL_SETUP_SIZE)
235 << "buffer was not correctly set: too small for the control header";
237 if (transfer.length >= (LIBUSB_CONTROL_SETUP_SIZE + actual_length)) {
238 // If the payload is zero bytes long, pad out the allocated buffer
239 // size to one byte so that an IOBuffer of that size can be allocated.
240 scoped_refptr<net::IOBuffer> resized_buffer =
241 new net::IOBuffer(static_cast<int>(
242 std::max(actual_length, static_cast<size_t>(1))));
243 memcpy(resized_buffer->data(),
244 buffer->data() + LIBUSB_CONTROL_SETUP_SIZE,
245 actual_length);
246 buffer = resized_buffer;
249 break;
251 case USB_TRANSFER_ISOCHRONOUS:
252 // Isochronous replies might carry data in the different isoc packets even
253 // if the transfer actual_data value is zero. Furthermore, not all of the
254 // received packets might contain data, so we need to calculate how many
255 // data bytes we are effectively providing and pack the results.
256 if (actual_length == 0) {
257 size_t packet_buffer_start = 0;
258 for (int i = 0; i < handle->num_iso_packets; ++i) {
259 PlatformUsbIsoPacketDescriptor packet = &handle->iso_packet_desc[i];
260 if (packet->actual_length > 0) {
261 // We don't need to copy as long as all packets until now provide
262 // all the data the packet can hold.
263 if (actual_length < packet_buffer_start) {
264 CHECK(packet_buffer_start + packet->actual_length <=
265 transfer.length);
266 memmove(buffer->data() + actual_length,
267 buffer->data() + packet_buffer_start,
268 packet->actual_length);
270 actual_length += packet->actual_length;
273 packet_buffer_start += packet->length;
276 break;
278 case USB_TRANSFER_BULK:
279 case USB_TRANSFER_INTERRUPT:
280 break;
282 default:
283 NOTREACHED() << "Invalid usb transfer type";
284 break;
287 transfer.message_loop_proxy->PostTask(
288 FROM_HERE,
289 base::Bind(transfer.callback,
290 ConvertTransferStatus(handle->status),
291 buffer,
292 actual_length));
294 // Must release interface first before actually delete this.
295 transfer.claimed_interface = NULL;
298 bool UsbDeviceHandle::ClaimInterface(const int interface_number) {
299 DCHECK(thread_checker_.CalledOnValidThread());
300 if (!device_)
301 return false;
302 if (ContainsKey(claimed_interfaces_, interface_number))
303 return true;
305 scoped_refptr<InterfaceClaimer> claimer =
306 new InterfaceClaimer(this, interface_number);
308 if (claimer->Claim()) {
309 claimed_interfaces_[interface_number] = claimer;
310 RefreshEndpointMap();
311 return true;
313 return false;
316 bool UsbDeviceHandle::ReleaseInterface(const int interface_number) {
317 DCHECK(thread_checker_.CalledOnValidThread());
318 if (!device_)
319 return false;
320 if (!ContainsKey(claimed_interfaces_, interface_number))
321 return false;
323 // Cancel all the transfers on that interface.
324 InterfaceClaimer* interface_claimer =
325 claimed_interfaces_[interface_number].get();
326 for (TransferMap::iterator it = transfers_.begin(); it != transfers_.end();
327 ++it) {
328 if (it->second.claimed_interface.get() == interface_claimer)
329 libusb_cancel_transfer(it->first);
331 claimed_interfaces_.erase(interface_number);
333 RefreshEndpointMap();
334 return true;
337 bool UsbDeviceHandle::SetInterfaceAlternateSetting(
338 const int interface_number,
339 const int alternate_setting) {
340 DCHECK(thread_checker_.CalledOnValidThread());
341 if (!device_)
342 return false;
343 if (!ContainsKey(claimed_interfaces_, interface_number))
344 return false;
345 const int rv = libusb_set_interface_alt_setting(
346 handle_, interface_number, alternate_setting);
347 if (rv == 0) {
348 claimed_interfaces_[interface_number]->set_alternate_setting(
349 alternate_setting);
350 RefreshEndpointMap();
351 return true;
353 return false;
356 bool UsbDeviceHandle::ResetDevice() {
357 DCHECK(thread_checker_.CalledOnValidThread());
358 if (!device_)
359 return false;
361 return libusb_reset_device(handle_) == 0;
364 bool UsbDeviceHandle::GetSerial(base::string16* serial) {
365 DCHECK(thread_checker_.CalledOnValidThread());
366 PlatformUsbDevice device = libusb_get_device(handle_);
367 libusb_device_descriptor desc;
369 if (libusb_get_device_descriptor(device, &desc) != LIBUSB_SUCCESS)
370 return false;
372 if (desc.iSerialNumber == 0)
373 return false;
375 // Getting supported language ID.
376 uint16 langid[128] = {0};
378 int size =
379 libusb_get_string_descriptor(handle_,
382 reinterpret_cast<unsigned char*>(&langid[0]),
383 sizeof(langid));
384 if (size < 0)
385 return false;
387 int language_count = (size - 2) / 2;
389 for (int i = 1; i <= language_count; ++i) {
390 // Get the string using language ID.
391 base::char16 text[256] = {0};
392 size =
393 libusb_get_string_descriptor(handle_,
394 desc.iSerialNumber,
395 langid[i],
396 reinterpret_cast<unsigned char*>(&text[0]),
397 sizeof(text));
398 if (size <= 2)
399 continue;
400 if ((text[0] >> 8) != LIBUSB_DT_STRING)
401 continue;
402 if ((text[0] & 255) > size)
403 continue;
405 size = size / 2 - 1;
406 *serial = base::string16(text + 1, size);
407 return true;
409 return false;
412 void UsbDeviceHandle::ControlTransfer(const UsbEndpointDirection direction,
413 const TransferRequestType request_type,
414 const TransferRecipient recipient,
415 const uint8 request,
416 const uint16 value,
417 const uint16 index,
418 net::IOBuffer* buffer,
419 const size_t length,
420 const unsigned int timeout,
421 const UsbTransferCallback& callback) {
422 if (!device_) {
423 callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
424 return;
427 const size_t resized_length = LIBUSB_CONTROL_SETUP_SIZE + length;
428 scoped_refptr<net::IOBuffer> resized_buffer(
429 new net::IOBufferWithSize(static_cast<int>(resized_length)));
430 if (!resized_buffer) {
431 callback.Run(USB_TRANSFER_ERROR, buffer, 0);
432 return;
434 memcpy(resized_buffer->data() + LIBUSB_CONTROL_SETUP_SIZE,
435 buffer->data(),
436 static_cast<int>(length));
438 PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(0);
439 const uint8 converted_type =
440 CreateRequestType(direction, request_type, recipient);
441 libusb_fill_control_setup(reinterpret_cast<uint8*>(resized_buffer->data()),
442 converted_type,
443 request,
444 value,
445 index,
446 static_cast<int16>(length));
447 libusb_fill_control_transfer(transfer,
448 handle_,
449 reinterpret_cast<uint8*>(resized_buffer->data()),
450 PlatformTransferCompletionCallback,
451 this,
452 timeout);
454 BrowserThread::PostTask(BrowserThread::FILE,
455 FROM_HERE,
456 base::Bind(&UsbDeviceHandle::SubmitTransfer,
457 this,
458 transfer,
459 USB_TRANSFER_CONTROL,
460 resized_buffer,
461 resized_length,
462 base::MessageLoopProxy::current(),
463 callback));
466 void UsbDeviceHandle::BulkTransfer(const UsbEndpointDirection direction,
467 const uint8 endpoint,
468 net::IOBuffer* buffer,
469 const size_t length,
470 const unsigned int timeout,
471 const UsbTransferCallback& callback) {
472 if (!device_) {
473 callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
474 return;
477 PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(0);
478 const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint;
479 libusb_fill_bulk_transfer(transfer,
480 handle_,
481 new_endpoint,
482 reinterpret_cast<uint8*>(buffer->data()),
483 static_cast<int>(length),
484 PlatformTransferCompletionCallback,
485 this,
486 timeout);
488 BrowserThread::PostTask(BrowserThread::FILE,
489 FROM_HERE,
490 base::Bind(&UsbDeviceHandle::SubmitTransfer,
491 this,
492 transfer,
493 USB_TRANSFER_BULK,
494 make_scoped_refptr(buffer),
495 length,
496 base::MessageLoopProxy::current(),
497 callback));
500 void UsbDeviceHandle::InterruptTransfer(const UsbEndpointDirection direction,
501 const uint8 endpoint,
502 net::IOBuffer* buffer,
503 const size_t length,
504 const unsigned int timeout,
505 const UsbTransferCallback& callback) {
506 if (!device_) {
507 callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
508 return;
511 PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(0);
512 const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint;
513 libusb_fill_interrupt_transfer(transfer,
514 handle_,
515 new_endpoint,
516 reinterpret_cast<uint8*>(buffer->data()),
517 static_cast<int>(length),
518 PlatformTransferCompletionCallback,
519 this,
520 timeout);
521 BrowserThread::PostTask(BrowserThread::FILE,
522 FROM_HERE,
523 base::Bind(&UsbDeviceHandle::SubmitTransfer,
524 this,
525 transfer,
526 USB_TRANSFER_INTERRUPT,
527 make_scoped_refptr(buffer),
528 length,
529 base::MessageLoopProxy::current(),
530 callback));
533 void UsbDeviceHandle::IsochronousTransfer(const UsbEndpointDirection direction,
534 const uint8 endpoint,
535 net::IOBuffer* buffer,
536 const size_t length,
537 const unsigned int packets,
538 const unsigned int packet_length,
539 const unsigned int timeout,
540 const UsbTransferCallback& callback) {
541 if (!device_) {
542 callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
543 return;
546 const uint64 total_length = packets * packet_length;
547 CHECK(packets <= length && total_length <= length)
548 << "transfer length is too small";
550 PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(packets);
551 const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint;
552 libusb_fill_iso_transfer(transfer,
553 handle_,
554 new_endpoint,
555 reinterpret_cast<uint8*>(buffer->data()),
556 static_cast<int>(length),
557 packets,
558 PlatformTransferCompletionCallback,
559 this,
560 timeout);
561 libusb_set_iso_packet_lengths(transfer, packet_length);
563 BrowserThread::PostTask(BrowserThread::FILE,
564 FROM_HERE,
565 base::Bind(&UsbDeviceHandle::SubmitTransfer,
566 this,
567 transfer,
568 USB_TRANSFER_ISOCHRONOUS,
569 make_scoped_refptr(buffer),
570 length,
571 base::MessageLoopProxy::current(),
572 callback));
575 void UsbDeviceHandle::RefreshEndpointMap() {
576 DCHECK(thread_checker_.CalledOnValidThread());
577 endpoint_map_.clear();
578 for (ClaimedInterfaceMap::iterator it = claimed_interfaces_.begin();
579 it != claimed_interfaces_.end();
580 ++it) {
581 scoped_refptr<const UsbInterfaceAltSettingDescriptor> interface_desc =
582 interfaces_->GetInterface(it->first)
583 ->GetAltSetting(it->second->alternate_setting());
584 for (size_t i = 0; i < interface_desc->GetNumEndpoints(); i++) {
585 scoped_refptr<const UsbEndpointDescriptor> endpoint =
586 interface_desc->GetEndpoint(i);
587 endpoint_map_[endpoint->GetAddress()] = it->first;
592 scoped_refptr<UsbDeviceHandle::InterfaceClaimer>
593 UsbDeviceHandle::GetClaimedInterfaceForEndpoint(unsigned char endpoint) {
594 unsigned char address = endpoint & LIBUSB_ENDPOINT_ADDRESS_MASK;
595 if (ContainsKey(endpoint_map_, address))
596 return claimed_interfaces_[endpoint_map_[address]];
597 return NULL;
600 void UsbDeviceHandle::SubmitTransfer(
601 PlatformUsbTransferHandle handle,
602 UsbTransferType transfer_type,
603 net::IOBuffer* buffer,
604 const size_t length,
605 scoped_refptr<base::MessageLoopProxy> message_loop_proxy,
606 const UsbTransferCallback& callback) {
607 DCHECK(thread_checker_.CalledOnValidThread());
608 if (!device_) {
609 message_loop_proxy->PostTask(
610 FROM_HERE,
611 base::Bind(
612 callback, USB_TRANSFER_DISCONNECT, make_scoped_refptr(buffer), 0));
615 Transfer transfer;
616 transfer.transfer_type = transfer_type;
617 transfer.buffer = buffer;
618 transfer.length = length;
619 transfer.callback = callback;
620 transfer.message_loop_proxy = message_loop_proxy;
622 // It's OK for this method to return NULL. libusb_submit_transfer will fail if
623 // it requires an interface we didn't claim.
624 transfer.claimed_interface = GetClaimedInterfaceForEndpoint(handle->endpoint);
626 if (libusb_submit_transfer(handle) == LIBUSB_SUCCESS) {
627 transfers_[handle] = transfer;
628 } else {
629 message_loop_proxy->PostTask(
630 FROM_HERE,
631 base::Bind(
632 callback, USB_TRANSFER_ERROR, make_scoped_refptr(buffer), 0));
636 void UsbDeviceHandle::InternalClose() {
637 DCHECK(thread_checker_.CalledOnValidThread());
638 if (!device_)
639 return;
641 // Cancel all the transfers.
642 for (TransferMap::iterator it = transfers_.begin(); it != transfers_.end();
643 ++it) {
644 // The callback will be called some time later.
645 libusb_cancel_transfer(it->first);
648 // Attempt-release all the interfaces.
649 // It will be retained until the transfer cancellation is finished.
650 claimed_interfaces_.clear();
652 // Cannot close device handle here. Need to wait for libusb_cancel_transfer to
653 // finish.
654 device_ = NULL;
657 } // namespace usb_service