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