1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* Copyright (c) The Exim Maintainers 2020 */
7 /* See the file NOTICE for conditions of use and distribution. */
12 /* We have buffers holding path names for database files.
13 PATH_MAX could be used here, but would be wasting memory, as we deal
14 with database files like $spooldirectory/db/<name> */
18 /* Functions for accessing Exim's hints database, which consists of a number of
19 different DBM files. This module does not contain code for reading DBM files
20 for (e.g.) alias expansion. That is all contained within the general search
21 functions. As Exim now has support for several DBM interfaces, all the relevant
22 functions are called as macros.
24 All the data in Exim's database is in the nature of *hints*. Therefore it
25 doesn't matter if it gets destroyed by accident. These functions are not
26 supposed to implement a "safe" database.
28 Keys are passed in as C strings, and the terminating zero *is* used when
29 building the dbm files. This just makes life easier when scanning the files
32 Synchronization is required on the database files, and this is achieved by
33 means of locking on independent lock files. (Earlier attempts to lock on the
34 DBM files themselves were never completely successful.) Since callers may in
35 general want to do more than one read or write while holding the lock, there
36 are separate open and close functions. However, the calling modules should
37 arrange to hold the locks for the bare minimum of time. */
41 /*************************************************
42 * Berkeley DB error callback *
43 *************************************************/
45 /* For Berkeley DB >= 2, we can define a function to be called in case of DB
46 errors. This should help with debugging strange DB problems, e.g. getting "File
47 exists" when you try to open a db file. The API for this function was changed
50 #if defined(USE_DB) && defined(DB_VERSION_STRING)
52 #if DB_VERSION_MAJOR > 4 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3)
53 dbfn_bdb_error_callback(const DB_ENV *dbenv, const char *pfx, const char *msg)
57 dbfn_bdb_error_callback(const char *pfx, char *msg)
61 log_write(0, LOG_MAIN, "Berkeley DB error: %s", msg);
69 PRIV_DROPPING, PRIV_DROPPED,
70 PRIV_RESTORING, PRIV_RESTORED
71 } priv_state = PRIV_RESTORED;
73 static uid_t priv_euid;
74 static gid_t priv_egid;
75 static gid_t priv_groups[EXIM_GROUPLIST_SIZE + 1];
76 static int priv_ngroups;
78 /* Inspired by OpenSSH's temporarily_use_uid(). Thanks! */
81 priv_drop_temp(const uid_t temp_uid, const gid_t temp_gid)
83 if (priv_state != PRIV_RESTORED) _exit(EXIT_FAILURE);
84 priv_state = PRIV_DROPPING;
86 priv_euid = geteuid();
87 if (priv_euid == root_uid)
89 priv_egid = getegid();
90 priv_ngroups = getgroups(nelem(priv_groups), priv_groups);
91 if (priv_ngroups < 0) _exit(EXIT_FAILURE);
93 if (priv_ngroups > 0 && setgroups(1, &temp_gid) != 0) _exit(EXIT_FAILURE);
94 if (setegid(temp_gid) != 0) _exit(EXIT_FAILURE);
95 if (seteuid(temp_uid) != 0) _exit(EXIT_FAILURE);
97 if (geteuid() != temp_uid) _exit(EXIT_FAILURE);
98 if (getegid() != temp_gid) _exit(EXIT_FAILURE);
101 priv_state = PRIV_DROPPED;
104 /* Inspired by OpenSSH's restore_uid(). Thanks! */
109 if (priv_state != PRIV_DROPPED) _exit(EXIT_FAILURE);
110 priv_state = PRIV_RESTORING;
112 if (priv_euid == root_uid)
114 if (seteuid(priv_euid) != 0) _exit(EXIT_FAILURE);
115 if (setegid(priv_egid) != 0) _exit(EXIT_FAILURE);
116 if (priv_ngroups > 0 && setgroups(priv_ngroups, priv_groups) != 0) _exit(EXIT_FAILURE);
118 if (geteuid() != priv_euid) _exit(EXIT_FAILURE);
119 if (getegid() != priv_egid) _exit(EXIT_FAILURE);
122 priv_state = PRIV_RESTORED;
128 /*************************************************
129 * Open and lock a database file *
130 *************************************************/
132 /* Used for accessing Exim's hints databases.
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 O_RDWR implies "create if necessary"
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
141 panic If TRUE, panic on failure to create the db directory
143 Returns: NULL if the open failed, or the locking failed. After locking
144 failures, errno is zero.
146 On success, dbblock is returned. This contains the dbm pointer and
147 the fd of the locked lock file.
149 There are some calls that use O_RDWR|O_CREAT for the flags. Having discovered
150 this in December 2005, I'm not sure if this is correct or not, but for the
151 moment I haven't changed them.
155 dbfn_open(uschar *name, int flags, open_db *dbblock, BOOL lof, BOOL panic)
158 BOOL read_only = flags == O_RDONLY;
160 uschar dirname[PATHLEN], filename[PATHLEN];
162 DEBUG(D_hints_lookup) acl_level++;
164 /* The first thing to do is to open a separate file on which to lock. This
165 ensures that Exim has exclusive use of the database before it even tries to
166 open it. Early versions tried to lock on the open database itself, but that
167 gave rise to mysterious problems from time to time - it was suspected that some
168 DB libraries "do things" on their open() calls which break the interlocking.
169 The lock file is never written to, but we open it for writing so we can get a
170 write lock if required. If it does not exist, we create it. This is done
171 separately so we know when we have done it, because when running as root we
172 need to change the ownership - see the bottom of this function. We also try to
173 make the directory as well, just in case. We won't be doing this many times
174 unnecessarily, because usually the lock file will be there. If the directory
175 exists, there is no error. */
177 snprintf(CS dirname, sizeof(dirname), "%s/db", spool_directory);
178 snprintf(CS filename, sizeof(filename), "%s/%s.lockfile", dirname, name);
180 priv_drop_temp(exim_uid, exim_gid);
181 if ((dbblock->lockfd = Uopen(filename, O_RDWR, EXIMDB_LOCKFILE_MODE)) < 0)
183 (void)directory_make(spool_directory, US"db", EXIMDB_DIRECTORY_MODE, panic);
184 dbblock->lockfd = Uopen(filename, O_RDWR|O_CREAT, EXIMDB_LOCKFILE_MODE);
188 if (dbblock->lockfd < 0)
190 log_write(0, LOG_MAIN, "%s",
191 string_open_failed("database lock file %s", filename));
192 errno = 0; /* Indicates locking failure */
193 DEBUG(D_hints_lookup) acl_level--;
197 /* Now we must get a lock on the opened lock file; do this with a blocking
198 lock that times out. */
200 lock_data.l_type = read_only? F_RDLCK : F_WRLCK;
201 lock_data.l_whence = lock_data.l_start = lock_data.l_len = 0;
203 DEBUG(D_hints_lookup|D_retry|D_route|D_deliver)
204 debug_printf_indent("locking %s\n", filename);
206 sigalrm_seen = FALSE;
207 ALARM(EXIMDB_LOCK_TIMEOUT);
208 rc = fcntl(dbblock->lockfd, F_SETLKW, &lock_data);
211 if (sigalrm_seen) errno = ETIMEDOUT;
214 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to get %s lock for %s: %s",
215 read_only ? "read" : "write", filename,
216 errno == ETIMEDOUT ? "timed out" : strerror(errno));
217 (void)close(dbblock->lockfd);
218 errno = 0; /* Indicates locking failure */
219 DEBUG(D_hints_lookup) acl_level--;
223 DEBUG(D_hints_lookup) debug_printf_indent("locked %s\n", filename);
225 /* At this point we have an opened and locked separate lock file, that is,
226 exclusive access to the database, so we can go ahead and open it. If we are
227 expected to create it, don't do so at first, again so that we can detect
228 whether we need to change its ownership (see comments about the lock file
229 above.) There have been regular reports of crashes while opening hints
230 databases - often this is caused by non-matching db.h and the library. To make
231 it easy to pin this down, there are now debug statements on either side of the
234 snprintf(CS filename, sizeof(filename), "%s/%s", dirname, name);
236 priv_drop_temp(exim_uid, exim_gid);
237 EXIM_DBOPEN(filename, dirname, flags, EXIMDB_MODE, &(dbblock->dbptr));
238 if (!dbblock->dbptr && errno == ENOENT && flags == O_RDWR)
240 DEBUG(D_hints_lookup)
241 debug_printf_indent("%s appears not to exist: trying to create\n", filename);
242 EXIM_DBOPEN(filename, dirname, flags|O_CREAT, EXIMDB_MODE, &(dbblock->dbptr));
247 /* If the open has failed, return NULL, leaving errno set. If lof is TRUE,
248 log the event - also for debugging - but debug only if the file just doesn't
254 if (lof && save_errno != ENOENT)
255 log_write(0, LOG_MAIN, "%s", string_open_failed("DB file %s",
258 DEBUG(D_hints_lookup)
259 debug_printf_indent("%s\n", CS string_open_failed("DB file %s",
261 (void)close(dbblock->lockfd);
263 DEBUG(D_hints_lookup) acl_level--;
267 DEBUG(D_hints_lookup)
268 debug_printf_indent("opened hints database %s: flags=%s\n", filename,
269 flags == O_RDONLY ? "O_RDONLY"
270 : flags == O_RDWR ? "O_RDWR"
271 : flags == (O_RDWR|O_CREAT) ? "O_RDWR|O_CREAT"
274 /* Pass back the block containing the opened database handle and the open fd
283 /*************************************************
284 * Unlock and close a database file *
285 *************************************************/
287 /* Closing a file automatically unlocks it, so after closing the database, just
290 Argument: a pointer to an open database block
295 dbfn_close(open_db *dbblock)
297 EXIM_DBCLOSE(dbblock->dbptr);
298 (void)close(dbblock->lockfd);
299 DEBUG(D_hints_lookup)
300 { debug_printf_indent("closed hints database and lockfile\n"); acl_level--; }
306 /*************************************************
307 * Read from database file *
308 *************************************************/
310 /* Passing back the pointer unchanged is useless, because there is
311 no guarantee of alignment. Since all the records used by Exim need
312 to be properly aligned to pick out the timestamps, etc., we might as
313 well do the copying centrally here.
315 Most calls don't need the length, so there is a macro called dbfn_read which
316 has two arguments; it calls this function adding NULL as the third.
319 dbblock a pointer to an open database block
320 key the key of the record to be read
321 length a pointer to an int into which to return the length, if not NULL
323 Returns: a pointer to the retrieved record, or
324 NULL if the record is not found
328 dbfn_read_with_length(open_db *dbblock, const uschar *key, int *length)
331 EXIM_DATUM key_datum, result_datum;
332 int klen = Ustrlen(key) + 1;
333 uschar * key_copy = store_get(klen, is_tainted(key));
335 memcpy(key_copy, key, klen);
337 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_read: key=%s\n", key);
339 EXIM_DATUM_INIT(key_datum); /* Some DBM libraries require the datum */
340 EXIM_DATUM_INIT(result_datum); /* to be cleared before use. */
341 EXIM_DATUM_DATA(key_datum) = CS key_copy;
342 EXIM_DATUM_SIZE(key_datum) = klen;
344 if (!EXIM_DBGET(dbblock->dbptr, key_datum, result_datum)) return NULL;
346 /* Assume the data store could have been tainted. Properly, we should
347 store the taint status with the data. */
349 yield = store_get(EXIM_DATUM_SIZE(result_datum), TRUE);
350 memcpy(yield, EXIM_DATUM_DATA(result_datum), EXIM_DATUM_SIZE(result_datum));
351 if (length != NULL) *length = EXIM_DATUM_SIZE(result_datum);
353 EXIM_DATUM_FREE(result_datum); /* Some DBM libs require freeing */
358 /* Read a record. If the length is not as expected then delete it, write
359 an error log line, delete the record and return NULL.
360 Use this for fixed-size records (so not retry or wait records).
363 dbblock a pointer to an open database block
364 key the key of the record to be read
365 length the expected record length
367 Returns: a pointer to the retrieved record, or
368 NULL if the record is not found/bad
372 dbfn_read_enforce_length(open_db * dbblock, const uschar * key, size_t length)
375 void * yield = dbfn_read_with_length(dbblock, key, &rlen);
379 if (rlen == length) return yield;
380 log_write(0, LOG_MAIN|LOG_PANIC, "Bad db record size for '%s'", key);
381 dbfn_delete(dbblock, key);
387 /*************************************************
388 * Write to database file *
389 *************************************************/
393 dbblock a pointer to an open database block
394 key the key of the record to be written
395 ptr a pointer to the record to be written
396 length the length of the record to be written
398 Returns: the yield of the underlying dbm or db "write" function. If this
399 is dbm, the value is zero for OK.
403 dbfn_write(open_db *dbblock, const uschar *key, void *ptr, int length)
405 EXIM_DATUM key_datum, value_datum;
406 dbdata_generic *gptr = (dbdata_generic *)ptr;
407 int klen = Ustrlen(key) + 1;
408 uschar * key_copy = store_get(klen, is_tainted(key));
410 memcpy(key_copy, key, klen);
411 gptr->time_stamp = time(NULL);
413 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_write: key=%s\n", key);
415 EXIM_DATUM_INIT(key_datum); /* Some DBM libraries require the datum */
416 EXIM_DATUM_INIT(value_datum); /* to be cleared before use. */
417 EXIM_DATUM_DATA(key_datum) = CS key_copy;
418 EXIM_DATUM_SIZE(key_datum) = klen;
419 EXIM_DATUM_DATA(value_datum) = CS ptr;
420 EXIM_DATUM_SIZE(value_datum) = length;
421 return EXIM_DBPUT(dbblock->dbptr, key_datum, value_datum);
426 /*************************************************
427 * Delete record from database file *
428 *************************************************/
432 dbblock a pointer to an open database block
433 key the key of the record to be deleted
435 Returns: the yield of the underlying dbm or db "delete" function.
439 dbfn_delete(open_db *dbblock, const uschar *key)
441 int klen = Ustrlen(key) + 1;
442 uschar * key_copy = store_get(klen, is_tainted(key));
444 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_delete: key=%s\n", key);
446 memcpy(key_copy, key, klen);
447 EXIM_DATUM key_datum;
448 EXIM_DATUM_INIT(key_datum); /* Some DBM libraries require clearing */
449 EXIM_DATUM_DATA(key_datum) = CS key_copy;
450 EXIM_DATUM_SIZE(key_datum) = klen;
451 return EXIM_DBDEL(dbblock->dbptr, key_datum);
456 /*************************************************
457 * Scan the keys of a database file *
458 *************************************************/
462 dbblock a pointer to an open database block
463 start TRUE if starting a new scan
464 FALSE if continuing with the current scan
465 cursor a pointer to a pointer to a cursor anchor, for those dbm libraries
466 that use the notion of a cursor
468 Returns: the next record from the file, or
469 NULL if there are no more
473 dbfn_scan(open_db *dbblock, BOOL start, EXIM_CURSOR **cursor)
475 EXIM_DATUM key_datum, value_datum;
478 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_scan\n");
480 /* Some dbm require an initialization */
482 if (start) EXIM_DBCREATE_CURSOR(dbblock->dbptr, cursor);
484 EXIM_DATUM_INIT(key_datum); /* Some DBM libraries require the datum */
485 EXIM_DATUM_INIT(value_datum); /* to be cleared before use. */
487 yield = (EXIM_DBSCAN(dbblock->dbptr, key_datum, value_datum, start, *cursor))?
488 US EXIM_DATUM_DATA(key_datum) : NULL;
490 /* Some dbm require a termination */
492 if (!yield) EXIM_DBDELETE_CURSOR(*cursor);
498 /*************************************************
499 **************************************************
500 * Stand-alone test program *
501 **************************************************
502 *************************************************/
507 main(int argc, char **cargv)
510 int max_db = sizeof(dbblock)/sizeof(open_db);
514 dbdata_wait *dbwait = NULL;
515 uschar **argv = USS cargv;
517 uschar structbuffer[1024];
521 printf("Usage: test_dbfn directory\n");
522 printf("The subdirectory called \"db\" in the given directory is used for\n");
523 printf("the files used in this test program.\n");
529 spool_directory = argv[1];
530 debug_selector = D_all - D_memory;
532 big_buffer = malloc(big_buffer_size);
534 for (i = 0; i < max_db; i++) dbblock[i].dbptr = NULL;
536 printf("\nExim's db functions tester: interface type is %s\n", EXIM_DBTYPE);
537 printf("DBM library: ");
539 #ifdef DB_VERSION_STRING
540 printf("Berkeley DB: %s\n", DB_VERSION_STRING);
541 #elif defined(BTREEVERSION) && defined(HASHVERSION)
543 printf("probably Berkeley DB version 1.8x (native mode)\n");
545 printf("probably Berkeley DB version 1.8x (compatibility mode)\n");
547 #elif defined(_DBM_RDONLY) || defined(dbm_dirfno)
548 printf("probably ndbm\n");
549 #elif defined(USE_TDB)
550 printf("using tdb\n");
553 printf("probably GDBM (native mode)\n");
555 printf("probably GDBM (compatibility mode)\n");
559 /* Test the functions */
561 printf("\nTest the functions\n> ");
563 while (Ufgets(buffer, 256, stdin) != NULL)
565 int len = Ustrlen(buffer);
569 uschar *cmd = buffer;
570 while (len > 0 && isspace((uschar)buffer[len-1])) len--;
573 if (isdigit((uschar)*cmd))
576 while (isdigit((uschar)*cmd)) cmd++;
577 while (isspace((uschar)*cmd)) cmd++;
580 if (Ustrncmp(cmd, "open", 4) == 0)
585 while (isspace((uschar)*s)) s++;
587 for (i = 0; i < max_db; i++)
588 if (dbblock[i].dbptr == NULL) break;
592 printf("Too many open databases\n> ");
597 odb = dbfn_open(s, O_RDWR, dbblock + i, TRUE, TRUE);
603 printf("opened %d\n", current);
605 /* Other error cases will have written messages */
606 else if (errno == ENOENT)
608 printf("open failed: %s%s\n", strerror(errno),
610 " (or other Berkeley DB error)"
618 else if (Ustrncmp(cmd, "write", 5) == 0)
621 uschar *key = cmd + 5;
626 printf("No current database\n");
630 while (isspace((uschar)*key)) key++;
632 while (*data != 0 && !isspace((uschar)*data)) data++;
634 while (isspace((uschar)*data)) data++;
636 dbwait = (dbdata_wait *)(&structbuffer);
637 Ustrcpy(dbwait->text, data);
641 rc = dbfn_write(dbblock + current, key, dbwait,
642 Ustrlen(data) + sizeof(dbdata_wait));
644 if (rc != 0) printf("Failed: %s\n", strerror(errno));
647 else if (Ustrncmp(cmd, "read", 4) == 0)
649 uschar *key = cmd + 4;
652 printf("No current database\n");
655 while (isspace((uschar)*key)) key++;
658 dbwait = (dbdata_wait *)dbfn_read_with_length(dbblock+ current, key, NULL);
660 printf("%s\n", (dbwait == NULL)? "<not found>" : CS dbwait->text);
663 else if (Ustrncmp(cmd, "delete", 6) == 0)
665 uschar *key = cmd + 6;
668 printf("No current database\n");
671 while (isspace((uschar)*key)) key++;
672 dbfn_delete(dbblock + current, key);
675 else if (Ustrncmp(cmd, "scan", 4) == 0)
678 BOOL startflag = TRUE;
680 uschar keybuffer[256];
683 printf("No current database\n");
687 while ((key = dbfn_scan(dbblock + current, startflag, &cursor)) != NULL)
690 Ustrcpy(keybuffer, key);
691 dbwait = (dbdata_wait *)dbfn_read_with_length(dbblock + current,
693 printf("%s: %s\n", keybuffer, dbwait->text);
696 printf("End of scan\n");
699 else if (Ustrncmp(cmd, "close", 5) == 0)
702 while (isspace((uschar)*s)) s++;
704 if (i >= max_db || dbblock[i].dbptr == NULL) printf("Not open\n"); else
707 dbfn_close(dbblock + i);
709 dbblock[i].dbptr = NULL;
710 if (i == current) current = -1;
714 else if (Ustrncmp(cmd, "file", 4) == 0)
717 while (isspace((uschar)*s)) s++;
719 if (i >= max_db || dbblock[i].dbptr == NULL) printf("Not open\n");
723 else if (Ustrncmp(cmd, "time", 4) == 0)
725 showtime = ~showtime;
726 printf("Timing %s\n", showtime? "on" : "off");
729 else if (Ustrcmp(cmd, "q") == 0 || Ustrncmp(cmd, "quit", 4) == 0) break;
731 else if (Ustrncmp(cmd, "help", 4) == 0)
733 printf("close [<number>] close file [<number>]\n");
734 printf("delete <key> remove record from current file\n");
735 printf("file <number> make file <number> current\n");
736 printf("open <name> open db file\n");
737 printf("q[uit] exit program\n");
738 printf("read <key> read record from current file\n");
739 printf("scan scan current file\n");
740 printf("time time display on/off\n");
741 printf("write <key> <rest-of-line> write record to current file\n");
744 else printf("Eh?\n");
746 if (showtime && stop >= start)
747 printf("start=%d stop=%d difference=%d\n", (int)start, (int)stop,
748 (int)(stop - start));
753 for (i = 0; i < max_db; i++)
755 if (dbblock[i].dbptr != NULL)
757 printf("\nClosing %d", i);
758 dbfn_close(dbblock + i);