]> git.pond.sub.org Git - empserver/blob - src/lib/common/file.c
d7fd63557edc0ce5bde0a7c8f9abe2123745c88f
[empserver] / src / lib / common / file.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2011, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *
6  *  Empire is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  *  ---
20  *
21  *  See files README, COPYING and CREDITS in the root of the source
22  *  tree for related information and legal notices.  It is expected
23  *  that future projects/authors will amend these files as needed.
24  *
25  *  ---
26  *
27  *  file.c: Operations on Empire tables (`files' for historical reasons)
28  *
29  *  Known contributors to this file:
30  *     Dave Pare, 1989
31  *     Steve McClure, 2000
32  *     Markus Armbruster, 2005-2011
33  */
34
35 #include <config.h>
36
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <limits.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <unistd.h>
43 #ifdef _WIN32
44 #include <io.h>
45 #include <share.h>
46 #endif
47 #include "file.h"
48 #include "match.h"
49 #include "misc.h"
50 #include "nsc.h"
51 #include "prototypes.h"
52
53 static int open_locked(char *, int, mode_t);
54 static int ef_realloc_cache(struct empfile *, int);
55 static int fillcache(struct empfile *, int);
56 static int do_read(struct empfile *, void *, int, int);
57 static int do_write(struct empfile *, void *, int, int);
58 static unsigned get_seqno(struct empfile *, int);
59 static void new_seqno(struct empfile *, void *);
60 static void must_be_fresh(struct empfile *, void *);
61 static void do_blank(struct empfile *, void *, int, int);
62 static int ef_check(int);
63
64 static unsigned ef_generation;
65
66 /*
67  * Open the file-backed table TYPE (EF_SECTOR, ...).
68  * HOW are flags to control operation.  Naturally, immutable flags are
69  * not permitted.
70  * The table must not be already open.
71  * Return non-zero on success, zero on failure.
72  */
73 int
74 ef_open(int type, int how)
75 {
76     struct empfile *ep;
77     int oflags, fd, fsiz, fids, nslots;
78
79     if (ef_check(type) < 0)
80         return 0;
81     if (CANT_HAPPEN(how & EFF_IMMUTABLE))
82         how &= ~EFF_IMMUTABLE;
83
84     /* open file */
85     ep = &empfile[type];
86     if (CANT_HAPPEN(!ep->file || ep->base != EF_BAD || ep->fd >= 0))
87         return 0;
88     oflags = O_RDWR;
89     if (how & EFF_PRIVATE)
90         oflags = O_RDONLY;
91     if (how & EFF_CREATE)
92         oflags |= O_CREAT | O_TRUNC;
93     fd = open_locked(ep->file, oflags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
94     if (fd < 0) {
95         logerror("Can't open %s (%s)", ep->file, strerror(errno));
96         return 0;
97     }
98
99     /* get file size */
100     fsiz = fsize(fd);
101     if (fsiz % ep->size) {
102         logerror("Can't open %s (file size not a multiple of record size %d)",
103                  ep->file, ep->size);
104         close(fd);
105         return 0;
106     }
107     fids = fsiz / ep->size;
108     if (ep->nent >= 0 && ep->nent != fids && !(how & EFF_CREATE)) {
109         logerror("Can't open %s (got %d records instead of %d)",
110                  ep->file, fids, ep->nent);
111         close(fd);
112         return 0;
113     }
114
115     /* allocate cache */
116     if (ep->flags & EFF_STATIC) {
117         /* ep->cache already points to space for ep->csize elements */
118         if (how & EFF_MEM) {
119             if (fids > ep->csize) {
120                 CANT_HAPPEN(ep->nent >= 0); /* insufficient static cache */
121                 logerror("Can't open %s (file larger than %d records)",
122                          ep->file, ep->csize);
123                 close(fd);
124                 return 0;
125             }
126         }
127     } else {
128         if (CANT_HAPPEN(ep->cache))
129             free(ep->cache);
130         if (how & EFF_MEM)
131             nslots = fids;
132         else
133             nslots = blksize(fd) / ep->size;
134         if (!ef_realloc_cache(ep, nslots)) {
135             logerror("Can't map %s (%s)", ep->file, strerror(errno));
136             close(fd);
137             return 0;
138         }
139     }
140     ep->baseid = 0;
141     ep->cids = 0;
142     ep->fids = fids;
143     ep->flags = (ep->flags & EFF_IMMUTABLE) | (how & ~EFF_CREATE);
144     ep->fd = fd;
145
146     /* map file into cache */
147     if ((how & EFF_MEM) && fids) {
148         if (fillcache(ep, 0) != fids) {
149             ep->cids = 0;       /* prevent cache flush */
150             ef_close(type);
151             return 0;
152         }
153     }
154
155     if (ep->onresize)
156         ep->onresize(type);
157     return 1;
158 }
159
160 static int
161 open_locked(char *name, int oflags, mode_t mode)
162 {
163     int rdlonly = (oflags & O_ACCMODE) == O_RDONLY;
164     int fd;
165
166 #ifdef _WIN32
167     fd = _sopen(name, oflags | O_BINARY, rdlonly ? SH_DENYNO : SH_DENYWR,
168                 mode);
169     if (fd < 0)
170         return -1;
171 #else  /* !_WIN32 */
172     struct flock lock;
173
174     fd = open(name, oflags, mode);
175     if (fd < 0)
176         return -1;
177
178     lock.l_type = rdlonly ? F_RDLCK : F_WRLCK;
179     lock.l_whence = SEEK_SET;
180     lock.l_start = lock.l_len = 0;
181     if (fcntl(fd, F_SETLK, &lock) == -1) {
182         close(fd);
183         return -1;
184     }
185 #endif  /* !_WIN32 */
186     return fd;
187 }
188
189 /*
190  * Reallocate cache for table EP to hold COUNT slots.
191  * The table must not be allocated statically.
192  * The cache may still be unmapped.
193  * If reallocation succeeds, any pointers obtained from ef_ptr()
194  * become invalid.
195  * If it fails, the cache is unchanged, and errno is set.
196  * Return non-zero on success, zero on failure.
197  */
198 static int
199 ef_realloc_cache(struct empfile *ep, int count)
200 {
201     void *cache;
202
203     if (CANT_HAPPEN(ep->flags & EFF_STATIC))
204         return 0;
205     if (CANT_HAPPEN(count < 0))
206         count = 0;
207
208     /*
209      * Avoid zero slots, because that can lead to null cache, which
210      * would be interpreted as unmapped cache.
211      */
212     if (count == 0)
213         count++;
214     cache = realloc(ep->cache, count * ep->size);
215     if (!cache)
216         return 0;
217
218     ep->cache = cache;
219     ep->csize = count;
220     return 1;
221 }
222
223 /*
224  * Open the table TYPE, which is a view of a base table
225  * The table must not be already open.
226  * Return non-zero on success, zero on failure.
227  * Beware: views work only as long as the base table doesn't change size!
228  * You must close the view before closing its base table.
229  */
230 int
231 ef_open_view(int type)
232 {
233     struct empfile *ep;
234     int base;
235
236     if (ef_check(type) < 0)
237         return 0;
238     ep = &empfile[type];
239     base = ep->base;
240     if (ef_check(base) < 0)
241         return 0;
242     if (CANT_HAPPEN(!(ef_flags(base) & EFF_MEM)
243                     || ep->file
244                     || ep->size != empfile[base].size
245                     || ep->nent != empfile[base].nent
246                     || ep->cache || ep->oninit || ep->postread
247                     || ep->prewrite || ep->onresize))
248         return -1;
249
250     ep->cache = empfile[base].cache;
251     ep->csize = empfile[base].csize;
252     ep->flags |= EFF_MEM;
253     ep->baseid = empfile[base].baseid;
254     ep->cids = empfile[base].cids;
255     ep->fids = empfile[base].fids;
256     return 0;
257 }
258
259 /*
260  * Close the open table TYPE (EF_SECTOR, ...).
261  * Return non-zero on success, zero on failure.
262  */
263 int
264 ef_close(int type)
265 {
266     struct empfile *ep;
267     int retval = 1;
268
269     if (ef_check(type) < 0)
270         return 0;
271     ep = &empfile[type];
272
273     if (EF_IS_VIEW(type)) {
274         ep->cache = NULL;
275         ep->csize = 0;
276     } else {
277         if (!ef_flush(type))
278             retval = 0;
279         if (!(ep->flags & EFF_STATIC)) {
280             free(ep->cache);
281             ep->cache = NULL;
282             ep->csize = 0;
283         }
284         if (close(ep->fd) < 0) {
285             logerror("Error closing %s (%s)", ep->file, strerror(errno));
286             retval = 0;
287         }
288         ep->fd = -1;
289     }
290     ep->flags &= EFF_IMMUTABLE;
291     ep->baseid = ep->cids = ep->fids = 0;
292     if (ep->onresize)
293         ep->onresize(type);
294     return retval;
295 }
296
297 /*
298  * Flush file-backed table TYPE (EF_SECTOR, ...) to its backing file.
299  * Do nothing if the table is privately mapped.
300  * Update timestamps of written elements if table is EFF_TYPED.
301  * Return non-zero on success, zero on failure.
302  */
303 int
304 ef_flush(int type)
305 {
306     struct empfile *ep;
307
308     if (ef_check(type) < 0)
309         return 0;
310     ep = &empfile[type];
311     if (ep->flags & EFF_PRIVATE)
312         return 1;               /* nothing to do */
313     if (CANT_HAPPEN(ep->fd < 0))
314         return 0;
315     /*
316      * We don't know which cache entries are dirty.  ef_write() writes
317      * through, but direct updates through ef_ptr() don't.  They are
318      * allowed only with EFF_MEM.  Assume the whole cash is dirty
319      * then.
320      */
321     if (ep->flags & EFF_MEM) {
322         if (do_write(ep, ep->cache, ep->baseid, ep->cids) < 0)
323             return 0;
324     }
325
326     return 1;
327 }
328
329 /*
330  * Return pointer to element ID in table TYPE if it exists, else NULL.
331  * The table must be fully cached, i.e. flags & EFF_MEM.
332  * The caller is responsible for flushing changes he makes.
333  */
334 void *
335 ef_ptr(int type, int id)
336 {
337     struct empfile *ep;
338
339     if (ef_check(type) < 0)
340         return NULL;
341     ep = &empfile[type];
342     if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
343         return NULL;
344     if (id < 0 || id >= ep->fids)
345         return NULL;
346     return ep->cache + ep->size * id;
347 }
348
349 /*
350  * Read element ID from table TYPE into buffer INTO.
351  * FIXME pass buffer size!
352  * INTO is marked fresh with ef_mark_fresh().
353  * Return non-zero on success, zero on failure.
354  */
355 int
356 ef_read(int type, int id, void *into)
357 {
358     struct empfile *ep;
359     void *cachep;
360
361     if (ef_check(type) < 0)
362         return 0;
363     ep = &empfile[type];
364     if (CANT_HAPPEN(!ep->cache))
365         return 0;
366     if (id < 0 || id >= ep->fids)
367         return 0;
368
369     if (ep->flags & EFF_MEM) {
370         cachep = ep->cache + id * ep->size;
371     } else {
372         if (ep->baseid + ep->cids <= id || ep->baseid > id) {
373             if (fillcache(ep, id) < 1)
374                 return 0;
375         }
376         cachep = ep->cache + (id - ep->baseid) * ep->size;
377     }
378     memcpy(into, cachep, ep->size);
379     ef_mark_fresh(type, into);
380
381     if (ep->postread)
382         ep->postread(id, into);
383     return 1;
384 }
385
386 /*
387  * Fill cache of file-backed EP with elements starting at ID.
388  * If any were read, return their number.
389  * Else return -1 and leave the cache unchanged.
390  */
391 static int
392 fillcache(struct empfile *ep, int id)
393 {
394     int ret;
395
396     if (CANT_HAPPEN(!ep->cache))
397         return -1;
398
399     ret = do_read(ep, ep->cache, id, MIN(ep->csize, ep->fids - id));
400     if (ret >= 0) {
401         /* cache changed */
402         ep->baseid = id;
403         ep->cids = ret;
404     }
405     return ret;
406 }
407
408 static int
409 do_read(struct empfile *ep, void *buf, int id, int count)
410 {
411     int n, ret;
412     char *p;
413
414     if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
415         return -1;
416
417     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
418         logerror("Error seeking %s to elt %d (%s)",
419                  ep->file, id, strerror(errno));
420         return -1;
421     }
422
423     p = buf;
424     n = count * ep->size;
425     while (n > 0) {
426         ret = read(ep->fd, p, n);
427         if (ret < 0) {
428             if (errno != EINTR) {
429                 logerror("Error reading %s elt %d (%s)",
430                          ep->file,
431                          id + (int)((p - (char *)buf) / ep->size),
432                          strerror(errno));
433                 break;
434             }
435         } else if (ret == 0) {
436             logerror("Unexpected EOF reading %s elt %d",
437                      ep->file, id + (int)((p - (char *)buf) / ep->size));
438             break;
439         } else {
440             p += ret;
441             n -= ret;
442         }
443     }
444
445     return (p - (char *)buf) / ep->size;
446 }
447
448 /*
449  * Write COUNT elements starting at ID from BUF to file-backed EP.
450  * Update the timestamp if the table is EFF_TYPED.
451  * Don't actually write if table is privately mapped.
452  * Return 0 on success, -1 on error (file may be corrupt then).
453  */
454 static int
455 do_write(struct empfile *ep, void *buf, int id, int count)
456 {
457     int i, n, ret;
458     char *p;
459     struct emptypedstr *elt;
460     time_t now;
461
462     if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
463         return -1;
464
465     if (ep->flags & EFF_TYPED) {
466         now = ep->flags & EFF_NOTIME ? (time_t)-1 : time(NULL);
467         for (i = 0; i < count; i++) {
468             /*
469              * TODO Oopses here could be due to bad data corruption.
470              * Fail instead of attempting to recover?
471              */
472             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
473             if (CANT_HAPPEN(elt->ef_type != ep->uid))
474                 elt->ef_type = ep->uid;
475             if (CANT_HAPPEN(elt->uid != id + i))
476                 elt->uid = id + i;
477             if (now != (time_t)-1)
478                 elt->timestamp = now;
479         }
480     }
481
482     if (ep->flags & EFF_PRIVATE)
483         return 0;
484
485     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
486         logerror("Error seeking %s to elt %d (%s)",
487                  ep->file, id, strerror(errno));
488         return -1;
489     }
490
491     p = buf;
492     n = count * ep->size;
493     while (n > 0) {
494         ret = write(ep->fd, p, n);
495         if (ret < 0) {
496             if (errno != EINTR) {
497                 logerror("Error writing %s elt %d (%s)",
498                          ep->file,
499                          id + (int)((p - (char *)buf) / ep->size),
500                          strerror(errno));
501                 return -1;
502             }
503         } else {
504             p += ret;
505             n -= ret;
506         }
507     }
508
509     return 0;
510 }
511
512 /*
513  * Write element ID into table TYPE from buffer FROM.
514  * FIXME pass buffer size!
515  * Update timestamp in FROM if table is EFF_TYPED.
516  * If table is file-backed and not privately mapped, write through
517  * cache straight to disk.
518  * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
519  * Can write at the end of partially cached table.
520  * FROM must be fresh; see ef_make_stale().
521  * Return non-zero on success, zero on failure.
522  */
523 int
524 ef_write(int type, int id, void *from)
525 {
526     struct empfile *ep;
527     char *cachep;
528
529     if (ef_check(type) < 0)
530         return 0;
531     ep = &empfile[type];
532     if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
533         return 0;
534     new_seqno(ep, from);
535     if (id >= ep->fids) {
536         /* beyond end of file */
537         if (CANT_HAPPEN((ep->flags & EFF_MEM) || id > ep->fids))
538             return 0;           /* not implemented */
539         /* write at end of file extends it */
540         ep->fids = id + 1;
541         if (ep->onresize)
542             ep->onresize(type);
543     }
544     if (id >= ep->baseid && id < ep->baseid + ep->cids) {
545         cachep = ep->cache + (id - ep->baseid) * ep->size;
546         if (cachep != from)
547             must_be_fresh(ep, from);
548     } else
549         cachep = NULL;
550     if (ep->prewrite)
551         ep->prewrite(id, cachep, from);
552     if (ep->fd >= 0) {
553         if (do_write(ep, from, id, 1) < 0)
554             return 0;
555     }
556     if (cachep && cachep != from)       /* update the cache if necessary */
557         memcpy(cachep, from, ep->size);
558     return 1;
559 }
560
561 /*
562  * Change element id.
563  * BUF is an element of table TYPE.
564  * ID is its new element ID.
565  * If table is EFF_TYPED, change id and sequence number stored in BUF.
566  * Else do nothing.
567  */
568 void
569 ef_set_uid(int type, void *buf, int uid)
570 {
571     struct emptypedstr *elt;
572     struct empfile *ep;
573
574     if (ef_check(type) < 0)
575         return;
576     ep = &empfile[type];
577     if (!(ep->flags & EFF_TYPED))
578         return;
579     elt = buf;
580     if (elt->uid == uid)
581         return;
582     elt->uid = uid;
583     elt->seqno = get_seqno(ep, uid);
584 }
585
586 /*
587  * Return sequence number of element ID in table EP.
588  * Return zero if table is not EFF_TYPED (it has no sequence number
589  * then).
590  */
591 static unsigned
592 get_seqno(struct empfile *ep, int id)
593 {
594     struct emptypedstr *elt;
595
596     if (!(ep->flags & EFF_TYPED))
597         return 0;
598     if (id < 0 || id >= ep->fids)
599         return 0;
600     if (id >= ep->baseid && id < ep->baseid + ep->cids)
601         elt = (void *)(ep->cache + (id - ep->baseid) * ep->size);
602     else {
603         /* need a buffer, steal last cache slot */
604         if (ep->cids == ep->csize)
605             ep->cids--;
606         elt = (void *)(ep->cache + ep->cids * ep->size);
607         if (do_read(ep, elt, id, 1) < 0)
608             return 0;           /* deep trouble */
609     }
610     return elt->seqno;
611 }
612
613 /*
614  * Increment sequence number in BUF, which is about to be written to EP.
615  * Do nothing if table is not EFF_TYPED (it has no sequence number
616  * then).
617  * Else, BUF's sequence number must match the one in EP's cache.  If
618  * it doesn't, we're about to clobber a previous write.
619  */
620 static void
621 new_seqno(struct empfile *ep, void *buf)
622 {
623     struct emptypedstr *elt = buf;
624     unsigned old_seqno;
625
626     if (!(ep->flags & EFF_TYPED))
627         return;
628     old_seqno = get_seqno(ep, elt->uid);
629     CANT_HAPPEN(old_seqno != elt->seqno);
630     elt->seqno = old_seqno + 1;
631 }
632
633 /*
634  * Make all copies stale.
635  * Only fresh copies may be written back to the cache.
636  * To be called by functions that may yield the processor.
637  * Writing an copy when there has been a yield since it was read is
638  * unsafe, because we could clobber another thread's write then.
639  * Robust code must assume the that any function that may yield does
640  * yield.  Marking copies stale there lets us catch unsafe writes.
641  */
642 void
643 ef_make_stale(void)
644 {
645     ef_generation++;
646 }
647
648 /* Mark copy of an element of table TYPE in BUF fresh.  */
649 void
650 ef_mark_fresh(int type, void *buf)
651 {
652     struct empfile *ep;
653
654     if (ef_check(type) < 0)
655         return;
656     ep = &empfile[type];
657     if (!(ep->flags & EFF_TYPED))
658         return;
659     ((struct emptypedstr *)buf)->generation = ef_generation;
660 }
661
662 static void
663 must_be_fresh(struct empfile *ep, void *buf)
664 {
665     struct emptypedstr *elt = buf;
666
667     if (!(ep->flags & EFF_TYPED))
668         return;
669     CANT_HAPPEN(elt->generation != (ef_generation & 0xfff));
670 }
671
672 /*
673  * Extend table TYPE by COUNT elements.
674  * Any pointers obtained from ef_ptr() become invalid.
675  * Return non-zero on success, zero on failure.
676  */
677 int
678 ef_extend(int type, int count)
679 {
680     struct empfile *ep;
681     char *p;
682     int need_sentinel, i, id;
683
684     if (ef_check(type) < 0 || CANT_HAPPEN(EF_IS_VIEW(type)))
685         return 0;
686     ep = &empfile[type];
687     if (CANT_HAPPEN(count < 0))
688         return 0;
689
690     id = ep->fids;
691     if (ep->flags & EFF_MEM) {
692         need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
693         if (id + count + need_sentinel > ep->csize) {
694             if (ep->flags & EFF_STATIC) {
695                 logerror("Can't extend %s beyond %d elements",
696                          ep->name, ep->csize - need_sentinel);
697                 return 0;
698             }
699             if (!ef_realloc_cache(ep, id + count + need_sentinel)) {
700                 logerror("Can't extend %s to %d elements (%s)",
701                          ep->name, id + count, strerror(errno));
702                 return 0;
703             }
704         }
705         p = ep->cache + id * ep->size;
706         do_blank(ep, p, id, count);
707         if (ep->fd >= 0) {
708             if (do_write(ep, p, id, count) < 0)
709                 return 0;
710         }
711         if (need_sentinel)
712             memset(ep->cache + (id + count) * ep->size, 0, ep->size);
713         ep->cids = id + count;
714     } else {
715         /* need a buffer, steal last cache slot */
716         if (ep->cids == ep->csize)
717             ep->cids--;
718         p = ep->cache + ep->cids * ep->size;
719         for (i = 0; i < count; i++) {
720             do_blank(ep, p, id + i, 1);
721             if (do_write(ep, p, id + i, 1) < 0)
722                 return 0;
723         }
724     }
725     ep->fids = id + count;
726     if (ep->onresize)
727         ep->onresize(type);
728     return 1;
729 }
730
731 /*
732  * Initialize element ID for table TYPE in BUF.
733  * FIXME pass buffer size!
734  * BUF is marked fresh with ef_mark_fresh().
735  */
736 void
737 ef_blank(int type, int id, void *buf)
738 {
739     struct empfile *ep;
740     struct emptypedstr *elt;
741
742     if (ef_check(type) < 0)
743         return;
744     ep = &empfile[type];
745     do_blank(ep, buf, id, 1);
746     if (ep->flags & EFF_TYPED) {
747         elt = buf;
748         elt->seqno = get_seqno(ep, elt->uid);
749     }
750     ef_mark_fresh(type, buf);
751 }
752
753 /*
754  * Initialize COUNT elements of EP in BUF, starting with element ID.
755  */
756 static void
757 do_blank(struct empfile *ep, void *buf, int id, int count)
758 {
759     int i;
760     struct emptypedstr *elt;
761
762     memset(buf, 0, count * ep->size);
763     for (i = 0; i < count; i++) {
764         elt = (struct emptypedstr *)((char *)buf + i * ep->size);
765         if (ep->flags & EFF_TYPED) {
766             elt->ef_type = ep->uid;
767             elt->uid = id + i;
768         }
769         if (ep->oninit)
770             ep->oninit(elt);
771     }
772 }
773
774 /*
775  * Truncate table TYPE to COUNT elements.
776  * Any pointers obtained from ef_ptr() become invalid.
777  * Return non-zero on success, zero on failure.
778  */
779 int
780 ef_truncate(int type, int count)
781 {
782     struct empfile *ep;
783     int need_sentinel;
784
785     if (ef_check(type) < 0 || CANT_HAPPEN(EF_IS_VIEW(type)))
786         return 0;
787     ep = &empfile[type];
788     if (CANT_HAPPEN(count < 0 || count > ep->fids))
789         return 0;
790
791     if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
792         if (ftruncate(ep->fd, count * ep->size) < 0) {
793             logerror("Can't truncate %s to %d elements (%s)",
794                      ep->file, count, strerror(errno));
795             return 0;
796         }
797     }
798     ep->fids = count;
799
800     if (ep->flags & EFF_MEM) {
801         need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
802         if (!(ep->flags & EFF_STATIC)) {
803             if (!ef_realloc_cache(ep, count + need_sentinel)) {
804                 logerror("Can't shrink %s cache after truncate (%s)",
805                          ep->name, strerror(errno));
806                 /* continue with unshrunk cache */
807             }
808         }
809         if (need_sentinel)
810             memset(ep->cache + count * ep->size, 0, ep->size);
811         ep->cids = count;
812     } else {
813         if (ep->baseid >= count)
814             ep->cids = 0;
815         else if (ep->cids > count - ep->baseid)
816             ep->cids = count - ep->baseid;
817     }
818
819     if (ep->onresize)
820         ep->onresize(type);
821     return 1;
822 }
823
824 struct castr *
825 ef_cadef(int type)
826 {
827     if (ef_check(type) < 0)
828         return NULL;
829     return empfile[type].cadef;
830 }
831
832 int
833 ef_nelem(int type)
834 {
835     if (ef_check(type) < 0)
836         return 0;
837     return empfile[type].fids;
838 }
839
840 int
841 ef_flags(int type)
842 {
843     if (ef_check(type) < 0)
844         return 0;
845     return empfile[type].flags;
846 }
847
848 time_t
849 ef_mtime(int type)
850 {
851     if (ef_check(type) < 0)
852         return 0;
853     if (empfile[type].fd <= 0)
854         return 0;
855     return fdate(empfile[type].fd);
856 }
857
858 /*
859  * Search for a table matching NAME, return its table type.
860  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
861  * several.
862  */
863 int
864 ef_byname(char *name)
865 {
866     return stmtch(name, empfile, offsetof(struct empfile, name),
867                   sizeof(empfile[0]));
868 }
869
870 /*
871  * Search CHOICES[] for a table type matching NAME, return it.
872  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
873  * several.
874  * CHOICES[] must be terminated with a negative value.
875  */
876 int
877 ef_byname_from(char *name, int choices[])
878 {
879     int res;
880     int *p;
881
882     res = M_NOTFOUND;
883     for (p = choices; *p >= 0; p++) {
884         if (ef_check(*p) < 0)
885             continue;
886         switch (mineq(name, empfile[*p].name)) {
887         case ME_MISMATCH:
888             break;
889         case ME_PARTIAL:
890             if (res >= 0)
891                 return M_NOTUNIQUE;
892             res = *p;
893             break;
894         case ME_EXACT:
895             return *p;
896         }
897     }
898     return res;
899 }
900
901 char *
902 ef_nameof(int type)
903 {
904     if (ef_check(type) < 0)
905         return "bad ef_type";
906     return empfile[type].name;
907 }
908
909 static int
910 ef_check(int type)
911 {
912     if (CANT_HAPPEN((unsigned)type >= EF_MAX))
913         return -1;
914     return 0;
915 }
916
917 /*
918  * Ensure table contains element ID.
919  * If necessary, extend it in steps of COUNT elements.
920  * Return non-zero on success, zero on failure.
921  */
922 int
923 ef_ensure_space(int type, int id, int count)
924 {
925     if (ef_check(type) < 0)
926         return 0;
927     CANT_HAPPEN(id < 0);
928
929     while (id >= empfile[type].fids) {
930         if (!ef_extend(type, count))
931             return 0;
932     }
933     return 1;
934 }
935
936 /*
937  * Return maximum ID acceptable for table TYPE.
938  * Assuming infinite memory and disk space.
939  */
940 int
941 ef_id_limit(int type)
942 {
943     struct empfile *ep;
944
945     if (ef_check(type) < 0)
946         return -1;
947     ep = &empfile[type];
948     if (ep->nent >= 0)
949         return ep->nent - 1;
950     if (ep->flags & EFF_MEM) {
951         if (ep->flags & EFF_STATIC)
952             return ep->csize - 1 - ((ep->flags & EFF_SENTINEL) != 0);
953     }
954     return INT_MAX;
955 }