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