- applied Time Zone parsing patches from Brian Edginton
[barry.git] / tools / btool.cc
blobdd52b14f791393833b72a1744d34f9cb8938c1bb
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 <getopt.h>
32 using namespace std;
33 using namespace Barry;
35 void Usage()
37 int major, minor;
38 const char *Version = Barry::Version(major, minor);
40 cerr
41 << "btool - Command line USB Blackberry Test Tool\n"
42 << " Copyright 2005-2008, Net Direct Inc. (http://www.netdirect.ca/)\n"
43 << " Using: " << Version << "\n"
44 << " Compiled "
45 #ifdef __BARRY_BOOST_MODE__
46 << "with"
47 #else
48 << "without"
49 #endif
50 << " Boost support\n"
51 << "\n"
52 << " -B bus Specify which USB bus to search on\n"
53 << " -N dev Specify which system device, using system specific string\n"
54 << "\n"
55 << " -c dn Convert address book database to LDIF format, using the\n"
56 << " specified baseDN\n"
57 << " -C dnattr LDIF attribute name to use when building the FQDN\n"
58 << " Defaults to 'cn'\n"
59 << " -d db Load database 'db' FROM device and dump to screen\n"
60 << " Can be used multiple times to fetch more than one DB\n"
61 << " -e epp Override endpoint pair detection. 'epp' is a single\n"
62 << " string separated by a comma, holding the read,write\n"
63 << " endpoint pair. Example: -e 83,5\n"
64 << " Note: Endpoints are specified in hex.\n"
65 << " You should never need to use this option.\n"
66 #ifdef __BARRY_BOOST_MODE__
67 << " -f file Filename to save or load handheld data to/from\n"
68 #endif
69 << " -h This help\n"
70 << " -l List devices\n"
71 << " -L List Contact field names\n"
72 << " -m Map LDIF name to Contact field / Unmap LDIF name\n"
73 << " Map: ldif,read,write - maps ldif to read/write Contact fields\n"
74 << " Unmap: ldif name alone\n"
75 << " -M List current LDIF mapping\n"
76 << " -p pin PIN of device to talk with\n"
77 << " If only one device is plugged in, this flag is optional\n"
78 << " -P pass Simplistic method to specify device password\n"
79 << " -s db Save database 'db' TO device from data loaded from -f file\n"
80 << " -S Show list of supported database parsers\n"
81 << " -t Show database database table\n"
82 << " -T db Show record state table for given database\n"
83 << " -v Dump protocol data during operation\n"
84 << " -X Reset device\n"
85 << "\n"
86 << " -d Command modifiers: (can be used multiple times for more than 1 record)\n"
87 << "\n"
88 << " -r # Record index number as seen in the -T state table.\n"
89 << " This overrides the default -d behaviour, and only\n"
90 << " downloads the one specified record, sending to stdout.\n"
91 << " -R # Same as -r, but also clears the record's dirty flags.\n"
92 << " -D # Record index number as seen in the -T state table,\n"
93 << " which indicates the record to delete. Used with the -d\n"
94 << " command to specify the database.\n"
95 << endl;
98 class Contact2Ldif
100 public:
101 Barry::ContactLdif &ldif;
103 Contact2Ldif(Barry::ContactLdif &ldif) : ldif(ldif) {}
105 void operator()(const Contact &rec)
107 ldif.DumpLdif(cout, rec);
111 template <class Record>
112 struct Store
114 std::vector<Record> records;
115 mutable typename std::vector<Record>::const_iterator rec_it;
116 std::string filename;
117 bool load;
118 int count;
120 Store(const string &filename, bool load)
121 : rec_it(records.end()),
122 filename(filename),
123 load(load),
124 count(0)
126 #ifdef __BARRY_BOOST_MODE__
127 try {
129 if( load && filename.size() ) {
130 // filename is available, attempt to load
131 cout << "Loading: " << filename << endl;
132 ifstream ifs(filename.c_str());
133 boost::archive::text_iarchive ia(ifs);
134 ia >> records;
135 cout << records.size()
136 << " records loaded from '"
137 << filename << "'" << endl;
138 sort(records.begin(), records.end());
139 rec_it = records.begin();
141 // debugging aid
142 typename std::vector<Record>::const_iterator beg = records.begin(), end = records.end();
143 for( ; beg != end; beg++ ) {
144 cout << (*beg) << endl;
148 } catch( boost::archive::archive_exception &ae ) {
149 cerr << "Archive exception in ~Store(): "
150 << ae.what() << endl;
152 #endif
154 ~Store()
156 cout << "Store counted " << dec << count << " records." << endl;
157 #ifdef __BARRY_BOOST_MODE__
158 try {
160 if( !load && filename.size() ) {
161 // filename is available, attempt to save
162 cout << "Saving: " << filename << endl;
163 const std::vector<Record> &r = records;
164 ofstream ofs(filename.c_str());
165 boost::archive::text_oarchive oa(ofs);
166 oa << r;
167 cout << dec << r.size() << " records saved to '"
168 << filename << "'" << endl;
171 } catch( boost::archive::archive_exception &ae ) {
172 cerr << "Archive exception in ~Store(): "
173 << ae.what() << endl;
175 #endif
178 // storage operator
179 void operator()(const Record &rec)
181 count++;
182 std::cout << rec << std::endl;
183 records.push_back(rec);
186 // retrieval operator
187 bool operator()(Record &rec, unsigned int databaseId) const
189 if( rec_it == records.end() )
190 return false;
191 rec = *rec_it;
192 rec_it++;
193 return true;
197 class DataDumpParser : public Barry::Parser
199 uint32_t m_id;
201 public:
202 virtual void SetUniqueId(uint32_t id)
204 m_id = id;
207 virtual void ParseFields(const Barry::Data &data, size_t &offset)
209 std::cout << "Raw record dump for record: "
210 << std::hex << m_id << std::endl;
211 std::cout << data << std::endl;
215 auto_ptr<Parser> GetParser(const string &name, const string &filename)
217 // check for recognized database names
218 if( name == Contact::GetDBName() ) {
219 return auto_ptr<Parser>(
220 new RecordParser<Contact, Store<Contact> > (
221 new Store<Contact>(filename, false)));
223 else if( name == Message::GetDBName() ) {
224 return auto_ptr<Parser>(
225 new RecordParser<Message, Store<Message> > (
226 new Store<Message>(filename, false)));
228 else if( name == Calendar::GetDBName() ) {
229 return auto_ptr<Parser>(
230 new RecordParser<Calendar, Store<Calendar> > (
231 new Store<Calendar>(filename, false)));
233 else if( name == ServiceBook::GetDBName() ) {
234 return auto_ptr<Parser>(
235 new RecordParser<ServiceBook, Store<ServiceBook> > (
236 new Store<ServiceBook>(filename, false)));
239 else if( name == Memo::GetDBName() ) {
240 return auto_ptr<Parser>(
241 new RecordParser<Memo, Store<Memo> > (
242 new Store<Memo>(filename, false)));
244 else if( name == Task::GetDBName() ) {
245 return auto_ptr<Parser>(
246 new RecordParser<Task, Store<Task> > (
247 new Store<Task>(filename, false)));
249 else if( name == PINMessage::GetDBName() ) {
250 return auto_ptr<Parser>(
251 new RecordParser<PINMessage, Store<PINMessage> > (
252 new Store<PINMessage>(filename, false)));
254 else if( name == SavedMessage::GetDBName() ) {
255 return auto_ptr<Parser>(
256 new RecordParser<SavedMessage, Store<SavedMessage> > (
257 new Store<SavedMessage>(filename, false)));
259 else if( name == Folder::GetDBName() ) {
260 return auto_ptr<Parser>(
261 new RecordParser<Folder, Store<Folder> > (
262 new Store<Folder>(filename, false)));
264 else if( name == Timezone::GetDBName() ) {
265 return auto_ptr<Parser>(
266 new RecordParser<Timezone, Store<Timezone> > (
267 new Store<Timezone>(filename, false)));
269 else {
270 // unknown database, use null parser
271 return auto_ptr<Parser>( new DataDumpParser );
275 auto_ptr<Builder> GetBuilder(const string &name, const string &filename)
277 // check for recognized database names
278 if( name == Contact::GetDBName() ) {
279 return auto_ptr<Builder>(
280 new RecordBuilder<Contact, Store<Contact> > (
281 new Store<Contact>(filename, true)));
284 else if( name == "Messages" ) {
285 return auto_ptr<Parser>(
286 new RecordParser<Message, Store<Message> > (
287 new Store<Message>(filename, true)));
289 else if( name == "Calendar" ) {
290 return auto_ptr<Parser>(
291 new RecordParser<Calendar, Store<Calendar> > (
292 new Store<Calendar>(filename, true)));
294 else if( name == "Service Book" ) {
295 return auto_ptr<Parser>(
296 new RecordParser<ServiceBook, Store<ServiceBook> > (
297 new Store<ServiceBook>(filename, true)));
299 else if( name == "Memos" ) {
300 return auto_ptr<Parser>(
301 new RecordParser<Memo, Store<Memo> > (
302 new Store<Memo>(filename, true)));
304 else if( name == "Tasks" ) {
305 return auto_ptr<Parser>(
306 new RecordParser<Task, Store<Task> > (
307 new Store<Task>(filename, true)));
310 else {
311 throw std::runtime_error("No Builder available for database");
315 void ShowParsers()
317 cout << "Supported Database parsers:\n"
318 << " Address Book\n"
319 << " Messages\n"
320 << " Calendar\n"
321 << " Service Book\n"
322 << " Memos\n"
323 << " Tasks\n"
324 << " PIN Messages\n"
325 << " Saved Email Messages\n"
326 << " Folders\n"
327 << "\n"
328 << "Supported Database builders:\n"
329 << " Address Book\n"
330 << endl;
333 struct StateTableCommand
335 char flag;
336 bool clear;
337 unsigned int index;
339 StateTableCommand(char f, bool c, unsigned int i)
340 : flag(f), clear(c), index(i) {}
343 bool SplitMap(const string &map, string &ldif, string &read, string &write)
345 string::size_type a = map.find(',');
346 if( a == string::npos )
347 return false;
349 string::size_type b = map.find(',', a+1);
350 if( b == string::npos )
351 return false;
353 ldif.assign(map, 0, a);
354 read.assign(map, a + 1, b - a - 1);
355 write.assign(map, b + 1, map.size() - b - 1);
357 return ldif.size() && read.size() && write.size();
360 void DoMapping(ContactLdif &ldif, const vector<string> &mapCommands)
362 for( vector<string>::const_iterator i = mapCommands.begin();
363 i != mapCommands.end();
364 ++i )
366 // single names mean unmapping
367 if( i->find(',') == string::npos ) {
368 // unmap
369 cerr << "Unmapping: " << *i << endl;
370 ldif.Unmap(*i);
372 else {
373 cerr << "Mapping: " << *i << endl;
375 // map... extract ldif/read/write names
376 string ldifname, read, write;
377 if( SplitMap(*i, ldifname, read, write) ) {
378 if( !ldif.Map(ldifname, read, write) ) {
379 cerr << "Read/Write name unknown: " << *i << endl;
382 else {
383 cerr << "Invalid map format: " << *i << endl;
389 bool ParseEpOverride(const char *arg, Usb::EndpointPair *epp)
391 int read, write;
392 char comma;
393 istringstream iss(arg);
394 iss >> hex >> read >> comma >> write;
395 if( !iss )
396 return false;
397 epp->read = read;
398 epp->write = write;
399 return true;
402 int main(int argc, char *argv[])
404 cout.sync_with_stdio(true); // leave this on, since libusb uses
405 // stdio for debug messages
407 try {
409 uint32_t pin = 0;
410 bool list_only = false,
411 show_dbdb = false,
412 ldif_contacts = false,
413 data_dump = false,
414 reset_device = false,
415 list_contact_fields = false,
416 list_ldif_map = false,
417 epp_override = false,
418 record_state = false;
419 string ldifBaseDN, ldifDnAttr;
420 string filename;
421 string password;
422 string busname;
423 string devname;
424 vector<string> dbNames, saveDbNames, mapCommands;
425 vector<StateTableCommand> stCommands;
426 Usb::EndpointPair epOverride;
428 // process command line options
429 for(;;) {
430 int cmd = getopt(argc, argv, "B:c:C:d:D:e:f:hlLm:MN:p:P:r:R:Ss:tT:vX");
431 if( cmd == -1 )
432 break;
434 switch( cmd )
436 case 'B': // busname
437 busname = optarg;
438 break;
440 case 'c': // contacts to ldap ldif
441 ldif_contacts = true;
442 ldifBaseDN = optarg;
443 break;
445 case 'C': // DN Attribute for FQDN
446 ldifDnAttr = optarg;
447 break;
449 case 'd': // show dbname
450 dbNames.push_back(string(optarg));
451 break;
453 case 'D': // delete record
454 stCommands.push_back(
455 StateTableCommand('D', false, atoi(optarg)));
456 break;
458 case 'e': // endpoint override
459 if( !ParseEpOverride(optarg, &epOverride) ) {
460 Usage();
461 return 1;
463 epp_override = true;
464 break;
466 case 'f': // filename
467 #ifdef __BARRY_BOOST_MODE__
468 filename = optarg;
469 #else
470 cerr << "-f option not supported - no Boost "
471 "serialization support available\n";
472 return 1;
473 #endif
474 break;
475 case 'l': // list only
476 list_only = true;
477 break;
479 case 'L': // List Contact field names
480 list_contact_fields = true;
481 break;
483 case 'm': // Map / Unmap
484 mapCommands.push_back(string(optarg));
485 break;
487 case 'M': // List LDIF map
488 list_ldif_map = true;
489 break;
491 case 'N': // Devname
492 devname = optarg;
493 break;
495 case 'p': // Blackberry PIN
496 pin = strtoul(optarg, NULL, 16);
497 break;
499 case 'P': // Device password
500 password = optarg;
501 break;
503 case 'r': // get specific record index
504 stCommands.push_back(
505 StateTableCommand('r', false, atoi(optarg)));
506 break;
508 case 'R': // same as 'r', and clears dirty
509 stCommands.push_back(
510 StateTableCommand('r', true, atoi(optarg)));
511 break;
513 case 's': // save dbname
514 saveDbNames.push_back(string(optarg));
515 break;
517 case 'S': // show supported databases
518 ShowParsers();
519 return 0;
521 case 't': // display database database
522 show_dbdb = true;
523 break;
525 case 'T': // show RecordStateTable
526 record_state = true;
527 dbNames.push_back(string(optarg));
528 break;
530 case 'v': // data dump on
531 data_dump = true;
532 break;
534 case 'X': // reset device
535 reset_device = true;
536 break;
538 case 'h': // help
539 default:
540 Usage();
541 return 0;
545 // Initialize the barry library. Must be called before
546 // anything else.
547 Barry::Init(data_dump);
549 // LDIF class... only needed if ldif output turned on
550 ContactLdif ldif(ldifBaseDN);
551 DoMapping(ldif, mapCommands);
552 if( ldifDnAttr.size() ) {
553 if( !ldif.SetDNAttr(ldifDnAttr) ) {
554 cerr << "Unable to set DN Attr: " << ldifDnAttr << endl;
558 // Probe the USB bus for Blackberry devices and display.
559 // If user has specified a PIN, search for it in the
560 // available device list here as well
561 Barry::Probe probe(busname.c_str(), devname.c_str());
562 int activeDevice = -1;
564 // show any errors during probe first
565 if( probe.GetFailCount() ) {
566 if( ldif_contacts )
567 cout << "# ";
568 cout << "Blackberry device errors with errors during probe:" << endl;
569 for( int i = 0; i < probe.GetFailCount(); i++ ) {
570 if( ldif_contacts )
571 cout << "# ";
572 cout << probe.GetFailMsg(i) << endl;
576 // show all successfully found devices
577 if( ldif_contacts )
578 cout << "# ";
579 cout << "Blackberry devices found:" << endl;
580 for( int i = 0; i < probe.GetCount(); i++ ) {
581 if( ldif_contacts )
582 cout << "# ";
583 cout << probe.Get(i) << endl;
584 if( probe.Get(i).m_pin == pin )
585 activeDevice = i;
588 if( list_only )
589 return 0; // done
591 if( activeDevice == -1 ) {
592 if( pin == 0 ) {
593 // can we default to single device?
594 if( probe.GetCount() == 1 )
595 activeDevice = 0;
596 else {
597 cerr << "No device selected" << endl;
598 return 1;
601 else {
602 cerr << "PIN " << setbase(16) << pin
603 << " not found" << endl;
604 return 1;
608 if( ldif_contacts )
609 cout << "# ";
610 cout << "Using device (PIN): " << setbase(16)
611 << probe.Get(activeDevice).m_pin << endl;
613 if( reset_device ) {
614 Usb::Device dev(probe.Get(activeDevice).m_dev);
615 dev.Reset();
616 return 0;
619 // Create our controller object
620 Barry::ProbeResult device = probe.Get(activeDevice);
621 if( epp_override ) {
622 device.m_ep.read = epOverride.read;
623 device.m_ep.write = epOverride.write;
624 device.m_ep.type = 2; // FIXME - override this too?
625 cout << "Endpoint pair (read,write) overridden with: "
626 << hex
627 << (unsigned int) device.m_ep.read << ","
628 << (unsigned int) device.m_ep.write << endl;
630 Barry::Controller con(device);
633 // execute each mode that was turned on
637 // Dump list of all databases to stdout
638 if( show_dbdb ) {
639 // open desktop mode socket
640 con.OpenMode(Controller::Desktop, password.c_str());
641 cout << con.GetDBDB() << endl;
644 // Dump list of Contact field names
645 if( list_contact_fields ) {
646 for( const ContactLdif::NameToFunc *n = ldif.GetFieldNames(); n->name; n++ ) {
647 cout.fill(' ');
648 cout << " " << left << setw(20) << n->name << ": "
649 << n->description << endl;
653 // Dump current LDIF mapping
654 if( list_ldif_map ) {
655 cout << ldif << endl;
658 // Dump list of contacts to an LDAP LDIF file
659 // This uses the Controller convenience templates
660 if( ldif_contacts ) {
661 // make sure we're in desktop mode
662 con.OpenMode(Controller::Desktop, password.c_str());
664 // create a storage functor object that accepts
665 // Barry::Contact objects as input
666 Contact2Ldif storage(ldif);
668 // load all the Contact records into storage
669 con.LoadDatabaseByType<Barry::Contact>(storage);
672 // Dump record state table to stdout
673 if( record_state ) {
674 if( dbNames.size() == 0 ) {
675 cout << "No db names to process" << endl;
676 return 1;
679 vector<string>::iterator b = dbNames.begin();
680 for( ; b != dbNames.end(); b++ ) {
681 con.OpenMode(Controller::Desktop, password.c_str());
682 unsigned int id = con.GetDBID(*b);
683 RecordStateTable state;
684 con.GetRecordStateTable(id, state);
685 cout << "Record state table for: " << *b << endl;
686 cout << state;
688 return 0;
691 // Get Record mode overrides the default name mode
692 if( stCommands.size() ) {
693 if( dbNames.size() != 1 ) {
694 cout << "Must have 1 db name to process" << endl;
695 return 1;
698 con.OpenMode(Controller::Desktop, password.c_str());
699 unsigned int id = con.GetDBID(dbNames[0]);
700 auto_ptr<Parser> parse = GetParser(dbNames[0],filename);
702 for( unsigned int i = 0; i < stCommands.size(); i++ ) {
703 con.GetRecord(id, stCommands[i].index, *parse.get());
705 if( stCommands[i].flag == 'r' && stCommands[i].clear ) {
706 cout << "Clearing record's dirty flags..." << endl;
707 con.ClearDirty(id, stCommands[i].index);
710 if( stCommands[i].flag == 'D' ) {
711 con.DeleteRecord(id, stCommands[i].index);
715 return 0;
718 // Dump contents of selected databases to stdout, or
719 // to file if specified.
720 // This is retrieving data from the Blackberry.
721 if( dbNames.size() ) {
722 vector<string>::iterator b = dbNames.begin();
724 for( ; b != dbNames.end(); b++ ) {
725 con.OpenMode(Controller::Desktop, password.c_str());
726 auto_ptr<Parser> parse = GetParser(*b,filename);
727 unsigned int id = con.GetDBID(*b);
728 con.LoadDatabase(id, *parse.get());
732 // Save contents of file to specified databases
733 // This is writing data to the Blackberry.
734 if( saveDbNames.size() ) {
735 vector<string>::iterator b = saveDbNames.begin();
737 for( ; b != saveDbNames.end(); b++ ) {
738 con.OpenMode(Controller::Desktop, password.c_str());
739 auto_ptr<Builder> build =
740 GetBuilder(*b, filename);
741 unsigned int id = con.GetDBID(*b);
742 con.SaveDatabase(id, *build);
747 catch( Usb::Error &ue) {
748 std::cerr << "Usb::Error caught: " << ue.what() << endl;
749 return 1;
751 catch( Barry::Error &se ) {
752 std::cerr << "Barry::Error caught: " << se.what() << endl;
753 return 1;
755 catch( std::exception &e ) {
756 std::cerr << "std::exception caught: " << e.what() << endl;
757 return 1;
760 return 0;