lib/tdb: convert print func to be py2/py3 compatible
[samba.git] / lib / tdb / tools / tdbtool.c
1 /*
2    Unix SMB/CIFS implementation.
3    Samba database functions
4    Copyright (C) Andrew Tridgell              1999-2000
5    Copyright (C) Paul `Rusty' Russell              2000
6    Copyright (C) Jeremy Allison                    2000
7    Copyright (C) Andrew Esh                        2001
8
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 3 of the License, or
12    (at your option) any later version.
13
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.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "replace.h"
24 #include "system/locale.h"
25 #include "system/time.h"
26 #include "system/filesys.h"
27 #include "system/wait.h"
28 #include "tdb.h"
29
30 static int do_command(void);
31 const char *cmdname;
32 char *arg1, *arg2;
33 size_t arg1len, arg2len;
34 int bIterate = 0;
35 char *line;
36 TDB_DATA iterate_kbuf;
37 char cmdline[1024];
38 static int disable_mmap;
39 static int disable_lock;
40
41 enum commands {
42         CMD_CREATE_TDB,
43         CMD_OPEN_TDB,
44         CMD_TRANSACTION_START,
45         CMD_TRANSACTION_COMMIT,
46         CMD_TRANSACTION_CANCEL,
47         CMD_ERASE,
48         CMD_DUMP,
49         CMD_INSERT,
50         CMD_MOVE,
51         CMD_STOREHEX,
52         CMD_STORE,
53         CMD_SHOW,
54         CMD_KEYS,
55         CMD_HEXKEYS,
56         CMD_DELETE,
57         CMD_LIST_HASH_FREE,
58         CMD_LIST_FREE,
59         CMD_FREELIST_SIZE,
60         CMD_INFO,
61         CMD_MMAP,
62         CMD_SPEED,
63         CMD_FIRST,
64         CMD_NEXT,
65         CMD_SYSTEM,
66         CMD_CHECK,
67         CMD_REPACK,
68         CMD_QUIT,
69         CMD_HELP
70 };
71
72 typedef struct {
73         const char *name;
74         enum commands cmd;
75 } COMMAND_TABLE;
76
77 COMMAND_TABLE cmd_table[] = {
78         {"create",      CMD_CREATE_TDB},
79         {"open",        CMD_OPEN_TDB},
80         {"transaction_start",   CMD_TRANSACTION_START},
81         {"transaction_commit",  CMD_TRANSACTION_COMMIT},
82         {"transaction_cancel",  CMD_TRANSACTION_CANCEL},
83         {"erase",       CMD_ERASE},
84         {"dump",        CMD_DUMP},
85         {"insert",      CMD_INSERT},
86         {"move",        CMD_MOVE},
87         {"storehex",    CMD_STOREHEX},
88         {"store",       CMD_STORE},
89         {"show",        CMD_SHOW},
90         {"keys",        CMD_KEYS},
91         {"hexkeys",     CMD_HEXKEYS},
92         {"delete",      CMD_DELETE},
93         {"list",        CMD_LIST_HASH_FREE},
94         {"free",        CMD_LIST_FREE},
95         {"freelist_size",       CMD_FREELIST_SIZE},
96         {"info",        CMD_INFO},
97         {"speed",       CMD_SPEED},
98         {"mmap",        CMD_MMAP},
99         {"first",       CMD_FIRST},
100         {"1",           CMD_FIRST},
101         {"next",        CMD_NEXT},
102         {"n",           CMD_NEXT},
103         {"check",       CMD_CHECK},
104         {"quit",        CMD_QUIT},
105         {"q",           CMD_QUIT},
106         {"!",           CMD_SYSTEM},
107         {"repack",      CMD_REPACK},
108         {NULL,          CMD_HELP}
109 };
110
111 struct timeval tp1,tp2;
112
113 static void _start_timer(void)
114 {
115         gettimeofday(&tp1,NULL);
116 }
117
118 static double _end_timer(void)
119 {
120         gettimeofday(&tp2,NULL);
121         return((tp2.tv_sec - tp1.tv_sec) +
122                (tp2.tv_usec - tp1.tv_usec)*1.0e-6);
123 }
124
125 #ifdef PRINTF_ATTRIBUTE
126 static void tdb_log_open(struct tdb_context *tdb, enum tdb_debug_level level,
127                          const char *format, ...) PRINTF_ATTRIBUTE(3,4);
128 #endif
129 static void tdb_log_open(struct tdb_context *tdb, enum tdb_debug_level level,
130                          const char *format, ...)
131 {
132         const char *mutex_msg =
133                 "Can use mutexes only with MUTEX_LOCKING or NOLOCK\n";
134         char *p;
135         va_list ap;
136
137         p = strstr(format, mutex_msg);
138         if (p != NULL) {
139                 /*
140                  * Yes, this is a hack, but we don't want to see this
141                  * message on first open, but we want to see
142                  * everything else.
143                  */
144                 return;
145         }
146
147         va_start(ap, format);
148         vfprintf(stderr, format, ap);
149         va_end(ap);
150 }
151
152 #ifdef PRINTF_ATTRIBUTE
153 static void tdb_log(struct tdb_context *tdb, enum tdb_debug_level level, const char *format, ...) PRINTF_ATTRIBUTE(3,4);
154 #endif
155 static void tdb_log(struct tdb_context *tdb, enum tdb_debug_level level, const char *format, ...)
156 {
157         va_list ap;
158
159         va_start(ap, format);
160         vfprintf(stderr, format, ap);
161         va_end(ap);
162 }
163
164 /* a tdb tool for manipulating a tdb database */
165
166 static TDB_CONTEXT *tdb;
167
168 static int print_rec(TDB_CONTEXT *the_tdb, TDB_DATA key, TDB_DATA dbuf, void *state);
169 static int print_key(TDB_CONTEXT *the_tdb, TDB_DATA key, TDB_DATA dbuf, void *state);
170 static int print_hexkey(TDB_CONTEXT *the_tdb, TDB_DATA key, TDB_DATA dbuf, void *state);
171
172 static void print_asc(const char *buf,int len)
173 {
174         int i;
175
176         /* We're probably printing ASCII strings so don't try to display
177            the trailing NULL character. */
178
179         if (buf[len - 1] == 0)
180                 len--;
181
182         for (i=0;i<len;i++)
183                 printf("%c",isprint(buf[i])?buf[i]:'.');
184 }
185
186 static void print_data(const char *buf,int len)
187 {
188         int i=0;
189         if (len<=0) return;
190         printf("[%03X] ",i);
191         for (i=0;i<len;) {
192                 printf("%02X ",(int)((unsigned char)buf[i]));
193                 i++;
194                 if (i%8 == 0) printf(" ");
195                 if (i%16 == 0) {
196                         print_asc(&buf[i-16],8); printf(" ");
197                         print_asc(&buf[i-8],8); printf("\n");
198                         if (i<len) printf("[%03X] ",i);
199                 }
200         }
201         if (i%16) {
202                 int n;
203
204                 n = 16 - (i%16);
205                 printf(" ");
206                 if (n>8) printf(" ");
207                 while (n--) printf("   ");
208
209                 n = i%16;
210                 if (n > 8) n = 8;
211                 print_asc(&buf[i-(i%16)],n); printf(" ");
212                 n = (i%16) - n;
213                 if (n>0) print_asc(&buf[i-n],n);
214                 printf("\n");
215         }
216 }
217
218 static void help(void)
219 {
220         printf("\n"
221 "tdbtool: \n"
222 "  create    dbname     : create a database\n"
223 "  open      dbname     : open an existing database\n"
224 "  transaction_start    : start a transaction\n"
225 "  transaction_commit   : commit a transaction\n"
226 "  transaction_cancel   : cancel a transaction\n"
227 "  erase                : erase the database\n"
228 "  dump                 : dump the database as strings\n"
229 "  keys                 : dump the database keys as strings\n"
230 "  hexkeys              : dump the database keys as hex values\n"
231 "  info                 : print summary info about the database\n"
232 "  insert    key  data  : insert a record\n"
233 "  move      key  file  : move a record to a destination tdb\n"
234 "  storehex  key  data  : store a record (replace), key/value in hex format\n"
235 "  store     key  data  : store a record (replace)\n"
236 "  show      key        : show a record by key\n"
237 "  delete    key        : delete a record by key\n"
238 "  list                 : print the database hash table and freelist\n"
239 "  free                 : print the database freelist\n"
240 "  freelist_size        : print the number of records in the freelist\n"
241 "  check                : check the integrity of an opened database\n"
242 "  repack               : repack the database\n"
243 "  speed                : perform speed tests on the database\n"
244 "  ! command            : execute system command\n"
245 "  1 | first            : print the first record\n"
246 "  n | next             : print the next record\n"
247 "  q | quit             : terminate\n"
248 "  \\n                   : repeat 'next' command\n"
249 "\n");
250 }
251
252 static void terror(const char *why)
253 {
254         printf("%s\n", why);
255 }
256
257 static void create_tdb(const char *tdbname)
258 {
259         struct tdb_logging_context log_ctx = { NULL, NULL};
260         log_ctx.log_fn = tdb_log;
261
262         if (tdb) tdb_close(tdb);
263         tdb = tdb_open_ex(tdbname, 0,
264                           TDB_CLEAR_IF_FIRST |
265                           (disable_mmap?TDB_NOMMAP:0) |
266                           (disable_lock?TDB_NOLOCK:0),
267                           O_RDWR | O_CREAT | O_TRUNC, 0600, &log_ctx, NULL);
268         if (!tdb) {
269                 printf("Could not create %s: %s\n", tdbname, strerror(errno));
270         }
271 }
272
273 static void open_tdb(const char *tdbname)
274 {
275         struct tdb_logging_context log_ctx = { NULL, NULL };
276         log_ctx.log_fn = tdb_log_open;
277
278         if (tdb) tdb_close(tdb);
279         tdb = tdb_open_ex(tdbname, 0,
280                           (disable_mmap?TDB_NOMMAP:0) |
281                           (disable_lock?TDB_NOLOCK:0),
282                           O_RDWR, 0600,
283                           &log_ctx, NULL);
284
285         log_ctx.log_fn = tdb_log;
286         if (tdb != NULL) {
287                 tdb_set_logging_function(tdb, &log_ctx);
288         }
289
290         if ((tdb == NULL) && (errno == EINVAL)) {
291                 /*
292                  * Retry NOLOCK and readonly. There we want to see all
293                  * error messages.
294                  */
295                 tdb = tdb_open_ex(tdbname, 0,
296                                   (disable_mmap?TDB_NOMMAP:0) |TDB_NOLOCK,
297                                   O_RDONLY, 0600,
298                                   &log_ctx, NULL);
299         }
300
301         if (!tdb) {
302                 printf("Could not open %s: %s\n", tdbname, strerror(errno));
303         }
304 }
305
306 static void insert_tdb(char *keyname, size_t keylen, char* data, size_t datalen)
307 {
308         TDB_DATA key, dbuf;
309
310         if ((keyname == NULL) || (keylen == 0)) {
311                 terror("need key");
312                 return;
313         }
314
315         key.dptr = (unsigned char *)keyname;
316         key.dsize = keylen;
317         dbuf.dptr = (unsigned char *)data;
318         dbuf.dsize = datalen;
319
320         if (tdb_store(tdb, key, dbuf, TDB_INSERT) != 0) {
321                 terror("insert failed");
322         }
323 }
324
325 static void store_tdb(char *keyname, size_t keylen, char* data, size_t datalen)
326 {
327         TDB_DATA key, dbuf;
328
329         if ((keyname == NULL) || (keylen == 0)) {
330                 terror("need key");
331                 return;
332         }
333
334         if ((data == NULL) || (datalen == 0)) {
335                 terror("need data");
336                 return;
337         }
338
339         key.dptr = (unsigned char *)keyname;
340         key.dsize = keylen;
341         dbuf.dptr = (unsigned char *)data;
342         dbuf.dsize = datalen;
343
344         printf("Storing key:\n");
345         print_rec(tdb, key, dbuf, NULL);
346
347         if (tdb_store(tdb, key, dbuf, TDB_REPLACE) != 0) {
348                 terror("store failed");
349         }
350 }
351
352 static bool hexchar(char c, uint8_t *v)
353 {
354         if ((c >= '0') && (c <= '9')) {
355                 *v = (c - '0');
356                 return true;
357         }
358         if ((c >= 'A') && (c <= 'F')) {
359                 *v = (c - 'A' + 10);
360                 return true;
361         }
362         if ((c >= 'a') && (c <= 'f')) {
363                 *v = (c - 'a' + 10);
364                 return true;
365         }
366         return false;
367 }
368
369 static bool parse_hex(const char *src, size_t srclen, uint8_t *dst)
370 {
371         size_t i=0;
372
373         if ((srclen % 2) != 0) {
374                 return false;
375         }
376
377         while (i<srclen) {
378                 bool ok;
379                 uint8_t hi,lo;
380
381                 ok = (hexchar(src[i++], &hi) && hexchar(src[i++], &lo));
382                 if (!ok) {
383                         return false;
384                 }
385                 *dst = (hi<<4)|lo;
386                 dst += 1;
387         }
388
389         return true;
390 }
391
392 static void store_hex_tdb(char *keystr, size_t keylen,
393                           char *datastr, size_t datalen)
394 {
395         if ((keystr == NULL) || (keylen == 0)) {
396                 terror("need key");
397                 return;
398         }
399         if ((datastr == NULL) || (datalen == 0)) {
400                 terror("need data");
401                 return;
402         }
403
404         {
405                 uint8_t keybuf[keylen/2];
406                 TDB_DATA key = { .dptr = keybuf, .dsize = sizeof(keybuf) };
407                 uint8_t databuf[datalen/2];
408                 TDB_DATA data = { .dptr = databuf, .dsize = sizeof(databuf) };
409                 bool ok;
410
411                 ok = parse_hex(keystr, keylen, keybuf);
412                 if (!ok) {
413                         terror("need hex key");
414                         return;
415                 }
416                 ok = parse_hex(datastr, datalen, databuf);
417                 if (!ok) {
418                         terror("need hex data");
419                         return;
420                 }
421
422                 printf("storing key/data:\n");
423                 print_data((char *)key.dptr, key.dsize);
424                 print_data((char *)data.dptr, data.dsize);
425
426                 if (tdb_store(tdb, key, data, TDB_REPLACE) != 0) {
427                         terror("store failed");
428                 }
429         }
430 }
431
432 static void show_tdb(char *keyname, size_t keylen)
433 {
434         TDB_DATA key, dbuf;
435
436         if ((keyname == NULL) || (keylen == 0)) {
437                 terror("need key");
438                 return;
439         }
440
441         key.dptr = (unsigned char *)keyname;
442         key.dsize = keylen;
443
444         dbuf = tdb_fetch(tdb, key);
445         if (!dbuf.dptr) {
446             terror("fetch failed");
447             return;
448         }
449
450         print_rec(tdb, key, dbuf, NULL);
451
452         free( dbuf.dptr );
453
454         return;
455 }
456
457 static void delete_tdb(char *keyname, size_t keylen)
458 {
459         TDB_DATA key;
460
461         if ((keyname == NULL) || (keylen == 0)) {
462                 terror("need key");
463                 return;
464         }
465
466         key.dptr = (unsigned char *)keyname;
467         key.dsize = keylen;
468
469         if (tdb_delete(tdb, key) != 0) {
470                 terror("delete failed");
471         }
472 }
473
474 static void move_rec(char *keyname, size_t keylen, char* tdbname)
475 {
476         TDB_DATA key, dbuf;
477         TDB_CONTEXT *dst_tdb;
478
479         if ((keyname == NULL) || (keylen == 0)) {
480                 terror("need key");
481                 return;
482         }
483
484         if ( !tdbname ) {
485                 terror("need destination tdb name");
486                 return;
487         }
488
489         key.dptr = (unsigned char *)keyname;
490         key.dsize = keylen;
491
492         dbuf = tdb_fetch(tdb, key);
493         if (!dbuf.dptr) {
494                 terror("fetch failed");
495                 return;
496         }
497
498         print_rec(tdb, key, dbuf, NULL);
499
500         dst_tdb = tdb_open(tdbname, 0, 0, O_RDWR, 0600);
501         if ( !dst_tdb ) {
502                 terror("unable to open destination tdb");
503                 return;
504         }
505
506         if (tdb_store( dst_tdb, key, dbuf, TDB_REPLACE ) != 0) {
507                 terror("failed to move record");
508         }
509         else
510                 printf("record moved\n");
511
512         tdb_close( dst_tdb );
513
514         return;
515 }
516
517 static int print_rec(TDB_CONTEXT *the_tdb, TDB_DATA key, TDB_DATA dbuf, void *state)
518 {
519         printf("\nkey %d bytes\n", (int)key.dsize);
520         print_asc((const char *)key.dptr, key.dsize);
521         printf("\ndata %d bytes\n", (int)dbuf.dsize);
522         print_data((const char *)dbuf.dptr, dbuf.dsize);
523         return 0;
524 }
525
526 static int print_key(TDB_CONTEXT *the_tdb, TDB_DATA key, TDB_DATA dbuf, void *state)
527 {
528         printf("key %d bytes: ", (int)key.dsize);
529         print_asc((const char *)key.dptr, key.dsize);
530         printf("\n");
531         return 0;
532 }
533
534 static int print_hexkey(TDB_CONTEXT *the_tdb, TDB_DATA key, TDB_DATA dbuf, void *state)
535 {
536         printf("key %d bytes\n", (int)key.dsize);
537         print_data((const char *)key.dptr, key.dsize);
538         printf("\n");
539         return 0;
540 }
541
542 static int total_bytes;
543
544 static int traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA key, TDB_DATA dbuf, void *state)
545 {
546         total_bytes += dbuf.dsize;
547         return 0;
548 }
549
550 static void info_tdb(void)
551 {
552         char *summary = tdb_summary(tdb);
553
554         if (!summary) {
555                 printf("Error = %s\n", tdb_errorstr(tdb));
556         } else {
557                 printf("%s", summary);
558                 free(summary);
559         }
560 }
561
562 static void speed_tdb(const char *tlimit)
563 {
564         const char *str = "store test", *str2 = "transaction test";
565         unsigned timelimit = tlimit?atoi(tlimit):0;
566         double t;
567         int ops;
568         if (timelimit == 0) timelimit = 5;
569
570         ops = 0;
571         printf("Testing store speed for %u seconds\n", timelimit);
572         _start_timer();
573         do {
574                 long int r = random();
575                 TDB_DATA key, dbuf;
576                 key.dptr = discard_const_p(uint8_t, str);
577                 key.dsize = strlen((char *)key.dptr);
578                 dbuf.dptr = (uint8_t *) &r;
579                 dbuf.dsize = sizeof(r);
580                 tdb_store(tdb, key, dbuf, TDB_REPLACE);
581                 t = _end_timer();
582                 ops++;
583         } while (t < timelimit);
584         printf("%10.3f ops/sec\n", ops/t);
585
586         ops = 0;
587         printf("Testing fetch speed for %u seconds\n", timelimit);
588         _start_timer();
589         do {
590                 TDB_DATA key;
591                 key.dptr = discard_const_p(uint8_t, str);
592                 key.dsize = strlen((char *)key.dptr);
593                 tdb_fetch(tdb, key);
594                 t = _end_timer();
595                 ops++;
596         } while (t < timelimit);
597         printf("%10.3f ops/sec\n", ops/t);
598
599         ops = 0;
600         printf("Testing transaction speed for %u seconds\n", timelimit);
601         _start_timer();
602         do {
603                 long int r = random();
604                 TDB_DATA key, dbuf;
605                 key.dptr = discard_const_p(uint8_t, str2);
606                 key.dsize = strlen((char *)key.dptr);
607                 dbuf.dptr = (uint8_t *) &r;
608                 dbuf.dsize = sizeof(r);
609                 tdb_transaction_start(tdb);
610                 tdb_store(tdb, key, dbuf, TDB_REPLACE);
611                 tdb_transaction_commit(tdb);
612                 t = _end_timer();
613                 ops++;
614         } while (t < timelimit);
615         printf("%10.3f ops/sec\n", ops/t);
616
617         ops = 0;
618         printf("Testing traverse speed for %u seconds\n", timelimit);
619         _start_timer();
620         do {
621                 tdb_traverse(tdb, traverse_fn, NULL);
622                 t = _end_timer();
623                 ops++;
624         } while (t < timelimit);
625         printf("%10.3f ops/sec\n", ops/t);
626 }
627
628 static void toggle_mmap(void)
629 {
630         disable_mmap = !disable_mmap;
631         if (disable_mmap) {
632                 printf("mmap is disabled\n");
633         } else {
634                 printf("mmap is enabled\n");
635         }
636 }
637
638 static char *tdb_getline(const char *prompt)
639 {
640         static char thisline[1024];
641         char *p;
642         fputs(prompt, stdout);
643         thisline[0] = 0;
644         p = fgets(thisline, sizeof(thisline)-1, stdin);
645         if (p) p = strchr(p, '\n');
646         if (p) *p = 0;
647         return p?thisline:NULL;
648 }
649
650 static int do_delete_fn(TDB_CONTEXT *the_tdb, TDB_DATA key, TDB_DATA dbuf,
651                      void *state)
652 {
653     return tdb_delete(the_tdb, key);
654 }
655
656 static void first_record(TDB_CONTEXT *the_tdb, TDB_DATA *pkey)
657 {
658         TDB_DATA dbuf;
659         *pkey = tdb_firstkey(the_tdb);
660
661         dbuf = tdb_fetch(the_tdb, *pkey);
662         if (!dbuf.dptr) terror("fetch failed");
663         else {
664                 print_rec(the_tdb, *pkey, dbuf, NULL);
665         }
666 }
667
668 static void next_record(TDB_CONTEXT *the_tdb, TDB_DATA *pkey)
669 {
670         TDB_DATA dbuf;
671         *pkey = tdb_nextkey(the_tdb, *pkey);
672
673         dbuf = tdb_fetch(the_tdb, *pkey);
674         if (!dbuf.dptr)
675                 terror("fetch failed");
676         else
677                 print_rec(the_tdb, *pkey, dbuf, NULL);
678 }
679
680 static int count(TDB_DATA key, TDB_DATA data, void *private_data)
681 {
682         (*(unsigned int *)private_data)++;
683         return 0;
684 }
685
686 static void check_db(TDB_CONTEXT *the_tdb)
687 {
688         int tdbcount = 0;
689         if (!the_tdb)
690                 printf("Error: No database opened!\n");
691         else if (tdb_check(the_tdb, count, &tdbcount) == -1)
692                 printf("Integrity check for the opened database failed.\n");
693         else
694                 printf("Database integrity is OK and has %d records.\n",
695                        tdbcount);
696 }
697
698 static int do_command(void)
699 {
700         COMMAND_TABLE *ctp = cmd_table;
701         enum commands mycmd = CMD_HELP;
702         int cmd_len;
703
704         if (cmdname && strlen(cmdname) == 0) {
705                 mycmd = CMD_NEXT;
706         } else {
707                 while (ctp->name) {
708                         cmd_len = strlen(ctp->name);
709                         if (strncmp(ctp->name,cmdname,cmd_len) == 0) {
710                                 mycmd = ctp->cmd;
711                                 break;
712                         }
713                         ctp++;
714                 }
715         }
716
717         switch (mycmd) {
718         case CMD_CREATE_TDB:
719                 bIterate = 0;
720                 create_tdb(arg1);
721                 return 0;
722         case CMD_OPEN_TDB:
723                 bIterate = 0;
724                 open_tdb(arg1);
725                 return 0;
726         case CMD_SYSTEM:
727                 /* Shell command */
728                 if (system(arg1) == -1) {
729                         terror("system() call failed\n");
730                 }
731                 return 0;
732         case CMD_QUIT:
733                 return 1;
734         default:
735                 /* all the rest require a open database */
736                 if (!tdb) {
737                         bIterate = 0;
738                         terror("database not open");
739                         help();
740                         return 0;
741                 }
742                 switch (mycmd) {
743                 case CMD_TRANSACTION_START:
744                         bIterate = 0;
745                         tdb_transaction_start(tdb);
746                         return 0;
747                 case CMD_TRANSACTION_COMMIT:
748                         bIterate = 0;
749                         tdb_transaction_commit(tdb);
750                         return 0;
751                 case CMD_REPACK:
752                         bIterate = 0;
753                         tdb_repack(tdb);
754                         return 0;
755                 case CMD_TRANSACTION_CANCEL:
756                         bIterate = 0;
757                         tdb_transaction_cancel(tdb);
758                         return 0;
759                 case CMD_ERASE:
760                         bIterate = 0;
761                         tdb_traverse(tdb, do_delete_fn, NULL);
762                         return 0;
763                 case CMD_DUMP:
764                         bIterate = 0;
765                         tdb_traverse(tdb, print_rec, NULL);
766                         return 0;
767                 case CMD_INSERT:
768                         bIterate = 0;
769                         insert_tdb(arg1, arg1len,arg2,arg2len);
770                         return 0;
771                 case CMD_MOVE:
772                         bIterate = 0;
773                         move_rec(arg1,arg1len,arg2);
774                         return 0;
775                 case CMD_STORE:
776                         bIterate = 0;
777                         store_tdb(arg1,arg1len,arg2,arg2len);
778                         return 0;
779                 case CMD_STOREHEX:
780                         bIterate = 0;
781                         store_hex_tdb(arg1,arg1len,arg2,arg2len);
782                         return 0;
783                 case CMD_SHOW:
784                         bIterate = 0;
785                         show_tdb(arg1, arg1len);
786                         return 0;
787                 case CMD_KEYS:
788                         tdb_traverse(tdb, print_key, NULL);
789                         return 0;
790                 case CMD_HEXKEYS:
791                         tdb_traverse(tdb, print_hexkey, NULL);
792                         return 0;
793                 case CMD_DELETE:
794                         bIterate = 0;
795                         delete_tdb(arg1,arg1len);
796                         return 0;
797                 case CMD_LIST_HASH_FREE:
798                         tdb_dump_all(tdb);
799                         return 0;
800                 case CMD_LIST_FREE:
801                         tdb_printfreelist(tdb);
802                         return 0;
803                 case CMD_FREELIST_SIZE: {
804                         int size;
805
806                         size = tdb_freelist_size(tdb);
807                         if (size < 0) {
808                                 printf("Error getting freelist size.\n");
809                         } else {
810                                 printf("freelist size: %d\n", size);
811                         }
812
813                         return 0;
814                 }
815                 case CMD_INFO:
816                         info_tdb();
817                         return 0;
818                 case CMD_SPEED:
819                         speed_tdb(arg1);
820                         return 0;
821                 case CMD_MMAP:
822                         toggle_mmap();
823                         return 0;
824                 case CMD_FIRST:
825                         bIterate = 1;
826                         first_record(tdb, &iterate_kbuf);
827                         return 0;
828                 case CMD_NEXT:
829                         if (bIterate)
830                                 next_record(tdb, &iterate_kbuf);
831                         return 0;
832                 case CMD_CHECK:
833                         check_db(tdb);
834                         return 0;
835                 case CMD_HELP:
836                         help();
837                         return 0;
838                 case CMD_CREATE_TDB:
839                 case CMD_OPEN_TDB:
840                 case CMD_SYSTEM:
841                 case CMD_QUIT:
842                         /*
843                          * unhandled commands.  cases included here to avoid compiler
844                          * warnings.
845                          */
846                         return 0;
847                 }
848         }
849
850         return 0;
851 }
852
853 static char *tdb_convert_string(char *instring, size_t *sizep)
854 {
855         size_t length = 0;
856         char *outp, *inp;
857         char temp[3];
858
859         outp = inp = instring;
860
861         while (*inp) {
862                 if (*inp == '\\') {
863                         inp++;
864                         if (*inp && strchr("0123456789abcdefABCDEF",(int)*inp)) {
865                                 temp[0] = *inp++;
866                                 temp[1] = '\0';
867                                 if (*inp && strchr("0123456789abcdefABCDEF",(int)*inp)) {
868                                         temp[1] = *inp++;
869                                         temp[2] = '\0';
870                                 }
871                                 *outp++ = (char)strtol((const char *)temp,NULL,16);
872                         } else {
873                                 *outp++ = *inp++;
874                         }
875                 } else {
876                         *outp++ = *inp++;
877                 }
878                 length++;
879         }
880         *sizep = length;
881         return instring;
882 }
883
884 int main(int argc, char *argv[])
885 {
886         cmdname = "";
887         arg1 = NULL;
888         arg1len = 0;
889         arg2 = NULL;
890         arg2len = 0;
891
892         if (argv[1] && (strcmp(argv[1], "-l") == 0)) {
893                 disable_lock = 1;
894                 argv[1] = argv[0];
895                 argv += 1;
896                 argc -= 1;
897         }
898
899         if (argv[1]) {
900                 cmdname = "open";
901                 arg1 = argv[1];
902                 do_command();
903                 cmdname =  "";
904                 arg1 = NULL;
905         }
906
907         switch (argc) {
908         case 1:
909         case 2:
910                 /* Interactive mode */
911                 while ((cmdname = tdb_getline("tdb> "))) {
912                         arg2 = arg1 = NULL;
913                         if ((arg1 = strchr((const char *)cmdname,' ')) != NULL) {
914                                 arg1++;
915                                 arg2 = arg1;
916                                 while (*arg2) {
917                                         if (*arg2 == ' ') {
918                                                 *arg2++ = '\0';
919                                                 break;
920                                         }
921                                         if ((*arg2++ == '\\') && (*arg2 == ' ')) {
922                                                 arg2++;
923                                         }
924                                 }
925                         }
926                         if (arg1) arg1 = tdb_convert_string(arg1,&arg1len);
927                         if (arg2) arg2 = tdb_convert_string(arg2,&arg2len);
928                         if (do_command()) break;
929                 }
930                 break;
931         case 5:
932                 arg2 = tdb_convert_string(argv[4],&arg2len);
933                 FALL_THROUGH;
934         case 4:
935                 arg1 = tdb_convert_string(argv[3],&arg1len);
936                 FALL_THROUGH;
937         case 3:
938                 cmdname = argv[2];
939                 FALL_THROUGH;
940         default:
941                 do_command();
942                 break;
943         }
944
945         if (tdb) tdb_close(tdb);
946
947         return 0;
948 }