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