lib: show offset and rectype in HexDumpParser
[barry.git] / tools / btool.cc
blobc122777becb149121d3b54833054e190fa5e0415
1 ///
2 /// \file btool.cc
3 /// Barry library tester
4 ///
6 /*
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>
23 #ifdef __BARRY_SYNC_MODE__
24 #include <barry/barrysync.h>
25 #endif
26 #ifdef __BARRY_BACKUP_MODE__
27 #include <barry/barrybackup.h>
28 #endif
30 #include <iomanip>
31 #include <iostream>
32 #include <fstream>
33 #include <sstream>
34 #include <vector>
35 #include <string>
36 #include <algorithm>
37 #include <getopt.h>
38 #include <tr1/memory>
39 #include "i18n.h"
42 using namespace std;
43 using namespace std::tr1;
44 using namespace Barry;
46 void Usage()
48 int major, minor;
49 const char *Version = Barry::Version(major, minor);
51 cerr
52 << "btool - Command line USB Blackberry Test Tool\n"
53 << " Copyright 2005-2010, Net Direct Inc. (http://www.netdirect.ca/)\n"
54 << " Using: " << Version << "\n"
55 << " Compiled "
56 #ifdef __BARRY_BOOST_MODE__
57 << "with"
58 #else
59 << "without"
60 #endif
61 << " Boost support\n"
62 << "\n"
63 << " -b file Filename to save or load a Barry Backup to (tar.gz)\n"
64 << " -B bus Specify which USB bus to search on\n"
65 << " -N dev Specify which system device, using system specific string\n"
66 << "\n"
67 << " -a db Erase / clear database 'db' FROM device, deleting all\n"
68 << " its records. Can be used multiple times to clear more\n"
69 << " than one DB.\n"
70 << " -c dn Convert address book database to LDIF format, using the\n"
71 << " specified baseDN\n"
72 << " -C dnattr LDIF attribute name to use when building the FQDN\n"
73 << " Defaults to 'cn'\n"
74 << " -d db Load database 'db' FROM device and dump to screen\n"
75 << " Can be used multiple times to fetch more than one DB\n"
76 << " -e epp Override endpoint pair detection. 'epp' is a single\n"
77 << " string separated by a comma, holding the read,write\n"
78 << " endpoint pair. Example: -e 83,5\n"
79 << " Note: Endpoints are specified in hex.\n"
80 << " You should never need to use this option.\n"
81 #ifdef __BARRY_BOOST_MODE__
82 << " -f file Filename to save or load handheld data to/from\n"
83 #endif
84 << " -h This help\n"
85 << " -i cs International charset for string conversions\n"
86 << " Valid values here are available with 'iconv --list'\n"
87 << " -I Sort records before output\n"
88 << " -l List devices\n"
89 << " -L List Contact field names\n"
90 << " -m Map LDIF name to Contact field / Unmap LDIF name\n"
91 << " Map: ldif,read,write - maps ldif to read/write Contact fields\n"
92 << " Unmap: ldif name alone\n"
93 << " -M List current LDIF mapping\n"
94 << " -n Use null parser on all databases.\n"
95 << " -p pin PIN of device to talk with\n"
96 << " If only one device is plugged in, this flag is optional\n"
97 << " -P pass Simplistic method to specify device password\n"
98 << " -s db Save database 'db' TO device from data loaded from -f file\n"
99 << " -S Show list of supported database parsers\n"
100 << " -t Show database database table\n"
101 << " -T db Show record state table for given database\n"
102 << " -v Dump protocol data during operation\n"
103 #ifdef __BARRY_SYNC_MODE__
104 << " -V Dump records using MIME vformats where possible\n"
105 #endif
106 << " -X Reset device\n"
107 << " -z Use non-threaded sockets\n"
108 << " -Z Use threaded socket router (default)\n"
109 << "\n"
110 << " -d Command modifiers: (can be used multiple times for more than 1 record)\n"
111 << "\n"
112 << " -r # Record index number as seen in the -T state table.\n"
113 << " This overrides the default -d behaviour, and only\n"
114 << " downloads the one specified record, sending to stdout.\n"
115 << " -R # Same as -r, but also clears the record's dirty flags.\n"
116 << " -D # Record index number as seen in the -T state table,\n"
117 << " which indicates the record to delete. Used with the -d\n"
118 << " command to specify the database.\n"
119 << endl;
122 class Contact2Ldif
124 public:
125 Barry::ContactLdif &ldif;
127 Contact2Ldif(Barry::ContactLdif &ldif) : ldif(ldif) {}
129 void operator()(const Contact &rec)
131 ldif.DumpLdif(cout, rec);
135 #ifdef __BARRY_SYNC_MODE__
136 template <class Record>
137 class MimeDump
139 public:
140 static void Dump(std::ostream &os, const Record &rec)
142 os << rec << endl;
145 static bool Supported() { return false; }
148 template <>
149 class MimeDump<Contact>
151 public:
152 static void Dump(std::ostream &os, const Contact &rec)
154 Sync::vCard vcard;
155 os << vcard.ToVCard(rec) << endl;
158 static bool Supported() { return true; }
161 template <>
162 class MimeDump<Calendar>
164 public:
165 static void Dump(std::ostream &os, const Calendar &rec)
167 Sync::vTimeConverter vtc;
168 Sync::vCalendar vcal(vtc);
169 os << vcal.ToVCal(rec) << endl;
172 static bool Supported() { return true; }
175 template <>
176 class MimeDump<Memo>
178 public:
179 static void Dump(std::ostream &os, const Memo &rec)
181 Sync::vJournal vjournal;
182 os << vjournal.ToMemo(rec) << endl;
185 static bool Supported() { return true; }
188 template <>
189 class MimeDump<Task>
191 public:
192 static void Dump(std::ostream &os, const Task &rec)
194 Sync::vTimeConverter vtc;
195 Sync::vTodo vtodo(vtc);
196 os << vtodo.ToTask(rec) << endl;
199 static bool Supported() { return true; }
201 #endif
203 template <class Record>
204 struct Store
206 std::vector<Record> records;
207 mutable typename std::vector<Record>::const_iterator rec_it;
208 std::string filename;
209 bool load;
210 bool immediate_display;
211 bool vformat_mode;
212 int count;
214 Store(const string &filename, bool load, bool immediate_display,
215 bool vformat_mode)
216 : rec_it(records.end()),
217 filename(filename),
218 load(load),
219 immediate_display(immediate_display),
220 vformat_mode(vformat_mode),
221 count(0)
223 #ifdef __BARRY_BOOST_MODE__
224 try {
226 if( load && filename.size() ) {
227 // filename is available, attempt to load
228 cout << "Loading: " << filename << endl;
229 ifstream ifs(filename.c_str());
230 std::string dbName;
231 getline(ifs, dbName);
232 boost::archive::text_iarchive ia(ifs);
233 ia >> records;
234 cout << records.size()
235 << " records loaded from '"
236 << filename << "'" << endl;
237 sort(records.begin(), records.end());
238 rec_it = records.begin();
240 // debugging aid
241 typename std::vector<Record>::const_iterator beg = records.begin(), end = records.end();
242 for( ; beg != end; beg++ ) {
243 cout << (*beg) << endl;
247 } catch( boost::archive::archive_exception &ae ) {
248 cerr << "Archive exception in ~Store(): "
249 << ae.what() << endl;
251 #endif
254 ~Store()
256 if( !immediate_display ) {
257 // not dumped yet, sort then dump
258 sort(records.begin(), records.end());
259 DumpAll();
262 cout << "Store counted " << dec << count << " records." << endl;
263 #ifdef __BARRY_BOOST_MODE__
264 try {
266 if( !load && filename.size() ) {
267 // filename is available, attempt to save
268 cout << "Saving: " << filename << endl;
269 const std::vector<Record> &r = records;
270 ofstream ofs(filename.c_str());
271 ofs << Record::GetDBName() << endl;
272 boost::archive::text_oarchive oa(ofs);
273 oa << r;
274 cout << dec << r.size() << " records saved to '"
275 << filename << "'" << endl;
278 } catch( boost::archive::archive_exception &ae ) {
279 cerr << "Archive exception in ~Store(): "
280 << ae.what() << endl;
282 #endif
285 void DumpAll()
287 typename vector<Record>::const_iterator i = records.begin();
288 for( ; i != records.end(); ++i ) {
289 Dump(*i);
293 void Dump(const Record &rec)
295 if( vformat_mode ) {
296 #ifdef __BARRY_SYNC_MODE__
297 MimeDump<Record> md;
298 md.Dump(cout, rec);
299 #endif
301 else {
302 cout << rec << endl;
306 // storage operator
307 void operator()(const Record &rec)
309 count++;
310 if( immediate_display )
311 Dump(rec);
312 records.push_back(rec);
315 // retrieval operator
316 bool operator()(Record &rec, Builder &builder) const
318 if( rec_it == records.end() )
319 return false;
320 rec = *rec_it;
321 rec_it++;
322 return true;
326 shared_ptr<Parser> GetParser(const string &name,
327 const string &filename,
328 bool null_parser,
329 bool immediate_display,
330 bool vformat_mode,
331 bool bbackup_mode)
333 bool dnow = immediate_display;
334 bool vmode = vformat_mode;
336 if( null_parser ) {
337 // use null parser
338 return shared_ptr<Parser>( new Barry::HexDumpParser(cout) );
340 else if( bbackup_mode ) {
341 #ifdef __BARRY_BACKUP_MODE__
342 // Only one backup file per run
343 static shared_ptr<Parser> backup;
344 if( !backup.get() ) {
345 backup.reset( new Backup(filename) );
347 return backup;
348 #else
349 return shared_ptr<Parser>( new Barry::HexDumpParser(cout) );
350 #endif
352 // check for recognized database names
353 else if( name == Contact::GetDBName() ) {
354 return shared_ptr<Parser>(
355 new RecordParser<Contact, Store<Contact> > (
356 new Store<Contact>(filename, false, dnow, vmode)));
358 else if( name == Message::GetDBName() ) {
359 return shared_ptr<Parser>(
360 new RecordParser<Message, Store<Message> > (
361 new Store<Message>(filename, false, dnow, vmode)));
363 else if( name == Calendar::GetDBName() ) {
364 return shared_ptr<Parser>(
365 new RecordParser<Calendar, Store<Calendar> > (
366 new Store<Calendar>(filename, false, dnow, vmode)));
368 else if( name == CalendarAll::GetDBName() ) {
369 return shared_ptr<Parser>(
370 new RecordParser<CalendarAll, Store<CalendarAll> > (
371 new Store<CalendarAll>(filename, false, dnow, vmode)));
373 else if( name == CallLog::GetDBName() ) {
374 return shared_ptr<Parser>(
375 new RecordParser<CallLog, Store<CallLog> > (
376 new Store<CallLog>(filename, false, dnow, vmode)));
378 else if( name == Bookmark::GetDBName() ) {
379 return shared_ptr<Parser>(
380 new RecordParser<Bookmark, Store<Bookmark> > (
381 new Store<Bookmark>(filename, false, dnow, vmode)));
383 else if( name == ServiceBook::GetDBName() ) {
384 return shared_ptr<Parser>(
385 new RecordParser<ServiceBook, Store<ServiceBook> > (
386 new Store<ServiceBook>(filename, false, dnow, vmode)));
389 else if( name == Memo::GetDBName() ) {
390 return shared_ptr<Parser>(
391 new RecordParser<Memo, Store<Memo> > (
392 new Store<Memo>(filename, false, dnow, vmode)));
394 else if( name == Task::GetDBName() ) {
395 return shared_ptr<Parser>(
396 new RecordParser<Task, Store<Task> > (
397 new Store<Task>(filename, false, dnow, vmode)));
399 else if( name == PINMessage::GetDBName() ) {
400 return shared_ptr<Parser>(
401 new RecordParser<PINMessage, Store<PINMessage> > (
402 new Store<PINMessage>(filename, false, dnow, vmode)));
404 else if( name == SavedMessage::GetDBName() ) {
405 return shared_ptr<Parser>(
406 new RecordParser<SavedMessage, Store<SavedMessage> > (
407 new Store<SavedMessage>(filename, false, dnow, vmode)));
409 else if( name == Sms::GetDBName() ) {
410 return shared_ptr<Parser>(
411 new RecordParser<Sms, Store<Sms> > (
412 new Store<Sms>(filename, false, dnow, vmode)));
414 else if( name == Folder::GetDBName() ) {
415 return shared_ptr<Parser>(
416 new RecordParser<Folder, Store<Folder> > (
417 new Store<Folder>(filename, false, dnow, vmode)));
419 else if( name == Timezone::GetDBName() ) {
420 return shared_ptr<Parser>(
421 new RecordParser<Timezone, Store<Timezone> > (
422 new Store<Timezone>(filename, false, dnow, vmode)));
424 else {
425 // unknown database, use null parser
426 return shared_ptr<Parser>( new Barry::HexDumpParser(cout) );
430 shared_ptr<Builder> GetBuilder(const string &name, const string &filename)
432 // check for recognized database names
433 if( name == Contact::GetDBName() ) {
434 return shared_ptr<Builder>(
435 new RecordBuilder<Contact, Store<Contact> > (
436 new Store<Contact>(filename, true, true, false)));
438 else if( name == Calendar::GetDBName() ) {
439 return shared_ptr<Builder>(
440 new RecordBuilder<Calendar, Store<Calendar> > (
441 new Store<Calendar>(filename, true, true, false)));
443 else if( name == CalendarAll::GetDBName() ) {
444 return shared_ptr<Builder>(
445 new RecordBuilder<CalendarAll, Store<CalendarAll> > (
446 new Store<CalendarAll>(filename, true, true, false)));
448 else if( name == Memo::GetDBName() ) {
449 return shared_ptr<Builder>(
450 new RecordBuilder<Memo, Store<Memo> > (
451 new Store<Memo>(filename, true, true, false)));
453 else if( name == Task::GetDBName() ) {
454 return shared_ptr<Builder>(
455 new RecordBuilder<Task, Store<Task> > (
456 new Store<Task>(filename, true, true, false)));
459 else if( name == "Messages" ) {
460 return shared_ptr<Parser>(
461 new RecordParser<Message, Store<Message> > (
462 new Store<Message>(filename, true, true, false)));
464 else if( name == "Service Book" ) {
465 return shared_ptr<Parser>(
466 new RecordParser<ServiceBook, Store<ServiceBook> > (
467 new Store<ServiceBook>(filename, true, true, false)));
470 else {
471 throw std::runtime_error("No Builder available for database");
475 void ShowParsers()
477 cout << "Supported Database parsers:\n"
478 #undef HANDLE_PARSER
479 #ifdef __BARRY_SYNC_MODE__
480 << " (* = can display in vformat MIME mode)\n"
481 #define HANDLE_PARSER(tname) << " " << tname::GetDBName() << (MimeDump<tname>::Supported() ? " *" : "") << "\n"
483 #else
484 #define HANDLE_PARSER(tname) << " " << tname::GetDBName() << "\n"
486 #endif
487 ALL_KNOWN_PARSER_TYPES
489 << "\n"
491 << "Supported Database builders:\n"
492 #undef HANDLE_BUILDER
493 #define HANDLE_BUILDER(tname) << " " << tname::GetDBName() << "\n"
494 ALL_KNOWN_BUILDER_TYPES
495 << endl;
498 struct StateTableCommand
500 char flag;
501 bool clear;
502 unsigned int index;
504 StateTableCommand(char f, bool c, unsigned int i)
505 : flag(f), clear(c), index(i) {}
508 bool SplitMap(const string &map, string &ldif, string &read, string &write)
510 string::size_type a = map.find(',');
511 if( a == string::npos )
512 return false;
514 string::size_type b = map.find(',', a+1);
515 if( b == string::npos )
516 return false;
518 ldif.assign(map, 0, a);
519 read.assign(map, a + 1, b - a - 1);
520 write.assign(map, b + 1, map.size() - b - 1);
522 return ldif.size() && read.size() && write.size();
525 void DoMapping(ContactLdif &ldif, const vector<string> &mapCommands)
527 for( vector<string>::const_iterator i = mapCommands.begin();
528 i != mapCommands.end();
529 ++i )
531 // single names mean unmapping
532 if( i->find(',') == string::npos ) {
533 // unmap
534 cerr << "Unmapping: " << *i << endl;
535 ldif.Unmap(*i);
537 else {
538 cerr << "Mapping: " << *i << endl;
540 // map... extract ldif/read/write names
541 string ldifname, read, write;
542 if( SplitMap(*i, ldifname, read, write) ) {
543 if( !ldif.Map(ldifname, read, write) ) {
544 cerr << "Read/Write name unknown: " << *i << endl;
547 else {
548 cerr << "Invalid map format: " << *i << endl;
554 bool ParseEpOverride(const char *arg, Usb::EndpointPair *epp)
556 int read, write;
557 char comma;
558 istringstream iss(arg);
559 iss >> hex >> read >> comma >> write;
560 if( !iss )
561 return false;
562 epp->read = read;
563 epp->write = write;
564 return true;
567 int main(int argc, char *argv[])
569 INIT_I18N(PACKAGE);
571 cout.sync_with_stdio(true); // leave this on, since libusb uses
572 // stdio for debug messages
574 try {
576 uint32_t pin = 0;
577 bool list_only = false,
578 show_dbdb = false,
579 ldif_contacts = false,
580 data_dump = false,
581 vformat_mode = false,
582 reset_device = false,
583 list_contact_fields = false,
584 list_ldif_map = false,
585 epp_override = false,
586 threaded_sockets = true,
587 record_state_table = false,
588 clear_database = false,
589 null_parser = false,
590 bbackup_mode = false,
591 sort_records = false;
592 string ldifBaseDN, ldifDnAttr;
593 string filename;
594 string password;
595 string busname;
596 string devname;
597 string iconvCharset;
598 vector<string> dbNames, saveDbNames, mapCommands, clearDbNames;
599 vector<StateTableCommand> stCommands;
600 Usb::EndpointPair epOverride;
602 // process command line options
603 for(;;) {
604 int cmd = getopt(argc, argv, "a:b:B:c:C:d:D:e:f:hi:IlLm:MnN:p:P:r:R:Ss:tT:vVXzZ");
605 if( cmd == -1 )
606 break;
608 switch( cmd )
610 case 'a': // Clear Database
611 clear_database = true;
612 clearDbNames.push_back(string(optarg));
613 break;
615 case 'b': // Barry backup filename (tar.gz)
616 #ifdef __BARRY_BACKUP_MODE__
617 if( filename.size() == 0 ) {
618 filename = optarg;
619 bbackup_mode = true;
621 else {
622 cerr << "Do not use -f with -b\n";
623 return 1;
625 #else
626 cerr << "-b option not supported - no Barry "
627 "Backup library support available\n";
628 return 1;
629 #endif
630 break;
632 case 'B': // busname
633 busname = optarg;
634 break;
636 case 'c': // contacts to ldap ldif
637 ldif_contacts = true;
638 ldifBaseDN = optarg;
639 break;
641 case 'C': // DN Attribute for FQDN
642 ldifDnAttr = optarg;
643 break;
645 case 'd': // show dbname
646 dbNames.push_back(string(optarg));
647 break;
649 case 'D': // delete record
650 stCommands.push_back(
651 StateTableCommand('D', false, atoi(optarg)));
652 break;
654 case 'e': // endpoint override
655 if( !ParseEpOverride(optarg, &epOverride) ) {
656 Usage();
657 return 1;
659 epp_override = true;
660 break;
662 case 'f': // filename
663 #ifdef __BARRY_BOOST_MODE__
664 if( !bbackup_mode && filename.size() == 0 ) {
665 filename = optarg;
667 else {
668 cerr << "Do not use -f with -b\n";
669 return 1;
671 #else
672 cerr << "-f option not supported - no Boost "
673 "serialization support available\n";
674 return 1;
675 #endif
676 break;
678 case 'i': // international charset (iconv)
679 iconvCharset = optarg;
680 break;
682 case 'I': // sort before dump
683 sort_records = true;
684 break;
686 case 'l': // list only
687 list_only = true;
688 break;
690 case 'L': // List Contact field names
691 list_contact_fields = true;
692 break;
694 case 'm': // Map / Unmap
695 mapCommands.push_back(string(optarg));
696 break;
698 case 'M': // List LDIF map
699 list_ldif_map = true;
700 break;
702 case 'n': // use null parser
703 null_parser = true;
704 break;
706 case 'N': // Devname
707 devname = optarg;
708 break;
710 case 'p': // Blackberry PIN
711 pin = strtoul(optarg, NULL, 16);
712 break;
714 case 'P': // Device password
715 password = optarg;
716 break;
718 case 'r': // get specific record index
719 stCommands.push_back(
720 StateTableCommand('r', false, atoi(optarg)));
721 break;
723 case 'R': // same as 'r', and clears dirty
724 stCommands.push_back(
725 StateTableCommand('r', true, atoi(optarg)));
726 break;
728 case 's': // save dbname
729 saveDbNames.push_back(string(optarg));
730 break;
732 case 'S': // show supported databases
733 ShowParsers();
734 return 0;
736 case 't': // display database database
737 show_dbdb = true;
738 break;
740 case 'T': // show RecordStateTable
741 record_state_table = true;
742 dbNames.push_back(string(optarg));
743 break;
745 case 'v': // data dump on
746 data_dump = true;
747 break;
749 case 'V': // vformat MIME mode
750 #ifdef __BARRY_SYNC_MODE__
751 vformat_mode = true;
752 #else
753 cerr << "-V option not supported - no Sync "
754 "library support available\n";
755 return 1;
756 #endif
757 break;
759 case 'X': // reset device
760 reset_device = true;
761 break;
763 case 'z': // non-threaded sockets
764 threaded_sockets = false;
765 break;
767 case 'Z': // threaded socket router
768 threaded_sockets = true;
769 break;
771 case 'h': // help
772 default:
773 Usage();
774 return 0;
778 // Initialize the barry library. Must be called before
779 // anything else.
780 Barry::Init(data_dump);
781 if( data_dump ) {
782 int major, minor;
783 const char *Version = Barry::Version(major, minor);
784 cout << Version << endl;
787 // Create an IConverter object if needed
788 auto_ptr<IConverter> ic;
789 if( iconvCharset.size() ) {
790 ic.reset( new IConverter(iconvCharset.c_str(), true) );
793 // LDIF class... only needed if ldif output turned on
794 ContactLdif ldif(ldifBaseDN);
795 DoMapping(ldif, mapCommands);
796 if( ldifDnAttr.size() ) {
797 if( !ldif.SetDNAttr(ldifDnAttr) ) {
798 cerr << "Unable to set DN Attr: " << ldifDnAttr << endl;
802 // Probe the USB bus for Blackberry devices and display.
803 // If user has specified a PIN, search for it in the
804 // available device list here as well
805 Barry::Probe probe(busname.c_str(), devname.c_str(),
806 epp_override ? &epOverride : 0);
807 int activeDevice = -1;
809 // show any errors during probe first
810 if( probe.GetFailCount() ) {
811 if( ldif_contacts )
812 cout << "# ";
813 cout << "Blackberry device errors with errors during probe:" << endl;
814 for( int i = 0; i < probe.GetFailCount(); i++ ) {
815 if( ldif_contacts )
816 cout << "# ";
817 cout << probe.GetFailMsg(i) << endl;
821 // show all successfully found devices
822 if( ldif_contacts )
823 cout << "# ";
824 cout << "Blackberry devices found:" << endl;
825 for( int i = 0; i < probe.GetCount(); i++ ) {
826 if( ldif_contacts )
827 cout << "# ";
828 if( data_dump )
829 probe.Get(i).DumpAll(cout);
830 else
831 cout << probe.Get(i);
832 cout << endl;
833 if( probe.Get(i).m_pin == pin )
834 activeDevice = i;
837 if( list_only )
838 return 0; // done
840 if( activeDevice == -1 ) {
841 if( pin == 0 ) {
842 // can we default to single device?
843 if( probe.GetCount() == 1 )
844 activeDevice = 0;
845 else {
846 cerr << "No device selected" << endl;
847 return 1;
850 else {
851 cerr << "PIN " << setbase(16) << pin
852 << " not found" << endl;
853 return 1;
857 if( ldif_contacts )
858 cout << "# ";
859 cout << "Using device (PIN): "
860 << probe.Get(activeDevice).m_pin.Str() << endl;
862 if( reset_device ) {
863 Usb::Device dev(probe.Get(activeDevice).m_dev);
864 dev.Reset();
865 return 0;
868 // Override device endpoints if user asks
869 Barry::ProbeResult device = probe.Get(activeDevice);
870 if( epp_override ) {
871 device.m_ep.read = epOverride.read;
872 device.m_ep.write = epOverride.write;
873 device.m_ep.type = 2; // FIXME - override this too?
874 cout << "Endpoint pair (read,write) overridden with: "
875 << hex
876 << (unsigned int) device.m_ep.read << ","
877 << (unsigned int) device.m_ep.write << endl;
881 // execute each mode that was turned on
885 // Dump current LDIF mapping
886 if( list_ldif_map ) {
887 cout << ldif << endl;
890 // Dump list of Contact field names
891 if( list_contact_fields ) {
892 for( const ContactLdif::NameToFunc *n = ldif.GetFieldNames(); n->name; n++ ) {
893 cout.fill(' ');
894 cout << " " << left << setw(20) << n->name << ": "
895 << n->description << endl;
899 // Check if Desktop access is needed
900 if( !( show_dbdb ||
901 ldif_contacts ||
902 record_state_table ||
903 clear_database ||
904 stCommands.size() ||
905 dbNames.size() ||
906 saveDbNames.size() ) )
907 return 0; // done
910 // Create our controller object
912 // Order is important in the following auto_ptr<> objects,
913 // since Controller must get destroyed before router.
914 // Normally you'd pick one method, and not bother
915 // with auto_ptr<> and so the normal C++ constructor
916 // rules would guarantee this safety for you, but
917 // here we want the user to pick.
919 auto_ptr<SocketRoutingQueue> router;
920 auto_ptr<Barry::Controller> pcon;
921 if( threaded_sockets ) {
922 router.reset( new SocketRoutingQueue );
923 router->SpinoffSimpleReadThread();
924 pcon.reset( new Barry::Controller(device, *router) );
926 else {
927 pcon.reset( new Barry::Controller(device) );
930 Barry::Controller &con = *pcon;
931 Barry::Mode::Desktop desktop(con, *ic);
932 desktop.Open(password.c_str());
934 // Dump list of all databases to stdout
935 if( show_dbdb ) {
936 // open desktop mode socket
937 cout << desktop.GetDBDB() << endl;
940 // Dump list of contacts to an LDAP LDIF file
941 // This uses the Controller convenience templates
942 if( ldif_contacts ) {
943 // create a storage functor object that accepts
944 // Barry::Contact objects as input
945 Contact2Ldif storage(ldif);
947 // load all the Contact records into storage
948 desktop.LoadDatabaseByType<Barry::Contact>(storage);
951 // Dump record state table to stdout
952 if( record_state_table ) {
953 if( dbNames.size() == 0 ) {
954 cout << "No db names to process" << endl;
955 return 1;
958 vector<string>::iterator b = dbNames.begin();
959 for( ; b != dbNames.end(); b++ ) {
960 unsigned int id = desktop.GetDBID(*b);
961 RecordStateTable state;
962 desktop.GetRecordStateTable(id, state);
963 cout << "Record state table for: " << *b << endl;
964 cout << state;
966 return 0;
969 // Get Record mode overrides the default name mode
970 if( stCommands.size() ) {
971 if( dbNames.size() != 1 ) {
972 cout << "Must have 1 db name to process" << endl;
973 return 1;
976 unsigned int id = desktop.GetDBID(dbNames[0]);
977 shared_ptr<Parser> parse = GetParser(dbNames[0],filename,
978 null_parser, true, vformat_mode, bbackup_mode);
980 for( unsigned int i = 0; i < stCommands.size(); i++ ) {
981 desktop.GetRecord(id, stCommands[i].index, *parse.get());
983 if( stCommands[i].flag == 'r' && stCommands[i].clear ) {
984 cout << "Clearing record's dirty flags..." << endl;
985 desktop.ClearDirty(id, stCommands[i].index);
988 if( stCommands[i].flag == 'D' ) {
989 desktop.DeleteRecord(id, stCommands[i].index);
993 return 0;
996 // Dump contents of selected databases to stdout, or
997 // to file if specified.
998 // This is retrieving data from the Blackberry.
999 if( dbNames.size() ) {
1000 vector<string>::iterator b = dbNames.begin();
1002 for( ; b != dbNames.end(); b++ ) {
1003 shared_ptr<Parser> parse = GetParser(*b,
1004 filename, null_parser, !sort_records,
1005 vformat_mode, bbackup_mode);
1006 unsigned int id = desktop.GetDBID(*b);
1007 desktop.LoadDatabase(id, *parse.get());
1011 // Clear databases
1012 if( clear_database ) {
1013 if( clearDbNames.size() == 0 ) {
1014 cout << "No db names to erase" << endl;
1015 return 1;
1018 vector<string>::iterator b = clearDbNames.begin();
1020 for( ; b != clearDbNames.end(); b++ ) {
1021 unsigned int id = desktop.GetDBID(*b);
1022 cout << "Deleting all records from " << (*b) << "..." << endl;
1023 desktop.ClearDatabase(id);
1026 return 0;
1029 // Save contents of file to specified databases
1030 // This is writing data to the Blackberry.
1031 if( saveDbNames.size() ) {
1032 vector<string>::iterator b = saveDbNames.begin();
1034 for( ; b != saveDbNames.end(); b++ ) {
1035 shared_ptr<Builder> build = GetBuilder(*b,
1036 filename);
1037 unsigned int id = desktop.GetDBID(*b);
1038 desktop.SaveDatabase(id, *build);
1043 catch( Usb::Error &ue ) {
1044 std::cerr << "Usb::Error caught: " << ue.what() << endl;
1045 return 1;
1047 catch( Barry::Error &se ) {
1048 std::cerr << "Barry::Error caught: " << se.what() << endl;
1049 return 1;
1051 catch( std::exception &e ) {
1052 std::cerr << "std::exception caught: " << e.what() << endl;
1053 return 1;
1056 return 0;