Removed bool reference argument in GetParser()
[barry/pauldeden.git] / tools / btool.cc
blob6d99aa98c9917994c240cb015fd6ece2c7ede862
1 ///
2 /// \file btool.cc
3 /// Barry library tester
4 ///
6 /*
7 Copyright (C) 2005-2008, 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>
23 #include <iomanip>
24 #include <iostream>
25 #include <fstream>
26 #include <sstream>
27 #include <vector>
28 #include <string>
29 #include <algorithm>
30 #include <getopt.h>
33 using namespace std;
34 using namespace Barry;
36 void Usage()
38 int major, minor;
39 const char *Version = Barry::Version(major, minor);
41 cerr
42 << "btool - Command line USB Blackberry Test Tool\n"
43 << " Copyright 2005-2008, Net Direct Inc. (http://www.netdirect.ca/)\n"
44 << " Using: " << Version << "\n"
45 << " Compiled "
46 #ifdef __BARRY_BOOST_MODE__
47 << "with"
48 #else
49 << "without"
50 #endif
51 << " Boost support\n"
52 << "\n"
53 << " -B bus Specify which USB bus to search on\n"
54 << " -N dev Specify which system device, using system specific string\n"
55 << "\n"
56 << " -c dn Convert address book database to LDIF format, using the\n"
57 << " specified baseDN\n"
58 << " -C dnattr LDIF attribute name to use when building the FQDN\n"
59 << " Defaults to 'cn'\n"
60 << " -d db Load database 'db' FROM device and dump to screen\n"
61 << " Can be used multiple times to fetch more than one DB\n"
62 << " -e epp Override endpoint pair detection. 'epp' is a single\n"
63 << " string separated by a comma, holding the read,write\n"
64 << " endpoint pair. Example: -e 83,5\n"
65 << " Note: Endpoints are specified in hex.\n"
66 << " You should never need to use this option.\n"
67 #ifdef __BARRY_BOOST_MODE__
68 << " -f file Filename to save or load handheld data to/from\n"
69 #endif
70 << " -h This help\n"
71 << " -l List devices\n"
72 << " -L List Contact field names\n"
73 << " -m Map LDIF name to Contact field / Unmap LDIF name\n"
74 << " Map: ldif,read,write - maps ldif to read/write Contact fields\n"
75 << " Unmap: ldif name alone\n"
76 << " -M List current LDIF mapping\n"
77 << " -n Use null parser on all databases.\n"
78 << " -p pin PIN of device to talk with\n"
79 << " If only one device is plugged in, this flag is optional\n"
80 << " -P pass Simplistic method to specify device password\n"
81 << " -s db Save database 'db' TO device from data loaded from -f file\n"
82 << " -S Show list of supported database parsers\n"
83 << " -t Show database database table\n"
84 << " -T db Show record state table for given database\n"
85 << " -v Dump protocol data during operation\n"
86 << " -X Reset device\n"
87 << " -z Use non-threaded sockets\n"
88 << " -Z Use threaded socket router (default)\n"
89 << "\n"
90 << " -d Command modifiers: (can be used multiple times for more than 1 record)\n"
91 << "\n"
92 << " -r # Record index number as seen in the -T state table.\n"
93 << " This overrides the default -d behaviour, and only\n"
94 << " downloads the one specified record, sending to stdout.\n"
95 << " -R # Same as -r, but also clears the record's dirty flags.\n"
96 << " -D # Record index number as seen in the -T state table,\n"
97 << " which indicates the record to delete. Used with the -d\n"
98 << " command to specify the database.\n"
99 << endl;
102 class Contact2Ldif
104 public:
105 Barry::ContactLdif &ldif;
107 Contact2Ldif(Barry::ContactLdif &ldif) : ldif(ldif) {}
109 void operator()(const Contact &rec)
111 ldif.DumpLdif(cout, rec);
115 template <class Record>
116 struct Store
118 std::vector<Record> records;
119 mutable typename std::vector<Record>::const_iterator rec_it;
120 std::string filename;
121 bool load;
122 int count;
124 Store(const string &filename, bool load)
125 : rec_it(records.end()),
126 filename(filename),
127 load(load),
128 count(0)
130 #ifdef __BARRY_BOOST_MODE__
131 try {
133 if( load && filename.size() ) {
134 // filename is available, attempt to load
135 cout << "Loading: " << filename << endl;
136 ifstream ifs(filename.c_str());
137 std::string dbName;
138 getline(ifs, dbName);
139 boost::archive::text_iarchive ia(ifs);
140 ia >> records;
141 cout << records.size()
142 << " records loaded from '"
143 << filename << "'" << endl;
144 sort(records.begin(), records.end());
145 rec_it = records.begin();
147 // debugging aid
148 typename std::vector<Record>::const_iterator beg = records.begin(), end = records.end();
149 for( ; beg != end; beg++ ) {
150 cout << (*beg) << endl;
154 } catch( boost::archive::archive_exception &ae ) {
155 cerr << "Archive exception in ~Store(): "
156 << ae.what() << endl;
158 #endif
160 ~Store()
162 cout << "Store counted " << dec << count << " records." << endl;
163 #ifdef __BARRY_BOOST_MODE__
164 try {
166 if( !load && filename.size() ) {
167 // filename is available, attempt to save
168 cout << "Saving: " << filename << endl;
169 const std::vector<Record> &r = records;
170 ofstream ofs(filename.c_str());
171 ofs << Record::GetDBName() << endl;
172 boost::archive::text_oarchive oa(ofs);
173 oa << r;
174 cout << dec << r.size() << " records saved to '"
175 << filename << "'" << endl;
178 } catch( boost::archive::archive_exception &ae ) {
179 cerr << "Archive exception in ~Store(): "
180 << ae.what() << endl;
182 #endif
185 // storage operator
186 void operator()(const Record &rec)
188 count++;
189 std::cout << rec << std::endl;
190 records.push_back(rec);
193 // retrieval operator
194 bool operator()(Record &rec, unsigned int databaseId) const
196 if( rec_it == records.end() )
197 return false;
198 rec = *rec_it;
199 rec_it++;
200 return true;
204 class DataDumpParser : public Barry::Parser
206 uint32_t m_id;
208 public:
209 virtual void SetIds(uint8_t RecType, uint32_t UniqueId)
211 m_id = UniqueId;
214 virtual void ParseFields(const Barry::Data &data, size_t &offset)
216 std::cout << "Raw record dump for record: "
217 << std::hex << m_id << std::endl;
218 std::cout << data << std::endl;
222 auto_ptr<Parser> GetParser(const string &name, const string &filename, bool null_parser)
224 if( null_parser ) {
225 // use null parser
226 return auto_ptr<Parser>( new DataDumpParser );
228 // check for recognized database names
229 else if( name == Contact::GetDBName() ) {
230 return auto_ptr<Parser>(
231 new RecordParser<Contact, Store<Contact> > (
232 new Store<Contact>(filename, false)));
234 else if( name == Message::GetDBName() ) {
235 return auto_ptr<Parser>(
236 new RecordParser<Message, Store<Message> > (
237 new Store<Message>(filename, false)));
239 else if( name == Calendar::GetDBName() ) {
240 return auto_ptr<Parser>(
241 new RecordParser<Calendar, Store<Calendar> > (
242 new Store<Calendar>(filename, false)));
244 else if( name == ServiceBook::GetDBName() ) {
245 return auto_ptr<Parser>(
246 new RecordParser<ServiceBook, Store<ServiceBook> > (
247 new Store<ServiceBook>(filename, false)));
250 else if( name == Memo::GetDBName() ) {
251 return auto_ptr<Parser>(
252 new RecordParser<Memo, Store<Memo> > (
253 new Store<Memo>(filename, false)));
255 else if( name == Task::GetDBName() ) {
256 return auto_ptr<Parser>(
257 new RecordParser<Task, Store<Task> > (
258 new Store<Task>(filename, false)));
260 else if( name == PINMessage::GetDBName() ) {
261 return auto_ptr<Parser>(
262 new RecordParser<PINMessage, Store<PINMessage> > (
263 new Store<PINMessage>(filename, false)));
265 else if( name == SavedMessage::GetDBName() ) {
266 return auto_ptr<Parser>(
267 new RecordParser<SavedMessage, Store<SavedMessage> > (
268 new Store<SavedMessage>(filename, false)));
270 else if( name == Folder::GetDBName() ) {
271 return auto_ptr<Parser>(
272 new RecordParser<Folder, Store<Folder> > (
273 new Store<Folder>(filename, false)));
275 else if( name == Timezone::GetDBName() ) {
276 return auto_ptr<Parser>(
277 new RecordParser<Timezone, Store<Timezone> > (
278 new Store<Timezone>(filename, false)));
280 else {
281 // unknown database, use null parser
282 return auto_ptr<Parser>( new DataDumpParser );
286 auto_ptr<Builder> GetBuilder(const string &name, const string &filename)
288 // check for recognized database names
289 if( name == Contact::GetDBName() ) {
290 return auto_ptr<Builder>(
291 new RecordBuilder<Contact, Store<Contact> > (
292 new Store<Contact>(filename, true)));
294 else if( name == Calendar::GetDBName() ) {
295 return auto_ptr<Builder>(
296 new RecordBuilder<Calendar, Store<Calendar> > (
297 new Store<Calendar>(filename, true)));
300 else if( name == "Messages" ) {
301 return auto_ptr<Parser>(
302 new RecordParser<Message, Store<Message> > (
303 new Store<Message>(filename, true)));
305 else if( name == "Service Book" ) {
306 return auto_ptr<Parser>(
307 new RecordParser<ServiceBook, Store<ServiceBook> > (
308 new Store<ServiceBook>(filename, true)));
310 else if( name == "Memos" ) {
311 return auto_ptr<Parser>(
312 new RecordParser<Memo, Store<Memo> > (
313 new Store<Memo>(filename, true)));
315 else if( name == "Tasks" ) {
316 return auto_ptr<Parser>(
317 new RecordParser<Task, Store<Task> > (
318 new Store<Task>(filename, true)));
321 else {
322 throw std::runtime_error("No Builder available for database");
326 void ShowParsers()
328 cout << "Supported Database parsers:\n"
329 << " Address Book\n"
330 << " Messages\n"
331 << " Calendar\n"
332 << " Service Book\n"
333 << " Memos\n"
334 << " Tasks\n"
335 << " PIN Messages\n"
336 << " Saved Email Messages\n"
337 << " Folders\n"
338 << " Time Zones (read only)\n"
339 << "\n"
340 << "Supported Database builders:\n"
341 << " Address Book\n"
342 << " Calendar\n"
343 << endl;
346 struct StateTableCommand
348 char flag;
349 bool clear;
350 unsigned int index;
352 StateTableCommand(char f, bool c, unsigned int i)
353 : flag(f), clear(c), index(i) {}
356 bool SplitMap(const string &map, string &ldif, string &read, string &write)
358 string::size_type a = map.find(',');
359 if( a == string::npos )
360 return false;
362 string::size_type b = map.find(',', a+1);
363 if( b == string::npos )
364 return false;
366 ldif.assign(map, 0, a);
367 read.assign(map, a + 1, b - a - 1);
368 write.assign(map, b + 1, map.size() - b - 1);
370 return ldif.size() && read.size() && write.size();
373 void DoMapping(ContactLdif &ldif, const vector<string> &mapCommands)
375 for( vector<string>::const_iterator i = mapCommands.begin();
376 i != mapCommands.end();
377 ++i )
379 // single names mean unmapping
380 if( i->find(',') == string::npos ) {
381 // unmap
382 cerr << "Unmapping: " << *i << endl;
383 ldif.Unmap(*i);
385 else {
386 cerr << "Mapping: " << *i << endl;
388 // map... extract ldif/read/write names
389 string ldifname, read, write;
390 if( SplitMap(*i, ldifname, read, write) ) {
391 if( !ldif.Map(ldifname, read, write) ) {
392 cerr << "Read/Write name unknown: " << *i << endl;
395 else {
396 cerr << "Invalid map format: " << *i << endl;
402 bool ParseEpOverride(const char *arg, Usb::EndpointPair *epp)
404 int read, write;
405 char comma;
406 istringstream iss(arg);
407 iss >> hex >> read >> comma >> write;
408 if( !iss )
409 return false;
410 epp->read = read;
411 epp->write = write;
412 return true;
415 int main(int argc, char *argv[])
417 cout.sync_with_stdio(true); // leave this on, since libusb uses
418 // stdio for debug messages
420 try {
422 uint32_t pin = 0;
423 bool list_only = false,
424 show_dbdb = false,
425 ldif_contacts = false,
426 data_dump = false,
427 reset_device = false,
428 list_contact_fields = false,
429 list_ldif_map = false,
430 epp_override = false,
431 threaded_sockets = true,
432 record_state = false,
433 null_parser = false;
434 string ldifBaseDN, ldifDnAttr;
435 string filename;
436 string password;
437 string busname;
438 string devname;
439 vector<string> dbNames, saveDbNames, mapCommands;
440 vector<StateTableCommand> stCommands;
441 Usb::EndpointPair epOverride;
443 // process command line options
444 for(;;) {
445 int cmd = getopt(argc, argv, "B:c:C:d:D:e:f:hlLm:MnN:p:P:r:R:Ss:tT:vXzZ");
446 if( cmd == -1 )
447 break;
449 switch( cmd )
451 case 'B': // busname
452 busname = optarg;
453 break;
455 case 'c': // contacts to ldap ldif
456 ldif_contacts = true;
457 ldifBaseDN = optarg;
458 break;
460 case 'C': // DN Attribute for FQDN
461 ldifDnAttr = optarg;
462 break;
464 case 'd': // show dbname
465 dbNames.push_back(string(optarg));
466 break;
468 case 'D': // delete record
469 stCommands.push_back(
470 StateTableCommand('D', false, atoi(optarg)));
471 break;
473 case 'e': // endpoint override
474 if( !ParseEpOverride(optarg, &epOverride) ) {
475 Usage();
476 return 1;
478 epp_override = true;
479 break;
481 case 'f': // filename
482 #ifdef __BARRY_BOOST_MODE__
483 filename = optarg;
484 #else
485 cerr << "-f option not supported - no Boost "
486 "serialization support available\n";
487 return 1;
488 #endif
489 break;
490 case 'l': // list only
491 list_only = true;
492 break;
494 case 'L': // List Contact field names
495 list_contact_fields = true;
496 break;
498 case 'm': // Map / Unmap
499 mapCommands.push_back(string(optarg));
500 break;
502 case 'M': // List LDIF map
503 list_ldif_map = true;
504 break;
506 case 'n': // use null parser
507 null_parser = true;
508 break;
510 case 'N': // Devname
511 devname = optarg;
512 break;
514 case 'p': // Blackberry PIN
515 pin = strtoul(optarg, NULL, 16);
516 break;
518 case 'P': // Device password
519 password = optarg;
520 break;
522 case 'r': // get specific record index
523 stCommands.push_back(
524 StateTableCommand('r', false, atoi(optarg)));
525 break;
527 case 'R': // same as 'r', and clears dirty
528 stCommands.push_back(
529 StateTableCommand('r', true, atoi(optarg)));
530 break;
532 case 's': // save dbname
533 saveDbNames.push_back(string(optarg));
534 break;
536 case 'S': // show supported databases
537 ShowParsers();
538 return 0;
540 case 't': // display database database
541 show_dbdb = true;
542 break;
544 case 'T': // show RecordStateTable
545 record_state = true;
546 dbNames.push_back(string(optarg));
547 break;
549 case 'v': // data dump on
550 data_dump = true;
551 break;
553 case 'X': // reset device
554 reset_device = true;
555 break;
557 case 'z': // non-threaded sockets
558 threaded_sockets = false;
559 break;
561 case 'Z': // threaded socket router
562 threaded_sockets = true;
563 break;
565 case 'h': // help
566 default:
567 Usage();
568 return 0;
572 // Initialize the barry library. Must be called before
573 // anything else.
574 Barry::Init(data_dump);
576 // LDIF class... only needed if ldif output turned on
577 ContactLdif ldif(ldifBaseDN);
578 DoMapping(ldif, mapCommands);
579 if( ldifDnAttr.size() ) {
580 if( !ldif.SetDNAttr(ldifDnAttr) ) {
581 cerr << "Unable to set DN Attr: " << ldifDnAttr << endl;
585 // Probe the USB bus for Blackberry devices and display.
586 // If user has specified a PIN, search for it in the
587 // available device list here as well
588 Barry::Probe probe(busname.c_str(), devname.c_str());
589 int activeDevice = -1;
591 // show any errors during probe first
592 if( probe.GetFailCount() ) {
593 if( ldif_contacts )
594 cout << "# ";
595 cout << "Blackberry device errors with errors during probe:" << endl;
596 for( int i = 0; i < probe.GetFailCount(); i++ ) {
597 if( ldif_contacts )
598 cout << "# ";
599 cout << probe.GetFailMsg(i) << endl;
603 // show all successfully found devices
604 if( ldif_contacts )
605 cout << "# ";
606 cout << "Blackberry devices found:" << endl;
607 for( int i = 0; i < probe.GetCount(); i++ ) {
608 if( ldif_contacts )
609 cout << "# ";
610 if( data_dump )
611 probe.Get(i).DumpAll(cout);
612 else
613 cout << probe.Get(i);
614 cout << endl;
615 if( probe.Get(i).m_pin == pin )
616 activeDevice = i;
619 if( list_only )
620 return 0; // done
622 if( activeDevice == -1 ) {
623 if( pin == 0 ) {
624 // can we default to single device?
625 if( probe.GetCount() == 1 )
626 activeDevice = 0;
627 else {
628 cerr << "No device selected" << endl;
629 return 1;
632 else {
633 cerr << "PIN " << setbase(16) << pin
634 << " not found" << endl;
635 return 1;
639 if( ldif_contacts )
640 cout << "# ";
641 cout << "Using device (PIN): " << setbase(16)
642 << probe.Get(activeDevice).m_pin << endl;
644 if( reset_device ) {
645 Usb::Device dev(probe.Get(activeDevice).m_dev);
646 dev.Reset();
647 return 0;
650 // Override device endpoints if user asks
651 Barry::ProbeResult device = probe.Get(activeDevice);
652 if( epp_override ) {
653 device.m_ep.read = epOverride.read;
654 device.m_ep.write = epOverride.write;
655 device.m_ep.type = 2; // FIXME - override this too?
656 cout << "Endpoint pair (read,write) overridden with: "
657 << hex
658 << (unsigned int) device.m_ep.read << ","
659 << (unsigned int) device.m_ep.write << endl;
663 // Create our controller object
665 // Order is important in the following auto_ptr<> objects,
666 // since Controller must get destroyed before router.
667 // Normally you'd pick one method, and not bother
668 // with auto_ptr<> and so the normal C++ constructor
669 // rules would guarantee this safety for you, but
670 // here we want the user to pick.
672 auto_ptr<SocketRoutingQueue> router;
673 auto_ptr<Barry::Controller> pcon;
674 if( threaded_sockets ) {
675 router.reset( new SocketRoutingQueue );
676 router->SpinoffSimpleReadThread();
677 pcon.reset( new Barry::Controller(device, *router) );
679 else {
680 pcon.reset( new Barry::Controller(device) );
683 Barry::Controller &con = *pcon;
684 Barry::Mode::Desktop desktop(con);
687 // execute each mode that was turned on
691 // Dump list of all databases to stdout
692 if( show_dbdb ) {
693 // open desktop mode socket
694 desktop.Open(password.c_str());
695 cout << desktop.GetDBDB() << endl;
698 // Dump list of Contact field names
699 if( list_contact_fields ) {
700 for( const ContactLdif::NameToFunc *n = ldif.GetFieldNames(); n->name; n++ ) {
701 cout.fill(' ');
702 cout << " " << left << setw(20) << n->name << ": "
703 << n->description << endl;
707 // Dump current LDIF mapping
708 if( list_ldif_map ) {
709 cout << ldif << endl;
712 // Dump list of contacts to an LDAP LDIF file
713 // This uses the Controller convenience templates
714 if( ldif_contacts ) {
715 // make sure we're in desktop mode
716 desktop.Open(password.c_str());
718 // create a storage functor object that accepts
719 // Barry::Contact objects as input
720 Contact2Ldif storage(ldif);
722 // load all the Contact records into storage
723 desktop.LoadDatabaseByType<Barry::Contact>(storage);
726 // Dump record state table to stdout
727 if( record_state ) {
728 if( dbNames.size() == 0 ) {
729 cout << "No db names to process" << endl;
730 return 1;
733 desktop.Open(password.c_str());
735 vector<string>::iterator b = dbNames.begin();
736 for( ; b != dbNames.end(); b++ ) {
737 unsigned int id = desktop.GetDBID(*b);
738 RecordStateTable state;
739 desktop.GetRecordStateTable(id, state);
740 cout << "Record state table for: " << *b << endl;
741 cout << state;
743 return 0;
746 // Get Record mode overrides the default name mode
747 if( stCommands.size() ) {
748 if( dbNames.size() != 1 ) {
749 cout << "Must have 1 db name to process" << endl;
750 return 1;
753 desktop.Open(password.c_str());
754 unsigned int id = desktop.GetDBID(dbNames[0]);
755 auto_ptr<Parser> parse = GetParser(dbNames[0],filename,null_parser);
757 for( unsigned int i = 0; i < stCommands.size(); i++ ) {
758 desktop.GetRecord(id, stCommands[i].index, *parse.get());
760 if( stCommands[i].flag == 'r' && stCommands[i].clear ) {
761 cout << "Clearing record's dirty flags..." << endl;
762 desktop.ClearDirty(id, stCommands[i].index);
765 if( stCommands[i].flag == 'D' ) {
766 desktop.DeleteRecord(id, stCommands[i].index);
770 return 0;
773 // Dump contents of selected databases to stdout, or
774 // to file if specified.
775 // This is retrieving data from the Blackberry.
776 if( dbNames.size() ) {
777 vector<string>::iterator b = dbNames.begin();
779 desktop.Open(password.c_str());
780 for( ; b != dbNames.end(); b++ ) {
781 auto_ptr<Parser> parse = GetParser(*b,filename,null_parser);
782 unsigned int id = desktop.GetDBID(*b);
783 desktop.LoadDatabase(id, *parse.get());
787 // Save contents of file to specified databases
788 // This is writing data to the Blackberry.
789 if( saveDbNames.size() ) {
790 vector<string>::iterator b = saveDbNames.begin();
792 desktop.Open(password.c_str());
793 for( ; b != saveDbNames.end(); b++ ) {
794 auto_ptr<Builder> build =
795 GetBuilder(*b, filename);
796 unsigned int id = desktop.GetDBID(*b);
797 desktop.SaveDatabase(id, *build);
802 catch( Usb::Error &ue) {
803 std::cerr << "Usb::Error caught: " << ue.what() << endl;
804 return 1;
806 catch( Barry::Error &se ) {
807 std::cerr << "Barry::Error caught: " << se.what() << endl;
808 return 1;
810 catch( std::exception &e ) {
811 std::cerr << "std::exception caught: " << e.what() << endl;
812 return 1;
815 return 0;