SPDX: Mass-update to GPL-2.0-or-later
[exim.git] / src / src / dbfn.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2020 - 2022 */
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 macros.
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
41
42 /*************************************************
43 *          Open and lock a database file         *
44 *************************************************/
45
46 /* Used for accessing Exim's hints databases.
47
48 Arguments:
49   name     The single-component name of one of Exim's database files.
50   flags    Either O_RDONLY or O_RDWR, indicating the type of open required;
51              O_RDWR implies "create if necessary"
52   dbblock  Points to an open_db block to be filled in.
53   lof      If TRUE, write to the log for actual open failures (locking failures
54            are always logged).
55   panic    If TRUE, panic on failure to create the db directory
56
57 Returns:   NULL if the open failed, or the locking failed. After locking
58            failures, errno is zero.
59
60            On success, dbblock is returned. This contains the dbm pointer and
61            the fd of the locked lock file.
62
63 There are some calls that use O_RDWR|O_CREAT for the flags. Having discovered
64 this in December 2005, I'm not sure if this is correct or not, but for the
65 moment I haven't changed them.
66 */
67
68 open_db *
69 dbfn_open(uschar *name, int flags, open_db *dbblock, BOOL lof, BOOL panic)
70 {
71 int rc, save_errno;
72 BOOL read_only = flags == O_RDONLY;
73 flock_t lock_data;
74 uschar dirname[PATHLEN], filename[PATHLEN];
75
76 DEBUG(D_hints_lookup) acl_level++;
77
78 /* The first thing to do is to open a separate file on which to lock. This
79 ensures that Exim has exclusive use of the database before it even tries to
80 open it. Early versions tried to lock on the open database itself, but that
81 gave rise to mysterious problems from time to time - it was suspected that some
82 DB libraries "do things" on their open() calls which break the interlocking.
83 The lock file is never written to, but we open it for writing so we can get a
84 write lock if required. If it does not exist, we create it. This is done
85 separately so we know when we have done it, because when running as root we
86 need to change the ownership - see the bottom of this function. We also try to
87 make the directory as well, just in case. We won't be doing this many times
88 unnecessarily, because usually the lock file will be there. If the directory
89 exists, there is no error. */
90
91 snprintf(CS dirname, sizeof(dirname), "%s/db", spool_directory);
92 snprintf(CS filename, sizeof(filename), "%s/%s.lockfile", dirname, name);
93
94 priv_drop_temp(exim_uid, exim_gid);
95 if ((dbblock->lockfd = Uopen(filename, O_RDWR, EXIMDB_LOCKFILE_MODE)) < 0)
96   {
97   (void)directory_make(spool_directory, US"db", EXIMDB_DIRECTORY_MODE, panic);
98   dbblock->lockfd = Uopen(filename, O_RDWR|O_CREAT, EXIMDB_LOCKFILE_MODE);
99   }
100 priv_restore();
101
102 if (dbblock->lockfd < 0)
103   {
104   log_write(0, LOG_MAIN, "%s",
105     string_open_failed("database lock file %s", filename));
106   errno = 0;      /* Indicates locking failure */
107   DEBUG(D_hints_lookup) acl_level--;
108   return NULL;
109   }
110
111 /* Now we must get a lock on the opened lock file; do this with a blocking
112 lock that times out. */
113
114 lock_data.l_type = read_only? F_RDLCK : F_WRLCK;
115 lock_data.l_whence = lock_data.l_start = lock_data.l_len = 0;
116
117 DEBUG(D_hints_lookup|D_retry|D_route|D_deliver)
118   debug_printf_indent("locking %s\n", filename);
119
120 sigalrm_seen = FALSE;
121 ALARM(EXIMDB_LOCK_TIMEOUT);
122 rc = fcntl(dbblock->lockfd, F_SETLKW, &lock_data);
123 ALARM_CLR(0);
124
125 if (sigalrm_seen) errno = ETIMEDOUT;
126 if (rc < 0)
127   {
128   log_write(0, LOG_MAIN|LOG_PANIC, "Failed to get %s lock for %s: %s",
129     read_only ? "read" : "write", filename,
130     errno == ETIMEDOUT ? "timed out" : strerror(errno));
131   (void)close(dbblock->lockfd);
132   errno = 0;       /* Indicates locking failure */
133   DEBUG(D_hints_lookup) acl_level--;
134   return NULL;
135   }
136
137 DEBUG(D_hints_lookup) debug_printf_indent("locked  %s\n", filename);
138
139 /* At this point we have an opened and locked separate lock file, that is,
140 exclusive access to the database, so we can go ahead and open it. If we are
141 expected to create it, don't do so at first, again so that we can detect
142 whether we need to change its ownership (see comments about the lock file
143 above.) There have been regular reports of crashes while opening hints
144 databases - often this is caused by non-matching db.h and the library. To make
145 it easy to pin this down, there are now debug statements on either side of the
146 open call. */
147
148 snprintf(CS filename, sizeof(filename), "%s/%s", dirname, name);
149
150 priv_drop_temp(exim_uid, exim_gid);
151 dbblock->dbptr = exim_dbopen(filename, dirname, flags, EXIMDB_MODE);
152 if (!dbblock->dbptr && errno == ENOENT && flags == O_RDWR)
153   {
154   DEBUG(D_hints_lookup)
155     debug_printf_indent("%s appears not to exist: trying to create\n", filename);
156   dbblock->dbptr = exim_dbopen(filename, dirname, flags|O_CREAT, EXIMDB_MODE);
157   }
158 save_errno = errno;
159 priv_restore();
160
161 /* If the open has failed, return NULL, leaving errno set. If lof is TRUE,
162 log the event - also for debugging - but debug only if the file just doesn't
163 exist. */
164
165 if (!dbblock->dbptr)
166   {
167   errno = save_errno;
168   if (lof && save_errno != ENOENT)
169     log_write(0, LOG_MAIN, "%s", string_open_failed("DB file %s",
170         filename));
171   else
172     DEBUG(D_hints_lookup)
173       debug_printf_indent("%s\n", CS string_open_failed("DB file %s",
174           filename));
175   (void)close(dbblock->lockfd);
176   errno = save_errno;
177   DEBUG(D_hints_lookup) acl_level--;
178   return NULL;
179   }
180
181 DEBUG(D_hints_lookup)
182   debug_printf_indent("opened hints database %s: flags=%s\n", filename,
183     flags == O_RDONLY ? "O_RDONLY"
184     : flags == O_RDWR ? "O_RDWR"
185     : flags == (O_RDWR|O_CREAT) ? "O_RDWR|O_CREAT"
186     : "??");
187
188 /* Pass back the block containing the opened database handle and the open fd
189 for the lock. */
190
191 return dbblock;
192 }
193
194
195
196
197 /*************************************************
198 *         Unlock and close a database file       *
199 *************************************************/
200
201 /* Closing a file automatically unlocks it, so after closing the database, just
202 close the lock file.
203
204 Argument: a pointer to an open database block
205 Returns:  nothing
206 */
207
208 void
209 dbfn_close(open_db *dbblock)
210 {
211 exim_dbclose(dbblock->dbptr);
212 (void)close(dbblock->lockfd);
213 DEBUG(D_hints_lookup)
214   { debug_printf_indent("closed hints database and lockfile\n"); acl_level--; }
215 }
216
217
218
219
220 /*************************************************
221 *             Read from database file            *
222 *************************************************/
223
224 /* Passing back the pointer unchanged is useless, because there is
225 no guarantee of alignment. Since all the records used by Exim need
226 to be properly aligned to pick out the timestamps, etc., we might as
227 well do the copying centrally here.
228
229 Most calls don't need the length, so there is a macro called dbfn_read which
230 has two arguments; it calls this function adding NULL as the third.
231
232 Arguments:
233   dbblock   a pointer to an open database block
234   key       the key of the record to be read
235   length    a pointer to an int into which to return the length, if not NULL
236
237 Returns: a pointer to the retrieved record, or
238          NULL if the record is not found
239 */
240
241 void *
242 dbfn_read_with_length(open_db *dbblock, const uschar *key, int *length)
243 {
244 void *yield;
245 EXIM_DATUM key_datum, result_datum;
246 int klen = Ustrlen(key) + 1;
247 uschar * key_copy = store_get(klen, key);
248
249 memcpy(key_copy, key, klen);
250
251 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_read: key=%s\n", key);
252
253 exim_datum_init(&key_datum);         /* Some DBM libraries require the datum */
254 exim_datum_init(&result_datum);      /* to be cleared before use. */
255 exim_datum_data_set(&key_datum, key_copy);
256 exim_datum_size_set(&key_datum, klen);
257
258 if (!exim_dbget(dbblock->dbptr, &key_datum, &result_datum)) return NULL;
259
260 /* Assume the data store could have been tainted.  Properly, we should
261 store the taint status with the data. */
262
263 yield = store_get(exim_datum_size_get(&result_datum), GET_TAINTED);
264 memcpy(yield, exim_datum_data_get(&result_datum), exim_datum_size_get(&result_datum));
265 if (length) *length = exim_datum_size_get(&result_datum);
266
267 exim_datum_free(&result_datum);    /* Some DBM libs require freeing */
268 return yield;
269 }
270
271
272 /* Read a record.  If the length is not as expected then delete it, write
273 an error log line, delete the record and return NULL.
274 Use this for fixed-size records (so not retry or wait records).
275
276 Arguments:
277   dbblock   a pointer to an open database block
278   key       the key of the record to be read
279   length    the expected record length
280
281 Returns: a pointer to the retrieved record, or
282          NULL if the record is not found/bad
283 */
284
285 void *
286 dbfn_read_enforce_length(open_db * dbblock, const uschar * key, size_t length)
287 {
288 int rlen;
289 void * yield = dbfn_read_with_length(dbblock, key, &rlen);
290
291 if (yield)
292   {
293   if (rlen == length) return yield;
294   log_write(0, LOG_MAIN|LOG_PANIC, "Bad db record size for '%s'", key);
295   dbfn_delete(dbblock, key);
296   }
297 return NULL;
298 }
299
300
301 /*************************************************
302 *             Write to database file             *
303 *************************************************/
304
305 /*
306 Arguments:
307   dbblock   a pointer to an open database block
308   key       the key of the record to be written
309   ptr       a pointer to the record to be written
310   length    the length of the record to be written
311
312 Returns:    the yield of the underlying dbm or db "write" function. If this
313             is dbm, the value is zero for OK.
314 */
315
316 int
317 dbfn_write(open_db *dbblock, const uschar *key, void *ptr, int length)
318 {
319 EXIM_DATUM key_datum, value_datum;
320 dbdata_generic *gptr = (dbdata_generic *)ptr;
321 int klen = Ustrlen(key) + 1;
322 uschar * key_copy = store_get(klen, key);
323
324 memcpy(key_copy, key, klen);
325 gptr->time_stamp = time(NULL);
326
327 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_write: key=%s\n", key);
328
329 exim_datum_init(&key_datum);         /* Some DBM libraries require the datum */
330 exim_datum_init(&value_datum);       /* to be cleared before use. */
331 exim_datum_data_set(&key_datum, key_copy);
332 exim_datum_size_set(&key_datum, klen);
333 exim_datum_data_set(&value_datum, ptr);
334 exim_datum_size_set(&value_datum, length);
335 return exim_dbput(dbblock->dbptr, &key_datum, &value_datum);
336 }
337
338
339
340 /*************************************************
341 *           Delete record from database file     *
342 *************************************************/
343
344 /*
345 Arguments:
346   dbblock    a pointer to an open database block
347   key        the key of the record to be deleted
348
349 Returns: the yield of the underlying dbm or db "delete" function.
350 */
351
352 int
353 dbfn_delete(open_db *dbblock, const uschar *key)
354 {
355 int klen = Ustrlen(key) + 1;
356 uschar * key_copy = store_get(klen, key);
357 EXIM_DATUM key_datum;
358
359 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_delete: key=%s\n", key);
360
361 memcpy(key_copy, key, klen);
362 exim_datum_init(&key_datum);         /* Some DBM libraries require clearing */
363 exim_datum_data_set(&key_datum, key_copy);
364 exim_datum_size_set(&key_datum, klen);
365 return exim_dbdel(dbblock->dbptr, &key_datum);
366 }
367
368
369
370 /*************************************************
371 *         Scan the keys of a database file       *
372 *************************************************/
373
374 /*
375 Arguments:
376   dbblock  a pointer to an open database block
377   start    TRUE if starting a new scan
378            FALSE if continuing with the current scan
379   cursor   a pointer to a pointer to a cursor anchor, for those dbm libraries
380            that use the notion of a cursor
381
382 Returns:   the next record from the file, or
383            NULL if there are no more
384 */
385
386 uschar *
387 dbfn_scan(open_db *dbblock, BOOL start, EXIM_CURSOR **cursor)
388 {
389 EXIM_DATUM key_datum, value_datum;
390 uschar *yield;
391
392 DEBUG(D_hints_lookup) debug_printf_indent("dbfn_scan\n");
393
394 /* Some dbm require an initialization */
395
396 if (start) *cursor = exim_dbcreate_cursor(dbblock->dbptr);
397
398 exim_datum_init(&key_datum);         /* Some DBM libraries require the datum */
399 exim_datum_init(&value_datum);       /* to be cleared before use. */
400
401 yield = exim_dbscan(dbblock->dbptr, &key_datum, &value_datum, start, *cursor)
402   ? US exim_datum_data_get(&key_datum) : NULL;
403
404 /* Some dbm require a termination */
405
406 if (!yield) exim_dbdelete_cursor(*cursor);
407 return yield;
408 }
409
410
411
412 /*************************************************
413 **************************************************
414 *             Stand-alone test program           *
415 **************************************************
416 *************************************************/
417
418 #ifdef STAND_ALONE
419
420 int
421 main(int argc, char **cargv)
422 {
423 open_db dbblock[8];
424 int max_db = sizeof(dbblock)/sizeof(open_db);
425 int current = -1;
426 int showtime = 0;
427 int i;
428 dbdata_wait *dbwait = NULL;
429 uschar **argv = USS cargv;
430 uschar buffer[256];
431 uschar structbuffer[1024];
432
433 if (argc != 2)
434   {
435   printf("Usage: test_dbfn directory\n");
436   printf("The subdirectory called \"db\" in the given directory is used for\n");
437   printf("the files used in this test program.\n");
438   return 1;
439   }
440
441 /* Initialize */
442
443 spool_directory = argv[1];
444 debug_selector = D_all - D_memory;
445 debug_file = stderr;
446 big_buffer = malloc(big_buffer_size);
447
448 for (i = 0; i < max_db; i++) dbblock[i].dbptr = NULL;
449
450 printf("\nExim's db functions tester: interface type is %s\n", EXIM_DBTYPE);
451 printf("DBM library: ");
452
453 #ifdef DB_VERSION_STRING
454 printf("Berkeley DB: %s\n", DB_VERSION_STRING);
455 #elif defined(BTREEVERSION) && defined(HASHVERSION)
456   #ifdef USE_DB
457   printf("probably Berkeley DB version 1.8x (native mode)\n");
458   #else
459   printf("probably Berkeley DB version 1.8x (compatibility mode)\n");
460   #endif
461 #elif defined(_DBM_RDONLY) || defined(dbm_dirfno)
462 printf("probably ndbm\n");
463 #elif defined(USE_TDB)
464 printf("using tdb\n");
465 #else
466   #ifdef USE_GDBM
467   printf("probably GDBM (native mode)\n");
468   #else
469   printf("probably GDBM (compatibility mode)\n");
470   #endif
471 #endif
472
473 /* Test the functions */
474
475 printf("\nTest the functions\n> ");
476
477 while (Ufgets(buffer, 256, stdin) != NULL)
478   {
479   int len = Ustrlen(buffer);
480   int count = 1;
481   clock_t start = 1;
482   clock_t stop = 0;
483   uschar *cmd = buffer;
484   while (len > 0 && isspace((uschar)buffer[len-1])) len--;
485   buffer[len] = 0;
486
487   if (isdigit((uschar)*cmd))
488     {
489     count = Uatoi(cmd);
490     while (isdigit((uschar)*cmd)) cmd++;
491     while (isspace((uschar)*cmd)) cmd++;
492     }
493
494   if (Ustrncmp(cmd, "open", 4) == 0)
495     {
496     int i;
497     open_db *odb;
498     uschar *s = cmd + 4;
499     while (isspace((uschar)*s)) s++;
500
501     for (i = 0; i < max_db; i++)
502       if (dbblock[i].dbptr == NULL) break;
503
504     if (i >= max_db)
505       {
506       printf("Too many open databases\n> ");
507       continue;
508       }
509
510     start = clock();
511     odb = dbfn_open(s, O_RDWR, dbblock + i, TRUE, TRUE);
512     stop = clock();
513
514     if (odb)
515       {
516       current = i;
517       printf("opened %d\n", current);
518       }
519     /* Other error cases will have written messages */
520     else if (errno == ENOENT)
521       {
522       printf("open failed: %s%s\n", strerror(errno),
523         #ifdef USE_DB
524         " (or other Berkeley DB error)"
525         #else
526         ""
527         #endif
528         );
529       }
530     }
531
532   else if (Ustrncmp(cmd, "write", 5) == 0)
533     {
534     int rc = 0;
535     uschar *key = cmd + 5;
536     uschar *data;
537
538     if (current < 0)
539       {
540       printf("No current database\n");
541       continue;
542       }
543
544     while (isspace((uschar)*key)) key++;
545     data = key;
546     while (*data != 0 && !isspace((uschar)*data)) data++;
547     *data++ = 0;
548     while (isspace((uschar)*data)) data++;
549
550     dbwait = (dbdata_wait *)(&structbuffer);
551     Ustrcpy(dbwait->text, data);
552
553     start = clock();
554     while (count-- > 0)
555       rc = dbfn_write(dbblock + current, key, dbwait,
556         Ustrlen(data) + sizeof(dbdata_wait));
557     stop = clock();
558     if (rc != 0) printf("Failed: %s\n", strerror(errno));
559     }
560
561   else if (Ustrncmp(cmd, "read", 4) == 0)
562     {
563     uschar *key = cmd + 4;
564     if (current < 0)
565       {
566       printf("No current database\n");
567       continue;
568       }
569     while (isspace((uschar)*key)) key++;
570     start = clock();
571     while (count-- > 0)
572       dbwait = (dbdata_wait *)dbfn_read_with_length(dbblock+ current, key, NULL);
573     stop = clock();
574     printf("%s\n", (dbwait == NULL)? "<not found>" : CS dbwait->text);
575     }
576
577   else if (Ustrncmp(cmd, "delete", 6) == 0)
578     {
579     uschar *key = cmd + 6;
580     if (current < 0)
581       {
582       printf("No current database\n");
583       continue;
584       }
585     while (isspace((uschar)*key)) key++;
586     dbfn_delete(dbblock + current, key);
587     }
588
589   else if (Ustrncmp(cmd, "scan", 4) == 0)
590     {
591     EXIM_CURSOR *cursor;
592     BOOL startflag = TRUE;
593     uschar *key;
594     uschar keybuffer[256];
595     if (current < 0)
596       {
597       printf("No current database\n");
598       continue;
599       }
600     start = clock();
601     while ((key = dbfn_scan(dbblock + current, startflag, &cursor)) != NULL)
602       {
603       startflag = FALSE;
604       Ustrcpy(keybuffer, key);
605       dbwait = (dbdata_wait *)dbfn_read_with_length(dbblock + current,
606         keybuffer, NULL);
607       printf("%s: %s\n", keybuffer, dbwait->text);
608       }
609     stop = clock();
610     printf("End of scan\n");
611     }
612
613   else if (Ustrncmp(cmd, "close", 5) == 0)
614     {
615     uschar *s = cmd + 5;
616     while (isspace((uschar)*s)) s++;
617     i = Uatoi(s);
618     if (i >= max_db || dbblock[i].dbptr == NULL) printf("Not open\n"); else
619       {
620       start = clock();
621       dbfn_close(dbblock + i);
622       stop = clock();
623       dbblock[i].dbptr = NULL;
624       if (i == current) current = -1;
625       }
626     }
627
628   else if (Ustrncmp(cmd, "file", 4) == 0)
629     {
630     uschar *s = cmd + 4;
631     while (isspace((uschar)*s)) s++;
632     i = Uatoi(s);
633     if (i >= max_db || dbblock[i].dbptr == NULL) printf("Not open\n");
634       else current = i;
635     }
636
637   else if (Ustrncmp(cmd, "time", 4) == 0)
638     {
639     showtime = ~showtime;
640     printf("Timing %s\n", showtime? "on" : "off");
641     }
642
643   else if (Ustrcmp(cmd, "q") == 0 || Ustrncmp(cmd, "quit", 4) == 0) break;
644
645   else if (Ustrncmp(cmd, "help", 4) == 0)
646     {
647     printf("close  [<number>]              close file [<number>]\n");
648     printf("delete <key>                   remove record from current file\n");
649     printf("file   <number>                make file <number> current\n");
650     printf("open   <name>                  open db file\n");
651     printf("q[uit]                         exit program\n");
652     printf("read   <key>                   read record from current file\n");
653     printf("scan                           scan current file\n");
654     printf("time                           time display on/off\n");
655     printf("write  <key> <rest-of-line>    write record to current file\n");
656     }
657
658   else printf("Eh?\n");
659
660   if (showtime && stop >= start)
661     printf("start=%d stop=%d difference=%d\n", (int)start, (int)stop,
662      (int)(stop - start));
663
664   printf("> ");
665   }
666
667 for (i = 0; i < max_db; i++)
668   {
669   if (dbblock[i].dbptr != NULL)
670     {
671     printf("\nClosing %d", i);
672     dbfn_close(dbblock + i);
673     }
674   }
675
676 printf("\n");
677 return 0;
678 }
679
680 #endif
681
682 /* End of dbfn.c */