build: Adding support for choice of USB library to configure
[barry.git] / src / probe.cc
bloba7a5cb05caa5f6e5cb172b55b3836ef3dbd1d701
1 ///
2 /// \file probe.cc
3 /// USB Blackberry detection routines
4 ///
6 /*
7 Copyright (C) 2005-2011, Net Direct Inc. (http://www.netdirect.ca/)
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.
22 #include "common.h"
23 #include "probe.h"
24 #include "usbwrap.h"
25 #include "data.h"
26 #include "endian.h"
27 #include "error.h"
28 #include "debug.h"
29 #include "packet.h"
30 #include "socket.h"
31 #include "protocol.h"
32 #include "protostructs.h"
33 #include "record-internal.h"
34 #include "strnlen.h"
35 #include "configfile.h"
36 #include "platform.h"
37 #include <iomanip>
38 #include <errno.h>
39 #include <string.h>
40 #include "ios_state.h"
42 using namespace Usb;
44 namespace Barry {
46 unsigned char Intro_Sends[][32] = {
47 // packet #1
48 { 0x00, 0x00, 0x10, 0x00, 0x01, 0xff, 0x00, 0x00,
49 0xa8, 0x18, 0xda, 0x8d, 0x6c, 0x02, 0x00, 0x00 }
53 unsigned char Intro_Receives[][32] = {
54 // response to packet #1
55 { 0x00, 0x00, 0x10, 0x00, 0x02, 0xff, 0x00, 0x00,
56 0xa8, 0x18, 0xda, 0x8d, 0x6c, 0x02, 0x00, 0x00 }
59 namespace {
61 unsigned int GetSize(const unsigned char *packet)
63 const Protocol::Packet *pack = (const Protocol::Packet*) packet;
64 return btohs(pack->size);
67 bool Intro(int IntroIndex, const EndpointPair &ep, Device &dev, Data &response)
69 dev.BulkWrite(ep.write, Intro_Sends[IntroIndex],
70 GetSize(Intro_Sends[IntroIndex]));
71 try {
72 dev.BulkRead(ep.read, response, 500);
74 catch( Usb::Timeout &to ) {
75 ddout("BulkRead: " << to.what());
76 return false;
78 ddout("BulkRead (" << (unsigned int)ep.read << "):\n" << response);
79 return true;
82 } // anonymous namespace
85 bool Probe::CheckSize(const Data &data, unsigned int required)
87 const unsigned char *pd = data.GetData();
89 if( GetSize(pd) != (unsigned int) data.GetSize() ||
90 data.GetSize() < required ||
91 pd[4] != SB_COMMAND_FETCHED_ATTRIBUTE )
93 dout("Probe: Parse data failure: GetSize(pd): " << GetSize(pd)
94 << ", data.GetSize(): " << data.GetSize()
95 << ", pd[4]: " << (unsigned int) pd[4]);
96 return false;
99 return true;
102 bool Probe::ParsePIN(const Data &data, uint32_t &pin)
104 // validate response data
105 const unsigned char *pd = data.GetData();
107 if( !CheckSize(data, 0x14) )
108 return false;
110 // capture the PIN
111 memcpy(&pin, &pd[16], sizeof(pin));
112 pin = btohl(pin);
114 return true;
117 bool Probe::ParseDesc(const Data &data, std::string &desc)
119 if( !CheckSize(data, 29) )
120 return false;
122 // capture the description
123 const char *d = (const char*) &data.GetData()[28];
124 int maxlen = data.GetSize() - 28;
125 desc.assign(d, strnlen(d, maxlen));
127 return true;
130 Probe::Probe(const char *busname, const char *devname,
131 const Usb::EndpointPair *epp)
132 : m_fail_count(0)
133 , m_epp_override(epp)
135 if( m_epp_override ) {
136 m_epp = *epp;
139 // let the programmer pass in "" as well as 0
140 if( busname && !strlen(busname) )
141 busname = 0;
142 if( devname && !strlen(devname) )
143 devname = 0;
145 // Search for standard product ID first
146 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_BLACKBERRY, busname, devname);
148 // Search for Pearl devices second
150 // productID 6 devices (PRODUCT_RIM_PEARL) do not expose
151 // the USB class 255 interface we need, but only the
152 // Mass Storage one. Here we search for PRODUCT_RIM_PEARL_DUAL,
153 // (ID 4) which has both enabled.
154 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_PEARL_DUAL, busname, devname);
155 // And a special case, which behaves similar to the PEARL_DUAL,
156 // but with a unique Product ID.
157 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_PEARL_8120, busname, devname);
158 // And one more! The Pearl Flip
159 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_PEARL_FLIP, busname, devname);
161 // And one more time, for the Blackberry Storm
162 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_STORM, busname, devname);
165 void Probe::ProbeMatching(int vendor, int product,
166 const char *busname, const char *devname)
168 Usb::DeviceIDType devid;
170 Match match(vendor, product, busname, devname);
171 while( match.next_device(&devid) ) try {
172 ProbeDevice(devid);
174 catch( Usb::Error &e ) {
175 dout("Usb::Error exception caught: " << e.what());
176 if( e.libusb_errcode() == -EBUSY ) {
177 m_fail_count++;
178 m_fail_msgs.push_back(e.what());
180 else {
181 throw;
186 void Probe::ProbeDevice(Usb::DeviceIDType devid)
188 // skip if we can't properly discover device config
189 DeviceDiscovery discover(devid);
190 ConfigDesc &config = discover.configs[BLACKBERRY_CONFIGURATION];
192 // search for interface class
193 InterfaceDiscovery::base_type::iterator idi = config.interfaces.begin();
194 for( ; idi != config.interfaces.end(); idi++ ) {
195 if( idi->second.desc.bInterfaceClass == BLACKBERRY_DB_CLASS )
196 break;
198 if( idi == config.interfaces.end() ) {
199 dout("Probe: Interface with BLACKBERRY_DB_CLASS ("
200 << BLACKBERRY_DB_CLASS << ") not found.");
201 return; // not found
204 unsigned char InterfaceNumber = idi->second.desc.bInterfaceNumber;
205 dout("Probe: using InterfaceNumber: " << (unsigned int) InterfaceNumber);
207 // check endpoint validity
208 EndpointDiscovery &ed = config.interfaces[InterfaceNumber].endpoints;
209 if( !ed.IsValid() || ed.GetEndpointPairs().size() == 0 ) {
210 dout("Probe: endpoint invalid. ed.IsValud() == "
211 << (ed.IsValid() ? "true" : "false")
212 << ", ed.GetEndpointPairs().size() == "
213 << ed.GetEndpointPairs().size());
214 return;
217 ProbeResult result;
218 result.m_dev = devid;
219 result.m_interface = InterfaceNumber;
220 result.m_zeroSocketSequence = 0;
222 // open device
223 Device dev(devid);
224 // dev.Reset();
225 // sleep(5);
227 // make sure we're talking to the right config
228 unsigned char cfg;
229 if( !dev.GetConfiguration(cfg) )
230 throw Usb::Error(dev.GetLastError(),
231 "Probe: GetConfiguration failed");
232 if( cfg != BLACKBERRY_CONFIGURATION || MUST_SET_CONFIGURATION ) {
233 if( !dev.SetConfiguration(BLACKBERRY_CONFIGURATION) )
234 throw Usb::Error(dev.GetLastError(),
235 "Probe: SetConfiguration failed");
238 // open interface
239 Interface iface(dev, InterfaceNumber);
241 // Try the initial probing of endpoints
242 ProbeDeviceEndpoints(dev, ed, result);
244 if( !result.m_ep.IsComplete() ) {
245 // Probing of end-points failed, so try reprobing
246 // after calling usb_set_altinterface().
248 // Calling usb_set_altinterface() should be harmless
249 // and can help the host and device to synchronize the
250 // USB state, especially on FreeBSD and Mac OS X.
251 // However it can cause usb-storage URBs to be lost
252 // on some devices, so is only used if necessary.
253 dout("Probe: probing endpoints failed, retrying after setting alternate interface");
254 dev.SetAltInterface(InterfaceNumber);
255 result.m_needSetAltInterface = true;
256 ProbeDeviceEndpoints(dev, ed, result);
259 // add to list
260 if( result.m_ep.IsComplete() ) {
261 // before adding to list, try to load the device's
262 // friendly name from the configfile... but don't
263 // fail if we can't do it
264 try {
265 ConfigFile cfg(result.m_pin);
266 result.m_cfgDeviceName = cfg.GetDeviceName();
268 catch( Barry::ConfigFileError & ) {
269 // ignore...
272 m_results.push_back(result);
273 ddout("Using ReadEndpoint: " << (unsigned int)result.m_ep.read);
274 ddout(" WriteEndpoint: " << (unsigned int)result.m_ep.write);
276 else {
277 ddout("Unable to discover endpoint pair for one device.");
281 void Probe::ProbeDeviceEndpoints(Device &dev, EndpointDiscovery &ed, ProbeResult &result)
283 if( m_epp_override ) {
284 // user has given us endpoints to try... so try them
285 uint32_t pin;
286 uint8_t zeroSocketSequence;
287 std::string desc;
288 bool needClearHalt;
289 if( ProbePair(dev, m_epp, pin, desc, zeroSocketSequence, needClearHalt) ) {
290 // looks good, finish filling out the result
291 result.m_ep = m_epp;
292 result.m_pin = pin;
293 result.m_description = desc;
294 result.m_zeroSocketSequence = zeroSocketSequence;
295 result.m_needClearHalt = needClearHalt;
298 else {
299 // find the first bulk read/write endpoint pair that answers
300 // to our probe commands
301 // Start with second pair, since evidence indicates the later pairs
302 // are the ones we need.
303 size_t i;
304 for(i = ed.GetEndpointPairs().size() > 1 ? 1 : 0;
305 i < ed.GetEndpointPairs().size();
306 i++ )
308 const EndpointPair &ep = ed.GetEndpointPairs()[i];
309 if( ep.type == USB_ENDPOINT_TYPE_BULK ) {
311 uint32_t pin;
312 uint8_t zeroSocketSequence;
313 std::string desc;
314 bool needClearHalt;
315 if( ProbePair(dev, ep, pin, desc, zeroSocketSequence, needClearHalt) ) {
316 result.m_ep = ep;
317 result.m_pin = pin;
318 result.m_description = desc;
319 result.m_zeroSocketSequence = zeroSocketSequence;
320 result.m_needClearHalt = needClearHalt;
321 break;
324 else {
325 dout("Probe: Skipping non-bulk endpoint pair (offset: "
326 << i-1 << ") ");
330 // check for ip modem endpoints
331 i++;
332 if( i < ed.GetEndpointPairs().size() ) {
333 const EndpointPair &ep = ed.GetEndpointPairs()[i];
334 if( ProbeModem(dev, ep) ) {
335 result.m_epModem = ep;
341 bool Probe::ProbePair(Usb::Device &dev,
342 const Usb::EndpointPair &ep,
343 uint32_t &pin,
344 std::string &desc,
345 uint8_t &zeroSocketSequence,
346 bool &needClearHalt)
348 // Initially assume that clear halt isn't needed as it causes some
349 // devices to drop packets. The suspicion is that the toggle bits
350 // get out of sync, but this hasn't been confirmed with hardware
351 // tracing.
353 // It is possible to always use clear halt, as long as SET
354 // INTERFACE has been sent before, via usb_set_altinterface().
355 // However this has the side affect that any outstanding URBs
356 // on other interfaces (i.e. usb-storage) timeout and lose
357 // their data. This is not a good thing as it can corrupt the
358 // file system exposed over usb-storage. This also has the
359 // side-affect that usb-storage issues a port reset after the
360 // 30 second timeout, which kills any current Barry
361 // connection.
363 // To further complicate matters some devices, such as the
364 // 8830, always need clear halt before they will respond to
365 // probes.
367 // So to work with all these device quirks the probe is first
368 // attempted without calling clear halt. If that probe fails
369 // then a clear halt is issued followed by a retry on the
370 // probing.
371 needClearHalt = false;
373 Data data;
374 dev.BulkDrain(ep.read);
375 if( !Intro(0, ep, dev, data) ) {
376 // Try clearing halt and then reprobing
377 dout("Probe: Intro(0) failed, retrying after clearing halt");
378 dev.ClearHalt(ep.read);
379 dev.ClearHalt(ep.write);
380 needClearHalt = true;
381 // Retry
382 dev.BulkDrain(ep.read);
383 if( !Intro(0, ep, dev, data) ) {
384 // Still no response so fail the probe
385 dout("Probe: Intro(0) still failed after clearing halt");
386 return false;
390 SocketZero socket(dev, ep.write, ep.read);
392 Data send, receive;
393 ZeroPacket packet(send, receive);
395 // unknown attribute: 0x14 / 0x01
396 packet.GetAttribute(SB_OBJECT_INITIAL_UNKNOWN,
397 SB_ATTR_INITIAL_UNKNOWN);
398 socket.Send(packet);
400 // fetch PIN
401 packet.GetAttribute(SB_OBJECT_PROFILE, SB_ATTR_PROFILE_PIN);
402 socket.Send(packet);
403 if( packet.ObjectID() != SB_OBJECT_PROFILE ||
404 packet.AttributeID() != SB_ATTR_PROFILE_PIN ||
405 !ParsePIN(receive, pin) )
407 dout("Probe: unable to fetch PIN");
408 return false;
411 // fetch Description
412 packet.GetAttribute(SB_OBJECT_PROFILE, SB_ATTR_PROFILE_DESC);
413 socket.Send(packet);
414 // response ObjectID does not match request... :-/
415 if( // packet.ObjectID() != SB_OBJECT_PROFILE ||
416 packet.AttributeID() != SB_ATTR_PROFILE_DESC ||
417 !ParseDesc(receive, desc) )
419 dout("Probe: unable to fetch description");
422 // more unknowns:
423 for( uint16_t attr = 5; attr < 9; attr++ ) {
424 packet.GetAttribute(SB_OBJECT_SOCKET_UNKNOWN, attr);
425 socket.Send(packet);
426 // FIXME parse these responses, if they turn
427 // out to be important
430 // all info obtained!
431 zeroSocketSequence = socket.GetZeroSocketSequence();
432 return true;
435 bool Probe::ProbeModem(Usb::Device &dev, const Usb::EndpointPair &ep)
438 // This check is not needed for all devices. Some devices,
439 // like the 8700 have both the RIM_UsbSerData mode and IpModem mode.
441 // If this function is called, then we have extra endpoints,
442 // so might as well try them.
444 // FIXME - someday, we might wish to confirm that the endpoints
445 // work as a modem, and return true/false based on that test.
447 return true;
450 // Thanks to Rick Scott (XmBlackBerry:bb_usb.c) for reverse engineering this
451 // int num_read;
452 // char data[255];
453 // int local_errno;
455 // num_read = usb_control_msg(dev.GetHandle(),
456 // /* bmRequestType */ USB_ENDPOINT_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
457 // /* bRequest */ 0xa5,
458 // /* wValue */ 0,
459 // /* wIndex */ 1,
460 // /* data */ data,
461 // /* wLength */ sizeof(data),
462 // /* timeout */ 2000);
463 // local_errno = errno;
464 // if( num_read > 1 ) {
465 // if( data[0] == 0x02 ) {
466 // return true;
467 // }
468 // }
469 // return false;
472 int Probe::FindActive(Barry::Pin pin) const
474 return FindActive(m_results, pin);
477 int Probe::FindActive(const Barry::Probe::Results &results, Barry::Pin pin)
479 int i = Find(results, pin);
481 if( i == -1 && pin == 0 ) {
482 // can we default to a single device?
483 if( results.size() == 1 )
484 return 0; // yes!
487 return i;
490 int Probe::Find(const Results &results, Barry::Pin pin)
492 Barry::Probe::Results::const_iterator ci = results.begin();
493 for( int i = 0; ci != results.end(); i++, ++ci ) {
494 if( ci->m_pin == pin )
495 return i;
497 // PIN not found
498 return -1;
501 void ProbeResult::DumpAll(std::ostream &os) const
503 ios_format_state state(os);
505 os << *this
506 << ", Interface: 0x" << std::hex << (unsigned int) m_interface
507 << ", Endpoints: (read: 0x" << std::hex << (unsigned int) m_ep.read
508 << ", write: 0x" << std::hex << (unsigned int) m_ep.write
509 << ", type: 0x" << std::hex << (unsigned int) m_ep.type
510 << ", ZeroSocketSequence: 0x" << std::hex << (unsigned int) m_zeroSocketSequence;
513 std::ostream& operator<< (std::ostream &os, const ProbeResult &pr)
515 ios_format_state state(os);
517 os << "Device ID: " << pr.m_dev
518 << ". PIN: " << pr.m_pin.Str()
519 << ", Description: " << pr.m_description;
520 if( pr.m_cfgDeviceName.size() )
521 os << ", Name: " << pr.m_cfgDeviceName;
522 return os;
525 } // namespace Barry