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