Barry-fied the sha1 code.
[barry/pauldeden.git] / src / usbwrap.cc
blobcb7f51e329fde1050890913e5338524b30ef9f2a
1 ///
2 /// \file usbwrap.cc
3 /// USB API wrapper
4 ///
6 /*
7 Copyright (C) 2005-2008, 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.
23 #include "usbwrap.h"
24 #include "data.h"
25 #include "error.h"
26 #include "debug.h"
28 #include <iomanip>
29 #include <sstream>
30 #include <errno.h>
31 #include <string.h>
33 #ifndef __DEBUG_MODE__
34 #define __DEBUG_MODE__
35 #endif
36 #include "debug.h"
38 namespace Usb {
40 ///////////////////////////////////////////////////////////////////////////////
41 // Usb::Error exception class
43 static std::string GetErrorString(int libusb_errcode, const std::string &str)
45 std::ostringstream oss;
46 oss << "(";
48 if( libusb_errcode ) {
49 oss << std::setbase(10) << libusb_errcode << ", ";
52 // oss << strerror(-libusb_errno) << "): "
53 oss << usb_strerror() << "): ";
54 oss << str;
55 return oss.str();
58 Error::Error(const std::string &str)
59 : Barry::Error(GetErrorString(0, str))
60 , m_libusb_errcode(0)
64 Error::Error(int libusb_errcode, const std::string &str)
65 : Barry::Error(GetErrorString(libusb_errcode, str))
66 , m_libusb_errcode(libusb_errcode)
71 ///////////////////////////////////////////////////////////////////////////////
72 // Match
74 Match::Match(int vendor, int product,
75 const char *busname, const char *devname)
76 : m_busses(0)
77 , m_dev(0)
78 , m_vendor(vendor)
79 , m_product(product)
80 , m_busname(busname)
81 , m_devname(devname)
83 usb_find_busses();
84 usb_find_devices();
85 m_busses = usb_get_busses();
88 Match::~Match()
92 bool Match::ToNum(const char *str, long &num)
94 char *end = 0;
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)
112 long l1, l2;
113 if( ToNum(n1, l1) && ToNum(n2, l2) ) {
114 return l1 == l2;
116 else {
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) )
127 continue;
129 if( !m_dev )
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) )
136 continue;
138 // is there a match?
139 if( m_dev->descriptor.idVendor == m_vendor &&
140 m_dev->descriptor.idProduct == m_product ) {
141 // found!
142 *devid = m_dev;
144 // advance for next time
145 m_dev = m_dev->next;
146 if( !m_dev )
147 m_busses = m_busses->next;
149 // done
150 return true;
154 return false;
158 ///////////////////////////////////////////////////////////////////////////////
159 // Device
161 Device::Device(Usb::DeviceIDType id, int timeout)
162 : m_id(id),
163 m_timeout(timeout)
165 dout("usb_open(" << std::dec << id << ")");
166 m_handle = usb_open(id);
167 if( !m_handle )
168 throw Error("open failed");
171 Device::~Device()
173 dout("usb_close(" << std::dec << m_handle << ")");
174 usb_close(m_handle);
177 bool Device::SetConfiguration(unsigned char cfg)
179 dout("usb_set_configuration(" << std::dec << m_handle << "," << std::dec << (unsigned int) cfg << ")");
180 int ret = usb_set_configuration(m_handle, cfg);
181 m_lasterror = ret;
182 return ret >= 0;
185 bool Device::ClearHalt(int ep)
187 dout("usb_clear_halt(" << std::dec << m_handle << "," << std::dec << ep << ")");
188 int ret = usb_clear_halt(m_handle, ep);
189 m_lasterror = ret;
190 return ret >= 0;
193 bool Device::Reset()
195 dout("usb_reset(" << std::dec << m_handle << ")");
196 int ret = usb_reset(m_handle);
197 m_lasterror = ret;
198 return ret == 0;
201 bool Device::BulkRead(int ep, Barry::Data &data, int timeout)
203 int ret;
204 do {
205 ret = usb_bulk_read(m_handle, ep,
206 (char*) data.GetBuffer(), data.GetBufSize(),
207 timeout == -1 ? m_timeout : timeout);
208 if( ret < 0 && ret != -EINTR && ret != -EAGAIN ) {
209 m_lasterror = ret;
210 if( ret == -ETIMEDOUT )
211 throw Timeout(ret, "Timeout in usb_bulk_read");
212 else
213 throw Error(ret, "Error in usb_bulk_read");
215 data.ReleaseBuffer(ret);
216 } while( ret == -EINTR || ret == -EAGAIN );
218 return ret >= 0;
221 bool Device::BulkWrite(int ep, const Barry::Data &data, int timeout)
223 ddout("BulkWrite to endpoint " << std::dec << ep << ":\n" << data);
224 int ret;
225 do {
226 ret = usb_bulk_write(m_handle, ep,
227 (char*) data.GetData(), data.GetSize(),
228 timeout == -1 ? m_timeout : timeout);
229 if( ret < 0 && ret != -EINTR && ret != -EAGAIN ) {
230 m_lasterror = ret;
231 if( ret == -ETIMEDOUT )
232 throw Timeout(ret, "Timeout in usb_bulk_write");
233 else
234 throw Error(ret, "Error in usb_bulk_write");
236 } while( ret == -EINTR || ret == -EAGAIN );
238 return ret >= 0;
241 bool Device::BulkWrite(int ep, const void *data, size_t size, int timeout)
243 #ifdef __DEBUG_MODE__
244 Barry::Data dump(data, size);
245 ddout("BulkWrite to endpoint " << std::dec << ep << ":\n" << dump);
246 #endif
248 int ret;
249 do {
250 ret = usb_bulk_write(m_handle, ep,
251 (char*) data, size,
252 timeout == -1 ? m_timeout : timeout);
253 if( ret < 0 && ret != -EINTR && ret != -EAGAIN ) {
254 m_lasterror = ret;
255 if( ret == -ETIMEDOUT )
256 throw Timeout(ret, "Timeout in usb_bulk_read");
257 else
258 throw Error(ret, "Error in usb_bulk_read");
260 } while( ret == -EINTR || ret == -EAGAIN );
262 return ret >= 0;
265 bool Device::InterruptRead(int ep, Barry::Data &data, int timeout)
267 int ret;
268 do {
269 ret = usb_interrupt_read(m_handle, ep,
270 (char*) data.GetBuffer(), data.GetBufSize(),
271 timeout == -1 ? m_timeout : timeout);
272 if( ret < 0 && ret != -EINTR && ret != -EAGAIN ) {
273 m_lasterror = ret;
274 if( ret == -ETIMEDOUT )
275 throw Timeout(ret, "Timeout in usb_bulk_read");
276 else
277 throw Error(ret, "Error in usb_bulk_read");
279 data.ReleaseBuffer(ret);
280 } while( ret == -EINTR || ret == -EAGAIN );
282 return ret >= 0;
285 bool Device::InterruptWrite(int ep, const Barry::Data &data, int timeout)
287 ddout("InterruptWrite to endpoint " << std::dec << ep << ":\n" << data);
289 int ret;
290 do {
291 ret = usb_interrupt_write(m_handle, ep,
292 (char*) data.GetData(), data.GetSize(),
293 timeout == -1 ? m_timeout : timeout);
294 if( ret < 0 && ret != -EINTR && ret != -EAGAIN ) {
295 m_lasterror = ret;
296 if( ret == -ETIMEDOUT )
297 throw Timeout(ret, "Timeout in usb_bulk_read");
298 else
299 throw Error(ret, "Error in usb_bulk_read");
301 } while( ret == -EINTR || ret == -EAGAIN );
303 return ret >= 0;
307 // BulkDrain
309 /// Reads anything available on the given endpoint, with a low timeout,
310 /// in order to clear any pending reads.
312 void Device::BulkDrain(int ep, int timeout)
314 try {
315 Barry::Data data;
316 while( BulkRead(ep, data, timeout) )
319 catch( Usb::Error & ) {}
323 // GetConfiguration
325 /// Uses the GET_CONFIGURATION control message to determine the currently
326 /// selected USB configuration, returning it in the cfg argument.
327 /// If unsuccessful, returns false.
329 bool Device::GetConfiguration(unsigned char &cfg)
331 int result = usb_control_msg(m_handle, 0x80, USB_REQ_GET_CONFIGURATION, 0, 0,
332 (char*) &cfg, 1, m_timeout);
333 m_lasterror = result;
334 return result >= 0;
339 ///////////////////////////////////////////////////////////////////////////////
340 // Interface
342 Interface::Interface(Device &dev, int iface)
343 : m_dev(dev), m_iface(iface)
345 dout("usb_claim_interface(" << dev.GetHandle() << "," << std::dec << iface << ")");
346 int ret = usb_claim_interface(dev.GetHandle(), iface);
347 if( ret < 0 )
348 throw Error(ret, "claim interface failed");
351 Interface::~Interface()
353 dout("usb_release_interface(" << m_dev.GetHandle() << "," << std::dec << m_iface << ")");
354 usb_release_interface(m_dev.GetHandle(), m_iface);
359 ///////////////////////////////////////////////////////////////////////////////
360 // EndpointDiscovery
362 bool EndpointDiscovery::Discover(struct usb_interface_descriptor *interface, int epcount)
364 // start fresh
365 clear();
366 m_valid = false;
368 EndpointPair pair;
370 if( !interface || !interface->endpoint ) {
371 dout("EndpointDiscovery::Discover: empty interface pointer");
372 return false;
375 for( int i = 0; i < epcount; i++ ) {
376 // load descriptor
377 usb_endpoint_descriptor desc;
378 desc = interface->endpoint[i];
379 dout(" endpoint_desc #" << i << " loaded"
380 << "\nbLength: " << (unsigned ) desc.bLength
381 << "\nbDescriptorType: " << (unsigned ) desc.bDescriptorType
382 << "\nbEndpointAddress: " << (unsigned ) desc.bEndpointAddress
383 << "\nbmAttributes: " << (unsigned ) desc.bmAttributes
384 << "\nwMaxPacketSize: " << (unsigned ) desc.wMaxPacketSize
385 << "\nbInterval: " << (unsigned ) desc.bInterval
386 << "\nbRefresh: " << (unsigned ) desc.bRefresh
387 << "\nbSynchAddress: " << (unsigned ) desc.bSynchAddress
388 << "\n"
391 // add to the map
392 (*this)[desc.bEndpointAddress] = desc;
393 dout(" endpoint added to map with bEndpointAddress: " << (unsigned int)desc.bEndpointAddress);
395 // parse the endpoint into read/write sets, if possible,
396 // going in discovery order...
397 // Assumptions:
398 // - endpoints of related utility will be grouped
399 // - endpoints with same type will be grouped
400 // - endpoints that do not meet the above assumptions
401 // do not belong in a pair
402 unsigned char type = desc.bmAttributes & USB_ENDPOINT_TYPE_MASK;
403 if( desc.bEndpointAddress & USB_ENDPOINT_DIR_MASK ) {
404 // read endpoint
405 pair.read = desc.bEndpointAddress;
406 dout(" pair.read = " << (unsigned int)pair.read);
407 if( pair.IsTypeSet() && pair.type != type ) {
408 // if type is already set, we must start over
409 pair.write = 0;
412 else {
413 // write endpoint
414 pair.write = desc.bEndpointAddress;
415 dout(" pair.write = " << (unsigned int)pair.write);
416 if( pair.IsTypeSet() && pair.type != type ) {
417 // if type is already set, we must start over
418 pair.read = 0;
421 // save the type last
422 pair.type = type;
423 dout(" pair.type = " << (unsigned int)pair.type);
425 // if pair is complete, add to array
426 if( pair.IsComplete() ) {
427 m_endpoints.push_back(pair);
428 dout(" pair added! ("
429 << "read: " << (unsigned int)pair.read << ","
430 << "write: " << (unsigned int)pair.write << ","
431 << "type: " << (unsigned int)pair.type << ")");
432 pair = EndpointPair(); // clear
436 // just for debugging purposes, check for extra descriptors, and
437 // dump them to dout if they exist
438 if( interface->extra ) {
439 dout("while parsing endpoints, found a block of extra descriptors:");
440 Barry::Data data(interface->extra, interface->extralen);
441 dout(data);
444 return m_valid = true;
448 ///////////////////////////////////////////////////////////////////////////////
449 // InterfaceDiscovery
451 bool InterfaceDiscovery::DiscoverInterface(struct usb_interface *interface)
453 if( !interface->altsetting ) {
454 dout("InterfaceDiscovery::DiscoverIterface: empty altsetting");
455 // some devices are buggy and return a higher bNumInterfaces
456 // than the number of interfaces available... in this case
457 // we just skip and continue
458 return true;
461 for( int i = 0; i < interface->num_altsetting; i++ ) {
462 // load descriptor
463 InterfaceDesc desc;
464 desc.desc = interface->altsetting[i];
465 dout(" interface_desc #" << i << " loaded"
466 << "\nbLength: " << (unsigned) desc.desc.bLength
467 << "\nbDescriptorType: " << (unsigned) desc.desc.bDescriptorType
468 << "\nbInterfaceNumber: " << (unsigned) desc.desc.bInterfaceNumber
469 << "\nbAlternateSetting: " << (unsigned) desc.desc.bAlternateSetting
470 << "\nbNumEndpoints: " << (unsigned) desc.desc.bNumEndpoints
471 << "\nbInterfaceClass: " << (unsigned) desc.desc.bInterfaceClass
472 << "\nbInterfaceSubClass: " << (unsigned) desc.desc.bInterfaceSubClass
473 << "\nbInterfaceProtocol: " << (unsigned) desc.desc.bInterfaceProtocol
474 << "\niInterface: " << (unsigned) desc.desc.iInterface
475 << "\n"
478 // load all endpoints on this interface
479 if( !desc.endpoints.Discover(&desc.desc, desc.desc.bNumEndpoints) ) {
480 dout(" endpoint discovery failed for bInterfaceNumber: " << (unsigned int)desc.desc.bInterfaceNumber << ", not added to map.");
481 return false;
484 // add to the map
485 (*this)[desc.desc.bInterfaceNumber] = desc;
486 dout(" interface added to map with bInterfaceNumber: " << (unsigned int)desc.desc.bInterfaceNumber);
488 return true;
491 bool InterfaceDiscovery::Discover(Usb::DeviceIDType devid, int cfgidx, int ifcount)
493 // start fresh
494 clear();
495 m_valid = false;
497 if( !devid || !devid->config || !devid->config[cfgidx].interface ) {
498 dout("InterfaceDiscovery::Discover: empty devid/config/interface");
499 return false;
502 for( int i = 0; i < ifcount; i++ ) {
503 if( !DiscoverInterface(&devid->config[cfgidx].interface[i]) )
504 return false;
507 return m_valid = true;
511 ///////////////////////////////////////////////////////////////////////////////
512 // ConfigDiscovery
514 bool ConfigDiscovery::Discover(Usb::DeviceIDType devid, int cfgcount)
516 // start fresh
517 clear();
518 m_valid = false;
520 for( int i = 0; i < cfgcount; i++ ) {
521 // load descriptor
522 ConfigDesc desc;
523 if( !devid || !devid->config ) {
524 dout("ConfigDiscovery::Discover: empty devid or config");
525 return false;
527 desc.desc = devid->config[i];
528 dout(" config_desc #" << i << " loaded"
529 << "\nbLength: " << (unsigned int) desc.desc.bLength
530 << "\nbDescriptorType: " << (unsigned int) desc.desc.bDescriptorType
531 << "\nwTotalLength: " << (unsigned int) desc.desc.wTotalLength
532 << "\nbNumInterfaces: " << (unsigned int) desc.desc.bNumInterfaces
533 << "\nbConfigurationValue: " << (unsigned int) desc.desc.bConfigurationValue
534 << "\niConfiguration: " << (unsigned int) desc.desc.iConfiguration
535 << "\nbmAttributes: " << (unsigned int) desc.desc.bmAttributes
536 << "\nMaxPower: " << (unsigned int) desc.desc.MaxPower
537 << "\n"
540 // just for debugging purposes, check for extra descriptors, and
541 // dump them to dout if they exist
542 if( desc.desc.extra ) {
543 dout("while parsing config descriptor, found a block of extra descriptors:");
544 Barry::Data data(desc.desc.extra, desc.desc.extralen);
545 dout(data);
548 // load all interfaces on this configuration
549 if( !desc.interfaces.Discover(devid, i, desc.desc.bNumInterfaces) ) {
550 dout(" config discovery failed for bConfigurationValue: " << (unsigned int)desc.desc.bConfigurationValue << ", not added to map.");
551 return false;
554 // add to the map
555 (*this)[desc.desc.bConfigurationValue] = desc;
556 dout(" config added to map with bConfigurationValue: " << (unsigned int)desc.desc.bConfigurationValue);
559 return m_valid = true;
563 ///////////////////////////////////////////////////////////////////////////////
564 // DeviceDiscovery
566 DeviceDiscovery::DeviceDiscovery(Usb::DeviceIDType devid)
567 : m_valid(false)
569 Discover(devid);
572 bool DeviceDiscovery::Discover(Usb::DeviceIDType devid)
574 // start fresh
575 configs.clear();
576 m_valid = false;
578 // copy the descriptor over to our memory
579 if( !devid ) {
580 dout("DeviceDiscovery::Discover: empty devid");
581 return false;
584 desc = devid->descriptor;
585 dout("device_desc loaded"
586 << "\nbLength: " << (unsigned int) desc.bLength
587 << "\nbDescriptorType: " << (unsigned int) desc.bDescriptorType
588 << "\nbcdUSB: " << (unsigned int) desc.bcdUSB
589 << "\nbDeviceClass: " << (unsigned int) desc.bDeviceClass
590 << "\nbDeviceSubClass: " << (unsigned int) desc.bDeviceSubClass
591 << "\nbDeviceProtocol: " << (unsigned int) desc.bDeviceProtocol
592 << "\nbMaxPacketSize0: " << (unsigned int) desc.bMaxPacketSize0
593 << "\nidVendor: " << (unsigned int) desc.idVendor
594 << "\nidProduct: " << (unsigned int) desc.idProduct
595 << "\nbcdDevice: " << (unsigned int) desc.bcdDevice
596 << "\niManufacturer: " << (unsigned int) desc.iManufacturer
597 << "\niProduct: " << (unsigned int) desc.iProduct
598 << "\niSerialNumber: " << (unsigned int) desc.iSerialNumber
599 << "\nbNumConfigurations: " << (unsigned int) desc.bNumConfigurations
600 << "\n"
603 m_valid = configs.Discover(devid, desc.bNumConfigurations);
604 return m_valid;
607 } // namespace Usb