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 /* Used for accessing Exim's hints databases.
67 name The single-component name of one of Exim's database files.
68 flags Either O_RDONLY or O_RDWR, indicating the type of open required;
69 O_RDWR implies "create if necessary"
70 dbblock Points to an open_db block to be filled in.
71 lof If TRUE, write to the log for actual open failures (locking failures
73 panic If TRUE, panic on failure to create the db directory
75 Returns: NULL if the open failed, or the locking failed. After locking
76 failures, errno is zero.
78 On success, dbblock is returned. This contains the dbm pointer and
79 the fd of the locked lock file.
81 There are some calls that use O_RDWR|O_CREAT for the flags. Having discovered
82 this in December 2005, I'm not sure if this is correct or not, but for the
83 moment I haven't changed them.
87 dbfn_open(uschar *name, int flags, open_db *dbblock, BOOL lof, BOOL panic)
90 BOOL read_only = flags == O_RDONLY;
92 uschar dirname[PATHLEN], filename[PATHLEN];
94 DEBUG(D_hints_lookup) acl_level++;
96 /* The first thing to do is to open a separate file on which to lock. This
97 ensures that Exim has exclusive use of the database before it even tries to
98 open it. Early versions tried to lock on the open database itself, but that
99 gave rise to mysterious problems from time to time - it was suspected that some
100 DB libraries "do things" on their open() calls which break the interlocking.
101 The lock file is never written to, but we open it for writing so we can get a
102 write lock if required. If it does not exist, we create it. This is done
103 separately so we know when we have done it, because when running as root we
104 need to change the ownership - see the bottom of this function. We also try to
105 make the directory as well, just in case. We won't be doing this many times
106 unnecessarily, because usually the lock file will be there. If the directory
107 exists, there is no error. */
109 snprintf(CS dirname, sizeof(dirname), "%s/db", spool_directory);
110 snprintf(CS filename, sizeof(filename), "%s/%s.lockfile", dirname, name);
112 priv_drop_temp(exim_uid, exim_gid);
113 if ((dbblock->lockfd = Uopen(filename, O_RDWR, EXIMDB_LOCKFILE_MODE)) < 0)
115 (void)directory_make(spool_directory, US"db", EXIMDB_DIRECTORY_MODE, panic);
116 dbblock->lockfd = Uopen(filename, O_RDWR|O_CREAT, EXIMDB_LOCKFILE_MODE);
120 if (dbblock->lockfd < 0)
122 log_write(0, LOG_MAIN, "%s",
123 string_open_failed("database lock file %s", filename));
124 errno = 0; /* Indicates locking failure */
125 DEBUG(D_hints_lookup) acl_level--;
129 /* Now we must get a lock on the opened lock file; do this with a blocking
130 lock that times out. */
132 lock_data.l_type = read_only? F_RDLCK : F_WRLCK;
133 lock_data.l_whence = lock_data.l_start = lock_data.l_len = 0;
135 DEBUG(D_hints_lookup|D_retry|D_route|D_deliver)
136 debug_printf_indent("locking %s\n", filename);
138 sigalrm_seen = FALSE;
139 ALARM(EXIMDB_LOCK_TIMEOUT);
140 rc = fcntl(dbblock->lockfd, F_SETLKW, &lock_data);
143 if (sigalrm_seen) errno = ETIMEDOUT;
146 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to get %s lock for %s: %s",
147 read_only ? "read" : "write", filename,
148 errno == ETIMEDOUT ? "timed out" : strerror(errno));
149 (void)close(dbblock->lockfd);
150 errno = 0; /* Indicates locking failure */
151 DEBUG(D_hints_lookup) acl_level--;
155 DEBUG(D_hints_lookup) debug_printf_indent("locked %s\n", filename);
157 /* At this point we have an opened and locked separate lock file, that is,
158 exclusive access to the database, so we can go ahead and open it. If we are
159 expected to create it, don't do so at first, again so that we can detect
160 whether we need to change its ownership (see comments about the lock file
161 above.) There have been regular reports of crashes while opening hints
162 databases - often this is caused by non-matching db.h and the library. To make
163 it easy to pin this down, there are now debug statements on either side of the
166 snprintf(CS filename, sizeof(filename), "%s/%s", dirname, name);
168 priv_drop_temp(exim_uid, exim_gid);
169 dbblock->dbptr = exim_dbopen(filename, dirname, flags, EXIMDB_MODE);
170 if (!dbblock->dbptr && errno == ENOENT && flags == O_RDWR)
172 DEBUG(D_hints_lookup)
173 debug_printf_indent("%s appears not to exist: trying to create\n", filename);
174 dbblock->dbptr = exim_dbopen(filename, dirname, flags|O_CREAT, EXIMDB_MODE);
179 /* If the open has failed, return NULL, leaving errno set. If lof is TRUE,
180 log the event - also for debugging - but debug only if the file just doesn't
186 if (lof && save_errno != ENOENT)
187 log_write(0, LOG_MAIN, "%s", string_open_failed("DB file %s",
190 DEBUG(D_hints_lookup)
191 debug_printf_indent("%s\n", CS string_open_failed("DB file %s",
193 (void)close(dbblock->lockfd);
195 DEBUG(D_hints_lookup) acl_level--;
199 DEBUG(D_hints_lookup)
200 debug_printf_indent("opened hints database %s: flags=%s\n", filename,
201 flags == O_RDONLY ? "O_RDONLY"
202 : flags == O_RDWR ? "O_RDWR"
203 : flags == (O_RDWR|O_CREAT) ? "O_RDWR|O_CREAT"
206 /* Pass back the block containing the opened database handle and the open fd
215 /*************************************************
216 * Unlock and close a database file *
217 *************************************************/
219 /* Closing a file automatically unlocks it, so after closing the database, just
222 Argument: a pointer to an open database block
227 dbfn_close(open_db *dbblock)
229 exim_dbclose(dbblock->dbptr);
230 (void)close(dbblock->lockfd);
231 DEBUG(D_hints_lookup)
232 { debug_printf_indent("closed hints database and lockfile\n"); acl_level--; }
238 /*************************************************
239 * Read from database file *
240 *************************************************/
242 /* Passing back the pointer unchanged is useless, because there is
243 no guarantee of alignment. Since all the records used by Exim need
244 to be properly aligned to pick out the timestamps, etc., we might as
245 well do the copying centrally here.
247 Most calls don't need the length, so there is a macro called dbfn_read which
248 has two arguments; it calls this function adding NULL as the third.
251 dbblock a pointer to an open database block
252 key the key of the record to be read
253 length a pointer to an int into which to return the length, if not NULL
255 Returns: a pointer to the retrieved record, or
256 NULL if the record is not found
260 dbfn_read_with_length(open_db * dbblock, const uschar * key, int * length)
263 EXIM_DATUM key_datum, result_datum;
264 int klen = Ustrlen(key) + 1;
265 uschar * key_copy = store_get(klen, key);
268 memcpy(key_copy, key, klen);
270 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_read: key=%s\n", key);
272 exim_datum_init(&key_datum); /* Some DBM libraries require the datum */
273 exim_datum_init(&result_datum); /* to be cleared before use. */
274 exim_datum_data_set(&key_datum, key_copy);
275 exim_datum_size_set(&key_datum, klen);
277 if (!exim_dbget(dbblock->dbptr, &key_datum, &result_datum))
279 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_read: null return\n");
283 /* Assume the data store could have been tainted. Properly, we should
284 store the taint status with the data. */
286 dlen = exim_datum_size_get(&result_datum);
287 yield = store_get(dlen, GET_TAINTED);
288 memcpy(yield, exim_datum_data_get(&result_datum), dlen);
289 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_read: size %u return\n", dlen);
290 if (length) *length = dlen;
292 exim_datum_free(&result_datum); /* Some DBM libs require freeing */
297 /* Read a record. If the length is not as expected then delete it, write
298 an error log line, delete the record and return NULL.
299 Use this for fixed-size records (so not retry or wait records).
302 dbblock a pointer to an open database block
303 key the key of the record to be read
304 length the expected record length
306 Returns: a pointer to the retrieved record, or
307 NULL if the record is not found/bad
311 dbfn_read_enforce_length(open_db * dbblock, const uschar * key, size_t length)
314 void * yield = dbfn_read_with_length(dbblock, key, &rlen);
318 if (rlen == length) return yield;
319 log_write(0, LOG_MAIN|LOG_PANIC, "Bad db record size for '%s'", key);
320 dbfn_delete(dbblock, key);
326 /*************************************************
327 * Write to database file *
328 *************************************************/
332 dbblock a pointer to an open database block
333 key the key of the record to be written
334 ptr a pointer to the record to be written
335 length the length of the record to be written
337 Returns: the yield of the underlying dbm or db "write" function. If this
338 is dbm, the value is zero for OK.
342 dbfn_write(open_db *dbblock, const uschar *key, void *ptr, int length)
344 EXIM_DATUM key_datum, value_datum;
345 dbdata_generic *gptr = (dbdata_generic *)ptr;
346 int klen = Ustrlen(key) + 1;
347 uschar * key_copy = store_get(klen, key);
349 memcpy(key_copy, key, klen);
350 gptr->time_stamp = time(NULL);
352 DEBUG(D_hints_lookup)
353 debug_printf_indent("dbfn_write: key=%s datalen %d\n", key, length);
355 exim_datum_init(&key_datum); /* Some DBM libraries require the datum */
356 exim_datum_init(&value_datum); /* to be cleared before use. */
357 exim_datum_data_set(&key_datum, key_copy);
358 exim_datum_size_set(&key_datum, klen);
359 exim_datum_data_set(&value_datum, ptr);
360 exim_datum_size_set(&value_datum, length);
361 return exim_dbput(dbblock->dbptr, &key_datum, &value_datum);
366 /*************************************************
367 * Delete record from database file *
368 *************************************************/
372 dbblock a pointer to an open database block
373 key the key of the record to be deleted
375 Returns: the yield of the underlying dbm or db "delete" function.
379 dbfn_delete(open_db *dbblock, const uschar *key)
381 int klen = Ustrlen(key) + 1;
382 uschar * key_copy = store_get(klen, key);
383 EXIM_DATUM key_datum;
385 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_delete: key=%s\n", key);
387 memcpy(key_copy, key, klen);
388 exim_datum_init(&key_datum); /* Some DBM libraries require clearing */
389 exim_datum_data_set(&key_datum, key_copy);
390 exim_datum_size_set(&key_datum, klen);
391 return exim_dbdel(dbblock->dbptr, &key_datum);
397 /* XXX This appears to be unused. There's a separate implementation
398 in dbutils.c for dumpdb and fixdb, using the same underlying support.
401 /*************************************************
402 * Scan the keys of a database file *
403 *************************************************/
407 dbblock a pointer to an open database block
408 start TRUE if starting a new scan
409 FALSE if continuing with the current scan
410 cursor a pointer to a pointer to a cursor anchor, for those dbm libraries
411 that use the notion of a cursor
413 Returns: the next record from the file, or
414 NULL if there are no more
418 dbfn_scan(open_db *dbblock, BOOL start, EXIM_CURSOR **cursor)
420 EXIM_DATUM key_datum, value_datum;
423 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_scan\n");
425 /* Some dbm require an initialization */
427 if (start) *cursor = exim_dbcreate_cursor(dbblock->dbptr);
429 exim_datum_init(&key_datum); /* Some DBM libraries require the datum */
430 exim_datum_init(&value_datum); /* to be cleared before use. */
432 yield = exim_dbscan(dbblock->dbptr, &key_datum, &value_datum, start, *cursor)
433 ? US exim_datum_data_get(&key_datum) : NULL;
435 /* Some dbm require a termination */
437 if (!yield) exim_dbdelete_cursor(*cursor);
444 /*************************************************
445 **************************************************
446 * Stand-alone test program *
447 **************************************************
448 *************************************************/
453 main(int argc, char **cargv)
456 int max_db = sizeof(dbblock)/sizeof(open_db);
460 dbdata_wait *dbwait = NULL;
461 uschar **argv = USS cargv;
463 uschar structbuffer[1024];
467 printf("Usage: test_dbfn directory\n");
468 printf("The subdirectory called \"db\" in the given directory is used for\n");
469 printf("the files used in this test program.\n");
475 spool_directory = argv[1];
476 debug_selector = D_all - D_memory;
478 big_buffer = malloc(big_buffer_size);
480 for (i = 0; i < max_db; i++) dbblock[i].dbptr = NULL;
482 printf("\nExim's db functions tester: interface type is %s\n", EXIM_DBTYPE);
483 printf("DBM library: ");
485 #ifdef DB_VERSION_STRING
486 printf("Berkeley DB: %s\n", DB_VERSION_STRING);
487 #elif defined(BTREEVERSION) && defined(HASHVERSION)
489 printf("probably Berkeley DB version 1.8x (native mode)\n");
491 printf("probably Berkeley DB version 1.8x (compatibility mode)\n");
493 #elif defined(_DBM_RDONLY) || defined(dbm_dirfno)
494 printf("probably ndbm\n");
495 #elif defined(USE_TDB)
496 printf("using tdb\n");
499 printf("probably GDBM (native mode)\n");
501 printf("probably GDBM (compatibility mode)\n");
505 /* Test the functions */
507 printf("\nTest the functions\n> ");
509 while (Ufgets(buffer, 256, stdin) != NULL)
511 int len = Ustrlen(buffer);
515 uschar *cmd = buffer;
516 while (len > 0 && isspace((uschar)buffer[len-1])) len--;
519 if (isdigit((uschar)*cmd))
522 while (isdigit((uschar)*cmd)) cmd++;
523 Uskip_whitespace(&cmd);
526 if (Ustrncmp(cmd, "open", 4) == 0)
531 Uskip_whitespace(&s);
533 for (i = 0; i < max_db; i++)
534 if (dbblock[i].dbptr == NULL) break;
538 printf("Too many open databases\n> ");
543 odb = dbfn_open(s, O_RDWR, dbblock + i, TRUE, TRUE);
549 printf("opened %d\n", current);
551 /* Other error cases will have written messages */
552 else if (errno == ENOENT)
554 printf("open failed: %s%s\n", strerror(errno),
556 " (or other Berkeley DB error)"
564 else if (Ustrncmp(cmd, "write", 5) == 0)
567 uschar * key = cmd + 5, * data;
571 printf("No current database\n");
575 Uskip_whitespace(&key);
577 Uskip_nonwhite(&data);
579 Uskip_whitespace(&data);
581 dbwait = (dbdata_wait *)(&structbuffer);
582 Ustrcpy(dbwait->text, data);
586 rc = dbfn_write(dbblock + current, key, dbwait,
587 Ustrlen(data) + sizeof(dbdata_wait));
589 if (rc != 0) printf("Failed: %s\n", strerror(errno));
592 else if (Ustrncmp(cmd, "read", 4) == 0)
594 uschar * key = cmd + 4;
597 printf("No current database\n");
600 Uskip_whitespace(&key);
603 dbwait = (dbdata_wait *)dbfn_read_with_length(dbblock+ current, key, NULL);
605 printf("%s\n", (dbwait == NULL)? "<not found>" : CS dbwait->text);
608 else if (Ustrncmp(cmd, "delete", 6) == 0)
610 uschar * key = cmd + 6;
613 printf("No current database\n");
616 Uskip_whitespace(&key);
617 dbfn_delete(dbblock + current, key);
620 else if (Ustrncmp(cmd, "scan", 4) == 0)
623 BOOL startflag = TRUE;
625 uschar keybuffer[256];
628 printf("No current database\n");
632 while ((key = dbfn_scan(dbblock + current, startflag, &cursor)) != NULL)
635 Ustrcpy(keybuffer, key);
636 dbwait = (dbdata_wait *)dbfn_read_with_length(dbblock + current,
638 printf("%s: %s\n", keybuffer, dbwait->text);
641 printf("End of scan\n");
644 else if (Ustrncmp(cmd, "close", 5) == 0)
646 uschar * s = cmd + 5;
647 Uskip_whitespace(&s);
649 if (i >= max_db || dbblock[i].dbptr == NULL) printf("Not open\n"); else
652 dbfn_close(dbblock + i);
654 dbblock[i].dbptr = NULL;
655 if (i == current) current = -1;
659 else if (Ustrncmp(cmd, "file", 4) == 0)
661 uschar * s = cmd + 4;
662 Uskip_whitespace(&s);
664 if (i >= max_db || dbblock[i].dbptr == NULL) printf("Not open\n");
668 else if (Ustrncmp(cmd, "time", 4) == 0)
670 showtime = ~showtime;
671 printf("Timing %s\n", showtime? "on" : "off");
674 else if (Ustrcmp(cmd, "q") == 0 || Ustrncmp(cmd, "quit", 4) == 0) break;
676 else if (Ustrncmp(cmd, "help", 4) == 0)
678 printf("close [<number>] close file [<number>]\n");
679 printf("delete <key> remove record from current file\n");
680 printf("file <number> make file <number> current\n");
681 printf("open <name> open db file\n");
682 printf("q[uit] exit program\n");
683 printf("read <key> read record from current file\n");
684 printf("scan scan current file\n");
685 printf("time time display on/off\n");
686 printf("write <key> <rest-of-line> write record to current file\n");
689 else printf("Eh?\n");
691 if (showtime && stop >= start)
692 printf("start=%d stop=%d difference=%d\n", (int)start, (int)stop,
693 (int)(stop - start));
698 for (i = 0; i < max_db; i++)
700 if (dbblock[i].dbptr != NULL)
702 printf("\nClosing %d", i);
703 dbfn_close(dbblock + i);