lib/tdb: fix c++ build warning in tdb_header_hash().
[metze/ctdb/wip.git] / lib / tdb / common / open.c
1  /* 
2    Unix SMB/CIFS implementation.
3
4    trivial database library
5
6    Copyright (C) Andrew Tridgell              1999-2005
7    Copyright (C) Paul `Rusty' Russell              2000
8    Copyright (C) Jeremy Allison                    2000-2003
9
10      ** NOTE! The following LGPL license applies to the tdb
11      ** library. This does NOT imply that all of Samba is released
12      ** under the LGPL
13
14    This library is free software; you can redistribute it and/or
15    modify it under the terms of the GNU Lesser General Public
16    License as published by the Free Software Foundation; either
17    version 3 of the License, or (at your option) any later version.
18
19    This library is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22    Lesser General Public License for more details.
23
24    You should have received a copy of the GNU Lesser General Public
25    License along with this library; if not, see <http://www.gnu.org/licenses/>.
26 */
27
28 #include "tdb_private.h"
29
30 /* all contexts, to ensure no double-opens (fcntl locks don't nest!) */
31 static struct tdb_context *tdbs = NULL;
32
33
34 /* This is based on the hash algorithm from gdbm */
35 static unsigned int default_tdb_hash(TDB_DATA *key)
36 {
37         uint32_t value; /* Used to compute the hash value.  */
38         uint32_t   i;   /* Used to cycle through random values. */
39
40         /* Set the initial value from the key size. */
41         for (value = 0x238F13AF * key->dsize, i=0; i < key->dsize; i++)
42                 value = (value + (key->dptr[i] << (i*5 % 24)));
43
44         return (1103515243 * value + 12345);  
45 }
46
47 /* We use two hashes to double-check they're using the right hash function. */
48 void tdb_header_hash(struct tdb_context *tdb,
49                      uint32_t *magic1_hash, uint32_t *magic2_hash)
50 {
51         TDB_DATA hash_key;
52         uint32_t tdb_magic = TDB_MAGIC;
53
54         hash_key.dptr = (unsigned char *)TDB_MAGIC_FOOD;
55         hash_key.dsize = sizeof(TDB_MAGIC_FOOD);
56         *magic1_hash = tdb->hash_fn(&hash_key);
57
58         hash_key.dptr = (unsigned char *)CONVERT(tdb_magic);
59         hash_key.dsize = sizeof(tdb_magic);
60         *magic2_hash = tdb->hash_fn(&hash_key);
61
62         /* Make sure at least one hash is non-zero! */
63         if (*magic1_hash == 0 && *magic2_hash == 0)
64                 *magic1_hash = 1;
65 }
66
67 /* initialise a new database with a specified hash size */
68 static int tdb_new_database(struct tdb_context *tdb, int hash_size)
69 {
70         struct tdb_header *newdb;
71         size_t size;
72         int ret = -1;
73
74         /* We make it up in memory, then write it out if not internal */
75         size = sizeof(struct tdb_header) + (hash_size+1)*sizeof(tdb_off_t);
76         if (!(newdb = (struct tdb_header *)calloc(size, 1))) {
77                 tdb->ecode = TDB_ERR_OOM;
78                 return -1;
79         }
80
81         /* Fill in the header */
82         newdb->version = TDB_VERSION;
83         newdb->hash_size = hash_size;
84
85         tdb_header_hash(tdb, &newdb->magic1_hash, &newdb->magic2_hash);
86
87         if (tdb->flags & TDB_INTERNAL) {
88                 tdb->map_size = size;
89                 tdb->map_ptr = (char *)newdb;
90                 memcpy(&tdb->header, newdb, sizeof(tdb->header));
91                 /* Convert the `ondisk' version if asked. */
92                 CONVERT(*newdb);
93                 return 0;
94         }
95         if (lseek(tdb->fd, 0, SEEK_SET) == -1)
96                 goto fail;
97
98         if (ftruncate(tdb->fd, 0) == -1)
99                 goto fail;
100
101         /* This creates an endian-converted header, as if read from disk */
102         CONVERT(*newdb);
103         memcpy(&tdb->header, newdb, sizeof(tdb->header));
104         /* Don't endian-convert the magic food! */
105         memcpy(newdb->magic_food, TDB_MAGIC_FOOD, strlen(TDB_MAGIC_FOOD)+1);
106         /* we still have "ret == -1" here */
107         if (tdb_write_all(tdb->fd, newdb, size))
108                 ret = 0;
109
110   fail:
111         SAFE_FREE(newdb);
112         return ret;
113 }
114
115
116
117 static int tdb_already_open(dev_t device,
118                             ino_t ino)
119 {
120         struct tdb_context *i;
121
122         for (i = tdbs; i; i = i->next) {
123                 if (i->device == device && i->inode == ino) {
124                         return 1;
125                 }
126         }
127
128         return 0;
129 }
130
131 /* open the database, creating it if necessary 
132
133    The open_flags and mode are passed straight to the open call on the
134    database file. A flags value of O_WRONLY is invalid. The hash size
135    is advisory, use zero for a default value.
136
137    Return is NULL on error, in which case errno is also set.  Don't 
138    try to call tdb_error or tdb_errname, just do strerror(errno).
139
140    @param name may be NULL for internal databases. */
141 struct tdb_context *tdb_open(const char *name, int hash_size, int tdb_flags,
142                       int open_flags, mode_t mode)
143 {
144         return tdb_open_ex(name, hash_size, tdb_flags, open_flags, mode, NULL, NULL);
145 }
146
147 /* a default logging function */
148 static void null_log_fn(struct tdb_context *tdb, enum tdb_debug_level level, const char *fmt, ...) PRINTF_ATTRIBUTE(3, 4);
149 static void null_log_fn(struct tdb_context *tdb, enum tdb_debug_level level, const char *fmt, ...)
150 {
151 }
152
153
154 struct tdb_context *tdb_open_ex(const char *name, int hash_size, int tdb_flags,
155                                 int open_flags, mode_t mode,
156                                 const struct tdb_logging_context *log_ctx,
157                                 tdb_hash_func hash_fn)
158 {
159         struct tdb_context *tdb;
160         struct stat st;
161         int rev = 0, locked = 0;
162         unsigned char *vp;
163         uint32_t vertest;
164         unsigned v;
165         uint32_t magic1_hash;
166         uint32_t magic2_hash;
167         const char *hash_alg;
168
169         if (!(tdb = (struct tdb_context *)calloc(1, sizeof *tdb))) {
170                 /* Can't log this */
171                 errno = ENOMEM;
172                 goto fail;
173         }
174         tdb_io_init(tdb);
175         tdb->fd = -1;
176 #ifdef TDB_TRACE
177         tdb->tracefd = -1;
178 #endif
179         tdb->name = NULL;
180         tdb->map_ptr = NULL;
181         tdb->flags = tdb_flags;
182         tdb->open_flags = open_flags;
183         if (log_ctx) {
184                 tdb->log = *log_ctx;
185         } else {
186                 tdb->log.log_fn = null_log_fn;
187                 tdb->log.log_private = NULL;
188         }
189
190         if (hash_fn) {
191                 tdb->hash_fn = hash_fn;
192                 hash_alg = "user defined";
193         } else {
194                 tdb->hash_fn = default_tdb_hash;
195                 hash_alg = "default";
196         }
197
198         /* cache the page size */
199         tdb->page_size = getpagesize();
200         if (tdb->page_size <= 0) {
201                 tdb->page_size = 0x2000;
202         }
203
204         tdb->max_dead_records = (tdb_flags & TDB_VOLATILE) ? 5 : 0;
205
206         if ((open_flags & O_ACCMODE) == O_WRONLY) {
207                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: can't open tdb %s write-only\n",
208                          name));
209                 errno = EINVAL;
210                 goto fail;
211         }
212
213         if (hash_size == 0)
214                 hash_size = DEFAULT_HASH_SIZE;
215         if ((open_flags & O_ACCMODE) == O_RDONLY) {
216                 tdb->read_only = 1;
217                 /* read only databases don't do locking or clear if first */
218                 tdb->flags |= TDB_NOLOCK;
219                 tdb->flags &= ~TDB_CLEAR_IF_FIRST;
220         }
221
222         if ((tdb->flags & TDB_ALLOW_NESTING) &&
223             (tdb->flags & TDB_DISALLOW_NESTING)) {
224                 tdb->ecode = TDB_ERR_NESTING;
225                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
226                         "allow_nesting and disallow_nesting are not allowed together!"));
227                 errno = EINVAL;
228                 goto fail;
229         }
230
231         if (getenv("TDB_NO_FSYNC")) {
232                 tdb->flags |= TDB_NOSYNC;
233         }
234
235         /*
236          * TDB_ALLOW_NESTING is the default behavior.
237          * Note: this may change in future versions!
238          */
239         if (!(tdb->flags & TDB_DISALLOW_NESTING)) {
240                 tdb->flags |= TDB_ALLOW_NESTING;
241         }
242
243         /* internal databases don't mmap or lock, and start off cleared */
244         if (tdb->flags & TDB_INTERNAL) {
245                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
246                 tdb->flags &= ~TDB_CLEAR_IF_FIRST;
247                 if (tdb_new_database(tdb, hash_size) != 0) {
248                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: tdb_new_database failed!"));
249                         goto fail;
250                 }
251                 goto internal;
252         }
253
254         if ((tdb->fd = open(name, open_flags, mode)) == -1) {
255                 TDB_LOG((tdb, TDB_DEBUG_WARNING, "tdb_open_ex: could not open file %s: %s\n",
256                          name, strerror(errno)));
257                 goto fail;      /* errno set by open(2) */
258         }
259
260         /* on exec, don't inherit the fd */
261         v = fcntl(tdb->fd, F_GETFD, 0);
262         fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
263
264         /* ensure there is only one process initialising at once */
265         if (tdb_nest_lock(tdb, OPEN_LOCK, F_WRLCK, TDB_LOCK_WAIT) == -1) {
266                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: failed to get open lock on %s: %s\n",
267                          name, strerror(errno)));
268                 goto fail;      /* errno set by tdb_brlock */
269         }
270
271         /* we need to zero database if we are the only one with it open */
272         if ((tdb_flags & TDB_CLEAR_IF_FIRST) &&
273             (!tdb->read_only) &&
274             (locked = (tdb_nest_lock(tdb, ACTIVE_LOCK, F_WRLCK, TDB_LOCK_NOWAIT|TDB_LOCK_PROBE) == 0))) {
275                 open_flags |= O_CREAT;
276                 if (ftruncate(tdb->fd, 0) == -1) {
277                         TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
278                                  "failed to truncate %s: %s\n",
279                                  name, strerror(errno)));
280                         goto fail; /* errno set by ftruncate */
281                 }
282         }
283
284         errno = 0;
285         if (read(tdb->fd, &tdb->header, sizeof(tdb->header)) != sizeof(tdb->header)
286             || strcmp(tdb->header.magic_food, TDB_MAGIC_FOOD) != 0) {
287                 if (!(open_flags & O_CREAT) || tdb_new_database(tdb, hash_size) == -1) {
288                         if (errno == 0) {
289                                 errno = EIO; /* ie bad format or something */
290                         }
291                         goto fail;
292                 }
293                 rev = (tdb->flags & TDB_CONVERT);
294         } else if (tdb->header.version != TDB_VERSION
295                    && !(rev = (tdb->header.version==TDB_BYTEREV(TDB_VERSION)))) {
296                 /* wrong version */
297                 errno = EIO;
298                 goto fail;
299         }
300         vp = (unsigned char *)&tdb->header.version;
301         vertest = (((uint32_t)vp[0]) << 24) | (((uint32_t)vp[1]) << 16) |
302                   (((uint32_t)vp[2]) << 8) | (uint32_t)vp[3];
303         tdb->flags |= (vertest==TDB_VERSION) ? TDB_BIGENDIAN : 0;
304         if (!rev)
305                 tdb->flags &= ~TDB_CONVERT;
306         else {
307                 tdb->flags |= TDB_CONVERT;
308                 tdb_convert(&tdb->header, sizeof(tdb->header));
309         }
310         if (fstat(tdb->fd, &st) == -1)
311                 goto fail;
312
313         if (tdb->header.rwlocks != 0) {
314                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: spinlocks no longer supported\n"));
315                 goto fail;
316         }
317
318         tdb_header_hash(tdb, &magic1_hash, &magic2_hash);
319
320         if ((tdb->header.magic1_hash == 0) && (tdb->header.magic2_hash == 0)) {
321                 /* older TDB without magic hash references */
322         } else if ((tdb->header.magic1_hash != magic1_hash) ||
323                    (tdb->header.magic2_hash != magic2_hash)) {
324                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
325                          "%s was not created with the %s hash function we are using\n"
326                          "magic1_hash[0x%08X %s 0x%08X] "
327                          "magic2_hash[0x%08X %s 0x%08X]\n",
328                          name, hash_alg,
329                          tdb->header.magic1_hash,
330                          (tdb->header.magic1_hash == magic1_hash) ? "==" : "!=",
331                          magic1_hash,
332                          tdb->header.magic2_hash,
333                          (tdb->header.magic2_hash == magic2_hash) ? "==" : "!=",
334                          magic2_hash));
335                 errno = EINVAL;
336                 goto fail;
337         }
338
339         /* Is it already in the open list?  If so, fail. */
340         if (tdb_already_open(st.st_dev, st.st_ino)) {
341                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
342                          "%s (%d,%d) is already open in this process\n",
343                          name, (int)st.st_dev, (int)st.st_ino));
344                 errno = EBUSY;
345                 goto fail;
346         }
347
348         if (!(tdb->name = (char *)strdup(name))) {
349                 errno = ENOMEM;
350                 goto fail;
351         }
352
353         tdb->map_size = st.st_size;
354         tdb->device = st.st_dev;
355         tdb->inode = st.st_ino;
356         tdb_mmap(tdb);
357         if (locked) {
358                 if (tdb_nest_unlock(tdb, ACTIVE_LOCK, F_WRLCK, false) == -1) {
359                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
360                                  "failed to release ACTIVE_LOCK on %s: %s\n",
361                                  name, strerror(errno)));
362                         goto fail;
363                 }
364
365         }
366
367         /* We always need to do this if the CLEAR_IF_FIRST flag is set, even if
368            we didn't get the initial exclusive lock as we need to let all other
369            users know we're using it. */
370
371         if (tdb_flags & TDB_CLEAR_IF_FIRST) {
372                 /* leave this lock in place to indicate it's in use */
373                 if (tdb_nest_lock(tdb, ACTIVE_LOCK, F_RDLCK, TDB_LOCK_WAIT) == -1) {
374                         goto fail;
375                 }
376         }
377
378         /* if needed, run recovery */
379         if (tdb_transaction_recover(tdb) == -1) {
380                 goto fail;
381         }
382
383 #ifdef TDB_TRACE
384         {
385                 char tracefile[strlen(name) + 32];
386
387                 snprintf(tracefile, sizeof(tracefile),
388                          "%s.trace.%li", name, (long)getpid());
389                 tdb->tracefd = open(tracefile, O_WRONLY|O_CREAT|O_EXCL, 0600);
390                 if (tdb->tracefd >= 0) {
391                         tdb_enable_seqnum(tdb);
392                         tdb_trace_open(tdb, "tdb_open", hash_size, tdb_flags,
393                                        open_flags);
394                 } else
395                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: failed to open trace file %s!\n", tracefile));
396         }
397 #endif
398
399  internal:
400         /* Internal (memory-only) databases skip all the code above to
401          * do with disk files, and resume here by releasing their
402          * open lock and hooking into the active list. */
403         if (tdb_nest_unlock(tdb, OPEN_LOCK, F_WRLCK, false) == -1) {
404                 goto fail;
405         }
406         tdb->next = tdbs;
407         tdbs = tdb;
408         return tdb;
409
410  fail:
411         { int save_errno = errno;
412
413         if (!tdb)
414                 return NULL;
415
416 #ifdef TDB_TRACE
417         close(tdb->tracefd);
418 #endif
419         if (tdb->map_ptr) {
420                 if (tdb->flags & TDB_INTERNAL)
421                         SAFE_FREE(tdb->map_ptr);
422                 else
423                         tdb_munmap(tdb);
424         }
425         SAFE_FREE(tdb->name);
426         if (tdb->fd != -1)
427                 if (close(tdb->fd) != 0)
428                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: failed to close tdb->fd on error!\n"));
429         SAFE_FREE(tdb->lockrecs);
430         SAFE_FREE(tdb);
431         errno = save_errno;
432         return NULL;
433         }
434 }
435
436 /*
437  * Set the maximum number of dead records per hash chain
438  */
439
440 void tdb_set_max_dead(struct tdb_context *tdb, int max_dead)
441 {
442         tdb->max_dead_records = max_dead;
443 }
444
445 /**
446  * Close a database.
447  *
448  * @returns -1 for error; 0 for success.
449  **/
450 int tdb_close(struct tdb_context *tdb)
451 {
452         struct tdb_context **i;
453         int ret = 0;
454
455         if (tdb->transaction) {
456                 tdb_transaction_cancel(tdb);
457         }
458         tdb_trace(tdb, "tdb_close");
459
460         if (tdb->map_ptr) {
461                 if (tdb->flags & TDB_INTERNAL)
462                         SAFE_FREE(tdb->map_ptr);
463                 else
464                         tdb_munmap(tdb);
465         }
466         SAFE_FREE(tdb->name);
467         if (tdb->fd != -1) {
468                 ret = close(tdb->fd);
469                 tdb->fd = -1;
470         }
471         SAFE_FREE(tdb->lockrecs);
472
473         /* Remove from contexts list */
474         for (i = &tdbs; *i; i = &(*i)->next) {
475                 if (*i == tdb) {
476                         *i = tdb->next;
477                         break;
478                 }
479         }
480
481 #ifdef TDB_TRACE
482         close(tdb->tracefd);
483 #endif
484         memset(tdb, 0, sizeof(*tdb));
485         SAFE_FREE(tdb);
486
487         return ret;
488 }
489
490 /* register a loging function */
491 void tdb_set_logging_function(struct tdb_context *tdb,
492                               const struct tdb_logging_context *log_ctx)
493 {
494         tdb->log = *log_ctx;
495 }
496
497 void *tdb_get_logging_private(struct tdb_context *tdb)
498 {
499         return tdb->log.log_private;
500 }
501
502 static int tdb_reopen_internal(struct tdb_context *tdb, bool active_lock)
503 {
504 #if !defined(LIBREPLACE_PREAD_NOT_REPLACED) || \
505         !defined(LIBREPLACE_PWRITE_NOT_REPLACED)
506         struct stat st;
507 #endif
508
509         if (tdb->flags & TDB_INTERNAL) {
510                 return 0; /* Nothing to do. */
511         }
512
513         if (tdb_have_extra_locks(tdb)) {
514                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_reopen: reopen not allowed with locks held\n"));
515                 goto fail;
516         }
517
518         if (tdb->transaction != 0) {
519                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_reopen: reopen not allowed inside a transaction\n"));
520                 goto fail;
521         }
522
523 /* If we have real pread & pwrite, we can skip reopen. */
524 #if !defined(LIBREPLACE_PREAD_NOT_REPLACED) || \
525         !defined(LIBREPLACE_PWRITE_NOT_REPLACED)
526         if (tdb_munmap(tdb) != 0) {
527                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: munmap failed (%s)\n", strerror(errno)));
528                 goto fail;
529         }
530         if (close(tdb->fd) != 0)
531                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: WARNING closing tdb->fd failed!\n"));
532         tdb->fd = open(tdb->name, tdb->open_flags & ~(O_CREAT|O_TRUNC), 0);
533         if (tdb->fd == -1) {
534                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: open failed (%s)\n", strerror(errno)));
535                 goto fail;
536         }
537         if (fstat(tdb->fd, &st) != 0) {
538                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: fstat failed (%s)\n", strerror(errno)));
539                 goto fail;
540         }
541         if (st.st_ino != tdb->inode || st.st_dev != tdb->device) {
542                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: file dev/inode has changed!\n"));
543                 goto fail;
544         }
545         tdb_mmap(tdb);
546 #endif /* fake pread or pwrite */
547
548         /* We may still think we hold the active lock. */
549         tdb->num_lockrecs = 0;
550         SAFE_FREE(tdb->lockrecs);
551
552         if (active_lock && tdb_nest_lock(tdb, ACTIVE_LOCK, F_RDLCK, TDB_LOCK_WAIT) == -1) {
553                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: failed to obtain active lock\n"));
554                 goto fail;
555         }
556
557         return 0;
558
559 fail:
560         tdb_close(tdb);
561         return -1;
562 }
563
564 /* reopen a tdb - this can be used after a fork to ensure that we have an independent
565    seek pointer from our parent and to re-establish locks */
566 int tdb_reopen(struct tdb_context *tdb)
567 {
568         return tdb_reopen_internal(tdb, tdb->flags & TDB_CLEAR_IF_FIRST);
569 }
570
571 /* reopen all tdb's */
572 int tdb_reopen_all(int parent_longlived)
573 {
574         struct tdb_context *tdb;
575
576         for (tdb=tdbs; tdb; tdb = tdb->next) {
577                 bool active_lock = (tdb->flags & TDB_CLEAR_IF_FIRST);
578
579                 /*
580                  * If the parent is longlived (ie. a
581                  * parent daemon architecture), we know
582                  * it will keep it's active lock on a
583                  * tdb opened with CLEAR_IF_FIRST. Thus
584                  * for child processes we don't have to
585                  * add an active lock. This is essential
586                  * to improve performance on systems that
587                  * keep POSIX locks as a non-scalable data
588                  * structure in the kernel.
589                  */
590                 if (parent_longlived) {
591                         /* Ensure no clear-if-first. */
592                         active_lock = false;
593                 }
594
595                 if (tdb_reopen_internal(tdb, active_lock) != 0)
596                         return -1;
597         }
598
599         return 0;
600 }