9eaa701b7d6ade35c7d0dd289c8847a6f9507ee6
[obnox/samba-ctdb.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 = 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         ssize_t written;
74
75         /* We make it up in memory, then write it out if not internal */
76         size = sizeof(struct tdb_header) + (hash_size+1)*sizeof(tdb_off_t);
77         if (!(newdb = (struct tdb_header *)calloc(size, 1)))
78                 return TDB_ERRCODE(TDB_ERR_OOM, -1);
79
80         /* Fill in the header */
81         newdb->version = TDB_VERSION;
82         newdb->hash_size = hash_size;
83
84         tdb_header_hash(tdb, &newdb->magic1_hash, &newdb->magic2_hash);
85
86         if (tdb->flags & TDB_INTERNAL) {
87                 tdb->map_size = size;
88                 tdb->map_ptr = (char *)newdb;
89                 memcpy(&tdb->header, newdb, sizeof(tdb->header));
90                 /* Convert the `ondisk' version if asked. */
91                 CONVERT(*newdb);
92                 return 0;
93         }
94         if (lseek(tdb->fd, 0, SEEK_SET) == -1)
95                 goto fail;
96
97         if (ftruncate(tdb->fd, 0) == -1)
98                 goto fail;
99
100         /* This creates an endian-converted header, as if read from disk */
101         CONVERT(*newdb);
102         memcpy(&tdb->header, newdb, sizeof(tdb->header));
103         /* Don't endian-convert the magic food! */
104         memcpy(newdb->magic_food, TDB_MAGIC_FOOD, strlen(TDB_MAGIC_FOOD)+1);
105         /* we still have "ret == -1" here */
106         written = write(tdb->fd, newdb, size);
107         if (written == size) {
108                 ret = 0;
109         } else if (written != -1) {
110                 /* call write once again, this usually should return -1 and
111                  * set errno appropriately */
112                 size -= written;
113                 written = write(tdb->fd, newdb+written, size);
114                 if (written == size) {
115                 ret = 0;
116                 } else if (written >= 0) {
117                         /* a second incomplete write - we give up.
118                          * guessing the errno... */
119                         errno = ENOSPC;
120                 }
121         }
122
123   fail:
124         SAFE_FREE(newdb);
125         return ret;
126 }
127
128
129
130 static int tdb_already_open(dev_t device,
131                             ino_t ino)
132 {
133         struct tdb_context *i;
134         
135         for (i = tdbs; i; i = i->next) {
136                 if (i->device == device && i->inode == ino) {
137                         return 1;
138                 }
139         }
140
141         return 0;
142 }
143
144 /* open the database, creating it if necessary 
145
146    The open_flags and mode are passed straight to the open call on the
147    database file. A flags value of O_WRONLY is invalid. The hash size
148    is advisory, use zero for a default value.
149
150    Return is NULL on error, in which case errno is also set.  Don't 
151    try to call tdb_error or tdb_errname, just do strerror(errno).
152
153    @param name may be NULL for internal databases. */
154 struct tdb_context *tdb_open(const char *name, int hash_size, int tdb_flags,
155                       int open_flags, mode_t mode)
156 {
157         return tdb_open_ex(name, hash_size, tdb_flags, open_flags, mode, NULL, NULL);
158 }
159
160 /* a default logging function */
161 static void null_log_fn(struct tdb_context *tdb, enum tdb_debug_level level, const char *fmt, ...) PRINTF_ATTRIBUTE(3, 4);
162 static void null_log_fn(struct tdb_context *tdb, enum tdb_debug_level level, const char *fmt, ...)
163 {
164 }
165
166
167 struct tdb_context *tdb_open_ex(const char *name, int hash_size, int tdb_flags,
168                                 int open_flags, mode_t mode,
169                                 const struct tdb_logging_context *log_ctx,
170                                 tdb_hash_func hash_fn)
171 {
172         struct tdb_context *tdb;
173         struct stat st;
174         int rev = 0, locked = 0;
175         unsigned char *vp;
176         uint32_t vertest;
177         unsigned v;
178         uint32_t magic1_hash;
179         uint32_t magic2_hash;
180         const char *hash_alg;
181
182         if (!(tdb = (struct tdb_context *)calloc(1, sizeof *tdb))) {
183                 /* Can't log this */
184                 errno = ENOMEM;
185                 goto fail;
186         }
187         tdb_io_init(tdb);
188         tdb->fd = -1;
189         tdb->name = NULL;
190         tdb->map_ptr = NULL;
191         tdb->flags = tdb_flags;
192         tdb->open_flags = open_flags;
193         if (log_ctx) {
194                 tdb->log = *log_ctx;
195         } else {
196                 tdb->log.log_fn = null_log_fn;
197                 tdb->log.log_private = NULL;
198         }
199
200         if (hash_fn) {
201                 tdb->hash_fn = hash_fn;
202                 hash_alg = "user defined";
203         } else {
204                 tdb->hash_fn = default_tdb_hash;
205                 hash_alg = "default";
206         }
207
208         /* cache the page size */
209         tdb->page_size = getpagesize();
210         if (tdb->page_size <= 0) {
211                 tdb->page_size = 0x2000;
212         }
213
214         tdb->max_dead_records = (tdb_flags & TDB_VOLATILE) ? 5 : 0;
215
216         if ((open_flags & O_ACCMODE) == O_WRONLY) {
217                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: can't open tdb %s write-only\n",
218                          name));
219                 errno = EINVAL;
220                 goto fail;
221         }
222         
223         if (hash_size == 0)
224                 hash_size = DEFAULT_HASH_SIZE;
225         if ((open_flags & O_ACCMODE) == O_RDONLY) {
226                 tdb->read_only = 1;
227                 /* read only databases don't do locking or clear if first */
228                 tdb->flags |= TDB_NOLOCK;
229                 tdb->flags &= ~TDB_CLEAR_IF_FIRST;
230         }
231
232         /* internal databases don't mmap or lock, and start off cleared */
233         if (tdb->flags & TDB_INTERNAL) {
234                 tdb->flags |= (TDB_NOLOCK | TDB_NOMMAP);
235                 tdb->flags &= ~TDB_CLEAR_IF_FIRST;
236                 if (tdb_new_database(tdb, hash_size) != 0) {
237                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: tdb_new_database failed!"));
238                         goto fail;
239                 }
240                 goto internal;
241         }
242
243         if ((tdb->fd = open(name, open_flags, mode)) == -1) {
244                 TDB_LOG((tdb, TDB_DEBUG_WARNING, "tdb_open_ex: could not open file %s: %s\n",
245                          name, strerror(errno)));
246                 goto fail;      /* errno set by open(2) */
247         }
248
249         /* on exec, don't inherit the fd */
250         v = fcntl(tdb->fd, F_GETFD, 0);
251         fcntl(tdb->fd, F_SETFD, v | FD_CLOEXEC);
252
253         /* ensure there is only one process initialising at once */
254         if (tdb->methods->tdb_brlock(tdb, GLOBAL_LOCK, F_WRLCK, F_SETLKW, 0, 1) == -1) {
255                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: failed to get global lock on %s: %s\n",
256                          name, strerror(errno)));
257                 goto fail;      /* errno set by tdb_brlock */
258         }
259
260         /* we need to zero database if we are the only one with it open */
261         if ((tdb_flags & TDB_CLEAR_IF_FIRST) &&
262             (!tdb->read_only) &&
263             (locked = (tdb->methods->tdb_brlock(tdb, ACTIVE_LOCK, F_WRLCK, F_SETLK, 0, 1) == 0))) {
264                 open_flags |= O_CREAT;
265                 if (ftruncate(tdb->fd, 0) == -1) {
266                         TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
267                                  "failed to truncate %s: %s\n",
268                                  name, strerror(errno)));
269                         goto fail; /* errno set by ftruncate */
270                 }
271         }
272
273         errno = 0;
274         if (read(tdb->fd, &tdb->header, sizeof(tdb->header)) != sizeof(tdb->header)
275             || strcmp(tdb->header.magic_food, TDB_MAGIC_FOOD) != 0
276             || (tdb->header.version != TDB_VERSION
277                 && !(rev = (tdb->header.version==TDB_BYTEREV(TDB_VERSION))))) {
278                 /* its not a valid database - possibly initialise it */
279                 if (!(open_flags & O_CREAT) || tdb_new_database(tdb, hash_size) == -1) {
280                         if (errno == 0) {
281                         errno = EIO; /* ie bad format or something */
282                         }
283                         goto fail;
284                 }
285                 rev = (tdb->flags & TDB_CONVERT);
286         }
287         vp = (unsigned char *)&tdb->header.version;
288         vertest = (((uint32_t)vp[0]) << 24) | (((uint32_t)vp[1]) << 16) |
289                   (((uint32_t)vp[2]) << 8) | (uint32_t)vp[3];
290         tdb->flags |= (vertest==TDB_VERSION) ? TDB_BIGENDIAN : 0;
291         if (!rev)
292                 tdb->flags &= ~TDB_CONVERT;
293         else {
294                 tdb->flags |= TDB_CONVERT;
295                 tdb_convert(&tdb->header, sizeof(tdb->header));
296         }
297         if (fstat(tdb->fd, &st) == -1)
298                 goto fail;
299
300         if (tdb->header.rwlocks != 0) {
301                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: spinlocks no longer supported\n"));
302                 goto fail;
303         }
304
305         tdb_header_hash(tdb, &magic1_hash, &magic2_hash);
306
307         if ((tdb->header.magic1_hash == 0) && (tdb->header.magic2_hash == 0)) {
308                 /* older TDB without magic hash references */
309         } else if ((tdb->header.magic1_hash != magic1_hash) ||
310                    (tdb->header.magic2_hash != magic2_hash)) {
311                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_open_ex: "
312                          "%s was not created with the %s hash function we are using\n"
313                          "magic1_hash[0x%08X %s 0x%08X] "
314                          "magic2_hash[0x%08X %s 0x%08X]\n",
315                          name, hash_alg,
316                          tdb->header.magic1_hash,
317                          (tdb->header.magic1_hash == magic1_hash) ? "==" : "!=",
318                          magic1_hash,
319                          tdb->header.magic2_hash,
320                          (tdb->header.magic2_hash == magic2_hash) ? "==" : "!=",
321                          magic2_hash));
322                 errno = EINVAL;
323                 goto fail;
324         }
325
326         /* Is it already in the open list?  If so, fail. */
327         if (tdb_already_open(st.st_dev, st.st_ino)) {
328                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
329                          "%s (%d,%d) is already open in this process\n",
330                          name, (int)st.st_dev, (int)st.st_ino));
331                 errno = EBUSY;
332                 goto fail;
333         }
334
335         if (!(tdb->name = (char *)strdup(name))) {
336                 errno = ENOMEM;
337                 goto fail;
338         }
339
340         tdb->map_size = st.st_size;
341         tdb->device = st.st_dev;
342         tdb->inode = st.st_ino;
343         tdb_mmap(tdb);
344         if (locked) {
345                 if (tdb->methods->tdb_brlock(tdb, ACTIVE_LOCK, F_UNLCK, F_SETLK, 0, 1) == -1) {
346                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: "
347                                  "failed to take ACTIVE_LOCK on %s: %s\n",
348                                  name, strerror(errno)));
349                         goto fail;
350                 }
351
352         }
353
354         /* We always need to do this if the CLEAR_IF_FIRST flag is set, even if
355            we didn't get the initial exclusive lock as we need to let all other
356            users know we're using it. */
357
358         if (tdb_flags & TDB_CLEAR_IF_FIRST) {
359                 /* leave this lock in place to indicate it's in use */
360                 if (tdb->methods->tdb_brlock(tdb, ACTIVE_LOCK, F_RDLCK, F_SETLKW, 0, 1) == -1)
361                         goto fail;
362         }
363
364         /* if needed, run recovery */
365         if (tdb_transaction_recover(tdb) == -1) {
366                 goto fail;
367         }
368
369  internal:
370         /* Internal (memory-only) databases skip all the code above to
371          * do with disk files, and resume here by releasing their
372          * global lock and hooking into the active list. */
373         if (tdb->methods->tdb_brlock(tdb, GLOBAL_LOCK, F_UNLCK, F_SETLKW, 0, 1) == -1)
374                 goto fail;
375         tdb->next = tdbs;
376         tdbs = tdb;
377         return tdb;
378
379  fail:
380         { int save_errno = errno;
381
382         if (!tdb)
383                 return NULL;
384         
385         if (tdb->map_ptr) {
386                 if (tdb->flags & TDB_INTERNAL)
387                         SAFE_FREE(tdb->map_ptr);
388                 else
389                         tdb_munmap(tdb);
390         }
391         SAFE_FREE(tdb->name);
392         if (tdb->fd != -1)
393                 if (close(tdb->fd) != 0)
394                         TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_open_ex: failed to close tdb->fd on error!\n"));
395         SAFE_FREE(tdb);
396         errno = save_errno;
397         return NULL;
398         }
399 }
400
401 /*
402  * Set the maximum number of dead records per hash chain
403  */
404
405 void tdb_set_max_dead(struct tdb_context *tdb, int max_dead)
406 {
407         tdb->max_dead_records = max_dead;
408 }
409
410 /**
411  * Close a database.
412  *
413  * @returns -1 for error; 0 for success.
414  **/
415 int tdb_close(struct tdb_context *tdb)
416 {
417         struct tdb_context **i;
418         int ret = 0;
419
420         if (tdb->transaction) {
421                 tdb_transaction_cancel(tdb);
422         }
423
424         if (tdb->map_ptr) {
425                 if (tdb->flags & TDB_INTERNAL)
426                         SAFE_FREE(tdb->map_ptr);
427                 else
428                         tdb_munmap(tdb);
429         }
430         SAFE_FREE(tdb->name);
431         if (tdb->fd != -1)
432                 ret = close(tdb->fd);
433         SAFE_FREE(tdb->lockrecs);
434
435         /* Remove from contexts list */
436         for (i = &tdbs; *i; i = &(*i)->next) {
437                 if (*i == tdb) {
438                         *i = tdb->next;
439                         break;
440                 }
441         }
442
443         memset(tdb, 0, sizeof(*tdb));
444         SAFE_FREE(tdb);
445
446         return ret;
447 }
448
449 /* register a loging function */
450 void tdb_set_logging_function(struct tdb_context *tdb,
451                               const struct tdb_logging_context *log_ctx)
452 {
453         tdb->log = *log_ctx;
454 }
455
456 void *tdb_get_logging_private(struct tdb_context *tdb)
457 {
458         return tdb->log.log_private;
459 }
460
461 /* reopen a tdb - this can be used after a fork to ensure that we have an independent
462    seek pointer from our parent and to re-establish locks */
463 int tdb_reopen(struct tdb_context *tdb)
464 {
465         struct stat st;
466
467         if (tdb->flags & TDB_INTERNAL) {
468                 return 0; /* Nothing to do. */
469         }
470
471         if (tdb->num_locks != 0 || tdb->global_lock.count) {
472                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_reopen: reopen not allowed with locks held\n"));
473                 goto fail;
474         }
475
476         if (tdb->transaction != 0) {
477                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "tdb_reopen: reopen not allowed inside a transaction\n"));
478                 goto fail;
479         }
480
481 /* If we have real pread & pwrite, we can skip reopen. */
482 #if !defined(LIBREPLACE_PREAD_NOT_REPLACED) || \
483         !defined(LIBREPLACE_PWRITE_NOT_REPLACED)
484         if (tdb_munmap(tdb) != 0) {
485                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: munmap failed (%s)\n", strerror(errno)));
486                 goto fail;
487         }
488         if (close(tdb->fd) != 0)
489                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: WARNING closing tdb->fd failed!\n"));
490         tdb->fd = open(tdb->name, tdb->open_flags & ~(O_CREAT|O_TRUNC), 0);
491         if (tdb->fd == -1) {
492                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: open failed (%s)\n", strerror(errno)));
493                 goto fail;
494         }
495         if (fstat(tdb->fd, &st) != 0) {
496                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: fstat failed (%s)\n", strerror(errno)));
497                 goto fail;
498         }
499         if (st.st_ino != tdb->inode || st.st_dev != tdb->device) {
500                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: file dev/inode has changed!\n"));
501                 goto fail;
502         }
503         tdb_mmap(tdb);
504 #endif /* fake pread or pwrite */
505
506         if ((tdb->flags & TDB_CLEAR_IF_FIRST) &&
507             (tdb->methods->tdb_brlock(tdb, ACTIVE_LOCK, F_RDLCK, F_SETLKW, 0, 1) == -1)) {
508                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_reopen: failed to obtain active lock\n"));
509                 goto fail;
510         }
511
512         return 0;
513
514 fail:
515         tdb_close(tdb);
516         return -1;
517 }
518
519 /* reopen all tdb's */
520 int tdb_reopen_all(int parent_longlived)
521 {
522         struct tdb_context *tdb;
523
524         for (tdb=tdbs; tdb; tdb = tdb->next) {
525                 /*
526                  * If the parent is longlived (ie. a
527                  * parent daemon architecture), we know
528                  * it will keep it's active lock on a
529                  * tdb opened with CLEAR_IF_FIRST. Thus
530                  * for child processes we don't have to
531                  * add an active lock. This is essential
532                  * to improve performance on systems that
533                  * keep POSIX locks as a non-scalable data
534                  * structure in the kernel.
535                  */
536                 if (parent_longlived) {
537                         /* Ensure no clear-if-first. */
538                         tdb->flags &= ~TDB_CLEAR_IF_FIRST;
539                 }
540
541                 if (tdb_reopen(tdb) != 0)
542                         return -1;
543         }
544
545         return 0;
546 }