1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
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 */
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> */
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.
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.
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
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.
44 dbfn_read_enforce_length
47 dbfn_scan unused; ifdeffout out
50 ACL ratelimit & seen conditions
51 delivery retry handling
52 delivery serialization
53 TLS session resumption
60 /*************************************************
61 * Open and lock a database file *
62 *************************************************/
64 /* Ensure the directory for the DB is present */
67 db_dir_make(BOOL panic)
69 (void) directory_make(spool_directory, US"db", EXIMDB_DIRECTORY_MODE, panic);
73 /* Lock a file to protect the DB. Return TRUE for success */
76 lockfile_take(open_db * dbblock, const uschar * filename, BOOL rdonly, BOOL panic)
79 int rc, * fdp = &dbblock->lockfd;
81 priv_drop_temp(exim_uid, exim_gid);
82 if ((*fdp = Uopen(filename, O_RDWR, EXIMDB_LOCKFILE_MODE)) < 0)
85 *fdp = Uopen(filename, O_RDWR|O_CREAT, EXIMDB_LOCKFILE_MODE);
91 log_write(0, LOG_MAIN, "%s",
92 string_open_failed("database lock file %s", filename));
93 errno = 0; /* Indicates locking failure */
97 /* Now we must get a lock on the opened lock file; do this with a blocking
98 lock that times out. */
100 lock_data.l_type = rdonly ? F_RDLCK : F_WRLCK;
101 lock_data.l_whence = lock_data.l_start = lock_data.l_len = 0;
103 DEBUG(D_hints_lookup|D_retry|D_route|D_deliver)
104 debug_printf_indent("locking %s\n", filename);
106 sigalrm_seen = FALSE;
107 ALARM(EXIMDB_LOCK_TIMEOUT);
108 rc = fcntl(*fdp, F_SETLKW, &lock_data);
111 if (sigalrm_seen) errno = ETIMEDOUT;
114 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to get %s lock for %s: %s",
115 rdonly ? "read" : "write", filename,
116 errno == ETIMEDOUT ? "timed out" : strerror(errno));
117 (void)close(*fdp); *fdp = -1;
118 errno = 0; /* Indicates locking failure */
122 DEBUG(D_hints_lookup) debug_printf_indent("locked %s\n", filename);
126 /* Used for accessing Exim's hints databases.
129 name The single-component name of one of Exim's database files.
130 flags Either O_RDONLY or O_RDWR, indicating the type of open required;
131 O_RDWR implies "create if necessary"
132 dbblock Points to an open_db block to be filled in.
133 lof If TRUE, write to the log for actual open failures (locking failures
135 panic If TRUE, panic on failure to create the db directory
137 Returns: NULL if the open failed, or the locking failed. After locking
138 failures, errno is zero.
140 On success, dbblock is returned. This contains the dbm pointer and
141 the fd of the locked lock file.
145 dbfn_open(const uschar * name, int flags, open_db * dbblock,
146 BOOL lof, BOOL panic)
148 int rc, save_errno, dlen, flen;
150 uschar dirname[PATHLEN], filename[PATHLEN];
152 DEBUG(D_hints_lookup) acl_level++;
154 /* The first thing to do is to open a separate file on which to lock. This
155 ensures that Exim has exclusive use of the database before it even tries to
156 open it. Early versions tried to lock on the open database itself, but that
157 gave rise to mysterious problems from time to time - it was suspected that some
158 DB libraries "do things" on their open() calls which break the interlocking.
159 The lock file is never written to, but we open it for writing so we can get a
160 write lock if required. If it does not exist, we create it. This is done
161 separately so we know when we have done it, because when running as root we
162 need to change the ownership - see the bottom of this function. We also try to
163 make the directory as well, just in case. We won't be doing this many times
164 unnecessarily, because usually the lock file will be there. If the directory
165 exists, there is no error. */
167 dlen = snprintf(CS dirname, sizeof(dirname), "%s/db", spool_directory);
168 flen = Ustrlen(name);
169 snprintf(CS filename, sizeof(filename), "%.*s/%.*s.lockfile",
170 (int)sizeof(filename) - dlen - flen - 11, dirname,
173 dbblock->lockfd = -1;
174 if (!exim_lockfile_needed())
178 if (!lockfile_take(dbblock, filename, flags == O_RDONLY, panic))
180 DEBUG(D_hints_lookup) acl_level--;
185 /* At this point we have an opened and locked separate lock file, that is,
186 exclusive access to the database, so we can go ahead and open it. If we are
187 expected to create it, don't do so at first, again so that we can detect
188 whether we need to change its ownership (see comments about the lock file
189 above.) There have been regular reports of crashes while opening hints
190 databases - often this is caused by non-matching db.h and the library. To make
191 it easy to pin this down, there are now debug statements on either side of the
194 flags &= O_RDONLY | O_RDWR;
195 snprintf(CS filename, sizeof(filename), "%.*s/%s", dlen, dirname, name);
197 priv_drop_temp(exim_uid, exim_gid);
198 dbblock->dbptr = exim_dbopen(filename, dirname, flags, EXIMDB_MODE);
199 if (!dbblock->dbptr && errno == ENOENT && flags == O_RDWR)
201 DEBUG(D_hints_lookup)
202 debug_printf_indent("%s appears not to exist: trying to create\n", filename);
203 dbblock->dbptr = exim_dbopen(filename, dirname, flags|O_CREAT, EXIMDB_MODE);
208 /* If the open has failed, return NULL, leaving errno set. If lof is TRUE,
209 log the event - also for debugging - but debug only if the file just doesn't
215 if (lof && save_errno != ENOENT)
216 log_write(0, LOG_MAIN, "%s", string_open_failed("DB file %s",
219 DEBUG(D_hints_lookup)
220 debug_printf_indent("%s\n", CS string_open_failed("DB file %s",
222 (void)close(dbblock->lockfd);
223 dbblock->lockfd = -1;
225 DEBUG(D_hints_lookup) acl_level--;
229 DEBUG(D_hints_lookup)
230 debug_printf_indent("opened hints database %s: flags=%s\n", filename,
231 flags == O_RDONLY ? "O_RDONLY"
232 : flags == O_RDWR ? "O_RDWR"
235 /* Pass back the block containing the opened database handle and the open fd
243 /* Only for transaction-capable DB types. Open without locking or
244 starting a transaction. "lof" and "panic" always true; read/write mode.
248 dbfn_open_multi(const uschar * name, int flags, open_db * dbblock)
250 int rc, save_errno, dlen;
252 uschar dirname[PATHLEN], filename[PATHLEN];
254 DEBUG(D_hints_lookup) acl_level++;
256 dbblock->lockfd = -1;
259 dlen = snprintf(CS dirname, sizeof(dirname), "%s/db", spool_directory);
260 snprintf(CS filename, sizeof(filename), "%.*s/%s", dlen, dirname, name);
262 priv_drop_temp(exim_uid, exim_gid);
263 dbblock->dbptr = exim_dbopen_multi(filename, dirname, flags, EXIMDB_MODE);
264 if (!dbblock->dbptr && errno == ENOENT && flags == O_RDWR)
266 DEBUG(D_hints_lookup)
267 debug_printf_indent("%s appears not to exist: trying to create\n", filename);
268 dbblock->dbptr = exim_dbopen_multi(filename, dirname, O_RDWR|O_CREAT, EXIMDB_MODE);
273 /* If the open has failed, return NULL, leaving errno set. If lof is TRUE,
274 log the event - also for debugging - but debug only if the file just doesn't
280 if (save_errno != ENOENT)
281 log_write(0, LOG_MAIN, "%s", string_open_failed("DB file %s",
284 DEBUG(D_hints_lookup)
285 debug_printf_indent("%s\n", CS string_open_failed("DB file %s",
288 DEBUG(D_hints_lookup) acl_level--;
292 DEBUG(D_hints_lookup) debug_printf_indent(
293 "opened hints database %s for transactions: NOLOCK flags=O_RDWR\n", filename);
295 /* Pass back the block containing the opened database handle */
302 dbfn_transaction_start(open_db * dbp)
304 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_transaction_start\n");
305 return exim_dbtransaction_start(dbp->dbptr);
308 dbfn_transaction_commit(open_db * dbp)
310 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_transaction_commit\n");
311 exim_dbtransaction_commit(dbp->dbptr);
316 /*************************************************
317 * Unlock and close a database file *
318 *************************************************/
320 /* Closing a file automatically unlocks it, so after closing the database, just
321 close the lock file if there was one.
323 Argument: a pointer to an open database block
328 dbfn_close(open_db * dbp)
330 int * fdp = &dbp->lockfd;
332 exim_dbclose(dbp->dbptr);
333 if (*fdp >= 0) (void)close(*fdp);
334 DEBUG(D_hints_lookup)
336 debug_printf_indent("closed hints database%s\n",
337 *fdp < 0 ? "" : " and lockfile");
345 dbfn_close_multi(open_db * dbp)
347 exim_dbclose_multi(dbp->dbptr);
348 DEBUG(D_hints_lookup)
350 debug_printf_indent("closed hints database\n");
358 /*************************************************
359 * Read from database file *
360 *************************************************/
362 /* Passing back the pointer unchanged is useless, because there is
363 no guarantee of alignment. Since all the records used by Exim need
364 to be properly aligned to pick out the timestamps, etc., we might as
365 well do the copying centrally here.
367 Most calls don't need the length, so there is a macro called dbfn_read which
368 has two arguments; it calls this function adding NULL as the third.
371 dbblock a pointer to an open database block
372 key the key of the record to be read
373 length a pointer to an int into which to return the length, if not NULL
375 Returns: a pointer to the retrieved record, or
376 NULL if the record is not found
380 dbfn_read_with_length(open_db * dbblock, const uschar * key, int * length)
383 EXIM_DATUM key_datum, result_datum;
384 int klen = Ustrlen(key) + 1;
385 uschar * key_copy = store_get(klen, key);
388 memcpy(key_copy, key, klen);
390 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_read: key=%s\n", key);
392 exim_datum_init(&key_datum); /* Some DBM libraries require the datum */
393 exim_datum_init(&result_datum); /* to be cleared before use. */
394 exim_datum_data_set(&key_datum, key_copy);
395 exim_datum_size_set(&key_datum, klen);
397 if (!exim_dbget(dbblock->dbptr, &key_datum, &result_datum))
399 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_read: null return\n");
403 /* Assume the data store could have been tainted. Properly, we should
404 store the taint status with the data. */
406 dlen = exim_datum_size_get(&result_datum);
407 yield = store_get(dlen, GET_TAINTED);
408 memcpy(yield, exim_datum_data_get(&result_datum), dlen);
409 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_read: size %u return\n", dlen);
410 if (length) *length = dlen;
412 exim_datum_free(&result_datum); /* Some DBM libs require freeing */
417 /* Read a record. If the length is not as expected then delete it, write
418 an error log line, delete the record and return NULL.
419 Use this for fixed-size records (so not retry or wait records).
422 dbblock a pointer to an open database block
423 key the key of the record to be read
424 length the expected record length
426 Returns: a pointer to the retrieved record, or
427 NULL if the record is not found/bad
431 dbfn_read_enforce_length(open_db * dbblock, const uschar * key, size_t length)
434 void * yield = dbfn_read_with_length(dbblock, key, &rlen);
438 if (rlen == length) return yield;
439 log_write(0, LOG_MAIN|LOG_PANIC, "Bad db record size for '%s'", key);
440 dbfn_delete(dbblock, key);
446 /*************************************************
447 * Write to database file *
448 *************************************************/
452 dbblock a pointer to an open database block
453 key the key of the record to be written
454 ptr a pointer to the record to be written
455 length the length of the record to be written
457 Returns: the yield of the underlying dbm or db "write" function. If this
458 is dbm, the value is zero for OK.
462 dbfn_write(open_db *dbblock, const uschar *key, void *ptr, int length)
464 EXIM_DATUM key_datum, value_datum;
465 dbdata_generic *gptr = (dbdata_generic *)ptr;
466 int klen = Ustrlen(key) + 1;
467 uschar * key_copy = store_get(klen, key);
469 memcpy(key_copy, key, klen);
470 gptr->time_stamp = time(NULL);
472 DEBUG(D_hints_lookup)
473 debug_printf_indent("dbfn_write: key=%s datalen %d\n", key, length);
475 exim_datum_init(&key_datum); /* Some DBM libraries require the datum */
476 exim_datum_init(&value_datum); /* to be cleared before use. */
477 exim_datum_data_set(&key_datum, key_copy);
478 exim_datum_size_set(&key_datum, klen);
479 exim_datum_data_set(&value_datum, ptr);
480 exim_datum_size_set(&value_datum, length);
481 return exim_dbput(dbblock->dbptr, &key_datum, &value_datum);
486 /*************************************************
487 * Delete record from database file *
488 *************************************************/
492 dbblock a pointer to an open database block
493 key the key of the record to be deleted
495 Returns: the yield of the underlying dbm or db "delete" function.
499 dbfn_delete(open_db *dbblock, const uschar *key)
501 int klen = Ustrlen(key) + 1;
502 uschar * key_copy = store_get(klen, key);
503 EXIM_DATUM key_datum;
505 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_delete: key=%s\n", key);
507 memcpy(key_copy, key, klen);
508 exim_datum_init(&key_datum); /* Some DBM libraries require clearing */
509 exim_datum_data_set(&key_datum, key_copy);
510 exim_datum_size_set(&key_datum, klen);
511 return exim_dbdel(dbblock->dbptr, &key_datum);
517 /* XXX This appears to be unused. There's a separate implementation
518 in dbutils.c for dumpdb and fixdb, using the same underlying support.
521 /*************************************************
522 * Scan the keys of a database file *
523 *************************************************/
527 dbblock a pointer to an open database block
528 start TRUE if starting a new scan
529 FALSE if continuing with the current scan
530 cursor a pointer to a pointer to a cursor anchor, for those dbm libraries
531 that use the notion of a cursor
533 Returns: the next record from the file, or
534 NULL if there are no more
538 dbfn_scan(open_db *dbblock, BOOL start, EXIM_CURSOR **cursor)
540 EXIM_DATUM key_datum, value_datum;
543 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_scan\n");
545 /* Some dbm require an initialization */
547 if (start) *cursor = exim_dbcreate_cursor(dbblock->dbptr);
549 exim_datum_init(&key_datum); /* Some DBM libraries require the datum */
550 exim_datum_init(&value_datum); /* to be cleared before use. */
552 yield = exim_dbscan(dbblock->dbptr, &key_datum, &value_datum, start, *cursor)
553 ? US exim_datum_data_get(&key_datum) : NULL;
555 /* Some dbm require a termination */
557 if (!yield) exim_dbdelete_cursor(*cursor);
564 /*************************************************
565 **************************************************
566 * Stand-alone test program *
567 **************************************************
568 *************************************************/
573 main(int argc, char **cargv)
576 int max_db = sizeof(dbblock)/sizeof(open_db);
580 dbdata_wait *dbwait = NULL;
581 uschar **argv = USS cargv;
583 uschar structbuffer[1024];
587 printf("Usage: test_dbfn directory\n");
588 printf("The subdirectory called \"db\" in the given directory is used for\n");
589 printf("the files used in this test program.\n");
595 spool_directory = argv[1];
596 debug_selector = D_all - D_memory;
598 big_buffer = malloc(big_buffer_size);
600 for (i = 0; i < max_db; i++) dbblock[i].dbptr = NULL;
602 printf("\nExim's db functions tester: interface type is %s\n", EXIM_DBTYPE);
603 printf("DBM library: ");
605 #ifdef DB_VERSION_STRING
606 printf("Berkeley DB: %s\n", DB_VERSION_STRING);
607 #elif defined(BTREEVERSION) && defined(HASHVERSION)
609 printf("probably Berkeley DB version 1.8x (native mode)\n");
611 printf("probably Berkeley DB version 1.8x (compatibility mode)\n");
613 #elif defined(_DBM_RDONLY) || defined(dbm_dirfno)
614 printf("probably ndbm\n");
615 #elif defined(USE_TDB)
616 printf("using tdb\n");
619 printf("probably GDBM (native mode)\n");
621 printf("probably GDBM (compatibility mode)\n");
625 /* Test the functions */
627 printf("\nTest the functions\n> ");
629 while (Ufgets(buffer, 256, stdin) != NULL)
631 int len = Ustrlen(buffer);
635 uschar *cmd = buffer;
636 while (len > 0 && isspace((uschar)buffer[len-1])) len--;
639 if (isdigit((uschar)*cmd))
642 while (isdigit((uschar)*cmd)) cmd++;
643 Uskip_whitespace(&cmd);
646 if (Ustrncmp(cmd, "open", 4) == 0)
651 Uskip_whitespace(&s);
653 for (i = 0; i < max_db; i++)
654 if (dbblock[i].dbptr == NULL) break;
658 printf("Too many open databases\n> ");
663 odb = dbfn_open(s, O_RDWR, dbblock + i, TRUE, TRUE);
669 printf("opened %d\n", current);
671 /* Other error cases will have written messages */
672 else if (errno == ENOENT)
674 printf("open failed: %s%s\n", strerror(errno),
676 " (or other Berkeley DB error)"
684 else if (Ustrncmp(cmd, "write", 5) == 0)
687 uschar * key = cmd + 5, * data;
691 printf("No current database\n");
695 Uskip_whitespace(&key);
697 Uskip_nonwhite(&data);
699 Uskip_whitespace(&data);
701 dbwait = (dbdata_wait *)(&structbuffer);
702 Ustrcpy(dbwait->text, data);
706 rc = dbfn_write(dbblock + current, key, dbwait,
707 Ustrlen(data) + sizeof(dbdata_wait));
709 if (rc != 0) printf("Failed: %s\n", strerror(errno));
712 else if (Ustrncmp(cmd, "read", 4) == 0)
714 uschar * key = cmd + 4;
717 printf("No current database\n");
720 Uskip_whitespace(&key);
723 dbwait = (dbdata_wait *)dbfn_read_with_length(dbblock+ current, key, NULL);
725 printf("%s\n", (dbwait == NULL)? "<not found>" : CS dbwait->text);
728 else if (Ustrncmp(cmd, "delete", 6) == 0)
730 uschar * key = cmd + 6;
733 printf("No current database\n");
736 Uskip_whitespace(&key);
737 dbfn_delete(dbblock + current, key);
740 else if (Ustrncmp(cmd, "scan", 4) == 0)
743 BOOL startflag = TRUE;
745 uschar keybuffer[256];
748 printf("No current database\n");
752 while ((key = dbfn_scan(dbblock + current, startflag, &cursor)) != NULL)
755 Ustrcpy(keybuffer, key);
756 dbwait = (dbdata_wait *)dbfn_read_with_length(dbblock + current,
758 printf("%s: %s\n", keybuffer, dbwait->text);
761 printf("End of scan\n");
764 else if (Ustrncmp(cmd, "close", 5) == 0)
766 uschar * s = cmd + 5;
767 Uskip_whitespace(&s);
769 if (i >= max_db || dbblock[i].dbptr == NULL) printf("Not open\n"); else
772 dbfn_close(dbblock + i);
774 dbblock[i].dbptr = NULL;
775 if (i == current) current = -1;
779 else if (Ustrncmp(cmd, "file", 4) == 0)
781 uschar * s = cmd + 4;
782 Uskip_whitespace(&s);
784 if (i >= max_db || dbblock[i].dbptr == NULL) printf("Not open\n");
788 else if (Ustrncmp(cmd, "time", 4) == 0)
790 showtime = ~showtime;
791 printf("Timing %s\n", showtime? "on" : "off");
794 else if (Ustrcmp(cmd, "q") == 0 || Ustrncmp(cmd, "quit", 4) == 0) break;
796 else if (Ustrncmp(cmd, "help", 4) == 0)
798 printf("close [<number>] close file [<number>]\n");
799 printf("delete <key> remove record from current file\n");
800 printf("file <number> make file <number> current\n");
801 printf("open <name> open db file\n");
802 printf("q[uit] exit program\n");
803 printf("read <key> read record from current file\n");
804 printf("scan scan current file\n");
805 printf("time time display on/off\n");
806 printf("write <key> <rest-of-line> write record to current file\n");
809 else printf("Eh?\n");
811 if (showtime && stop >= start)
812 printf("start=%d stop=%d difference=%d\n", (int)start, (int)stop,
813 (int)(stop - start));
818 for (i = 0; i < max_db; i++)
820 if (dbblock[i].dbptr != NULL)
822 printf("\nClosing %d", i);
823 dbfn_close(dbblock + i);