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