Added Barry::JDWP::Error and Timeout exceptions to doc/Exceptions
[barry.git] / src / probe.cc
bloba132fff2ac9841ea5ffd746c8a2655f500794cf6
1 ///
2 /// \file probe.cc
3 /// USB Blackberry detection routines
4 ///
6 /*
7 Copyright (C) 2005-2009, 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 <iomanip>
35 #include <errno.h>
36 #include <string.h>
38 using namespace Usb;
40 namespace Barry {
42 unsigned char Intro_Sends[][32] = {
43 // packet #1
44 { 0x00, 0x00, 0x10, 0x00, 0x01, 0xff, 0x00, 0x00,
45 0xa8, 0x18, 0xda, 0x8d, 0x6c, 0x02, 0x00, 0x00 }
49 unsigned char Intro_Receives[][32] = {
50 // response to packet #1
51 { 0x00, 0x00, 0x10, 0x00, 0x02, 0xff, 0x00, 0x00,
52 0xa8, 0x18, 0xda, 0x8d, 0x6c, 0x02, 0x00, 0x00 }
55 namespace {
57 unsigned int GetSize(const unsigned char *packet)
59 uint16_t size = *((uint16_t *)&packet[2]);
60 return btohs(size);
63 bool Intro(int IntroIndex, const EndpointPair &ep, Device &dev, Data &response)
65 dev.BulkWrite(ep.write, Intro_Sends[IntroIndex],
66 GetSize(Intro_Sends[IntroIndex]));
67 try {
68 dev.BulkRead(ep.read, response, 500);
70 catch( Usb::Timeout &to ) {
71 ddout("BulkRead: " << to.what());
72 return false;
74 ddout("BulkRead (" << (unsigned int)ep.read << "):\n" << response);
75 return true;
78 } // anonymous namespace
81 bool Probe::CheckSize(const Data &data, unsigned int required)
83 const unsigned char *pd = data.GetData();
85 if( GetSize(pd) != (unsigned int) data.GetSize() ||
86 data.GetSize() < required ||
87 pd[4] != SB_COMMAND_FETCHED_ATTRIBUTE )
89 dout("Probe: Parse data failure: GetSize(pd): " << GetSize(pd)
90 << ", data.GetSize(): " << data.GetSize()
91 << ", pd[4]: " << (unsigned int) pd[4]);
92 return false;
95 return true;
98 bool Probe::ParsePIN(const Data &data, uint32_t &pin)
100 // validate response data
101 const unsigned char *pd = data.GetData();
103 if( !CheckSize(data, 0x14) )
104 return false;
106 // capture the PIN
107 pin = btohl(*((uint32_t *) &pd[16]));
109 return true;
112 bool Probe::ParseDesc(const Data &data, std::string &desc)
114 if( !CheckSize(data, 29) )
115 return false;
117 // capture the description
118 const char *d = (const char*) &data.GetData()[28];
119 int maxlen = data.GetSize() - 28;
120 desc.assign(d, strnlen(d, maxlen));
122 return true;
125 Probe::Probe(const char *busname, const char *devname,
126 const Usb::EndpointPair *epp)
127 : m_fail_count(0)
128 , m_epp_override(epp)
130 if( m_epp_override ) {
131 m_epp = *epp;
134 // let the programmer pass in "" as well as 0
135 if( busname && !strlen(busname) )
136 busname = 0;
137 if( devname && !strlen(devname) )
138 devname = 0;
140 // Search for standard product ID first
141 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_BLACKBERRY, busname, devname);
143 // Search for Pearl devices second
145 // productID 6 devices (PRODUCT_RIM_PEARL) do not expose
146 // the USB class 255 interface we need, but only the
147 // Mass Storage one. Here we search for PRODUCT_RIM_PEARL_DUAL,
148 // (ID 4) which has both enabled.
149 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_PEARL_DUAL, busname, devname);
150 // And a special case, which behaves similar to the PEARL_DUAL,
151 // but with a unique Product ID.
152 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_PEARL_8120, busname, devname);
153 // And one more! The Pearl Flip
154 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_PEARL_FLIP, busname, devname);
156 // And one more time, for the Blackberry Storm
157 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_STORM, busname, devname);
160 void Probe::ProbeMatching(int vendor, int product,
161 const char *busname, const char *devname)
163 Usb::DeviceIDType devid;
165 Match match(vendor, product, busname, devname);
166 while( match.next_device(&devid) ) try {
167 ProbeDevice(devid);
169 catch( Usb::Error &e ) {
170 dout("Usb::Error exception caught: " << e.what());
171 if( e.libusb_errcode() == -EBUSY ) {
172 m_fail_count++;
173 m_fail_msgs.push_back(e.what());
175 else {
176 throw;
181 void Probe::ProbeDevice(Usb::DeviceIDType devid)
183 // skip if we can't properly discover device config
184 DeviceDiscovery discover(devid);
185 ConfigDesc &config = discover.configs[BLACKBERRY_CONFIGURATION];
187 // search for interface class
188 InterfaceDiscovery::base_type::iterator idi = config.interfaces.begin();
189 for( ; idi != config.interfaces.end(); idi++ ) {
190 if( idi->second.desc.bInterfaceClass == BLACKBERRY_DB_CLASS )
191 break;
193 if( idi == config.interfaces.end() ) {
194 dout("Probe: Interface with BLACKBERRY_DB_CLASS ("
195 << BLACKBERRY_DB_CLASS << ") not found.");
196 return; // not found
199 unsigned char InterfaceNumber = idi->second.desc.bInterfaceNumber;
200 dout("Probe: using InterfaceNumber: " << (unsigned int) InterfaceNumber);
202 // check endpoint validity
203 EndpointDiscovery &ed = config.interfaces[InterfaceNumber].endpoints;
204 if( !ed.IsValid() || ed.GetEndpointPairs().size() == 0 ) {
205 dout("Probe: endpoint invalid. ed.IsValud() == "
206 << (ed.IsValid() ? "true" : "false")
207 << ", ed.GetEndpointPairs().size() == "
208 << ed.GetEndpointPairs().size());
209 return;
212 ProbeResult result;
213 result.m_dev = devid;
214 result.m_interface = InterfaceNumber;
215 result.m_zeroSocketSequence = 0;
217 // open device
218 Device dev(devid);
219 // dev.Reset();
220 // sleep(5);
222 // make sure we're talking to the right config
223 unsigned char cfg;
224 if( !dev.GetConfiguration(cfg) )
225 throw Usb::Error(dev.GetLastError(),
226 "Probe: GetConfiguration failed");
227 if( cfg != BLACKBERRY_CONFIGURATION ) {
228 if( !dev.SetConfiguration(BLACKBERRY_CONFIGURATION) )
229 throw Usb::Error(dev.GetLastError(),
230 "Probe: SetConfiguration failed");
233 // open interface
234 Interface iface(dev, InterfaceNumber);
236 if( m_epp_override ) {
237 // user has given us endpoints to try... so try them
238 uint32_t pin;
239 uint8_t zeroSocketSequence;
240 std::string desc;
241 if( ProbePair(dev, m_epp, pin, desc, zeroSocketSequence) ) {
242 // looks good, finish filling out the result
243 result.m_ep = m_epp;
244 result.m_pin = pin;
245 result.m_description = desc;
246 result.m_zeroSocketSequence = zeroSocketSequence;
249 else {
250 // find the first bulk read/write endpoint pair that answers
251 // to our probe commands
252 // Start with second pair, since evidence indicates the later pairs
253 // are the ones we need.
254 size_t i;
255 for(i = ed.GetEndpointPairs().size() > 1 ? 1 : 0;
256 i < ed.GetEndpointPairs().size();
257 i++ )
259 const EndpointPair &ep = ed.GetEndpointPairs()[i];
260 if( ep.type == USB_ENDPOINT_TYPE_BULK ) {
262 uint32_t pin;
263 uint8_t zeroSocketSequence;
264 std::string desc;
265 if( ProbePair(dev, ep, pin, desc, zeroSocketSequence) ) {
266 result.m_ep = ep;
267 result.m_pin = pin;
268 result.m_description = desc;
269 result.m_zeroSocketSequence = zeroSocketSequence;
270 break;
273 else {
274 dout("Probe: Skipping non-bulk endpoint pair (offset: "
275 << i-1 << ") ");
279 // check for ip modem endpoints
280 i++;
281 if( i < ed.GetEndpointPairs().size() ) {
282 const EndpointPair &ep = ed.GetEndpointPairs()[i];
283 if( ProbeModem(dev, ep) ) {
284 result.m_epModem = ep;
289 // add to list
290 if( result.m_ep.IsComplete() ) {
291 m_results.push_back(result);
292 ddout("Using ReadEndpoint: " << (unsigned int)result.m_ep.read);
293 ddout(" WriteEndpoint: " << (unsigned int)result.m_ep.write);
295 else {
296 ddout("Unable to discover endpoint pair for one device.");
300 bool Probe::ProbePair(Usb::Device &dev,
301 const Usb::EndpointPair &ep,
302 uint32_t &pin,
303 std::string &desc,
304 uint8_t &zeroSocketSequence)
306 dev.ClearHalt(ep.read);
307 dev.ClearHalt(ep.write);
309 Data data;
310 dev.BulkDrain(ep.read);
311 if( !Intro(0, ep, dev, data) ) {
312 dout("Probe: Intro(0) failed");
313 return false;
316 SocketZero socket(dev, ep.write, ep.read);
318 Data send, receive;
319 ZeroPacket packet(send, receive);
321 // unknown attribute: 0x14 / 0x01
322 packet.GetAttribute(SB_OBJECT_INITIAL_UNKNOWN,
323 SB_ATTR_INITIAL_UNKNOWN);
324 socket.Send(packet);
326 // fetch PIN
327 packet.GetAttribute(SB_OBJECT_PROFILE, SB_ATTR_PROFILE_PIN);
328 socket.Send(packet);
329 if( packet.ObjectID() != SB_OBJECT_PROFILE ||
330 packet.AttributeID() != SB_ATTR_PROFILE_PIN ||
331 !ParsePIN(receive, pin) )
333 dout("Probe: unable to fetch PIN");
334 return false;
337 // fetch Description
338 packet.GetAttribute(SB_OBJECT_PROFILE, SB_ATTR_PROFILE_DESC);
339 socket.Send(packet);
340 // response ObjectID does not match request... :-/
341 if( // packet.ObjectID() != SB_OBJECT_PROFILE ||
342 packet.AttributeID() != SB_ATTR_PROFILE_DESC ||
343 !ParseDesc(receive, desc) )
345 dout("Probe: unable to fetch description");
348 // more unknowns:
349 for( uint16_t attr = 5; attr < 9; attr++ ) {
350 packet.GetAttribute(SB_OBJECT_SOCKET_UNKNOWN, attr);
351 socket.Send(packet);
352 // FIXME parse these responses, if they turn
353 // out to be important
356 // all info obtained!
357 zeroSocketSequence = socket.GetZeroSocketSequence();
358 return true;
361 bool Probe::ProbeModem(Usb::Device &dev, const Usb::EndpointPair &ep)
364 // This check is not needed for all devices. Some devices,
365 // like the 8700 have both the RIM_UsbSerData mode and IpModem mode.
367 // If this function is called, then we have extra endpoints,
368 // so might as well try them.
370 // FIXME - someday, we might wish to confirm that the endpoints
371 // work as a modem, and return true/false based on that test.
373 return true;
376 // Thanks to Rick Scott (XmBlackBerry:bb_usb.c) for reverse engineering this
377 // int num_read;
378 // char data[255];
379 // int local_errno;
381 // num_read = usb_control_msg(dev.GetHandle(),
382 // /* bmRequestType */ USB_ENDPOINT_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
383 // /* bRequest */ 0xa5,
384 // /* wValue */ 0,
385 // /* wIndex */ 1,
386 // /* data */ data,
387 // /* wLength */ sizeof(data),
388 // /* timeout */ 2000);
389 // local_errno = errno;
390 // if( num_read > 1 ) {
391 // if( data[0] == 0x02 ) {
392 // return true;
393 // }
394 // }
395 // return false;
398 int Probe::FindActive(uint32_t pin) const
400 for( int i = 0; i < GetCount(); i++ ) {
401 if( Get(i).m_pin == pin )
402 return i;
404 if( pin == 0 ) {
405 // can we default to a single device?
406 if( GetCount() == 1 )
407 return 0; // yes!
410 // PIN not found
411 return -1;
414 void ProbeResult::DumpAll(std::ostream &os) const
416 os << *this
417 << ", Interface: 0x" << std::hex << (unsigned int) m_interface
418 << ", Endpoints: (read: 0x" << std::hex << (unsigned int) m_ep.read
419 << ", write: 0x" << std::hex << (unsigned int) m_ep.write
420 << ", type: 0x" << std::hex << (unsigned int) m_ep.type
421 << ", ZeroSocketSequence: 0x" << std::hex << (unsigned int) m_zeroSocketSequence;
424 std::ostream& operator<< (std::ostream &os, const ProbeResult &pr)
426 os << "Device ID: " << pr.m_dev
427 << std::hex << ". PIN: " << pr.m_pin
428 << ", Description: " << pr.m_description;
429 return os;
432 } // namespace Barry