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