Added missing string.h header to src/m_javaloader.cc
[barry.git] / src / probe.cc
blob5ca93a858ab1a8723de59f316d0f97aef04741cb
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 : m_fail_count(0)
128 // let the programmer pass in "" as well as 0
129 if( busname && !strlen(busname) )
130 busname = 0;
131 if( devname && !strlen(devname) )
132 devname = 0;
134 // Search for standard product ID first
135 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_BLACKBERRY, busname, devname);
137 // Search for Pearl devices second
139 // productID 6 devices (PRODUCT_RIM_PEARL) do not expose
140 // the USB class 255 interface we need, but only the
141 // Mass Storage one. Here we search for PRODUCT_RIM_PEARL_DUAL,
142 // (ID 4) which has both enabled.
143 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_PEARL_DUAL, busname, devname);
144 // And a special case, which behaves similar to the PEARL_DUAL,
145 // but with a unique Product ID.
146 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_PEARL_8120, busname, devname);
148 // And one more time, for the Blackberry Storm
149 ProbeMatching(VENDOR_RIM, PRODUCT_RIM_STORM, busname, devname);
152 void Probe::ProbeMatching(int vendor, int product,
153 const char *busname, const char *devname)
155 Usb::DeviceIDType devid;
157 Match match(vendor, product, busname, devname);
158 while( match.next_device(&devid) ) try {
159 ProbeDevice(devid);
161 catch( Usb::Error &e ) {
162 dout("Usb::Error exception caught: " << e.what());
163 if( e.libusb_errcode() == -EBUSY ) {
164 m_fail_count++;
165 m_fail_msgs.push_back(e.what());
167 else {
168 throw;
173 void Probe::ProbeDevice(Usb::DeviceIDType devid)
175 // skip if we can't properly discover device config
176 DeviceDiscovery discover(devid);
177 ConfigDesc &config = discover.configs[BLACKBERRY_CONFIGURATION];
179 // search for interface class
180 InterfaceDiscovery::base_type::iterator idi = config.interfaces.begin();
181 for( ; idi != config.interfaces.end(); idi++ ) {
182 if( idi->second.desc.bInterfaceClass == BLACKBERRY_DB_CLASS )
183 break;
185 if( idi == config.interfaces.end() ) {
186 dout("Probe: Interface with BLACKBERRY_DB_CLASS ("
187 << BLACKBERRY_DB_CLASS << ") not found.");
188 return; // not found
191 unsigned char InterfaceNumber = idi->second.desc.bInterfaceNumber;
192 dout("Probe: using InterfaceNumber: " << (unsigned int) InterfaceNumber);
194 // check endpoint validity
195 EndpointDiscovery &ed = config.interfaces[InterfaceNumber].endpoints;
196 if( !ed.IsValid() || ed.GetEndpointPairs().size() == 0 ) {
197 dout("Probe: endpoint invalid. ed.IsValud() == "
198 << (ed.IsValid() ? "true" : "false")
199 << ", ed.GetEndpointPairs().size() == "
200 << ed.GetEndpointPairs().size());
201 return;
204 ProbeResult result;
205 result.m_dev = devid;
206 result.m_interface = InterfaceNumber;
207 result.m_zeroSocketSequence = 0;
209 // open device
210 Device dev(devid);
211 // dev.Reset();
212 // sleep(5);
214 // make sure we're talking to the right config
215 unsigned char cfg;
216 if( !dev.GetConfiguration(cfg) )
217 throw Usb::Error(dev.GetLastError(),
218 "Probe: GetConfiguration failed");
219 if( cfg != BLACKBERRY_CONFIGURATION ) {
220 if( !dev.SetConfiguration(BLACKBERRY_CONFIGURATION) )
221 throw Usb::Error(dev.GetLastError(),
222 "Probe: SetConfiguration failed");
225 // open interface
226 Interface iface(dev, InterfaceNumber);
228 // find the first bulk read/write endpoint pair that answers
229 // to our probe commands
230 // Start with second pair, since evidence indicates the later pairs
231 // are the ones we need.
232 size_t i;
233 for(i = ed.GetEndpointPairs().size() > 1 ? 1 : 0;
234 i < ed.GetEndpointPairs().size();
235 i++ )
237 const EndpointPair &ep = ed.GetEndpointPairs()[i];
238 if( ep.type == USB_ENDPOINT_TYPE_BULK ) {
240 uint32_t pin;
241 uint8_t zeroSocketSequence;
242 std::string desc;
243 if( ProbePair(dev, ep, pin, desc, zeroSocketSequence) ) {
244 result.m_ep = ep;
245 result.m_pin = pin;
246 result.m_description = desc;
247 result.m_zeroSocketSequence = zeroSocketSequence;
248 break;
251 else {
252 dout("Probe: Skipping non-bulk endpoint pair (offset: "
253 << i-1 << ") ");
257 // check for ip modem endpoints
258 i++;
259 if( i < ed.GetEndpointPairs().size() ) {
260 const EndpointPair &ep = ed.GetEndpointPairs()[i];
261 if( ProbeModem(dev, ep) ) {
262 result.m_epModem = ep;
266 // add to list
267 if( result.m_ep.IsComplete() ) {
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 bool Probe::ProbePair(Usb::Device &dev,
278 const Usb::EndpointPair &ep,
279 uint32_t &pin,
280 std::string &desc,
281 uint8_t &zeroSocketSequence)
283 dev.ClearHalt(ep.read);
284 dev.ClearHalt(ep.write);
286 Data data;
287 dev.BulkDrain(ep.read);
288 if( !Intro(0, ep, dev, data) ) {
289 dout("Probe: Intro(0) failed");
290 return false;
293 SocketZero socket(dev, ep.write, ep.read);
295 Data send, receive;
296 ZeroPacket packet(send, receive);
298 // unknown attribute: 0x14 / 0x01
299 packet.GetAttribute(SB_OBJECT_INITIAL_UNKNOWN,
300 SB_ATTR_INITIAL_UNKNOWN);
301 socket.Send(packet);
303 // fetch PIN
304 packet.GetAttribute(SB_OBJECT_PROFILE, SB_ATTR_PROFILE_PIN);
305 socket.Send(packet);
306 if( packet.ObjectID() != SB_OBJECT_PROFILE ||
307 packet.AttributeID() != SB_ATTR_PROFILE_PIN ||
308 !ParsePIN(receive, pin) )
310 dout("Probe: unable to fetch PIN");
311 return false;
314 // fetch Description
315 packet.GetAttribute(SB_OBJECT_PROFILE, SB_ATTR_PROFILE_DESC);
316 socket.Send(packet);
317 // response ObjectID does not match request... :-/
318 if( // packet.ObjectID() != SB_OBJECT_PROFILE ||
319 packet.AttributeID() != SB_ATTR_PROFILE_DESC ||
320 !ParseDesc(receive, desc) )
322 dout("Probe: unable to fetch description");
325 // more unknowns:
326 for( uint16_t attr = 5; attr < 9; attr++ ) {
327 packet.GetAttribute(SB_OBJECT_SOCKET_UNKNOWN, attr);
328 socket.Send(packet);
329 // FIXME parse these responses, if they turn
330 // out to be important
333 // all info obtained!
334 zeroSocketSequence = socket.GetZeroSocketSequence();
335 return true;
338 bool Probe::ProbeModem(Usb::Device &dev, const Usb::EndpointPair &ep)
341 // This check is not needed for all devices. Some devices,
342 // like the 8700 have both the RIM_UsbSerData mode and IpModem mode.
344 // If this function is called, then we have extra endpoints,
345 // so might as well try them.
347 // FIXME - someday, we might wish to confirm that the endpoints
348 // work as a modem, and return true/false based on that test.
350 return true;
353 // Thanks to Rick Scott (XmBlackBerry:bb_usb.c) for reverse engineering this
354 // int num_read;
355 // char data[255];
356 // int local_errno;
358 // num_read = usb_control_msg(dev.GetHandle(),
359 // /* bmRequestType */ USB_ENDPOINT_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
360 // /* bRequest */ 0xa5,
361 // /* wValue */ 0,
362 // /* wIndex */ 1,
363 // /* data */ data,
364 // /* wLength */ sizeof(data),
365 // /* timeout */ 2000);
366 // local_errno = errno;
367 // if( num_read > 1 ) {
368 // if( data[0] == 0x02 ) {
369 // return true;
370 // }
371 // }
372 // return false;
375 int Probe::FindActive(uint32_t pin) const
377 for( int i = 0; i < GetCount(); i++ ) {
378 if( Get(i).m_pin == pin )
379 return i;
381 if( pin == 0 ) {
382 // can we default to a single device?
383 if( GetCount() == 1 )
384 return 0; // yes!
387 // PIN not found
388 return -1;
391 void ProbeResult::DumpAll(std::ostream &os) const
393 os << *this
394 << ", Interface: 0x" << std::hex << (unsigned int) m_interface
395 << ", Endpoints: (read: 0x" << std::hex << (unsigned int) m_ep.read
396 << ", write: 0x" << std::hex << (unsigned int) m_ep.write
397 << ", type: 0x" << std::hex << (unsigned int) m_ep.type
398 << ", ZeroSocketSequence: 0x" << std::hex << (unsigned int) m_zeroSocketSequence;
401 std::ostream& operator<< (std::ostream &os, const ProbeResult &pr)
403 os << "Device ID: " << pr.m_dev
404 << std::hex << ". PIN: " << pr.m_pin
405 << ", Description: " << pr.m_description;
406 return os;
409 } // namespace Barry