Check syscall return values.
[exim.git] / src / src / dbfn.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2009 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8
9 #include "exim.h"
10
11
12 /* Functions for accessing Exim's hints database, which consists of a number of
13 different DBM files. This module does not contain code for reading DBM files
14 for (e.g.) alias expansion. That is all contained within the general search
15 functions. As Exim now has support for several DBM interfaces, all the relevant
16 functions are called as macros.
17
18 All the data in Exim's database is in the nature of *hints*. Therefore it
19 doesn't matter if it gets destroyed by accident. These functions are not
20 supposed to implement a "safe" database.
21
22 Keys are passed in as C strings, and the terminating zero *is* used when
23 building the dbm files. This just makes life easier when scanning the files
24 sequentially.
25
26 Synchronization is required on the database files, and this is achieved by
27 means of locking on independent lock files. (Earlier attempts to lock on the
28 DBM files themselves were never completely successful.) Since callers may in
29 general want to do more than one read or write while holding the lock, there
30 are separate open and close functions. However, the calling modules should
31 arrange to hold the locks for the bare minimum of time. */
32
33
34
35 /*************************************************
36 *         Berkeley DB error callback             *
37 *************************************************/
38
39 /* For Berkeley DB >= 2, we can define a function to be called in case of DB
40 errors. This should help with debugging strange DB problems, e.g. getting "File
41 exists" when you try to open a db file. The API for this function was changed
42 at DB release 4.3. */
43
44 #if defined(USE_DB) && defined(DB_VERSION_STRING)
45 void
46 #if DB_VERSION_MAJOR > 4 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3)
47 dbfn_bdb_error_callback(const DB_ENV *dbenv, const char *pfx, const char *msg)
48 {
49 dbenv = dbenv;
50 #else
51 dbfn_bdb_error_callback(const char *pfx, char *msg)
52 {
53 #endif
54 pfx = pfx;
55 log_write(0, LOG_MAIN, "Berkeley DB error: %s", msg);
56 }
57 #endif
58
59
60
61
62 /*************************************************
63 *          Open and lock a database file         *
64 *************************************************/
65
66 /* Used for accessing Exim's hints databases.
67
68 Arguments:
69   name     The single-component name of one of Exim's database files.
70   flags    Either O_RDONLY or O_RDWR, indicating the type of open required;
71              O_RDWR implies "create if necessary"
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
76 Returns:   NULL if the open failed, or the locking failed. After locking
77            failures, errno is zero.
78
79            On success, dbblock is returned. This contains the dbm pointer and
80            the fd of the locked lock file.
81
82 There are some calls that use O_RDWR|O_CREAT for the flags. Having discovered
83 this in December 2005, I'm not sure if this is correct or not, but for the
84 moment I haven't changed them.
85 */
86
87 open_db *
88 dbfn_open(uschar *name, int flags, open_db *dbblock, BOOL lof)
89 {
90 int rc, save_errno;
91 BOOL read_only = flags == O_RDONLY;
92 BOOL created = FALSE;
93 flock_t lock_data;
94 uschar buffer[256];
95
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. */
108
109 sprintf(CS buffer, "%s/db/%s.lockfile", spool_directory, name);
110
111 if ((dbblock->lockfd = Uopen(buffer, O_RDWR, EXIMDB_LOCKFILE_MODE)) < 0)
112   {
113   created = TRUE;
114   (void)directory_make(spool_directory, US"db", EXIMDB_DIRECTORY_MODE, TRUE);
115   dbblock->lockfd = Uopen(buffer, O_RDWR|O_CREAT, EXIMDB_LOCKFILE_MODE);
116   }
117
118 if (dbblock->lockfd < 0)
119   {
120   log_write(0, LOG_MAIN, "%s",
121     string_open_failed(errno, "database lock file %s", buffer));
122   errno = 0;      /* Indicates locking failure */
123   return NULL;
124   }
125
126 /* Now we must get a lock on the opened lock file; do this with a blocking
127 lock that times out. */
128
129 lock_data.l_type = read_only? F_RDLCK : F_WRLCK;
130 lock_data.l_whence = lock_data.l_start = lock_data.l_len = 0;
131
132 DEBUG(D_hints_lookup|D_retry|D_route|D_deliver)
133   debug_printf("locking %s\n", buffer);
134
135 sigalrm_seen = FALSE;
136 alarm(EXIMDB_LOCK_TIMEOUT);
137 rc = fcntl(dbblock->lockfd, F_SETLKW, &lock_data);
138 alarm(0);
139
140 if (sigalrm_seen) errno = ETIMEDOUT;
141 if (rc < 0)
142   {
143   log_write(0, LOG_MAIN|LOG_PANIC, "Failed to get %s lock for %s: %s",
144     read_only? "read" : "write", buffer,
145     (errno == ETIMEDOUT)? "timed out" : strerror(errno));
146   (void)close(dbblock->lockfd);
147   errno = 0;       /* Indicates locking failure */
148   return NULL;
149   }
150
151 DEBUG(D_hints_lookup) debug_printf("locked %s\n", buffer);
152
153 /* At this point we have an opened and locked separate lock file, that is,
154 exclusive access to the database, so we can go ahead and open it. If we are
155 expected to create it, don't do so at first, again so that we can detect
156 whether we need to change its ownership (see comments about the lock file
157 above.) There have been regular reports of crashes while opening hints
158 databases - often this is caused by non-matching db.h and the library. To make
159 it easy to pin this down, there are now debug statements on either side of the
160 open call. */
161
162 sprintf(CS buffer, "%s/db/%s", spool_directory, name);
163 DEBUG(D_hints_lookup) debug_printf("EXIM_DBOPEN(%s)\n", buffer);
164 EXIM_DBOPEN(buffer, flags, EXIMDB_MODE, &(dbblock->dbptr));
165 DEBUG(D_hints_lookup) debug_printf("returned from EXIM_DBOPEN\n");
166
167 if (dbblock->dbptr == NULL && errno == ENOENT && flags == O_RDWR)
168   {
169   DEBUG(D_hints_lookup)
170     debug_printf("%s appears not to exist: trying to create\n", buffer);
171   created = TRUE;
172   EXIM_DBOPEN(buffer, flags|O_CREAT, EXIMDB_MODE, &(dbblock->dbptr));
173   DEBUG(D_hints_lookup) debug_printf("returned from EXIM_DBOPEN\n");
174   }
175
176 save_errno = errno;
177
178 /* If we are running as root and this is the first access to the database, its
179 files will be owned by root. We want them to be owned by exim. We detect this
180 situation by noting above when we had to create the lock file or the database
181 itself. Because the different dbm libraries use different extensions for their
182 files, I don't know of any easier way of arranging this than scanning the
183 directory for files with the appropriate base name. At least this deals with
184 the lock file at the same time. Also, the directory will typically have only
185 half a dozen files, so the scan will be quick.
186
187 This code is placed here, before the test for successful opening, because there
188 was a case when a file was created, but the DBM library still returned NULL
189 because of some problem. It also sorts out the lock file if that was created
190 but creation of the database file failed. */
191
192 if (created && geteuid() == root_uid)
193   {
194   DIR *dd;
195   struct dirent *ent;
196   uschar *lastname = Ustrrchr(buffer, '/') + 1;
197   int namelen = Ustrlen(name);
198
199   *lastname = 0;
200   dd = opendir(CS buffer);
201
202   while ((ent = readdir(dd)) != NULL)
203     {
204     if (Ustrncmp(ent->d_name, name, namelen) == 0)
205       {
206       struct stat statbuf;
207       Ustrcpy(lastname, ent->d_name);
208       if (Ustat(buffer, &statbuf) >= 0 && statbuf.st_uid != exim_uid)
209         {
210         DEBUG(D_hints_lookup) debug_printf("ensuring %s is owned by exim\n", buffer);
211         if (Uchown(buffer, exim_uid, exim_gid))
212           DEBUG(D_hints_lookup) debug_printf("failed setting %s to owned by exim\n", buffer);
213         }
214       }
215     }
216
217   closedir(dd);
218   }
219
220 /* If the open has failed, return NULL, leaving errno set. If lof is TRUE,
221 log the event - also for debugging - but not if the file just doesn't exist. */
222
223 if (dbblock->dbptr == NULL)
224   {
225   if (save_errno != ENOENT)
226     {
227     if (lof)
228       log_write(0, LOG_MAIN, "%s", string_open_failed(save_errno, "DB file %s",
229         buffer));
230     else
231       DEBUG(D_hints_lookup)
232         debug_printf("%s", CS string_open_failed(save_errno, "DB file %s\n",
233           buffer));
234     }
235   (void)close(dbblock->lockfd);
236   errno = save_errno;
237   return NULL;
238   }
239
240 DEBUG(D_hints_lookup)
241   debug_printf("opened hints database %s: flags=%s\n", buffer,
242     (flags == O_RDONLY)? "O_RDONLY" : (flags == O_RDWR)? "O_RDWR" :
243     (flags == (O_RDWR|O_CREAT))? "O_RDWR|O_CREAT" : "??");
244
245 /* Pass back the block containing the opened database handle and the open fd
246 for the lock. */
247
248 return dbblock;
249 }
250
251
252
253
254 /*************************************************
255 *         Unlock and close a database file       *
256 *************************************************/
257
258 /* Closing a file automatically unlocks it, so after closing the database, just
259 close the lock file.
260
261 Argument: a pointer to an open database block
262 Returns:  nothing
263 */
264
265 void
266 dbfn_close(open_db *dbblock)
267 {
268 EXIM_DBCLOSE(dbblock->dbptr);
269 (void)close(dbblock->lockfd);
270 }
271
272
273
274
275 /*************************************************
276 *             Read from database file            *
277 *************************************************/
278
279 /* Passing back the pointer unchanged is useless, because there is
280 no guarantee of alignment. Since all the records used by Exim need
281 to be properly aligned to pick out the timestamps, etc., we might as
282 well do the copying centrally here.
283
284 Most calls don't need the length, so there is a macro called dbfn_read which
285 has two arguments; it calls this function adding NULL as the third.
286
287 Arguments:
288   dbblock   a pointer to an open database block
289   key       the key of the record to be read
290   length    a pointer to an int into which to return the length, if not NULL
291
292 Returns: a pointer to the retrieved record, or
293          NULL if the record is not found
294 */
295
296 void *
297 dbfn_read_with_length(open_db *dbblock, uschar *key, int *length)
298 {
299 void *yield;
300 EXIM_DATUM key_datum, result_datum;
301
302 DEBUG(D_hints_lookup) debug_printf("dbfn_read: key=%s\n", key);
303
304 EXIM_DATUM_INIT(key_datum);         /* Some DBM libraries require the datum */
305 EXIM_DATUM_INIT(result_datum);      /* to be cleared before use. */
306 EXIM_DATUM_DATA(key_datum) = CS key;
307 EXIM_DATUM_SIZE(key_datum) = Ustrlen(key) + 1;
308
309 if (!EXIM_DBGET(dbblock->dbptr, key_datum, result_datum)) return NULL;
310
311 yield = store_get(EXIM_DATUM_SIZE(result_datum));
312 memcpy(yield, EXIM_DATUM_DATA(result_datum), EXIM_DATUM_SIZE(result_datum));
313 if (length != NULL) *length = EXIM_DATUM_SIZE(result_datum);
314
315 EXIM_DATUM_FREE(result_datum);    /* Some DBM libs require freeing */
316 return yield;
317 }
318
319
320
321 /*************************************************
322 *             Write to database file             *
323 *************************************************/
324
325 /*
326 Arguments:
327   dbblock   a pointer to an open database block
328   key       the key of the record to be written
329   ptr       a pointer to the record to be written
330   length    the length of the record to be written
331
332 Returns:    the yield of the underlying dbm or db "write" function. If this
333             is dbm, the value is zero for OK.
334 */
335
336 int
337 dbfn_write(open_db *dbblock, uschar *key, void *ptr, int length)
338 {
339 EXIM_DATUM key_datum, value_datum;
340 dbdata_generic *gptr = (dbdata_generic *)ptr;
341 gptr->time_stamp = time(NULL);
342
343 DEBUG(D_hints_lookup) debug_printf("dbfn_write: key=%s\n", key);
344
345 EXIM_DATUM_INIT(key_datum);         /* Some DBM libraries require the datum */
346 EXIM_DATUM_INIT(value_datum);       /* to be cleared before use. */
347 EXIM_DATUM_DATA(key_datum) = CS key;
348 EXIM_DATUM_SIZE(key_datum) = Ustrlen(key) + 1;
349 EXIM_DATUM_DATA(value_datum) = CS ptr;
350 EXIM_DATUM_SIZE(value_datum) = length;
351 return EXIM_DBPUT(dbblock->dbptr, key_datum, value_datum);
352 }
353
354
355
356 /*************************************************
357 *           Delete record from database file     *
358 *************************************************/
359
360 /*
361 Arguments:
362   dbblock    a pointer to an open database block
363   key        the key of the record to be deleted
364
365 Returns: the yield of the underlying dbm or db "delete" function.
366 */
367
368 int
369 dbfn_delete(open_db *dbblock, uschar *key)
370 {
371 EXIM_DATUM key_datum;
372 EXIM_DATUM_INIT(key_datum);         /* Some DBM libraries require clearing */
373 EXIM_DATUM_DATA(key_datum) = CS key;
374 EXIM_DATUM_SIZE(key_datum) = Ustrlen(key) + 1;
375 return EXIM_DBDEL(dbblock->dbptr, key_datum);
376 }
377
378
379
380 /*************************************************
381 *         Scan the keys of a database file       *
382 *************************************************/
383
384 /*
385 Arguments:
386   dbblock  a pointer to an open database block
387   start    TRUE if starting a new scan
388            FALSE if continuing with the current scan
389   cursor   a pointer to a pointer to a cursor anchor, for those dbm libraries
390            that use the notion of a cursor
391
392 Returns:   the next record from the file, or
393            NULL if there are no more
394 */
395
396 uschar *
397 dbfn_scan(open_db *dbblock, BOOL start, EXIM_CURSOR **cursor)
398 {
399 EXIM_DATUM key_datum, value_datum;
400 uschar *yield;
401 value_datum = value_datum;    /* dummy; not all db libraries use this */
402
403 /* Some dbm require an initialization */
404
405 if (start) EXIM_DBCREATE_CURSOR(dbblock->dbptr, cursor);
406
407 EXIM_DATUM_INIT(key_datum);         /* Some DBM libraries require the datum */
408 EXIM_DATUM_INIT(value_datum);       /* to be cleared before use. */
409
410 yield = (EXIM_DBSCAN(dbblock->dbptr, key_datum, value_datum, start, *cursor))?
411   US EXIM_DATUM_DATA(key_datum) : NULL;
412
413 /* Some dbm require a termination */
414
415 if (!yield) EXIM_DBDELETE_CURSOR(*cursor);
416 return yield;
417 }
418
419
420
421 /*************************************************
422 **************************************************
423 *             Stand-alone test program           *
424 **************************************************
425 *************************************************/
426
427 #ifdef STAND_ALONE
428
429 int
430 main(int argc, char **cargv)
431 {
432 open_db dbblock[8];
433 int max_db = sizeof(dbblock)/sizeof(open_db);
434 int current = -1;
435 int showtime = 0;
436 int i;
437 dbdata_wait *dbwait = NULL;
438 uschar **argv = USS cargv;
439 uschar buffer[256];
440 uschar structbuffer[1024];
441
442 if (argc != 2)
443   {
444   printf("Usage: test_dbfn directory\n");
445   printf("The subdirectory called \"db\" in the given directory is used for\n");
446   printf("the files used in this test program.\n");
447   return 1;
448   }
449
450 /* Initialize */
451
452 spool_directory = argv[1];
453 debug_selector = D_all - D_memory;
454 debug_file = stderr;
455 big_buffer = malloc(big_buffer_size);
456
457 for (i = 0; i < max_db; i++) dbblock[i].dbptr = NULL;
458
459 printf("\nExim's db functions tester: interface type is %s\n", EXIM_DBTYPE);
460 printf("DBM library: ");
461
462 #ifdef DB_VERSION_STRING
463 printf("Berkeley DB: %s\n", DB_VERSION_STRING);
464 #elif defined(BTREEVERSION) && defined(HASHVERSION)
465   #ifdef USE_DB
466   printf("probably Berkeley DB version 1.8x (native mode)\n");
467   #else
468   printf("probably Berkeley DB version 1.8x (compatibility mode)\n");
469   #endif
470 #elif defined(_DBM_RDONLY) || defined(dbm_dirfno)
471 printf("probably ndbm\n");
472 #elif defined(USE_TDB)
473 printf("using tdb\n");
474 #else
475   #ifdef USE_GDBM
476   printf("probably GDBM (native mode)\n");
477   #else
478   printf("probably GDBM (compatibility mode)\n");
479   #endif
480 #endif
481
482 /* Test the functions */
483
484 printf("\nTest the functions\n> ");
485
486 while (Ufgets(buffer, 256, stdin) != NULL)
487   {
488   int len = Ustrlen(buffer);
489   int count = 1;
490   clock_t start = 1;
491   clock_t stop = 0;
492   uschar *cmd = buffer;
493   while (len > 0 && isspace((uschar)buffer[len-1])) len--;
494   buffer[len] = 0;
495
496   if (isdigit((uschar)*cmd))
497     {
498     count = Uatoi(cmd);
499     while (isdigit((uschar)*cmd)) cmd++;
500     while (isspace((uschar)*cmd)) cmd++;
501     }
502
503   if (Ustrncmp(cmd, "open", 4) == 0)
504     {
505     int i;
506     open_db *odb;
507     uschar *s = cmd + 4;
508     while (isspace((uschar)*s)) s++;
509
510     for (i = 0; i < max_db; i++)
511       if (dbblock[i].dbptr == NULL) break;
512
513     if (i >= max_db)
514       {
515       printf("Too many open databases\n> ");
516       continue;
517       }
518
519     start = clock();
520     odb = dbfn_open(s, O_RDWR, dbblock + i, TRUE);
521     stop = clock();
522
523     if (odb != NULL)
524       {
525       current = i;
526       printf("opened %d\n", current);
527       }
528     /* Other error cases will have written messages */
529     else if (errno == ENOENT)
530       {
531       printf("open failed: %s%s\n", strerror(errno),
532         #ifdef USE_DB
533         " (or other Berkeley DB error)"
534         #else
535         ""
536         #endif
537         );
538       }
539     }
540
541   else if (Ustrncmp(cmd, "write", 5) == 0)
542     {
543     int rc = 0;
544     uschar *key = cmd + 5;
545     uschar *data;
546
547     if (current < 0)
548       {
549       printf("No current database\n");
550       continue;
551       }
552
553     while (isspace((uschar)*key)) key++;
554     data = key;
555     while (*data != 0 && !isspace((uschar)*data)) data++;
556     *data++ = 0;
557     while (isspace((uschar)*data)) data++;
558
559     dbwait = (dbdata_wait *)(&structbuffer);
560     Ustrcpy(dbwait->text, data);
561
562     start = clock();
563     while (count-- > 0)
564       rc = dbfn_write(dbblock + current, key, dbwait,
565         Ustrlen(data) + sizeof(dbdata_wait));
566     stop = clock();
567     if (rc != 0) printf("Failed: %s\n", strerror(errno));
568     }
569
570   else if (Ustrncmp(cmd, "read", 4) == 0)
571     {
572     uschar *key = cmd + 4;
573     if (current < 0)
574       {
575       printf("No current database\n");
576       continue;
577       }
578     while (isspace((uschar)*key)) key++;
579     start = clock();
580     while (count-- > 0)
581       dbwait = (dbdata_wait *)dbfn_read_with_length(dbblock+ current, key, NULL);
582     stop = clock();
583     printf("%s\n", (dbwait == NULL)? "<not found>" : CS dbwait->text);
584     }
585
586   else if (Ustrncmp(cmd, "delete", 6) == 0)
587     {
588     uschar *key = cmd + 6;
589     if (current < 0)
590       {
591       printf("No current database\n");
592       continue;
593       }
594     while (isspace((uschar)*key)) key++;
595     dbfn_delete(dbblock + current, key);
596     }
597
598   else if (Ustrncmp(cmd, "scan", 4) == 0)
599     {
600     EXIM_CURSOR *cursor;
601     BOOL startflag = TRUE;
602     uschar *key;
603     uschar keybuffer[256];
604     if (current < 0)
605       {
606       printf("No current database\n");
607       continue;
608       }
609     start = clock();
610     while ((key = dbfn_scan(dbblock + current, startflag, &cursor)) != NULL)
611       {
612       startflag = FALSE;
613       Ustrcpy(keybuffer, key);
614       dbwait = (dbdata_wait *)dbfn_read_with_length(dbblock + current,
615         keybuffer, NULL);
616       printf("%s: %s\n", keybuffer, dbwait->text);
617       }
618     stop = clock();
619     printf("End of scan\n");
620     }
621
622   else if (Ustrncmp(cmd, "close", 5) == 0)
623     {
624     uschar *s = cmd + 5;
625     while (isspace((uschar)*s)) s++;
626     i = Uatoi(s);
627     if (i >= max_db || dbblock[i].dbptr == NULL) printf("Not open\n"); else
628       {
629       start = clock();
630       dbfn_close(dbblock + i);
631       stop = clock();
632       dbblock[i].dbptr = NULL;
633       if (i == current) current = -1;
634       }
635     }
636
637   else if (Ustrncmp(cmd, "file", 4) == 0)
638     {
639     uschar *s = cmd + 4;
640     while (isspace((uschar)*s)) s++;
641     i = Uatoi(s);
642     if (i >= max_db || dbblock[i].dbptr == NULL) printf("Not open\n");
643       else current = i;
644     }
645
646   else if (Ustrncmp(cmd, "time", 4) == 0)
647     {
648     showtime = ~showtime;
649     printf("Timing %s\n", showtime? "on" : "off");
650     }
651
652   else if (Ustrcmp(cmd, "q") == 0 || Ustrncmp(cmd, "quit", 4) == 0) break;
653
654   else if (Ustrncmp(cmd, "help", 4) == 0)
655     {
656     printf("close  [<number>]              close file [<number>]\n");
657     printf("delete <key>                   remove record from current file\n");
658     printf("file   <number>                make file <number> current\n");
659     printf("open   <name>                  open db file\n");
660     printf("q[uit]                         exit program\n");
661     printf("read   <key>                   read record from current file\n");
662     printf("scan                           scan current file\n");
663     printf("time                           time display on/off\n");
664     printf("write  <key> <rest-of-line>    write record to current file\n");
665     }
666
667   else printf("Eh?\n");
668
669   if (showtime && stop >= start)
670     printf("start=%d stop=%d difference=%d\n", (int)start, (int)stop,
671      (int)(stop - start));
672
673   printf("> ");
674   }
675
676 for (i = 0; i < max_db; i++)
677   {
678   if (dbblock[i].dbptr != NULL)
679     {
680     printf("\nClosing %d", i);
681     dbfn_close(dbblock + i);
682     }
683   }
684
685 printf("\n");
686 return 0;
687 }
688
689 #endif
690
691 /* End of dbfn.c */