Updated ChangeLog and whitespace
[barry.git] / src / probe.cc
blob80bcdd91fbcbf442f4c9519b273e2bc00615f5b0
1 ///
2 /// \file probe.cc
3 /// USB Blackberry detection routines
4 ///
6 /*
7 Copyright (C) 2005-2010, 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 "record-internal.h"
33 #include "strnlen.h"
34 #include "configfile.h"
35 #include <iomanip>
36 #include <errno.h>
37 #include <string.h>
39 using namespace Usb;
41 namespace Barry {
43 unsigned char Intro_Sends[][32] = {
44 // packet #1
45 { 0x00, 0x00, 0x10, 0x00, 0x01, 0xff, 0x00, 0x00,
46 0xa8, 0x18, 0xda, 0x8d, 0x6c, 0x02, 0x00, 0x00 }
50 unsigned char Intro_Receives[][32] = {
51 // response to packet #1
52 { 0x00, 0x00, 0x10, 0x00, 0x02, 0xff, 0x00, 0x00,
53 0xa8, 0x18, 0xda, 0x8d, 0x6c, 0x02, 0x00, 0x00 }
56 namespace {
58 unsigned int GetSize(const unsigned char *packet)
60 uint16_t size = *((uint16_t *)&packet[2]);
61 return btohs(size);
64 bool Intro(int IntroIndex, const EndpointPair &ep, Device &dev, Data &response)
66 dev.BulkWrite(ep.write, Intro_Sends[IntroIndex],
67 GetSize(Intro_Sends[IntroIndex]));
68 try {
69 dev.BulkRead(ep.read, response, 500);
71 catch( Usb::Timeout &to ) {
72 ddout("BulkRead: " << to.what());
73 return false;
75 ddout("BulkRead (" << (unsigned int)ep.read << "):\n" << response);
76 return true;
79 } // anonymous namespace
82 bool Probe::CheckSize(const Data &data, unsigned int required)
84 const unsigned char *pd = data.GetData();
86 if( GetSize(pd) != (unsigned int) data.GetSize() ||
87 data.GetSize() < required ||
88 pd[4] != SB_COMMAND_FETCHED_ATTRIBUTE )
90 dout("Probe: Parse data failure: GetSize(pd): " << GetSize(pd)
91 << ", data.GetSize(): " << data.GetSize()
92 << ", pd[4]: " << (unsigned int) pd[4]);
93 return false;
96 return true;
99 bool Probe::ParsePIN(const Data &data, uint32_t &pin)
101 // validate response data
102 const unsigned char *pd = data.GetData();
104 if( !CheckSize(data, 0x14) )
105 return false;
107 // capture the PIN
108 pin = btohl(*((uint32_t *) &pd[16]));
110 return true;
113 bool Probe::ParseDesc(const Data &data, std::string &desc)
115 if( !CheckSize(data, 29) )
116 return false;
118 // capture the description
119 const char *d = (const char*) &data.GetData()[28];
120 int maxlen = data.GetSize() - 28;
121 desc.assign(d, strnlen(d, maxlen));
123 return true;
126 Probe::Probe(const char *busname, const char *devname,
127 const Usb::EndpointPair *epp)
128 : m_fail_count(0)
129 , m_epp_override(epp)
131 if( m_epp_override ) {
132 m_epp = *epp;
135 // let the programmer pass in "" as well as 0
136 if( busname && !strlen(busname) )
137 busname = 0;
138 if( devname && !strlen(devname) )
139 devname = 0;
141 // Search for standard product ID first
142 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_BLACKBERRY, busname, devname);
144 // Search for Pearl devices second
146 // productID 6 devices (PRODUCT_RIM_PEARL) do not expose
147 // the USB class 255 interface we need, but only the
148 // Mass Storage one. Here we search for PRODUCT_RIM_PEARL_DUAL,
149 // (ID 4) which has both enabled.
150 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_PEARL_DUAL, busname, devname);
151 // And a special case, which behaves similar to the PEARL_DUAL,
152 // but with a unique Product ID.
153 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_PEARL_8120, busname, devname);
154 // And one more! The Pearl Flip
155 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_PEARL_FLIP, busname, devname);
157 // And one more time, for the Blackberry Storm
158 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_STORM, busname, devname);
161 void Probe::ProbeMatching(int vendor, int product,
162 const char *busname, const char *devname)
164 Usb::DeviceIDType devid;
166 Match match(vendor, product, busname, devname);
167 while( match.next_device(&devid) ) try {
168 ProbeDevice(devid);
170 catch( Usb::Error &e ) {
171 dout("Usb::Error exception caught: " << e.what());
172 if( e.libusb_errcode() == -EBUSY ) {
173 m_fail_count++;
174 m_fail_msgs.push_back(e.what());
176 else {
177 throw;
182 void Probe::ProbeDevice(Usb::DeviceIDType devid)
184 // skip if we can't properly discover device config
185 DeviceDiscovery discover(devid);
186 ConfigDesc &config = discover.configs[BLACKBERRY_CONFIGURATION];
188 // search for interface class
189 InterfaceDiscovery::base_type::iterator idi = config.interfaces.begin();
190 for( ; idi != config.interfaces.end(); idi++ ) {
191 if( idi->second.desc.bInterfaceClass == BLACKBERRY_DB_CLASS )
192 break;
194 if( idi == config.interfaces.end() ) {
195 dout("Probe: Interface with BLACKBERRY_DB_CLASS ("
196 << BLACKBERRY_DB_CLASS << ") not found.");
197 return; // not found
200 unsigned char InterfaceNumber = idi->second.desc.bInterfaceNumber;
201 dout("Probe: using InterfaceNumber: " << (unsigned int) InterfaceNumber);
203 // check endpoint validity
204 EndpointDiscovery &ed = config.interfaces[InterfaceNumber].endpoints;
205 if( !ed.IsValid() || ed.GetEndpointPairs().size() == 0 ) {
206 dout("Probe: endpoint invalid. ed.IsValud() == "
207 << (ed.IsValid() ? "true" : "false")
208 << ", ed.GetEndpointPairs().size() == "
209 << ed.GetEndpointPairs().size());
210 return;
213 ProbeResult result;
214 result.m_dev = devid;
215 result.m_interface = InterfaceNumber;
216 result.m_zeroSocketSequence = 0;
218 // open device
219 Device dev(devid);
220 // dev.Reset();
221 // sleep(5);
223 // make sure we're talking to the right config
224 unsigned char cfg;
225 if( !dev.GetConfiguration(cfg) )
226 throw Usb::Error(dev.GetLastError(),
227 "Probe: GetConfiguration failed");
228 if( cfg != BLACKBERRY_CONFIGURATION ) {
229 if( !dev.SetConfiguration(BLACKBERRY_CONFIGURATION) )
230 throw Usb::Error(dev.GetLastError(),
231 "Probe: SetConfiguration failed");
234 // open interface
235 Interface iface(dev, InterfaceNumber);
237 // Try the initial probing of endpoints
238 ProbeDeviceEndpoints(dev, ed, result);
240 if( !result.m_ep.IsComplete() ) {
241 // Probing of end-points failed, so try reprobing
242 // after calling usb_set_altinterface().
244 // Calling usb_set_altinterface() should be harmless
245 // and can help the host and device to synchronize the
246 // USB state, especially on FreeBSD and Mac OS X.
247 // However it can cause usb-storage URBs to be lost
248 // on some devices, so is only used if necessary.
249 dout("Probe: probing endpoints failed, retrying after setting alternate interface");
250 dev.SetAltInterface(InterfaceNumber);
251 result.m_needSetAltInterface = true;
252 ProbeDeviceEndpoints(dev, ed, result);
255 // add to list
256 if( result.m_ep.IsComplete() ) {
257 // before adding to list, try to load the device's
258 // friendly name from the configfile... but don't
259 // fail if we can't do it
260 try {
261 ConfigFile cfg(result.m_pin);
262 result.m_cfgDeviceName = cfg.GetDeviceName();
264 catch( Barry::ConfigFileError & ) {
265 // ignore...
268 m_results.push_back(result);
269 ddout("Using ReadEndpoint: " << (unsigned int)result.m_ep.read);
270 ddout(" WriteEndpoint: " << (unsigned int)result.m_ep.write);
272 else {
273 ddout("Unable to discover endpoint pair for one device.");
277 void Probe::ProbeDeviceEndpoints(Device &dev, EndpointDiscovery &ed, ProbeResult &result)
279 if( m_epp_override ) {
280 // user has given us endpoints to try... so try them
281 uint32_t pin;
282 uint8_t zeroSocketSequence;
283 std::string desc;
284 bool needClearHalt;
285 if( ProbePair(dev, m_epp, pin, desc, zeroSocketSequence, needClearHalt) ) {
286 // looks good, finish filling out the result
287 result.m_ep = m_epp;
288 result.m_pin = pin;
289 result.m_description = desc;
290 result.m_zeroSocketSequence = zeroSocketSequence;
291 result.m_needClearHalt = needClearHalt;
294 else {
295 // find the first bulk read/write endpoint pair that answers
296 // to our probe commands
297 // Start with second pair, since evidence indicates the later pairs
298 // are the ones we need.
299 size_t i;
300 for(i = ed.GetEndpointPairs().size() > 1 ? 1 : 0;
301 i < ed.GetEndpointPairs().size();
302 i++ )
304 const EndpointPair &ep = ed.GetEndpointPairs()[i];
305 if( ep.type == USB_ENDPOINT_TYPE_BULK ) {
307 uint32_t pin;
308 uint8_t zeroSocketSequence;
309 std::string desc;
310 bool needClearHalt;
311 if( ProbePair(dev, ep, pin, desc, zeroSocketSequence, needClearHalt) ) {
312 result.m_ep = ep;
313 result.m_pin = pin;
314 result.m_description = desc;
315 result.m_zeroSocketSequence = zeroSocketSequence;
316 result.m_needClearHalt = needClearHalt;
317 break;
320 else {
321 dout("Probe: Skipping non-bulk endpoint pair (offset: "
322 << i-1 << ") ");
326 // check for ip modem endpoints
327 i++;
328 if( i < ed.GetEndpointPairs().size() ) {
329 const EndpointPair &ep = ed.GetEndpointPairs()[i];
330 if( ProbeModem(dev, ep) ) {
331 result.m_epModem = ep;
337 bool Probe::ProbePair(Usb::Device &dev,
338 const Usb::EndpointPair &ep,
339 uint32_t &pin,
340 std::string &desc,
341 uint8_t &zeroSocketSequence,
342 bool &needClearHalt)
344 // Initially assume that clear halt isn't needed as it causes some
345 // devices to drop packets. The suspicion is that the toggle bits
346 // get out of sync, but this hasn't been confirmed with hardware
347 // tracing.
349 // It is possible to always use clear halt, as long as SET
350 // INTERFACE has been sent before, via usb_set_altinterface().
351 // However this has the side affect that any outstanding URBs
352 // on other interfaces (i.e. usb-storage) timeout and lose
353 // their data. This is not a good thing as it can corrupt the
354 // file system exposed over usb-storage. This also has the
355 // side-affect that usb-storage issues a port reset after the
356 // 30 second timeout, which kills any current Barry
357 // connection.
359 // To further complicate matters some devices, such as the
360 // 8830, always need clear halt before they will respond to
361 // probes.
363 // So to work with all these device quirks the probe is first
364 // attempted without calling clear halt. If that probe fails
365 // then a clear halt is issued followed by a retry on the
366 // probing.
367 needClearHalt = false;
369 Data data;
370 dev.BulkDrain(ep.read);
371 if( !Intro(0, ep, dev, data) ) {
372 // Try clearing halt and then reprobing
373 dout("Probe: Intro(0) failed, retrying after clearing halt");
374 dev.ClearHalt(ep.read);
375 dev.ClearHalt(ep.write);
376 needClearHalt = true;
377 // Retry
378 dev.BulkDrain(ep.read);
379 if( !Intro(0, ep, dev, data) ) {
380 // Still no response so fail the probe
381 dout("Probe: Intro(0) still failed after clearing halt");
382 return false;
386 SocketZero socket(dev, ep.write, ep.read);
388 Data send, receive;
389 ZeroPacket packet(send, receive);
391 // unknown attribute: 0x14 / 0x01
392 packet.GetAttribute(SB_OBJECT_INITIAL_UNKNOWN,
393 SB_ATTR_INITIAL_UNKNOWN);
394 socket.Send(packet);
396 // fetch PIN
397 packet.GetAttribute(SB_OBJECT_PROFILE, SB_ATTR_PROFILE_PIN);
398 socket.Send(packet);
399 if( packet.ObjectID() != SB_OBJECT_PROFILE ||
400 packet.AttributeID() != SB_ATTR_PROFILE_PIN ||
401 !ParsePIN(receive, pin) )
403 dout("Probe: unable to fetch PIN");
404 return false;
407 // fetch Description
408 packet.GetAttribute(SB_OBJECT_PROFILE, SB_ATTR_PROFILE_DESC);
409 socket.Send(packet);
410 // response ObjectID does not match request... :-/
411 if( // packet.ObjectID() != SB_OBJECT_PROFILE ||
412 packet.AttributeID() != SB_ATTR_PROFILE_DESC ||
413 !ParseDesc(receive, desc) )
415 dout("Probe: unable to fetch description");
418 // more unknowns:
419 for( uint16_t attr = 5; attr < 9; attr++ ) {
420 packet.GetAttribute(SB_OBJECT_SOCKET_UNKNOWN, attr);
421 socket.Send(packet);
422 // FIXME parse these responses, if they turn
423 // out to be important
426 // all info obtained!
427 zeroSocketSequence = socket.GetZeroSocketSequence();
428 return true;
431 bool Probe::ProbeModem(Usb::Device &dev, const Usb::EndpointPair &ep)
434 // This check is not needed for all devices. Some devices,
435 // like the 8700 have both the RIM_UsbSerData mode and IpModem mode.
437 // If this function is called, then we have extra endpoints,
438 // so might as well try them.
440 // FIXME - someday, we might wish to confirm that the endpoints
441 // work as a modem, and return true/false based on that test.
443 return true;
446 // Thanks to Rick Scott (XmBlackBerry:bb_usb.c) for reverse engineering this
447 // int num_read;
448 // char data[255];
449 // int local_errno;
451 // num_read = usb_control_msg(dev.GetHandle(),
452 // /* bmRequestType */ USB_ENDPOINT_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
453 // /* bRequest */ 0xa5,
454 // /* wValue */ 0,
455 // /* wIndex */ 1,
456 // /* data */ data,
457 // /* wLength */ sizeof(data),
458 // /* timeout */ 2000);
459 // local_errno = errno;
460 // if( num_read > 1 ) {
461 // if( data[0] == 0x02 ) {
462 // return true;
463 // }
464 // }
465 // return false;
468 int Probe::FindActive(Barry::Pin pin) const
470 return FindActive(m_results, pin);
473 int Probe::FindActive(const Barry::Probe::Results &results, Barry::Pin pin)
475 int i = Find(results, pin);
477 if( i == -1 && pin == 0 ) {
478 // can we default to a single device?
479 if( results.size() == 1 )
480 return 0; // yes!
483 return i;
486 int Probe::Find(const Results &results, Barry::Pin pin)
488 Barry::Probe::Results::const_iterator ci = results.begin();
489 for( int i = 0; ci != results.end(); i++, ++ci ) {
490 if( ci->m_pin == pin )
491 return i;
493 // PIN not found
494 return -1;
497 void ProbeResult::DumpAll(std::ostream &os) const
499 os << *this
500 << ", Interface: 0x" << std::hex << (unsigned int) m_interface
501 << ", Endpoints: (read: 0x" << std::hex << (unsigned int) m_ep.read
502 << ", write: 0x" << std::hex << (unsigned int) m_ep.write
503 << ", type: 0x" << std::hex << (unsigned int) m_ep.type
504 << ", ZeroSocketSequence: 0x" << std::hex << (unsigned int) m_zeroSocketSequence;
507 std::ostream& operator<< (std::ostream &os, const ProbeResult &pr)
509 os << "Device ID: " << pr.m_dev
510 << ". PIN: " << pr.m_pin.str()
511 << ", Description: " << pr.m_description;
512 if( pr.m_cfgDeviceName.size() )
513 os << ", Name: " << pr.m_cfgDeviceName;
514 return os;
517 } // namespace Barry