24c2d615aba14fb73deecb619659b7419893636d
[kai/samba.git] / lib / tdb / common / io.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
29 #include "tdb_private.h"
30
31 /* check for an out of bounds access - if it is out of bounds then
32    see if the database has been expanded by someone else and expand
33    if necessary 
34 */
35 static int tdb_oob(struct tdb_context *tdb, tdb_off_t off, tdb_len_t len,
36                    int probe)
37 {
38         struct stat st;
39         if (len + off < len) {
40                 if (!probe) {
41                         /* Ensure ecode is set for log fn. */
42                         tdb->ecode = TDB_ERR_IO;
43                         TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_oob off %d len %d wrap\n",
44                                  (int)off, (int)len));
45                 }
46                 return -1;
47         }
48
49         if (off + len <= tdb->map_size)
50                 return 0;
51         if (tdb->flags & TDB_INTERNAL) {
52                 if (!probe) {
53                         /* Ensure ecode is set for log fn. */
54                         tdb->ecode = TDB_ERR_IO;
55                         TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_oob len %u beyond internal malloc size %u\n",
56                                  (int)(off + len), (int)tdb->map_size));
57                 }
58                 return -1;
59         }
60
61         if (fstat(tdb->fd, &st) == -1) {
62                 tdb->ecode = TDB_ERR_IO;
63                 return -1;
64         }
65
66         if (st.st_size < (size_t)off + len) {
67                 if (!probe) {
68                         /* Ensure ecode is set for log fn. */
69                         tdb->ecode = TDB_ERR_IO;
70                         TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_oob len %u beyond eof at %u\n",
71                                  (int)(off + len), (int)st.st_size));
72                 }
73                 return -1;
74         }
75
76         /* Beware >4G files! */
77         if ((tdb_off_t)st.st_size != st.st_size) {
78                 /* Ensure ecode is set for log fn. */
79                 tdb->ecode = TDB_ERR_IO;
80                 TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_oob len %llu too large!\n",
81                          (long long)st.st_size));
82                 return -1;
83         }
84
85         /* Unmap, update size, remap */
86         if (tdb_munmap(tdb) == -1) {
87                 tdb->ecode = TDB_ERR_IO;
88                 return -1;
89         }
90         tdb->map_size = st.st_size;
91         return tdb_mmap(tdb);
92 }
93
94 /* write a lump of data at a specified offset */
95 static int tdb_write(struct tdb_context *tdb, tdb_off_t off, 
96                      const void *buf, tdb_len_t len)
97 {
98         if (len == 0) {
99                 return 0;
100         }
101
102         if (tdb->read_only || tdb->traverse_read) {
103                 tdb->ecode = TDB_ERR_RDONLY;
104                 return -1;
105         }
106
107         if (tdb->methods->tdb_oob(tdb, off, len, 0) != 0)
108                 return -1;
109
110         if (tdb->map_ptr) {
111                 memcpy(off + (char *)tdb->map_ptr, buf, len);
112         } else {
113 #ifdef HAVE_INCOHERENT_MMAP
114                 tdb->ecode = TDB_ERR_IO;
115                 return -1;
116 #else
117                 ssize_t written = pwrite(tdb->fd, buf, len, off);
118                 if ((written != (ssize_t)len) && (written != -1)) {
119                         /* try once more */
120                         tdb->ecode = TDB_ERR_IO;
121                         TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_write: wrote only "
122                                  "%d of %d bytes at %d, trying once more\n",
123                                  (int)written, len, off));
124                         written = pwrite(tdb->fd, (const char *)buf+written,
125                                          len-written,
126                                          off+written);
127                 }
128                 if (written == -1) {
129                         /* Ensure ecode is set for log fn. */
130                         tdb->ecode = TDB_ERR_IO;
131                         TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_write failed at %d "
132                                  "len=%d (%s)\n", off, len, strerror(errno)));
133                         return -1;
134                 } else if (written != (ssize_t)len) {
135                         tdb->ecode = TDB_ERR_IO;
136                         TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_write: failed to "
137                                  "write %d bytes at %d in two attempts\n",
138                                  len, off));
139                         return -1;
140                 }
141 #endif
142         }
143         return 0;
144 }
145
146 /* Endian conversion: we only ever deal with 4 byte quantities */
147 void *tdb_convert(void *buf, uint32_t size)
148 {
149         uint32_t i, *p = (uint32_t *)buf;
150         for (i = 0; i < size / 4; i++)
151                 p[i] = TDB_BYTEREV(p[i]);
152         return buf;
153 }
154
155
156 /* read a lump of data at a specified offset, maybe convert */
157 static int tdb_read(struct tdb_context *tdb, tdb_off_t off, void *buf, 
158                     tdb_len_t len, int cv)
159 {
160         if (tdb->methods->tdb_oob(tdb, off, len, 0) != 0) {
161                 return -1;
162         }
163
164         if (tdb->map_ptr) {
165                 memcpy(buf, off + (char *)tdb->map_ptr, len);
166         } else {
167 #ifdef HAVE_INCOHERENT_MMAP
168                 tdb->ecode = TDB_ERR_IO;
169                 return -1;
170 #else
171                 ssize_t ret = pread(tdb->fd, buf, len, off);
172                 if (ret != (ssize_t)len) {
173                         /* Ensure ecode is set for log fn. */
174                         tdb->ecode = TDB_ERR_IO;
175                         TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_read failed at %d "
176                                  "len=%d ret=%d (%s) map_size=%d\n",
177                                  (int)off, (int)len, (int)ret, strerror(errno),
178                                  (int)tdb->map_size));
179                         return -1;
180                 }
181 #endif
182         }
183         if (cv) {
184                 tdb_convert(buf, len);
185         }
186         return 0;
187 }
188
189
190
191 /*
192   do an unlocked scan of the hash table heads to find the next non-zero head. The value
193   will then be confirmed with the lock held
194 */              
195 static void tdb_next_hash_chain(struct tdb_context *tdb, uint32_t *chain)
196 {
197         uint32_t h = *chain;
198         if (tdb->map_ptr) {
199                 for (;h < tdb->header.hash_size;h++) {
200                         if (0 != *(uint32_t *)(TDB_HASH_TOP(h) + (unsigned char *)tdb->map_ptr)) {
201                                 break;
202                         }
203                 }
204         } else {
205                 uint32_t off=0;
206                 for (;h < tdb->header.hash_size;h++) {
207                         if (tdb_ofs_read(tdb, TDB_HASH_TOP(h), &off) != 0 || off != 0) {
208                                 break;
209                         }
210                 }
211         }
212         (*chain) = h;
213 }
214
215
216 int tdb_munmap(struct tdb_context *tdb)
217 {
218         if (tdb->flags & TDB_INTERNAL)
219                 return 0;
220
221 #ifdef HAVE_MMAP
222         if (tdb->map_ptr) {
223                 int ret;
224
225                 ret = munmap(tdb->map_ptr, tdb->map_size);
226                 if (ret != 0)
227                         return ret;
228         }
229 #endif
230         tdb->map_ptr = NULL;
231         return 0;
232 }
233
234 /* If mmap isn't coherent, *everyone* must always mmap. */
235 static bool should_mmap(const struct tdb_context *tdb)
236 {
237 #ifdef HAVE_INCOHERENT_MMAP
238         return true;
239 #else
240         return !(tdb->flags & TDB_NOMMAP);
241 #endif
242 }
243
244 int tdb_mmap(struct tdb_context *tdb)
245 {
246         if (tdb->flags & TDB_INTERNAL)
247                 return;
248
249 #ifdef HAVE_MMAP
250         if (should_mmap(tdb)) {
251                 tdb->map_ptr = mmap(NULL, tdb->map_size, 
252                                     PROT_READ|(tdb->read_only? 0:PROT_WRITE), 
253                                     MAP_SHARED|MAP_FILE, tdb->fd, 0);
254
255                 /*
256                  * NB. When mmap fails it returns MAP_FAILED *NOT* NULL !!!!
257                  */
258
259                 if (tdb->map_ptr == MAP_FAILED) {
260                         tdb->map_ptr = NULL;
261                         TDB_LOG((tdb, TDB_DEBUG_WARNING, "tdb_mmap failed for size %d (%s)\n", 
262                                  tdb->map_size, strerror(errno)));
263 #ifdef HAVE_INCOHERENT_MMAP
264                         tdb->ecode = TDB_ERR_IO;
265                         return -1;
266 #endif
267                 }
268         } else {
269                 tdb->map_ptr = NULL;
270         }
271 #else
272         tdb->map_ptr = NULL;
273 #endif
274         return 0;
275 }
276
277 /* expand a file.  we prefer to use ftruncate, as that is what posix
278   says to use for mmap expansion */
279 static int tdb_expand_file(struct tdb_context *tdb, tdb_off_t size, tdb_off_t addition)
280 {
281         char buf[8192];
282
283         if (tdb->read_only || tdb->traverse_read) {
284                 tdb->ecode = TDB_ERR_RDONLY;
285                 return -1;
286         }
287
288         if (ftruncate(tdb->fd, size+addition) == -1) {
289                 char b = 0;
290                 ssize_t written = pwrite(tdb->fd,  &b, 1, (size+addition) - 1);
291                 if (written == 0) {
292                         /* try once more, potentially revealing errno */
293                         written = pwrite(tdb->fd,  &b, 1, (size+addition) - 1);
294                 }
295                 if (written == 0) {
296                         /* again - give up, guessing errno */
297                         errno = ENOSPC;
298                 }
299                 if (written != 1) {
300                         TDB_LOG((tdb, TDB_DEBUG_FATAL, "expand_file to %d failed (%s)\n", 
301                                  size+addition, strerror(errno)));
302                         return -1;
303                 }
304         }
305
306         /* now fill the file with something. This ensures that the
307            file isn't sparse, which would be very bad if we ran out of
308            disk. This must be done with write, not via mmap */
309         memset(buf, TDB_PAD_BYTE, sizeof(buf));
310         while (addition) {
311                 size_t n = addition>sizeof(buf)?sizeof(buf):addition;
312                 ssize_t written = pwrite(tdb->fd, buf, n, size);
313                 if (written == 0) {
314                         /* prevent infinite loops: try _once_ more */
315                         written = pwrite(tdb->fd, buf, n, size);
316                 }
317                 if (written == 0) {
318                         /* give up, trying to provide a useful errno */
319                         TDB_LOG((tdb, TDB_DEBUG_FATAL, "expand_file write "
320                                 "returned 0 twice: giving up!\n"));
321                         errno = ENOSPC;
322                         return -1;
323                 } else if (written == -1) {
324                         TDB_LOG((tdb, TDB_DEBUG_FATAL, "expand_file write of "
325                                  "%d bytes failed (%s)\n", (int)n,
326                                  strerror(errno)));
327                         return -1;
328                 } else if (written != n) {
329                         TDB_LOG((tdb, TDB_DEBUG_WARNING, "expand_file: wrote "
330                                  "only %d of %d bytes - retrying\n", (int)written,
331                                  (int)n));
332                 }
333                 addition -= written;
334                 size += written;
335         }
336         return 0;
337 }
338
339
340 /* You need 'size', this tells you how much you should expand by. */
341 tdb_off_t tdb_expand_adjust(tdb_off_t map_size, tdb_off_t size, int page_size)
342 {
343         tdb_off_t new_size, top_size;
344
345         /* limit size in order to avoid using up huge amounts of memory for
346          * in memory tdbs if an oddball huge record creeps in */
347         if (size > 100 * 1024) {
348                 top_size = map_size + size * 2;
349         } else {
350                 top_size = map_size + size * 100;
351         }
352
353         /* always make room for at least top_size more records, and at
354            least 25% more space. if the DB is smaller than 100MiB,
355            otherwise grow it by 10% only. */
356         if (map_size > 100 * 1024 * 1024) {
357                 new_size = map_size * 1.10;
358         } else {
359                 new_size = map_size * 1.25;
360         }
361
362         /* Round the database up to a multiple of the page size */
363         new_size = MAX(top_size, new_size);
364         return TDB_ALIGN(new_size, page_size) - map_size;
365 }
366
367 /* expand the database at least size bytes by expanding the underlying
368    file and doing the mmap again if necessary */
369 int tdb_expand(struct tdb_context *tdb, tdb_off_t size)
370 {
371         struct tdb_record rec;
372         tdb_off_t offset;
373
374         if (tdb_lock(tdb, -1, F_WRLCK) == -1) {
375                 TDB_LOG((tdb, TDB_DEBUG_ERROR, "lock failed in tdb_expand\n"));
376                 return -1;
377         }
378
379         /* must know about any previous expansions by another process */
380         tdb->methods->tdb_oob(tdb, tdb->map_size, 1, 1);
381
382         size = tdb_expand_adjust(tdb->map_size, size, tdb->page_size);
383
384         if (!(tdb->flags & TDB_INTERNAL))
385                 tdb_munmap(tdb);
386
387         /* expand the file itself */
388         if (!(tdb->flags & TDB_INTERNAL)) {
389                 if (tdb->methods->tdb_expand_file(tdb, tdb->map_size, size) != 0)
390                         goto fail;
391         }
392
393         tdb->map_size += size;
394
395         if (tdb->flags & TDB_INTERNAL) {
396                 char *new_map_ptr = (char *)realloc(tdb->map_ptr,
397                                                     tdb->map_size);
398                 if (!new_map_ptr) {
399                         tdb->map_size -= size;
400                         goto fail;
401                 }
402                 tdb->map_ptr = new_map_ptr;
403         } else {
404                 if (tdb_mmap(tdb) != 0) {
405                         goto fail;
406                 }
407         }
408
409         /* form a new freelist record */
410         memset(&rec,'\0',sizeof(rec));
411         rec.rec_len = size - sizeof(rec);
412
413         /* link it into the free list */
414         offset = tdb->map_size - size;
415         if (tdb_free(tdb, offset, &rec) == -1)
416                 goto fail;
417
418         tdb_unlock(tdb, -1, F_WRLCK);
419         return 0;
420  fail:
421         tdb_unlock(tdb, -1, F_WRLCK);
422         return -1;
423 }
424
425 /* read/write a tdb_off_t */
426 int tdb_ofs_read(struct tdb_context *tdb, tdb_off_t offset, tdb_off_t *d)
427 {
428         return tdb->methods->tdb_read(tdb, offset, (char*)d, sizeof(*d), DOCONV());
429 }
430
431 int tdb_ofs_write(struct tdb_context *tdb, tdb_off_t offset, tdb_off_t *d)
432 {
433         tdb_off_t off = *d;
434         return tdb->methods->tdb_write(tdb, offset, CONVERT(off), sizeof(*d));
435 }
436
437
438 /* read a lump of data, allocating the space for it */
439 unsigned char *tdb_alloc_read(struct tdb_context *tdb, tdb_off_t offset, tdb_len_t len)
440 {
441         unsigned char *buf;
442
443         /* some systems don't like zero length malloc */
444
445         if (!(buf = (unsigned char *)malloc(len ? len : 1))) {
446                 /* Ensure ecode is set for log fn. */
447                 tdb->ecode = TDB_ERR_OOM;
448                 TDB_LOG((tdb, TDB_DEBUG_ERROR,"tdb_alloc_read malloc failed len=%d (%s)\n",
449                            len, strerror(errno)));
450                 return NULL;
451         }
452         if (tdb->methods->tdb_read(tdb, offset, buf, len, 0) == -1) {
453                 SAFE_FREE(buf);
454                 return NULL;
455         }
456         return buf;
457 }
458
459 /* Give a piece of tdb data to a parser */
460
461 int tdb_parse_data(struct tdb_context *tdb, TDB_DATA key,
462                    tdb_off_t offset, tdb_len_t len,
463                    int (*parser)(TDB_DATA key, TDB_DATA data,
464                                  void *private_data),
465                    void *private_data)
466 {
467         TDB_DATA data;
468         int result;
469
470         data.dsize = len;
471
472         if ((tdb->transaction == NULL) && (tdb->map_ptr != NULL)) {
473                 /*
474                  * Optimize by avoiding the malloc/memcpy/free, point the
475                  * parser directly at the mmap area.
476                  */
477                 if (tdb->methods->tdb_oob(tdb, offset, len, 0) != 0) {
478                         return -1;
479                 }
480                 data.dptr = offset + (unsigned char *)tdb->map_ptr;
481                 return parser(key, data, private_data);
482         }
483
484         if (!(data.dptr = tdb_alloc_read(tdb, offset, len))) {
485                 return -1;
486         }
487
488         result = parser(key, data, private_data);
489         free(data.dptr);
490         return result;
491 }
492
493 /* read/write a record */
494 int tdb_rec_read(struct tdb_context *tdb, tdb_off_t offset, struct tdb_record *rec)
495 {
496         if (tdb->methods->tdb_read(tdb, offset, rec, sizeof(*rec),DOCONV()) == -1)
497                 return -1;
498         if (TDB_BAD_MAGIC(rec)) {
499                 /* Ensure ecode is set for log fn. */
500                 tdb->ecode = TDB_ERR_CORRUPT;
501                 TDB_LOG((tdb, TDB_DEBUG_FATAL,"tdb_rec_read bad magic 0x%x at offset=%d\n", rec->magic, offset));
502                 return -1;
503         }
504         return tdb->methods->tdb_oob(tdb, rec->next, sizeof(*rec), 0);
505 }
506
507 int tdb_rec_write(struct tdb_context *tdb, tdb_off_t offset, struct tdb_record *rec)
508 {
509         struct tdb_record r = *rec;
510         return tdb->methods->tdb_write(tdb, offset, CONVERT(r), sizeof(r));
511 }
512
513 static const struct tdb_methods io_methods = {
514         tdb_read,
515         tdb_write,
516         tdb_next_hash_chain,
517         tdb_oob,
518         tdb_expand_file,
519 };
520
521 /*
522   initialise the default methods table
523 */
524 void tdb_io_init(struct tdb_context *tdb)
525 {
526         tdb->methods = &io_methods;
527 }