7 Copyright (C) 2005-2009, Chris Frey
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18 See the GNU General Public License in the COPYING file at the
19 root directory of this project for more details.
33 #ifndef __DEBUG_MODE__
34 #define __DEBUG_MODE__
40 ///////////////////////////////////////////////////////////////////////////////
41 // Usb::Error exception class
43 static std::string
GetErrorString(int libusb_errcode
, const std::string
&str
)
45 std::ostringstream oss
;
48 if( libusb_errcode
) {
49 oss
<< std::setbase(10) << libusb_errcode
<< ", ";
52 // oss << strerror(-libusb_errno) << "): "
53 oss
<< usb_strerror() << "): ";
58 Error::Error(const std::string
&str
)
59 : Barry::Error(GetErrorString(0, str
))
64 Error::Error(int libusb_errcode
, const std::string
&str
)
65 : Barry::Error(GetErrorString(libusb_errcode
, str
))
66 , m_libusb_errcode(libusb_errcode
)
71 ///////////////////////////////////////////////////////////////////////////////
74 Match::Match(int vendor
, int product
,
75 const char *busname
, const char *devname
)
85 m_busses
= usb_get_busses();
92 bool Match::ToNum(const char *str
, long &num
)
95 num
= strtol(str
, &end
, 10);
96 return num
>= 0 && // no negative numbers
97 num
!= LONG_MIN
&& num
!= LONG_MAX
&& // no overflow
98 str
!= end
&& *end
== '\0'; // whole string valid
102 // Linux treats bus and device path names as numbers, sometimes left
103 // padded with zeros. Other platforms, such as Windows, use strings,
104 // such as "bus-1" or similar.
106 // Here we try to convert each string to a number, and if successful,
107 // compare them. If unable to convert, then compare as strings.
108 // This way, "3" == "003" and "bus-foobar" == "bus-foobar".
110 bool Match::NameCompare(const char *n1
, const char *n2
)
113 if( ToNum(n1
, l1
) && ToNum(n2
, l2
) ) {
117 return strcmp(n1
, n2
) == 0;
121 bool Match::next_device(Usb::DeviceIDType
*devid
)
123 for( ; m_busses
; m_busses
= m_busses
->next
) {
125 // only search on given bus
126 if( m_busname
&& !NameCompare(m_busname
, m_busses
->dirname
) )
130 m_dev
= m_busses
->devices
;
132 for( ; m_dev
; m_dev
= m_dev
->next
) {
134 // search for specific device
135 if( m_devname
&& !NameCompare(m_devname
, m_dev
->filename
) )
139 if( m_dev
->descriptor
.idVendor
== m_vendor
&&
140 m_dev
->descriptor
.idProduct
== m_product
) {
144 // advance for next time
147 m_busses
= m_busses
->next
;
158 ///////////////////////////////////////////////////////////////////////////////
161 Device::Device(Usb::DeviceIDType id
, int timeout
)
165 dout("usb_open(" << std::dec
<< id
<< ")");
166 m_handle
= usb_open(id
);
168 throw Error("open failed");
173 dout("usb_close(" << std::dec
<< m_handle
<< ")");
177 bool Device::SetConfiguration(unsigned char cfg
)
179 dout("usb_set_configuration(" << std::dec
<< m_handle
<< ", 0x" << std::hex
<< (unsigned int) cfg
<< ")");
180 int ret
= usb_set_configuration(m_handle
, cfg
);
185 bool Device::ClearHalt(int ep
)
187 dout("usb_clear_halt(" << std::dec
<< m_handle
<< ", 0x" << std::hex
<< ep
<< ")");
188 int ret
= usb_clear_halt(m_handle
, ep
);
195 dout("usb_reset(" << std::dec
<< m_handle
<< ")");
196 int ret
= usb_reset(m_handle
);
201 bool Device::BulkRead(int ep
, Barry::Data
&data
, int timeout
)
206 ret
= usb_bulk_read(m_handle
, ep
,
207 (char*) data
.GetBuffer(), data
.GetBufSize(),
208 timeout
== -1 ? m_timeout
: timeout
);
209 if( ret
< 0 && ret
!= -EINTR
&& ret
!= -EAGAIN
) {
211 if( ret
== -ETIMEDOUT
)
212 throw Timeout(ret
, "Timeout in usb_bulk_read");
214 throw Error(ret
, "Error in usb_bulk_read");
216 data
.ReleaseBuffer(ret
);
217 } while( ret
== -EINTR
|| ret
== -EAGAIN
);
222 bool Device::BulkWrite(int ep
, const Barry::Data
&data
, int timeout
)
224 ddout("BulkWrite to endpoint 0x" << std::hex
<< ep
<< ":\n" << data
);
227 ret
= usb_bulk_write(m_handle
, ep
,
228 (char*) data
.GetData(), data
.GetSize(),
229 timeout
== -1 ? m_timeout
: timeout
);
230 if( ret
< 0 && ret
!= -EINTR
&& ret
!= -EAGAIN
) {
232 if( ret
== -ETIMEDOUT
)
233 throw Timeout(ret
, "Timeout in usb_bulk_write (1)");
235 throw Error(ret
, "Error in usb_bulk_write (1)");
237 } while( ret
== -EINTR
|| ret
== -EAGAIN
);
242 bool Device::BulkWrite(int ep
, const void *data
, size_t size
, int timeout
)
244 #ifdef __DEBUG_MODE__
245 Barry::Data
dump(data
, size
);
246 ddout("BulkWrite to endpoint 0x" << std::hex
<< ep
<< ":\n" << dump
);
251 ret
= usb_bulk_write(m_handle
, ep
,
253 timeout
== -1 ? m_timeout
: timeout
);
254 if( ret
< 0 && ret
!= -EINTR
&& ret
!= -EAGAIN
) {
256 if( ret
== -ETIMEDOUT
)
257 throw Timeout(ret
, "Timeout in usb_bulk_write (2)");
259 throw Error(ret
, "Error in usb_bulk_write (2)");
261 } while( ret
== -EINTR
|| ret
== -EAGAIN
);
266 bool Device::InterruptRead(int ep
, Barry::Data
&data
, int timeout
)
271 ret
= usb_interrupt_read(m_handle
, ep
,
272 (char*) data
.GetBuffer(), data
.GetBufSize(),
273 timeout
== -1 ? m_timeout
: timeout
);
274 if( ret
< 0 && ret
!= -EINTR
&& ret
!= -EAGAIN
) {
276 if( ret
== -ETIMEDOUT
)
277 throw Timeout(ret
, "Timeout in usb_interrupt_read");
279 throw Error(ret
, "Error in usb_interrupt_read");
281 data
.ReleaseBuffer(ret
);
282 } while( ret
== -EINTR
|| ret
== -EAGAIN
);
287 bool Device::InterruptWrite(int ep
, const Barry::Data
&data
, int timeout
)
289 ddout("InterruptWrite to endpoint 0x" << std::hex
<< ep
<< ":\n" << data
);
293 ret
= usb_interrupt_write(m_handle
, ep
,
294 (char*) data
.GetData(), data
.GetSize(),
295 timeout
== -1 ? m_timeout
: timeout
);
296 if( ret
< 0 && ret
!= -EINTR
&& ret
!= -EAGAIN
) {
298 if( ret
== -ETIMEDOUT
)
299 throw Timeout(ret
, "Timeout in usb_interrupt_write");
301 throw Error(ret
, "Error in usb_interrupt_write");
303 } while( ret
== -EINTR
|| ret
== -EAGAIN
);
311 /// Reads anything available on the given endpoint, with a low timeout,
312 /// in order to clear any pending reads.
314 void Device::BulkDrain(int ep
, int timeout
)
318 while( BulkRead(ep
, data
, timeout
) )
321 catch( Usb::Error
& ) {}
327 /// Uses the GET_CONFIGURATION control message to determine the currently
328 /// selected USB configuration, returning it in the cfg argument.
329 /// If unsuccessful, returns false.
331 bool Device::GetConfiguration(unsigned char &cfg
)
333 int result
= usb_control_msg(m_handle
, 0x80, USB_REQ_GET_CONFIGURATION
, 0, 0,
334 (char*) &cfg
, 1, m_timeout
);
335 m_lasterror
= result
;
341 ///////////////////////////////////////////////////////////////////////////////
344 Interface::Interface(Device
&dev
, int iface
)
345 : m_dev(dev
), m_iface(iface
)
347 dout("usb_claim_interface(" << dev
.GetHandle() << ", 0x" << std::hex
<< iface
<< ")");
348 int ret
= usb_claim_interface(dev
.GetHandle(), iface
);
350 throw Error(ret
, "claim interface failed");
352 // kernels >= 2.6.28 don't set the interface the same as
353 // previous versions did, and the Blackberry gets confused
354 // if it isn't explicitly set
355 ret
= usb_set_altinterface(dev
.GetHandle(), iface
);
357 throw Error(ret
, "set alt interface failed");
360 Interface::~Interface()
362 dout("usb_release_interface(" << m_dev
.GetHandle() << ", 0x" << std::hex
<< m_iface
<< ")");
363 usb_release_interface(m_dev
.GetHandle(), m_iface
);
368 ///////////////////////////////////////////////////////////////////////////////
371 bool EndpointDiscovery::Discover(struct usb_interface_descriptor
*interface
, int epcount
)
379 if( !interface
|| !interface
->endpoint
) {
380 dout("EndpointDiscovery::Discover: empty interface pointer");
384 for( int i
= 0; i
< epcount
; i
++ ) {
386 usb_endpoint_descriptor desc
;
387 desc
= interface
->endpoint
[i
];
388 dout(" endpoint_desc #" << std::dec
<< i
<< " loaded"
389 << "\nbLength: " << std::dec
<< (unsigned ) desc
.bLength
390 << "\nbDescriptorType: " << std::dec
<< (unsigned ) desc
.bDescriptorType
391 << "\nbEndpointAddress: 0x" << std::hex
<< (unsigned ) desc
.bEndpointAddress
392 << "\nbmAttributes: 0x" << std::hex
<< (unsigned ) desc
.bmAttributes
393 << "\nwMaxPacketSize: " << std::dec
<< (unsigned ) desc
.wMaxPacketSize
394 << "\nbInterval: " << std::dec
<< (unsigned ) desc
.bInterval
395 << "\nbRefresh: " << std::dec
<< (unsigned ) desc
.bRefresh
396 << "\nbSynchAddress: " << std::dec
<< (unsigned ) desc
.bSynchAddress
401 (*this)[desc
.bEndpointAddress
] = desc
;
402 dout(" endpoint added to map with bEndpointAddress: 0x" << std::hex
<< (unsigned int)desc
.bEndpointAddress
);
404 // parse the endpoint into read/write sets, if possible,
405 // going in discovery order...
407 // - endpoints of related utility will be grouped
408 // - endpoints with same type will be grouped
409 // - endpoints that do not meet the above assumptions
410 // do not belong in a pair
411 unsigned char type
= desc
.bmAttributes
& USB_ENDPOINT_TYPE_MASK
;
412 if( desc
.bEndpointAddress
& USB_ENDPOINT_DIR_MASK
) {
414 pair
.read
= desc
.bEndpointAddress
;
415 dout(" pair.read = 0x" << std::hex
<< (unsigned int)pair
.read
);
416 if( pair
.IsTypeSet() && pair
.type
!= type
) {
417 // if type is already set, we must start over
423 pair
.write
= desc
.bEndpointAddress
;
424 dout(" pair.write = 0x" << std::hex
<< (unsigned int)pair
.write
);
425 if( pair
.IsTypeSet() && pair
.type
!= type
) {
426 // if type is already set, we must start over
430 // save the type last
432 dout(" pair.type = 0x" << std::hex
<< (unsigned int)pair
.type
);
434 // if pair is complete, add to array
435 if( pair
.IsComplete() ) {
436 m_endpoints
.push_back(pair
);
437 dout(" pair added! ("
438 << "read: 0x" << std::hex
<< (unsigned int)pair
.read
<< ","
439 << "write: 0x" << std::hex
<< (unsigned int)pair
.write
<< ","
440 << "type: 0x" << std::hex
<< (unsigned int)pair
.type
<< ")");
441 pair
= EndpointPair(); // clear
445 // just for debugging purposes, check for extra descriptors, and
446 // dump them to dout if they exist
447 if( interface
->extra
) {
448 dout("while parsing endpoints, found a block of extra descriptors:");
449 Barry::Data
data(interface
->extra
, interface
->extralen
);
453 return m_valid
= true;
457 ///////////////////////////////////////////////////////////////////////////////
458 // InterfaceDiscovery
460 bool InterfaceDiscovery::DiscoverInterface(struct usb_interface
*interface
)
462 if( !interface
->altsetting
) {
463 dout("InterfaceDiscovery::DiscoverIterface: empty altsetting");
464 // some devices are buggy and return a higher bNumInterfaces
465 // than the number of interfaces available... in this case
466 // we just skip and continue
470 for( int i
= 0; i
< interface
->num_altsetting
; i
++ ) {
473 desc
.desc
= interface
->altsetting
[i
];
474 dout(" interface_desc #" << std::dec
<< i
<< " loaded"
475 << "\nbLength: " << std::dec
<< (unsigned) desc
.desc
.bLength
476 << "\nbDescriptorType: " << std::dec
<< (unsigned) desc
.desc
.bDescriptorType
477 << "\nbInterfaceNumber: " << std::dec
<< (unsigned) desc
.desc
.bInterfaceNumber
478 << "\nbAlternateSetting: " << std::dec
<< (unsigned) desc
.desc
.bAlternateSetting
479 << "\nbNumEndpoints: " << std::dec
<< (unsigned) desc
.desc
.bNumEndpoints
480 << "\nbInterfaceClass: " << std::dec
<< (unsigned) desc
.desc
.bInterfaceClass
481 << "\nbInterfaceSubClass: " << std::dec
<< (unsigned) desc
.desc
.bInterfaceSubClass
482 << "\nbInterfaceProtocol: " << std::dec
<< (unsigned) desc
.desc
.bInterfaceProtocol
483 << "\niInterface: " << std::dec
<< (unsigned) desc
.desc
.iInterface
487 // load all endpoints on this interface
488 if( !desc
.endpoints
.Discover(&desc
.desc
, desc
.desc
.bNumEndpoints
) ) {
489 dout(" endpoint discovery failed for bInterfaceNumber: " << std::dec
<< (unsigned int)desc
.desc
.bInterfaceNumber
<< ", not added to map.");
494 (*this)[desc
.desc
.bInterfaceNumber
] = desc
;
495 dout(" interface added to map with bInterfaceNumber: " << std::dec
<< (unsigned int)desc
.desc
.bInterfaceNumber
);
500 bool InterfaceDiscovery::Discover(Usb::DeviceIDType devid
, int cfgidx
, int ifcount
)
506 if( !devid
|| !devid
->config
|| !devid
->config
[cfgidx
].interface
) {
507 dout("InterfaceDiscovery::Discover: empty devid/config/interface");
511 for( int i
= 0; i
< ifcount
; i
++ ) {
512 if( !DiscoverInterface(&devid
->config
[cfgidx
].interface
[i
]) )
516 return m_valid
= true;
520 ///////////////////////////////////////////////////////////////////////////////
523 bool ConfigDiscovery::Discover(Usb::DeviceIDType devid
, int cfgcount
)
529 for( int i
= 0; i
< cfgcount
; i
++ ) {
532 if( !devid
|| !devid
->config
) {
533 dout("ConfigDiscovery::Discover: empty devid or config");
536 desc
.desc
= devid
->config
[i
];
537 dout(" config_desc #" << std::dec
<< i
<< " loaded"
538 << "\nbLength: " << std::dec
<< (unsigned int) desc
.desc
.bLength
539 << "\nbDescriptorType: " << std::dec
<< (unsigned int) desc
.desc
.bDescriptorType
540 << "\nwTotalLength: " << std::dec
<< (unsigned int) desc
.desc
.wTotalLength
541 << "\nbNumInterfaces: " << std::dec
<< (unsigned int) desc
.desc
.bNumInterfaces
542 << "\nbConfigurationValue: " << std::dec
<< (unsigned int) desc
.desc
.bConfigurationValue
543 << "\niConfiguration: " << std::dec
<< (unsigned int) desc
.desc
.iConfiguration
544 << "\nbmAttributes: 0x" << std::hex
<< (unsigned int) desc
.desc
.bmAttributes
545 << "\nMaxPower: " << std::dec
<< (unsigned int) desc
.desc
.MaxPower
549 // just for debugging purposes, check for extra descriptors, and
550 // dump them to dout if they exist
551 if( desc
.desc
.extra
) {
552 dout("while parsing config descriptor, found a block of extra descriptors:");
553 Barry::Data
data(desc
.desc
.extra
, desc
.desc
.extralen
);
557 // load all interfaces on this configuration
558 if( !desc
.interfaces
.Discover(devid
, i
, desc
.desc
.bNumInterfaces
) ) {
559 dout(" config discovery failed for bConfigurationValue: " << std::dec
<< (unsigned int)desc
.desc
.bConfigurationValue
<< ", not added to map.");
564 (*this)[desc
.desc
.bConfigurationValue
] = desc
;
565 dout(" config added to map with bConfigurationValue: " << std::dec
<< (unsigned int)desc
.desc
.bConfigurationValue
);
568 return m_valid
= true;
572 ///////////////////////////////////////////////////////////////////////////////
575 DeviceDiscovery::DeviceDiscovery(Usb::DeviceIDType devid
)
581 bool DeviceDiscovery::Discover(Usb::DeviceIDType devid
)
587 // copy the descriptor over to our memory
589 dout("DeviceDiscovery::Discover: empty devid");
593 desc
= devid
->descriptor
;
594 dout("device_desc loaded"
595 << "\nbLength: " << std::dec
<< (unsigned int) desc
.bLength
596 << "\nbDescriptorType: " << std::dec
<< (unsigned int) desc
.bDescriptorType
597 << "\nbcdUSB: 0x" << std::hex
<< (unsigned int) desc
.bcdUSB
598 << "\nbDeviceClass: " << std::dec
<< (unsigned int) desc
.bDeviceClass
599 << "\nbDeviceSubClass: " << std::dec
<< (unsigned int) desc
.bDeviceSubClass
600 << "\nbDeviceProtocol: " << std::dec
<< (unsigned int) desc
.bDeviceProtocol
601 << "\nbMaxPacketSize0: " << std::dec
<< (unsigned int) desc
.bMaxPacketSize0
602 << "\nidVendor: 0x" << std::hex
<< (unsigned int) desc
.idVendor
603 << "\nidProduct: 0x" << std::hex
<< (unsigned int) desc
.idProduct
604 << "\nbcdDevice: 0x" << std::hex
<< (unsigned int) desc
.bcdDevice
605 << "\niManufacturer: " << std::dec
<< (unsigned int) desc
.iManufacturer
606 << "\niProduct: " << std::dec
<< (unsigned int) desc
.iProduct
607 << "\niSerialNumber: " << std::dec
<< (unsigned int) desc
.iSerialNumber
608 << "\nbNumConfigurations: " << std::dec
<< (unsigned int) desc
.bNumConfigurations
612 m_valid
= configs
.Discover(devid
, desc
.bNumConfigurations
);