3 /// Barry library tester
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 <barry/barry.h>
35 using namespace Barry
;
40 const char *Version
= Barry::Version(major
, minor
);
43 << "btool - Command line USB Blackberry Test Tool\n"
44 << " Copyright 2005-2010, Net Direct Inc. (http://www.netdirect.ca/)\n"
45 << " Using: " << Version
<< "\n"
47 #ifdef __BARRY_BOOST_MODE__
54 << " -B bus Specify which USB bus to search on\n"
55 << " -N dev Specify which system device, using system specific string\n"
57 << " -a db Erase / clear database 'db' FROM device, deleting all\n"
58 << " its records. Can be used multiple times to clear more\n"
60 << " -c dn Convert address book database to LDIF format, using the\n"
61 << " specified baseDN\n"
62 << " -C dnattr LDIF attribute name to use when building the FQDN\n"
63 << " Defaults to 'cn'\n"
64 << " -d db Load database 'db' FROM device and dump to screen\n"
65 << " Can be used multiple times to fetch more than one DB\n"
66 << " -e epp Override endpoint pair detection. 'epp' is a single\n"
67 << " string separated by a comma, holding the read,write\n"
68 << " endpoint pair. Example: -e 83,5\n"
69 << " Note: Endpoints are specified in hex.\n"
70 << " You should never need to use this option.\n"
71 #ifdef __BARRY_BOOST_MODE__
72 << " -f file Filename to save or load handheld data to/from\n"
75 << " -i cs International charset for string conversions\n"
76 << " Valid values here are available with 'iconv --list'\n"
77 << " -I Sort records before output\n"
78 << " -l List devices\n"
79 << " -L List Contact field names\n"
80 << " -m Map LDIF name to Contact field / Unmap LDIF name\n"
81 << " Map: ldif,read,write - maps ldif to read/write Contact fields\n"
82 << " Unmap: ldif name alone\n"
83 << " -M List current LDIF mapping\n"
84 << " -n Use null parser on all databases.\n"
85 << " -p pin PIN of device to talk with\n"
86 << " If only one device is plugged in, this flag is optional\n"
87 << " -P pass Simplistic method to specify device password\n"
88 << " -s db Save database 'db' TO device from data loaded from -f file\n"
89 << " -S Show list of supported database parsers\n"
90 << " -t Show database database table\n"
91 << " -T db Show record state table for given database\n"
92 << " -v Dump protocol data during operation\n"
93 << " -X Reset device\n"
94 << " -z Use non-threaded sockets\n"
95 << " -Z Use threaded socket router (default)\n"
97 << " -d Command modifiers: (can be used multiple times for more than 1 record)\n"
99 << " -r # Record index number as seen in the -T state table.\n"
100 << " This overrides the default -d behaviour, and only\n"
101 << " downloads the one specified record, sending to stdout.\n"
102 << " -R # Same as -r, but also clears the record's dirty flags.\n"
103 << " -D # Record index number as seen in the -T state table,\n"
104 << " which indicates the record to delete. Used with the -d\n"
105 << " command to specify the database.\n"
112 Barry::ContactLdif
&ldif
;
114 Contact2Ldif(Barry::ContactLdif
&ldif
) : ldif(ldif
) {}
116 void operator()(const Contact
&rec
)
118 ldif
.DumpLdif(cout
, rec
);
122 template <class Record
>
125 std::vector
<Record
> records
;
126 mutable typename
std::vector
<Record
>::const_iterator rec_it
;
127 std::string filename
;
129 bool immediate_display
;
132 Store(const string
&filename
, bool load
, bool immediate_display
)
133 : rec_it(records
.end()),
136 immediate_display(immediate_display
),
139 #ifdef __BARRY_BOOST_MODE__
142 if( load
&& filename
.size() ) {
143 // filename is available, attempt to load
144 cout
<< "Loading: " << filename
<< endl
;
145 ifstream
ifs(filename
.c_str());
147 getline(ifs
, dbName
);
148 boost::archive::text_iarchive
ia(ifs
);
150 cout
<< records
.size()
151 << " records loaded from '"
152 << filename
<< "'" << endl
;
153 sort(records
.begin(), records
.end());
154 rec_it
= records
.begin();
157 typename
std::vector
<Record
>::const_iterator beg
= records
.begin(), end
= records
.end();
158 for( ; beg
!= end
; beg
++ ) {
159 cout
<< (*beg
) << endl
;
163 } catch( boost::archive::archive_exception
&ae
) {
164 cerr
<< "Archive exception in ~Store(): "
165 << ae
.what() << endl
;
172 if( !immediate_display
) {
173 // not dumped yet, sort then dump
174 sort(records
.begin(), records
.end());
178 cout
<< "Store counted " << dec
<< count
<< " records." << endl
;
179 #ifdef __BARRY_BOOST_MODE__
182 if( !load
&& filename
.size() ) {
183 // filename is available, attempt to save
184 cout
<< "Saving: " << filename
<< endl
;
185 const std::vector
<Record
> &r
= records
;
186 ofstream
ofs(filename
.c_str());
187 ofs
<< Record::GetDBName() << endl
;
188 boost::archive::text_oarchive
oa(ofs
);
190 cout
<< dec
<< r
.size() << " records saved to '"
191 << filename
<< "'" << endl
;
194 } catch( boost::archive::archive_exception
&ae
) {
195 cerr
<< "Archive exception in ~Store(): "
196 << ae
.what() << endl
;
203 typename vector
<Record
>::const_iterator i
= records
.begin();
204 for( ; i
!= records
.end(); ++i
) {
210 void operator()(const Record
&rec
)
213 if( immediate_display
)
214 std::cout
<< rec
<< std::endl
;
215 records
.push_back(rec
);
218 // retrieval operator
219 bool operator()(Record
&rec
, unsigned int databaseId
) const
221 if( rec_it
== records
.end() )
229 class DataDumpParser
: public Barry::Parser
234 virtual void Clear() {}
236 virtual void SetIds(uint8_t RecType
, uint32_t UniqueId
)
241 virtual void ParseHeader(const Data
&, size_t &) {}
243 virtual void ParseFields(const Barry::Data
&data
, size_t &offset
,
244 const IConverter
*ic
)
246 std::cout
<< "Raw record dump for record: "
247 << std::hex
<< m_id
<< std::endl
;
248 std::cout
<< data
<< std::endl
;
251 virtual void Store() {}
254 auto_ptr
<Parser
> GetParser(const string
&name
,
255 const string
&filename
,
257 bool immediate_display
)
259 bool dnow
= immediate_display
;
263 return auto_ptr
<Parser
>( new DataDumpParser
);
265 // check for recognized database names
266 else if( name
== Contact::GetDBName() ) {
267 return auto_ptr
<Parser
>(
268 new RecordParser
<Contact
, Store
<Contact
> > (
269 new Store
<Contact
>(filename
, false, dnow
)));
271 else if( name
== Message::GetDBName() ) {
272 return auto_ptr
<Parser
>(
273 new RecordParser
<Message
, Store
<Message
> > (
274 new Store
<Message
>(filename
, false, dnow
)));
276 else if( name
== Calendar::GetDBName() ) {
277 return auto_ptr
<Parser
>(
278 new RecordParser
<Calendar
, Store
<Calendar
> > (
279 new Store
<Calendar
>(filename
, false, dnow
)));
281 else if( name
== CalendarAll::GetDBName() ) {
282 return auto_ptr
<Parser
>(
283 new RecordParser
<CalendarAll
, Store
<CalendarAll
> > (
284 new Store
<CalendarAll
>(filename
, false, dnow
)));
286 else if( name
== CallLog::GetDBName() ) {
287 return auto_ptr
<Parser
>(
288 new RecordParser
<CallLog
, Store
<CallLog
> > (
289 new Store
<CallLog
>(filename
, false, dnow
)));
291 else if( name
== ServiceBook::GetDBName() ) {
292 return auto_ptr
<Parser
>(
293 new RecordParser
<ServiceBook
, Store
<ServiceBook
> > (
294 new Store
<ServiceBook
>(filename
, false, dnow
)));
297 else if( name
== Memo::GetDBName() ) {
298 return auto_ptr
<Parser
>(
299 new RecordParser
<Memo
, Store
<Memo
> > (
300 new Store
<Memo
>(filename
, false, dnow
)));
302 else if( name
== Task::GetDBName() ) {
303 return auto_ptr
<Parser
>(
304 new RecordParser
<Task
, Store
<Task
> > (
305 new Store
<Task
>(filename
, false, dnow
)));
307 else if( name
== PINMessage::GetDBName() ) {
308 return auto_ptr
<Parser
>(
309 new RecordParser
<PINMessage
, Store
<PINMessage
> > (
310 new Store
<PINMessage
>(filename
, false, dnow
)));
312 else if( name
== SavedMessage::GetDBName() ) {
313 return auto_ptr
<Parser
>(
314 new RecordParser
<SavedMessage
, Store
<SavedMessage
> > (
315 new Store
<SavedMessage
>(filename
, false, dnow
)));
317 else if( name
== Sms::GetDBName() ) {
318 return auto_ptr
<Parser
>(
319 new RecordParser
<Sms
, Store
<Sms
> > (
320 new Store
<Sms
>(filename
, false, dnow
)));
322 else if( name
== Folder::GetDBName() ) {
323 return auto_ptr
<Parser
>(
324 new RecordParser
<Folder
, Store
<Folder
> > (
325 new Store
<Folder
>(filename
, false, dnow
)));
327 else if( name
== Timezone::GetDBName() ) {
328 return auto_ptr
<Parser
>(
329 new RecordParser
<Timezone
, Store
<Timezone
> > (
330 new Store
<Timezone
>(filename
, false, dnow
)));
333 // unknown database, use null parser
334 return auto_ptr
<Parser
>( new DataDumpParser
);
338 auto_ptr
<Builder
> GetBuilder(const string
&name
, const string
&filename
)
340 // check for recognized database names
341 if( name
== Contact::GetDBName() ) {
342 return auto_ptr
<Builder
>(
343 new RecordBuilder
<Contact
, Store
<Contact
> > (
344 new Store
<Contact
>(filename
, true, true)));
346 else if( name
== Calendar::GetDBName() ) {
347 return auto_ptr
<Builder
>(
348 new RecordBuilder
<Calendar
, Store
<Calendar
> > (
349 new Store
<Calendar
>(filename
, true, true)));
351 else if( name
== CalendarAll::GetDBName() ) {
352 return auto_ptr
<Builder
>(
353 new RecordBuilder
<CalendarAll
, Store
<CalendarAll
> > (
354 new Store
<CalendarAll
>(filename
, true, true)));
356 else if( name
== Memo::GetDBName() ) {
357 return auto_ptr
<Builder
>(
358 new RecordBuilder
<Memo
, Store
<Memo
> > (
359 new Store
<Memo
>(filename
, true, true)));
361 else if( name
== Task::GetDBName() ) {
362 return auto_ptr
<Builder
>(
363 new RecordBuilder
<Task
, Store
<Task
> > (
364 new Store
<Task
>(filename
, true, true)));
367 else if( name == "Messages" ) {
368 return auto_ptr<Parser>(
369 new RecordParser<Message, Store<Message> > (
370 new Store<Message>(filename, true, true)));
372 else if( name == "Service Book" ) {
373 return auto_ptr<Parser>(
374 new RecordParser<ServiceBook, Store<ServiceBook> > (
375 new Store<ServiceBook>(filename, true, true)));
379 throw std::runtime_error("No Builder available for database");
385 cout
<< "Supported Database parsers:\n"
389 << " Calendar - All\n"
390 << " Phone Call Logs\n"
395 << " Saved Email Messages\n"
398 << " Time Zones (read only)\n"
400 << "Supported Database builders:\n"
403 << " Calendar - All\n"
409 struct StateTableCommand
415 StateTableCommand(char f
, bool c
, unsigned int i
)
416 : flag(f
), clear(c
), index(i
) {}
419 bool SplitMap(const string
&map
, string
&ldif
, string
&read
, string
&write
)
421 string::size_type a
= map
.find(',');
422 if( a
== string::npos
)
425 string::size_type b
= map
.find(',', a
+1);
426 if( b
== string::npos
)
429 ldif
.assign(map
, 0, a
);
430 read
.assign(map
, a
+ 1, b
- a
- 1);
431 write
.assign(map
, b
+ 1, map
.size() - b
- 1);
433 return ldif
.size() && read
.size() && write
.size();
436 void DoMapping(ContactLdif
&ldif
, const vector
<string
> &mapCommands
)
438 for( vector
<string
>::const_iterator i
= mapCommands
.begin();
439 i
!= mapCommands
.end();
442 // single names mean unmapping
443 if( i
->find(',') == string::npos
) {
445 cerr
<< "Unmapping: " << *i
<< endl
;
449 cerr
<< "Mapping: " << *i
<< endl
;
451 // map... extract ldif/read/write names
452 string ldifname
, read
, write
;
453 if( SplitMap(*i
, ldifname
, read
, write
) ) {
454 if( !ldif
.Map(ldifname
, read
, write
) ) {
455 cerr
<< "Read/Write name unknown: " << *i
<< endl
;
459 cerr
<< "Invalid map format: " << *i
<< endl
;
465 bool ParseEpOverride(const char *arg
, Usb::EndpointPair
*epp
)
469 istringstream
iss(arg
);
470 iss
>> hex
>> read
>> comma
>> write
;
478 int main(int argc
, char *argv
[])
482 cout
.sync_with_stdio(true); // leave this on, since libusb uses
483 // stdio for debug messages
488 bool list_only
= false,
490 ldif_contacts
= false,
492 reset_device
= false,
493 list_contact_fields
= false,
494 list_ldif_map
= false,
495 epp_override
= false,
496 threaded_sockets
= true,
497 record_state
= false,
498 clear_database
= false,
500 sort_records
= false;
501 string ldifBaseDN
, ldifDnAttr
;
507 vector
<string
> dbNames
, saveDbNames
, mapCommands
, clearDbNames
;
508 vector
<StateTableCommand
> stCommands
;
509 Usb::EndpointPair epOverride
;
511 // process command line options
513 int cmd
= getopt(argc
, argv
, "a:B:c:C:d:D:e:f:hi:IlLm:MnN:p:P:r:R:Ss:tT:vXzZ");
519 case 'a': // Clear Database
520 clear_database
= true;
521 clearDbNames
.push_back(string(optarg
));
528 case 'c': // contacts to ldap ldif
529 ldif_contacts
= true;
533 case 'C': // DN Attribute for FQDN
537 case 'd': // show dbname
538 dbNames
.push_back(string(optarg
));
541 case 'D': // delete record
542 stCommands
.push_back(
543 StateTableCommand('D', false, atoi(optarg
)));
546 case 'e': // endpoint override
547 if( !ParseEpOverride(optarg
, &epOverride
) ) {
554 case 'f': // filename
555 #ifdef __BARRY_BOOST_MODE__
558 cerr
<< "-f option not supported - no Boost "
559 "serialization support available\n";
564 case 'i': // international charset (iconv)
565 iconvCharset
= optarg
;
568 case 'I': // sort before dump
572 case 'l': // list only
576 case 'L': // List Contact field names
577 list_contact_fields
= true;
580 case 'm': // Map / Unmap
581 mapCommands
.push_back(string(optarg
));
584 case 'M': // List LDIF map
585 list_ldif_map
= true;
588 case 'n': // use null parser
596 case 'p': // Blackberry PIN
597 pin
= strtoul(optarg
, NULL
, 16);
600 case 'P': // Device password
604 case 'r': // get specific record index
605 stCommands
.push_back(
606 StateTableCommand('r', false, atoi(optarg
)));
609 case 'R': // same as 'r', and clears dirty
610 stCommands
.push_back(
611 StateTableCommand('r', true, atoi(optarg
)));
614 case 's': // save dbname
615 saveDbNames
.push_back(string(optarg
));
618 case 'S': // show supported databases
622 case 't': // display database database
626 case 'T': // show RecordStateTable
628 dbNames
.push_back(string(optarg
));
631 case 'v': // data dump on
635 case 'X': // reset device
639 case 'z': // non-threaded sockets
640 threaded_sockets
= false;
643 case 'Z': // threaded socket router
644 threaded_sockets
= true;
654 // Initialize the barry library. Must be called before
656 Barry::Init(data_dump
);
659 const char *Version
= Barry::Version(major
, minor
);
660 cout
<< Version
<< endl
;
663 // Create an IConverter object if needed
664 auto_ptr
<IConverter
> ic
;
665 if( iconvCharset
.size() ) {
666 ic
.reset( new IConverter(iconvCharset
.c_str(), true) );
669 // LDIF class... only needed if ldif output turned on
670 ContactLdif
ldif(ldifBaseDN
);
671 DoMapping(ldif
, mapCommands
);
672 if( ldifDnAttr
.size() ) {
673 if( !ldif
.SetDNAttr(ldifDnAttr
) ) {
674 cerr
<< "Unable to set DN Attr: " << ldifDnAttr
<< endl
;
678 // Probe the USB bus for Blackberry devices and display.
679 // If user has specified a PIN, search for it in the
680 // available device list here as well
681 Barry::Probe
probe(busname
.c_str(), devname
.c_str(),
682 epp_override
? &epOverride
: 0);
683 int activeDevice
= -1;
685 // show any errors during probe first
686 if( probe
.GetFailCount() ) {
689 cout
<< "Blackberry device errors with errors during probe:" << endl
;
690 for( int i
= 0; i
< probe
.GetFailCount(); i
++ ) {
693 cout
<< probe
.GetFailMsg(i
) << endl
;
697 // show all successfully found devices
700 cout
<< "Blackberry devices found:" << endl
;
701 for( int i
= 0; i
< probe
.GetCount(); i
++ ) {
705 probe
.Get(i
).DumpAll(cout
);
707 cout
<< probe
.Get(i
);
709 if( probe
.Get(i
).m_pin
== pin
)
716 if( activeDevice
== -1 ) {
718 // can we default to single device?
719 if( probe
.GetCount() == 1 )
722 cerr
<< "No device selected" << endl
;
727 cerr
<< "PIN " << setbase(16) << pin
728 << " not found" << endl
;
735 cout
<< "Using device (PIN): "
736 << probe
.Get(activeDevice
).m_pin
.str() << endl
;
739 Usb::Device
dev(probe
.Get(activeDevice
).m_dev
);
744 // Override device endpoints if user asks
745 Barry::ProbeResult device
= probe
.Get(activeDevice
);
747 device
.m_ep
.read
= epOverride
.read
;
748 device
.m_ep
.write
= epOverride
.write
;
749 device
.m_ep
.type
= 2; // FIXME - override this too?
750 cout
<< "Endpoint pair (read,write) overridden with: "
752 << (unsigned int) device
.m_ep
.read
<< ","
753 << (unsigned int) device
.m_ep
.write
<< endl
;
757 // Create our controller object
759 // Order is important in the following auto_ptr<> objects,
760 // since Controller must get destroyed before router.
761 // Normally you'd pick one method, and not bother
762 // with auto_ptr<> and so the normal C++ constructor
763 // rules would guarantee this safety for you, but
764 // here we want the user to pick.
766 auto_ptr
<SocketRoutingQueue
> router
;
767 auto_ptr
<Barry::Controller
> pcon
;
768 if( threaded_sockets
) {
769 router
.reset( new SocketRoutingQueue
);
770 router
->SpinoffSimpleReadThread();
771 pcon
.reset( new Barry::Controller(device
, *router
) );
774 pcon
.reset( new Barry::Controller(device
) );
777 Barry::Controller
&con
= *pcon
;
778 Barry::Mode::Desktop
desktop(con
, *ic
);
781 // execute each mode that was turned on
785 // Dump list of all databases to stdout
787 // open desktop mode socket
788 desktop
.Open(password
.c_str());
789 cout
<< desktop
.GetDBDB() << endl
;
792 // Dump list of Contact field names
793 if( list_contact_fields
) {
794 for( const ContactLdif::NameToFunc
*n
= ldif
.GetFieldNames(); n
->name
; n
++ ) {
796 cout
<< " " << left
<< setw(20) << n
->name
<< ": "
797 << n
->description
<< endl
;
801 // Dump current LDIF mapping
802 if( list_ldif_map
) {
803 cout
<< ldif
<< endl
;
806 // Dump list of contacts to an LDAP LDIF file
807 // This uses the Controller convenience templates
808 if( ldif_contacts
) {
809 // make sure we're in desktop mode
810 desktop
.Open(password
.c_str());
812 // create a storage functor object that accepts
813 // Barry::Contact objects as input
814 Contact2Ldif
storage(ldif
);
816 // load all the Contact records into storage
817 desktop
.LoadDatabaseByType
<Barry::Contact
>(storage
);
820 // Dump record state table to stdout
822 if( dbNames
.size() == 0 ) {
823 cout
<< "No db names to process" << endl
;
827 desktop
.Open(password
.c_str());
829 vector
<string
>::iterator b
= dbNames
.begin();
830 for( ; b
!= dbNames
.end(); b
++ ) {
831 unsigned int id
= desktop
.GetDBID(*b
);
832 RecordStateTable state
;
833 desktop
.GetRecordStateTable(id
, state
);
834 cout
<< "Record state table for: " << *b
<< endl
;
840 // Get Record mode overrides the default name mode
841 if( stCommands
.size() ) {
842 if( dbNames
.size() != 1 ) {
843 cout
<< "Must have 1 db name to process" << endl
;
847 desktop
.Open(password
.c_str());
848 unsigned int id
= desktop
.GetDBID(dbNames
[0]);
849 auto_ptr
<Parser
> parse
= GetParser(dbNames
[0],filename
,
852 for( unsigned int i
= 0; i
< stCommands
.size(); i
++ ) {
853 desktop
.GetRecord(id
, stCommands
[i
].index
, *parse
.get());
855 if( stCommands
[i
].flag
== 'r' && stCommands
[i
].clear
) {
856 cout
<< "Clearing record's dirty flags..." << endl
;
857 desktop
.ClearDirty(id
, stCommands
[i
].index
);
860 if( stCommands
[i
].flag
== 'D' ) {
861 desktop
.DeleteRecord(id
, stCommands
[i
].index
);
869 if (clear_database
) {
870 if( clearDbNames
.size() == 0 ) {
871 cout
<< "No db names to erase" << endl
;
875 vector
<string
>::iterator b
= clearDbNames
.begin();
877 desktop
.Open(password
.c_str());
879 for( ; b
!= clearDbNames
.end(); b
++ ) {
880 unsigned int id
= desktop
.GetDBID(*b
);
881 cout
<< "Deleting all records from " << (*b
) << "..." << endl
;
882 desktop
.ClearDatabase(id
);
888 // Dump contents of selected databases to stdout, or
889 // to file if specified.
890 // This is retrieving data from the Blackberry.
891 if( dbNames
.size() ) {
892 vector
<string
>::iterator b
= dbNames
.begin();
894 desktop
.Open(password
.c_str());
895 for( ; b
!= dbNames
.end(); b
++ ) {
896 auto_ptr
<Parser
> parse
= GetParser(*b
,filename
,
897 null_parser
, !sort_records
);
898 unsigned int id
= desktop
.GetDBID(*b
);
899 desktop
.LoadDatabase(id
, *parse
.get());
903 // Save contents of file to specified databases
904 // This is writing data to the Blackberry.
905 if( saveDbNames
.size() ) {
906 vector
<string
>::iterator b
= saveDbNames
.begin();
908 desktop
.Open(password
.c_str());
909 for( ; b
!= saveDbNames
.end(); b
++ ) {
910 auto_ptr
<Builder
> build
=
911 GetBuilder(*b
, filename
);
912 unsigned int id
= desktop
.GetDBID(*b
);
913 desktop
.SaveDatabase(id
, *build
);
918 catch( Usb::Error
&ue
) {
919 std::cerr
<< "Usb::Error caught: " << ue
.what() << endl
;
922 catch( Barry::Error
&se
) {
923 std::cerr
<< "Barry::Error caught: " << se
.what() << endl
;
926 catch( std::exception
&e
) {
927 std::cerr
<< "std::exception caught: " << e
.what() << endl
;