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