1f69891646f0a73f6db0dfd146f973bba75f1a99
[exim.git] / src / src / dbfn.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2020 - 2024 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
9
10
11 #include "exim.h"
12
13 /* We have buffers holding path names for database files.
14 PATH_MAX could be used here, but would be wasting memory, as we deal
15 with database files like $spooldirectory/db/<name> */
16 #define PATHLEN 256
17
18
19 /* Functions for accessing Exim's hints database, which consists of a number of
20 different DBM files. This module does not contain code for reading DBM files
21 for (e.g.) alias expansion. That is all contained within the general search
22 functions. As Exim now has support for several DBM interfaces, all the relevant
23 functions are called as inlinable functions from an included file.
24
25 All the data in Exim's database is in the nature of *hints*. Therefore it
26 doesn't matter if it gets destroyed by accident. These functions are not
27 supposed to implement a "safe" database.
28
29 Keys are passed in as C strings, and the terminating zero *is* used when
30 building the dbm files. This just makes life easier when scanning the files
31 sequentially.
32
33 Synchronization is required on the database files, and this is achieved by
34 means of locking on independent lock files. (Earlier attempts to lock on the
35 DBM files themselves were never completely successful.) Since callers may in
36 general want to do more than one read or write while holding the lock, there
37 are separate open and close functions. However, the calling modules should
38 arrange to hold the locks for the bare minimum of time.
39
40 API:
41   exim_lockfile_needed                  facilities predicate
42   dbfn_open                             takes lockfile or opens transaction
43   dbfn_open_multi                       only if transactions supported;
44                                         no lock or transaction taken
45   dbfn_close                            release lockfile or transaction
46   dbfn_close_multi
47   dbfn_transaction_start                only if transactions supported
48   dbfn_transaction_commit
49   dbfn_read_with_length
50   dbfn_read_enforce_length
51   dbfn_write
52   dbfn_delete
53   dbfn_scan                             unused; ifdeffout out
54
55 Users:
56   ACL ratelimit & seen conditions
57   delivery retry handling
58   delivery serialization
59   TLS session resumption
60   peer capability cache
61   callout & quota cache
62 */
63
64
65
66 /*************************************************
67 *          Open and lock a database file         *
68 *************************************************/
69
70 /* Ensure the directory for the DB is present */
71
72 static inline void
73 db_dir_make(BOOL panic)
74 {
75 (void) directory_make(spool_directory, US"db", EXIMDB_DIRECTORY_MODE, panic);
76 }
77
78
79 /* Lock a file to protect the DB.  Return TRUE for success */
80
81 static inline BOOL
82 lockfile_take(open_db * dbblock, const uschar * filename, BOOL rdonly, BOOL panic)
83 {
84 flock_t lock_data;
85 int rc, * fdp = &dbblock->lockfd;
86
87 priv_drop_temp(exim_uid, exim_gid);
88 if ((*fdp = Uopen(filename, O_RDWR, EXIMDB_LOCKFILE_MODE)) < 0)
89   {
90   db_dir_make(panic);
91   *fdp = Uopen(filename, O_RDWR|O_CREAT, EXIMDB_LOCKFILE_MODE);
92   }
93 priv_restore();
94
95 if (*fdp < 0)
96   {
97   log_write(0, LOG_MAIN, "%s",
98     string_open_failed("database lock file %s", filename));
99   errno = 0;      /* Indicates locking failure */
100   return FALSE;
101   }
102
103 /* Now we must get a lock on the opened lock file; do this with a blocking
104 lock that times out. */
105
106 lock_data.l_type = rdonly ? F_RDLCK : F_WRLCK;
107 lock_data.l_whence = lock_data.l_start = lock_data.l_len = 0;
108
109 DEBUG(D_hints_lookup|D_retry|D_route|D_deliver)
110   debug_printf_indent("locking %s\n", filename);
111
112 sigalrm_seen = FALSE;
113 ALARM(EXIMDB_LOCK_TIMEOUT);
114 rc = fcntl(*fdp, F_SETLKW, &lock_data);
115 ALARM_CLR(0);
116
117 if (sigalrm_seen) errno = ETIMEDOUT;
118 if (rc < 0)
119   {
120   log_write(0, LOG_MAIN|LOG_PANIC, "Failed to get %s lock for %s: %s",
121     rdonly ? "read" : "write", filename,
122     errno == ETIMEDOUT ? "timed out" : strerror(errno));
123   (void)close(*fdp); *fdp = -1;
124   errno = 0;       /* Indicates locking failure */
125   return FALSE;
126   }
127
128 DEBUG(D_hints_lookup) debug_printf_indent("locked  %s\n", filename);
129 return TRUE;
130 }
131
132 /* Used for accessing Exim's hints databases.
133
134 Arguments:
135   name     The single-component name of one of Exim's database files.
136   flags    Either O_RDONLY or O_RDWR, indicating the type of open required;
137              optionally O_CREAT
138   dbblock  Points to an open_db block to be filled in.
139   lof      If TRUE, write to the log for actual open failures (locking failures
140            are always logged).
141   panic    If TRUE, panic on failure to create the db directory
142
143 Returns:   NULL if the open failed, or the locking failed. After locking
144            failures, errno is zero.
145
146            On success, dbblock is returned. This contains the dbm pointer and
147            the fd of the locked lock file.
148 */
149
150 open_db *
151 dbfn_open(const uschar * name, int flags, open_db * dbblock,
152   BOOL lof, BOOL panic)
153 {
154 int rc, save_errno, dlen, flen;
155 flock_t lock_data;
156 uschar dirname[PATHLEN], filename[PATHLEN];
157
158 DEBUG(D_hints_lookup) acl_level++;
159
160 /* The first thing to do is to open a separate file on which to lock. This
161 ensures that Exim has exclusive use of the database before it even tries to
162 open it. Early versions tried to lock on the open database itself, but that
163 gave rise to mysterious problems from time to time - it was suspected that some
164 DB libraries "do things" on their open() calls which break the interlocking.
165 The lock file is never written to, but we open it for writing so we can get a
166 write lock if required. If it does not exist, we create it. This is done
167 separately so we know when we have done it, because when running as root we
168 need to change the ownership - see the bottom of this function. We also try to
169 make the directory as well, just in case. We won't be doing this many times
170 unnecessarily, because usually the lock file will be there. If the directory
171 exists, there is no error. */
172
173 dlen = snprintf(CS dirname, sizeof(dirname), "%s/db", spool_directory);
174
175 dbblock->readonly = (flags & O_ACCMODE) == O_RDONLY;
176 dbblock->lockfd = -1;
177 if (!exim_lockfile_needed())
178   db_dir_make(panic);
179 else
180   {
181   flen = Ustrlen(name);
182   snprintf(CS filename, sizeof(filename), "%.*s/%.*s.lockfile",
183             (int)sizeof(filename) - dlen - flen - 11, dirname,
184             flen, name);
185   if (!lockfile_take(dbblock, filename, flags == O_RDONLY, panic))
186     {
187     DEBUG(D_hints_lookup) acl_level--;
188     return NULL;
189     }
190   }
191
192 /* At this point we have an opened and locked separate lock file, that is,
193 exclusive access to the database, so we can go ahead and open it. If we are
194 expected to create it, don't do so at first, again so that we can detect
195 whether we need to change its ownership (see comments about the lock file
196 above.) There have been regular reports of crashes while opening hints
197 databases - often this is caused by non-matching db.h and the library. To make
198 it easy to pin this down, there are now debug statements on either side of the
199 open call. */
200
201 snprintf(CS filename, sizeof(filename), "%.*s/%s", dlen, dirname, name);
202
203 priv_drop_temp(exim_uid, exim_gid);
204 dbblock->dbptr = dbblock->readonly && !exim_lockfile_needed()
205   ? exim_dbopen_multi(filename, dirname, flags & O_ACCMODE, EXIMDB_MODE)
206   : exim_dbopen(filename, dirname, flags & O_ACCMODE, EXIMDB_MODE);
207
208 if (!dbblock->dbptr && errno == ENOENT && flags & O_CREAT)
209   {
210   DEBUG(D_hints_lookup)
211     debug_printf_indent("%s appears not to exist: trying to create\n", filename);
212   dbblock->dbptr = exim_dbopen(filename, dirname, flags, EXIMDB_MODE);
213   }
214 save_errno = errno;
215 priv_restore();
216
217 /* If the open has failed, return NULL, leaving errno set. If lof is TRUE,
218 log the event - also for debugging - but debug only if the file just doesn't
219 exist. */
220
221 if (!dbblock->dbptr)
222   {
223   errno = save_errno;
224   if (lof && save_errno != ENOENT)
225     log_write(0, LOG_MAIN, "%s", string_open_failed("DB file %s",
226         filename));
227   else
228     DEBUG(D_hints_lookup)
229       debug_printf_indent("%s\n", CS string_open_failed("DB file %s",
230           filename));
231   (void)close(dbblock->lockfd);
232   dbblock->lockfd = -1;
233   dbblock = NULL;
234   }
235
236 /* Pass back the block containing the opened database handle and the open fd
237 for the lock. */
238
239 DEBUG(D_hints_lookup) acl_level--;
240 return dbblock;
241 }
242
243
244
245 /* Only for transaction-capable DB types.  Open without locking or
246 starting a transaction.  "lof" and "panic" always true; read/write mode.
247 */
248
249 open_db *
250 dbfn_open_multi(const uschar * name, int flags, open_db * dbblock)
251 {
252 int rc, save_errno, dlen;
253 flock_t lock_data;
254 uschar dirname[PATHLEN], filename[PATHLEN];
255
256 DEBUG(D_hints_lookup) acl_level++;
257
258 dbblock->lockfd = -1;
259 db_dir_make(TRUE);
260
261 dlen = snprintf(CS dirname, sizeof(dirname), "%s/db", spool_directory);
262 snprintf(CS filename, sizeof(filename), "%.*s/%s", dlen, dirname, name);
263
264 priv_drop_temp(exim_uid, exim_gid);
265 dbblock->dbptr = exim_dbopen_multi(filename, dirname, flags & O_ACCMODE, EXIMDB_MODE);
266 if (!dbblock->dbptr && errno == ENOENT && flags & O_CREAT)
267   {
268   DEBUG(D_hints_lookup)
269     debug_printf_indent("%s appears not to exist: trying to create\n", filename);
270   dbblock->dbptr = exim_dbopen_multi(filename, dirname, flags, EXIMDB_MODE);
271   }
272 save_errno = errno;
273 priv_restore();
274
275 /* If the open has failed, return NULL, leaving errno set. If lof is TRUE,
276 log the event - also for debugging - but debug only if the file just doesn't
277 exist. */
278
279 if (!dbblock->dbptr)
280   {
281   errno = save_errno;
282   if (save_errno != ENOENT)
283     log_write(0, LOG_MAIN, "%s", string_open_failed("DB file %s",
284         filename));
285   else
286     DEBUG(D_hints_lookup)
287       debug_printf_indent("%s\n", CS string_open_failed("DB file %s",
288           filename));
289   dbblock =  NULL;
290   }
291
292 /* Pass back the block containing the opened database handle */
293 DEBUG(D_hints_lookup) acl_level--;
294 return dbblock;
295 }
296
297
298 BOOL
299 dbfn_transaction_start(open_db * dbp)
300 {
301 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_transaction_start\n");
302 if (!dbp->readonly) return exim_dbtransaction_start(dbp->dbptr);
303 }
304 void
305 dbfn_transaction_commit(open_db * dbp)
306 {
307 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_transaction_commit\n");
308 if (!dbp->readonly) exim_dbtransaction_commit(dbp->dbptr);
309 }
310
311
312
313 /*************************************************
314 *         Unlock and close a database file       *
315 *************************************************/
316
317 /* Closing a file automatically unlocks it, so after closing the database, just
318 close the lock file if there was one.
319
320 Argument: a pointer to an open database block
321 Returns:  nothing
322 */
323
324 void
325 dbfn_close(open_db * dbp)
326 {
327 int * fdp = &dbp->lockfd;
328
329 if (dbp->readonly && !exim_lockfile_needed())
330   exim_dbclose_multi(dbp->dbptr);
331 else
332   exim_dbclose(dbp->dbptr);
333
334 if (*fdp >= 0) (void)close(*fdp);
335 DEBUG(D_hints_lookup)
336   debug_printf_indent("closed hints database%s\n",
337                       *fdp < 0 ? "" : " and lockfile");
338 *fdp = -1;
339 }
340
341
342 void
343 dbfn_close_multi(open_db * dbp)
344 {
345 exim_dbclose_multi(dbp->dbptr);
346 DEBUG(D_hints_lookup)
347   debug_printf_indent("closed hints database\n");
348 }
349
350
351
352
353 /*************************************************
354 *             Read from database file            *
355 *************************************************/
356
357 /* Passing back the pointer unchanged is useless, because there is
358 no guarantee of alignment. Since all the records used by Exim need
359 to be properly aligned to pick out the timestamps, etc., we might as
360 well do the copying centrally here.
361
362 Most calls don't need the length, so there is a macro called dbfn_read which
363 has two arguments; it calls this function adding NULL as the third.
364
365 Arguments:
366   dbblock   a pointer to an open database block
367   key       the key of the record to be read
368   length    a pointer to an int into which to return the length, if not NULL
369
370 Returns: a pointer to the retrieved record, or
371          NULL if the record is not found
372 */
373
374 void *
375 dbfn_read_with_length(open_db * dbblock, const uschar * key, int * length)
376 {
377 void * yield;
378 EXIM_DATUM key_datum, result_datum;
379 int klen = Ustrlen(key) + 1;
380 uschar * key_copy = store_get(klen, key);
381 unsigned dlen;
382
383 memcpy(key_copy, key, klen);
384
385 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_read: key=%s\n", key);
386
387 exim_datum_init(&key_datum);         /* Some DBM libraries require the datum */
388 exim_datum_init(&result_datum);      /* to be cleared before use. */
389 exim_datum_data_set(&key_datum, key_copy);
390 exim_datum_size_set(&key_datum, klen);
391
392 if (!exim_dbget(dbblock->dbptr, &key_datum, &result_datum))
393   {
394   DEBUG(D_hints_lookup) debug_printf_indent("dbfn_read: null return\n");
395   return NULL;
396   }
397
398 /* Assume the data store could have been tainted.  Properly, we should
399 store the taint status with the data. */
400
401 dlen = exim_datum_size_get(&result_datum);
402 yield = store_get(dlen, GET_TAINTED);
403 memcpy(yield, exim_datum_data_get(&result_datum), dlen);
404 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_read: size %u return\n", dlen);
405 if (length) *length = dlen;
406
407 exim_datum_free(&result_datum);    /* Some DBM libs require freeing */
408 return yield;
409 }
410
411
412 /* Read a record.  If the length is not as expected then delete it, write
413 an error log line, delete the record and return NULL.
414 Use this for fixed-size records (so not retry or wait records).
415
416 Arguments:
417   dbblock   a pointer to an open database block
418   key       the key of the record to be read
419   length    the expected record length
420
421 Returns: a pointer to the retrieved record, or
422          NULL if the record is not found/bad
423 */
424
425 void *
426 dbfn_read_enforce_length(open_db * dbblock, const uschar * key, size_t length)
427 {
428 int rlen;
429 void * yield = dbfn_read_with_length(dbblock, key, &rlen);
430
431 if (yield)
432   {
433   if (rlen == length) return yield;
434   log_write(0, LOG_MAIN|LOG_PANIC, "Bad db record size for '%s'", key);
435   dbfn_delete(dbblock, key);
436   }
437 return NULL;
438 }
439
440
441 /*************************************************
442 *             Write to database file             *
443 *************************************************/
444
445 /*
446 Arguments:
447   dbblock   a pointer to an open database block
448   key       the key of the record to be written
449   ptr       a pointer to the record to be written
450   length    the length of the record to be written
451
452 Returns:    the yield of the underlying dbm or db "write" function. If this
453             is dbm, the value is zero for OK.
454 */
455
456 int
457 dbfn_write(open_db *dbblock, const uschar *key, void *ptr, int length)
458 {
459 EXIM_DATUM key_datum, value_datum;
460 dbdata_generic *gptr = (dbdata_generic *)ptr;
461 int klen = Ustrlen(key) + 1;
462 uschar * key_copy = store_get(klen, key);
463
464 memcpy(key_copy, key, klen);
465 gptr->time_stamp = time(NULL);
466
467 DEBUG(D_hints_lookup)
468   debug_printf_indent("dbfn_write: key=%s datalen %d\n", key, length);
469
470 exim_datum_init(&key_datum);         /* Some DBM libraries require the datum */
471 exim_datum_init(&value_datum);       /* to be cleared before use. */
472 exim_datum_data_set(&key_datum, key_copy);
473 exim_datum_size_set(&key_datum, klen);
474 exim_datum_data_set(&value_datum, ptr);
475 exim_datum_size_set(&value_datum, length);
476 return exim_dbput(dbblock->dbptr, &key_datum, &value_datum);
477 }
478
479
480
481 /*************************************************
482 *           Delete record from database file     *
483 *************************************************/
484
485 /*
486 Arguments:
487   dbblock    a pointer to an open database block
488   key        the key of the record to be deleted
489
490 Returns: the yield of the underlying dbm or db "delete" function.
491 */
492
493 int
494 dbfn_delete(open_db *dbblock, const uschar *key)
495 {
496 int klen = Ustrlen(key) + 1;
497 uschar * key_copy = store_get(klen, key);
498 EXIM_DATUM key_datum;
499
500 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_delete: key=%s\n", key);
501
502 memcpy(key_copy, key, klen);
503 exim_datum_init(&key_datum);         /* Some DBM libraries require clearing */
504 exim_datum_data_set(&key_datum, key_copy);
505 exim_datum_size_set(&key_datum, klen);
506 return exim_dbdel(dbblock->dbptr, &key_datum);
507 }
508
509
510
511 #ifdef notdef
512 /* XXX This appears to be unused.  There's a separate implementation
513 in dbutils.c for dumpdb and fixdb, using the same underlying support.
514 */
515
516 /*************************************************
517 *         Scan the keys of a database file       *
518 *************************************************/
519
520 /*
521 Arguments:
522   dbblock  a pointer to an open database block
523   start    TRUE if starting a new scan
524            FALSE if continuing with the current scan
525   cursor   a pointer to a pointer to a cursor anchor, for those dbm libraries
526            that use the notion of a cursor
527
528 Returns:   the next record from the file, or
529            NULL if there are no more
530 */
531
532 uschar *
533 dbfn_scan(open_db *dbblock, BOOL start, EXIM_CURSOR **cursor)
534 {
535 EXIM_DATUM key_datum, value_datum;
536 uschar *yield;
537
538 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_scan\n");
539
540 /* Some dbm require an initialization */
541
542 if (start) *cursor = exim_dbcreate_cursor(dbblock->dbptr);
543
544 exim_datum_init(&key_datum);         /* Some DBM libraries require the datum */
545 exim_datum_init(&value_datum);       /* to be cleared before use. */
546
547 yield = exim_dbscan(dbblock->dbptr, &key_datum, &value_datum, start, *cursor)
548   ? US exim_datum_data_get(&key_datum) : NULL;
549
550 /* Some dbm require a termination */
551
552 if (!yield) exim_dbdelete_cursor(*cursor);
553 return yield;
554 }
555 #endif
556
557
558
559 /*************************************************
560 **************************************************
561 *             Stand-alone test program           *
562 **************************************************
563 *************************************************/
564
565 #ifdef STAND_ALONE
566
567 int
568 main(int argc, char **cargv)
569 {
570 open_db dbblock[8];
571 int max_db = sizeof(dbblock)/sizeof(open_db);
572 int current = -1;
573 int showtime = 0;
574 int i;
575 dbdata_wait *dbwait = NULL;
576 uschar **argv = USS cargv;
577 uschar buffer[256];
578 uschar structbuffer[1024];
579
580 if (argc != 2)
581   {
582   printf("Usage: test_dbfn directory\n");
583   printf("The subdirectory called \"db\" in the given directory is used for\n");
584   printf("the files used in this test program.\n");
585   return 1;
586   }
587
588 /* Initialize */
589
590 spool_directory = argv[1];
591 debug_selector = D_all - D_memory;
592 debug_file = stderr;
593 big_buffer = malloc(big_buffer_size);
594
595 for (i = 0; i < max_db; i++) dbblock[i].dbptr = NULL;
596
597 printf("\nExim's db functions tester: interface type is %s\n", EXIM_DBTYPE);
598 printf("DBM library: ");
599
600 #ifdef DB_VERSION_STRING
601 printf("Berkeley DB: %s\n", DB_VERSION_STRING);
602 #elif defined(BTREEVERSION) && defined(HASHVERSION)
603   #ifdef USE_DB
604   printf("probably Berkeley DB version 1.8x (native mode)\n");
605   #else
606   printf("probably Berkeley DB version 1.8x (compatibility mode)\n");
607   #endif
608 #elif defined(_DBM_RDONLY) || defined(dbm_dirfno)
609 printf("probably ndbm\n");
610 #elif defined(USE_TDB)
611 printf("using tdb\n");
612 #else
613   #ifdef USE_GDBM
614   printf("probably GDBM (native mode)\n");
615   #else
616   printf("probably GDBM (compatibility mode)\n");
617   #endif
618 #endif
619
620 /* Test the functions */
621
622 printf("\nTest the functions\n> ");
623
624 while (Ufgets(buffer, 256, stdin) != NULL)
625   {
626   int len = Ustrlen(buffer);
627   int count = 1;
628   clock_t start = 1;
629   clock_t stop = 0;
630   uschar *cmd = buffer;
631   while (len > 0 && isspace((uschar)buffer[len-1])) len--;
632   buffer[len] = 0;
633
634   if (isdigit((uschar)*cmd))
635     {
636     count = Uatoi(cmd);
637     while (isdigit((uschar)*cmd)) cmd++;
638     Uskip_whitespace(&cmd);
639     }
640
641   if (Ustrncmp(cmd, "open", 4) == 0)
642     {
643     int i;
644     open_db *odb;
645     uschar *s = cmd + 4;
646     Uskip_whitespace(&s);
647
648     for (i = 0; i < max_db; i++)
649       if (dbblock[i].dbptr == NULL) break;
650
651     if (i >= max_db)
652       {
653       printf("Too many open databases\n> ");
654       continue;
655       }
656
657     start = clock();
658     odb = dbfn_open(s, O_RDWR|O_CREAT, dbblock + i, TRUE, TRUE);
659     stop = clock();
660
661     if (odb)
662       {
663       current = i;
664       printf("opened %d\n", current);
665       }
666     /* Other error cases will have written messages */
667     else if (errno == ENOENT)
668       {
669       printf("open failed: %s%s\n", strerror(errno),
670         #ifdef USE_DB
671         " (or other Berkeley DB error)"
672         #else
673         ""
674         #endif
675         );
676       }
677     }
678
679   else if (Ustrncmp(cmd, "write", 5) == 0)
680     {
681     int rc = 0;
682     uschar * key = cmd + 5, * data;
683
684     if (current < 0)
685       {
686       printf("No current database\n");
687       continue;
688       }
689
690     Uskip_whitespace(&key);
691     data = key;
692     Uskip_nonwhite(&data);
693     *data++ = '\0';
694     Uskip_whitespace(&data);
695
696     dbwait = (dbdata_wait *)(&structbuffer);
697     Ustrcpy(dbwait->text, data);
698
699     start = clock();
700     while (count-- > 0)
701       rc = dbfn_write(dbblock + current, key, dbwait,
702         Ustrlen(data) + sizeof(dbdata_wait));
703     stop = clock();
704     if (rc != 0) printf("Failed: %s\n", strerror(errno));
705     }
706
707   else if (Ustrncmp(cmd, "read", 4) == 0)
708     {
709     uschar * key = cmd + 4;
710     if (current < 0)
711       {
712       printf("No current database\n");
713       continue;
714       }
715     Uskip_whitespace(&key);
716     start = clock();
717     while (count-- > 0)
718       dbwait = (dbdata_wait *)dbfn_read_with_length(dbblock+ current, key, NULL);
719     stop = clock();
720     printf("%s\n", (dbwait == NULL)? "<not found>" : CS dbwait->text);
721     }
722
723   else if (Ustrncmp(cmd, "delete", 6) == 0)
724     {
725     uschar * key = cmd + 6;
726     if (current < 0)
727       {
728       printf("No current database\n");
729       continue;
730       }
731     Uskip_whitespace(&key);
732     dbfn_delete(dbblock + current, key);
733     }
734
735   else if (Ustrncmp(cmd, "scan", 4) == 0)
736     {
737     EXIM_CURSOR *cursor;
738     BOOL startflag = TRUE;
739     uschar *key;
740     uschar keybuffer[256];
741     if (current < 0)
742       {
743       printf("No current database\n");
744       continue;
745       }
746     start = clock();
747     while ((key = dbfn_scan(dbblock + current, startflag, &cursor)) != NULL)
748       {
749       startflag = FALSE;
750       Ustrcpy(keybuffer, key);
751       dbwait = (dbdata_wait *)dbfn_read_with_length(dbblock + current,
752         keybuffer, NULL);
753       printf("%s: %s\n", keybuffer, dbwait->text);
754       }
755     stop = clock();
756     printf("End of scan\n");
757     }
758
759   else if (Ustrncmp(cmd, "close", 5) == 0)
760     {
761     uschar * s = cmd + 5;
762     Uskip_whitespace(&s);
763     i = Uatoi(s);
764     if (i >= max_db || dbblock[i].dbptr == NULL) printf("Not open\n"); else
765       {
766       start = clock();
767       dbfn_close(dbblock + i);
768       stop = clock();
769       dbblock[i].dbptr = NULL;
770       if (i == current) current = -1;
771       }
772     }
773
774   else if (Ustrncmp(cmd, "file", 4) == 0)
775     {
776     uschar * s = cmd + 4;
777     Uskip_whitespace(&s);
778     i = Uatoi(s);
779     if (i >= max_db || dbblock[i].dbptr == NULL) printf("Not open\n");
780       else current = i;
781     }
782
783   else if (Ustrncmp(cmd, "time", 4) == 0)
784     {
785     showtime = ~showtime;
786     printf("Timing %s\n", showtime? "on" : "off");
787     }
788
789   else if (Ustrcmp(cmd, "q") == 0 || Ustrncmp(cmd, "quit", 4) == 0) break;
790
791   else if (Ustrncmp(cmd, "help", 4) == 0)
792     {
793     printf("close  [<number>]              close file [<number>]\n");
794     printf("delete <key>                   remove record from current file\n");
795     printf("file   <number>                make file <number> current\n");
796     printf("open   <name>                  open db file\n");
797     printf("q[uit]                         exit program\n");
798     printf("read   <key>                   read record from current file\n");
799     printf("scan                           scan current file\n");
800     printf("time                           time display on/off\n");
801     printf("write  <key> <rest-of-line>    write record to current file\n");
802     }
803
804   else printf("Eh?\n");
805
806   if (showtime && stop >= start)
807     printf("start=%d stop=%d difference=%d\n", (int)start, (int)stop,
808      (int)(stop - start));
809
810   printf("> ");
811   }
812
813 for (i = 0; i < max_db; i++)
814   {
815   if (dbblock[i].dbptr != NULL)
816     {
817     printf("\nClosing %d", i);
818     dbfn_close(dbblock + i);
819     }
820   }
821
822 printf("\n");
823 return 0;
824 }
825
826 #endif
827
828 /* End of dbfn.c */
829 /* vi: aw ai sw=2
830 */