]> git.pond.sub.org Git - empserver/blob - src/lib/common/file.c
Clean up maintenance of config table sentinels
[empserver] / src / lib / common / file.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2008, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                           Ken Stevens, Steve McClure
5  *
6  *  This program 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 2 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, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  *  ---
21  *
22  *  See files README, COPYING and CREDITS in the root of the source
23  *  tree for related information and legal notices.  It is expected
24  *  that future projects/authors will amend these files as needed.
25  *
26  *  ---
27  *
28  *  file.c: Operations on Empire tables (`files' for historical reasons)
29  * 
30  *  Known contributors to this file:
31  *     Dave Pare, 1989
32  *     Steve McClure, 2000
33  *     Markus Armbruster, 2005-2008
34  */
35
36 #include <config.h>
37
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <unistd.h>
43 #include "file.h"
44 #include "match.h"
45 #include "misc.h"
46 #include "nsc.h"
47 #include "prototypes.h"
48
49 static int ef_realloc_cache(struct empfile *, int);
50 static int fillcache(struct empfile *, int);
51 static int do_read(struct empfile *, void *, int, int);
52 static int do_write(struct empfile *, void *, int, int);
53 static unsigned get_seqno(struct empfile *, int);
54 static void new_seqno(struct empfile *, void *);
55 static void do_blank(struct empfile *, void *, int, int);
56
57 /*
58  * Open the file-backed table TYPE (EF_SECTOR, ...).
59  * HOW are flags to control operation.  Naturally, immutable flags are
60  * not permitted.
61  * If NELT is non-negative, the table must have that many elements.
62  * Return non-zero on success, zero on failure.
63  * You must call ef_close() before the next ef_open().
64  */
65 int
66 ef_open(int type, int how, int nelt)
67 {
68     struct empfile *ep;
69     struct flock lock;
70     int oflags, fd, fsiz, nslots;
71
72     if (ef_check(type) < 0)
73         return 0;
74     if (CANT_HAPPEN(how & EFF_IMMUTABLE))
75         how &= ~EFF_IMMUTABLE;
76
77     /* open file */
78     ep = &empfile[type];
79     if (CANT_HAPPEN(ep->fd >= 0))
80         return 0;
81     oflags = O_RDWR;
82     if (how & EFF_PRIVATE)
83         oflags = O_RDONLY;
84     if (how & EFF_CREATE)
85         oflags |= O_CREAT | O_TRUNC;
86 #if defined(_WIN32)
87     oflags |= O_BINARY;
88 #endif
89     if ((fd = open(ep->file, oflags, S_IRWUG)) < 0) {
90         logerror("Can't open %s (%s)", ep->file, strerror(errno));
91         return 0;
92     }
93
94     lock.l_type = how & EFF_PRIVATE ? F_RDLCK : F_WRLCK;
95     lock.l_whence = SEEK_SET;
96     lock.l_start = lock.l_len = 0;
97     if (fcntl(fd, F_SETLK, &lock) == -1) {
98         logerror("Can't lock %s (%s)", ep->file, strerror(errno));
99         close(fd);
100         return 0;
101     }
102
103     /* get file size */
104     fsiz = fsize(fd);
105     if (fsiz % ep->size) {
106         logerror("Can't open %s (file size not a multiple of record size %d)",
107                  ep->file, ep->size);
108         close(fd);
109         return 0;
110     }
111     ep->fids = fsiz / ep->size;
112     if (nelt >= 0 && nelt != ep->fids) {
113         logerror("Can't open %s (got %d records instead of %d)",
114                  ep->file, ep->fids, nelt);
115         close(fd);
116         return 0;
117     }
118
119     /* allocate cache */
120     if (ep->flags & EFF_STATIC) {
121         /* ep->cache already points to space for ep->csize elements */
122         if (how & EFF_MEM) {
123             if (ep->fids > ep->csize) {
124                 logerror("Can't open %s: file larger than %d bytes",
125                          ep->file, ep->fids * ep->size);
126                 close(fd);
127                 return 0;
128             }
129         }
130     } else {
131         if (CANT_HAPPEN(ep->cache))
132             free(ep->cache);
133         if (how & EFF_MEM)
134             nslots = ep->fids;
135         else
136             nslots = blksize(fd) / ep->size;
137         if (!ef_realloc_cache(ep, nslots)) {
138             logerror("Can't map %s (%s)", ep->file, strerror(errno));
139             close(fd);
140             return 0;
141         }
142     }
143     ep->baseid = 0;
144     ep->cids = 0;
145     ep->flags = (ep->flags & EFF_IMMUTABLE) | (how & ~EFF_CREATE);
146     ep->fd = fd;
147
148     /* map file into cache */
149     if ((how & EFF_MEM) && ep->fids) {
150         if (fillcache(ep, 0) != ep->fids) {
151             ep->cids = 0;       /* prevent cache flush */
152             ep->flags &= EFF_IMMUTABLE; /* maintain invariant */
153             ef_close(type);
154             return 0;
155         }
156     }
157
158     return 1;
159 }
160
161 /*
162  * Reallocate cache for table EP to hold COUNT slots.
163  * The table must not be allocated statically.
164  * The cache may still be unmapped.
165  * If reallocation succeeds, any pointers obtained from ef_ptr()
166  * become invalid.
167  * If it fails, the cache is unchanged, and errno is set.
168  * Return non-zero on success, zero on failure.
169  */
170 static int
171 ef_realloc_cache(struct empfile *ep, int count)
172 {
173     void *cache;
174
175     if (CANT_HAPPEN(ep->flags & EFF_STATIC))
176         return 0;
177     if (CANT_HAPPEN(count < 0))
178         count = 0;
179
180     /*
181      * Avoid zero slots, because that can lead to null cache, which
182      * would be interpreted as unmapped cache.
183      */
184     if (count == 0)
185         count++;
186     cache = realloc(ep->cache, count * ep->size);
187     if (!cache)
188         return 0;
189
190     ep->cache = cache;
191     ep->csize = count;
192     return 1;
193 }
194
195 /*
196  * Close the file-backed table TYPE (EF_SECTOR, ...).
197  * Return non-zero on success, zero on failure.
198  */
199 int
200 ef_close(int type)
201 {
202     struct empfile *ep;
203     int retval;
204
205     retval = ef_flush(type);
206     ep = &empfile[type];
207     ep->flags &= EFF_IMMUTABLE;
208     if (!(ep->flags & EFF_STATIC)) {
209         free(ep->cache);
210         ep->cache = NULL;
211     }
212     if (close(ep->fd) < 0) {
213         logerror("Error closing %s (%s)", ep->file, strerror(errno));
214         retval = 0;
215     }
216     ep->fd = -1;
217     return retval;
218 }
219
220 /*
221  * Flush table TYPE (EF_SECTOR, ...) to disk.
222  * Do nothing if the table is privately mapped.
223  * Update timestamps of written elements if table is EFF_TYPED.
224  * Return non-zero on success, zero on failure.
225  */
226 int
227 ef_flush(int type)
228 {
229     struct empfile *ep;
230
231     if (ef_check(type) < 0)
232         return 0;
233     ep = &empfile[type];
234     if (ep->flags & EFF_PRIVATE)
235         return 1;               /* nothing to do */
236     if (CANT_HAPPEN(ep->fd < 0))
237         return 0;
238     /*
239      * We don't know which cache entries are dirty.  ef_write() writes
240      * through, but direct updates through ef_ptr() don't.  They are
241      * allowed only with EFF_MEM.  Assume the whole cash is dirty
242      * then.
243      */
244     if (ep->flags & EFF_MEM) {
245         if (do_write(ep, ep->cache, ep->baseid, ep->cids) < 0)
246             return 0;
247     }
248
249     return 1;
250 }
251
252 /*
253  * Return pointer to element ID in table TYPE if it exists, else NULL.
254  * The table must be fully cached, i.e. flags & EFF_MEM.
255  * The caller is responsible for flushing changes he makes.
256  */
257 void *
258 ef_ptr(int type, int id)
259 {
260     struct empfile *ep;
261
262     if (ef_check(type) < 0)
263         return NULL;
264     ep = &empfile[type];
265     if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
266         return NULL;
267     if (id < 0 || id >= ep->fids)
268         return NULL;
269     return ep->cache + ep->size * id;
270 }
271
272 /*
273  * Read element ID from table TYPE into buffer INTO.
274  * FIXME pass buffer size!
275  * Return non-zero on success, zero on failure.
276  */
277 int
278 ef_read(int type, int id, void *into)
279 {
280     struct empfile *ep;
281     void *from;
282
283     if (ef_check(type) < 0)
284         return 0;
285     ep = &empfile[type];
286     if (CANT_HAPPEN(!ep->cache))
287         return 0;
288     if (id < 0 || id >= ep->fids)
289         return 0;
290
291     if (ep->flags & EFF_MEM) {
292         from = ep->cache + id * ep->size;
293     } else {
294         if (ep->baseid + ep->cids <= id || ep->baseid > id) {
295             if (fillcache(ep, id) < 1)
296                 return 0;
297         }
298         from = ep->cache + (id - ep->baseid) * ep->size;
299     }
300     memcpy(into, from, ep->size);
301
302     if (ep->postread)
303         ep->postread(id, into);
304     return 1;
305 }
306
307 /*
308  * Fill cache of file-backed EP with elements starting at ID.
309  * If any were read, return their number.
310  * Else return -1 and leave the cache unchanged.
311  */
312 static int
313 fillcache(struct empfile *ep, int id)
314 {
315     int ret;
316
317     if (CANT_HAPPEN(!ep->cache))
318         return -1;
319
320     ret = do_read(ep, ep->cache, id, MIN(ep->csize, ep->fids - id));
321     if (ret >= 0) {
322         /* cache changed */
323         ep->baseid = id;
324         ep->cids = ret;
325     }
326     return ret;
327 }
328
329 static int
330 do_read(struct empfile *ep, void *buf, int id, int count)
331 {
332     int n, ret;
333     char *p;
334
335     if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
336         return -1;
337
338     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
339         logerror("Error seeking %s to elt %d (%s)",
340                  ep->file, id, strerror(errno));
341         return -1;
342     }
343
344     p = buf;
345     n = count * ep->size;
346     while (n > 0) {
347         ret = read(ep->fd, p, n);
348         if (ret < 0) {
349             if (errno != EINTR) {
350                 logerror("Error reading %s elt %d (%s)",
351                          ep->file,
352                          id + (int)((p - (char *)buf) / ep->size),
353                          strerror(errno));
354                 break;
355             }
356         } else if (ret == 0) {
357             logerror("Unexpected EOF reading %s elt %d",
358                      ep->file, id + (int)((p - (char *)buf) / ep->size));
359             break;
360         } else {
361             p += ret;
362             n -= ret;
363         }
364     }
365
366     return (p - (char *)buf) / ep->size;
367 }
368
369 /*
370  * Write COUNT elements starting at ID from BUF to file-backed EP.
371  * Update the timestamp if the table is EFF_TYPED.
372  * Don't actually write if table is privately mapped.
373  * Return 0 on success, -1 on error (file may be corrupt then).
374  */
375 static int
376 do_write(struct empfile *ep, void *buf, int id, int count)
377 {
378     int i, n, ret;
379     char *p;
380     struct emptypedstr *elt;
381     time_t now;
382
383     if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
384         return -1;
385
386     if (ep->flags & EFF_TYPED) {
387         now = ep->flags & EFF_NOTIME ? (time_t)-1 : time(NULL);
388         for (i = 0; i < count; i++) {
389             /*
390              * TODO Oopses here could be due to bad data corruption.
391              * Fail instead of attempting to recover?
392              */
393             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
394             if (CANT_HAPPEN(elt->ef_type != ep->uid))
395                 elt->ef_type = ep->uid;
396             if (CANT_HAPPEN(elt->uid != id + i))
397                 elt->uid = id + i;
398             if (now != (time_t)-1)
399                 elt->timestamp = now;
400         }
401     }
402
403     if (ep->flags & EFF_PRIVATE)
404         return 0;
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 = write(ep->fd, p, n);
416         if (ret < 0) {
417             if (errno != EINTR) {
418                 logerror("Error writing %s elt %d (%s)",
419                          ep->file,
420                          id + (int)((p - (char *)buf) / ep->size),
421                          strerror(errno));
422                 return -1;
423             }
424         } else {
425             p += ret;
426             n -= ret;
427         }
428     }
429
430     return 0;
431 }
432
433 /*
434  * Write element ID into table TYPE from buffer FROM.
435  * FIXME pass buffer size!
436  * Update timestamp in FROM if table is EFF_TYPED.
437  * If table is file-backed and not privately mapped, write through
438  * cache straight to disk.
439  * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
440  * Can write at the end of partially cached table.
441  * Return non-zero on success, zero on failure.
442  */
443 int
444 ef_write(int type, int id, void *from)
445 {
446     struct empfile *ep;
447     char *to;
448
449     if (ef_check(type) < 0)
450         return 0;
451     ep = &empfile[type];
452     if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
453         return 0;
454     if (ep->prewrite)
455         ep->prewrite(id, from);
456     if (CANT_HAPPEN((ep->flags & EFF_MEM) ? id >= ep->fids : id > ep->fids))
457         return 0;               /* not implemented */
458     new_seqno(ep, from);
459     if (ep->fd >= 0) {
460         if (do_write(ep, from, id, 1) < 0)
461             return 0;
462     }
463     if (id >= ep->baseid && id < ep->baseid + ep->cids) {
464         /* update the cache if necessary */
465         to = ep->cache + (id - ep->baseid) * ep->size;
466         if (to != from)
467             memcpy(to, from, ep->size);
468     }
469     if (id >= ep->fids) {
470         /* write beyond end of file extends it, take note */
471         ep->fids = id + 1;
472     }
473     return 1;
474 }
475
476 /*
477  * Change element id.
478  * BUF is an element of table TYPE.
479  * ID is its new element ID.
480  * If table is EFF_TYPED, change id and sequence number stored in BUF.
481  * Else do nothing.
482  */
483 void
484 ef_set_uid(int type, void *buf, int uid)
485 {
486     struct emptypedstr *elt;
487     struct empfile *ep;
488
489     if (ef_check(type) < 0)
490         return;
491     ep = &empfile[type];
492     if (!(ep->flags & EFF_TYPED))
493         return;
494     elt = buf;
495     if (elt->uid == uid)
496         return;
497     elt->uid = uid;
498     elt->seqno = get_seqno(ep, uid);
499 }
500
501 /*
502  * Return sequence number of element ID in table EP.
503  * Return zero if table is not EFF_TYPED (it has no sequence number
504  * then).
505  */
506 static unsigned
507 get_seqno(struct empfile *ep, int id)
508 {
509     struct emptypedstr *elt;
510
511     if (!(ep->flags & EFF_TYPED))
512         return 0;
513     if (id < 0 || id >= ep->fids)
514         return 0;
515     if (id >= ep->baseid && id < ep->baseid + ep->cids)
516         elt = (void *)(ep->cache + (id - ep->baseid) * ep->size);
517     else {
518         /* need a buffer, steal last cache slot */
519         if (ep->cids == ep->csize)
520             ep->cids--;
521         elt = (void *)(ep->cache + ep->cids * ep->size);
522         if (do_read(ep, elt, id, 1) < 0)
523             return 0;           /* deep trouble */
524     }
525     return elt->seqno;
526 }
527
528 /*
529  * Increment sequence number in BUF, which is about to be written to EP.
530  * Do nothing if table is not EFF_TYPED (it has no sequence number
531  * then).
532  */
533 static void
534 new_seqno(struct empfile *ep, void *buf)
535 {
536     struct emptypedstr *elt = buf;
537     unsigned old_seqno;
538
539     if (!(ep->flags & EFF_TYPED))
540         return;
541     old_seqno = get_seqno(ep, elt->uid);
542     if (CANT_HAPPEN(old_seqno != elt->seqno))
543         old_seqno = MAX(old_seqno, elt->seqno);
544     elt->seqno = old_seqno + 1;
545 }
546
547 /*
548  * Extend table TYPE by COUNT elements.
549  * Any pointers obtained from ef_ptr() become invalid.
550  * Return non-zero on success, zero on failure.
551  */
552 int
553 ef_extend(int type, int count)
554 {
555     struct empfile *ep;
556     char *p;
557     int need_sentinel, i, id;
558
559     if (ef_check(type) < 0)
560         return 0;
561     ep = &empfile[type];
562     if (CANT_HAPPEN(count < 0))
563         return 0;
564
565     id = ep->fids;
566     if (ep->flags & EFF_MEM) {
567         need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
568         if (id + count + need_sentinel > ep->csize) {
569             if (ep->flags & EFF_STATIC) {
570                 logerror("Can't extend %s beyond %d elements",
571                          ep->name, ep->csize - need_sentinel);
572                 return 0;
573             }
574             if (!ef_realloc_cache(ep, id + count + need_sentinel)) {
575                 logerror("Can't extend %s to %d elements (%s)",
576                          ep->name, id + count, strerror(errno));
577                 return 0;
578             }
579         }
580         p = ep->cache + id * ep->size;
581         do_blank(ep, p, id, count);
582         if (ep->fd >= 0) {
583             if (do_write(ep, p, id, count) < 0)
584                 return 0;
585         }
586         if (need_sentinel)
587             memset(ep->cache + (id + count) * ep->size, 0, ep->size);
588         ep->cids = id + count;
589     } else {
590         /* need a buffer, steal last cache slot */
591         if (ep->cids == ep->csize)
592             ep->cids--;
593         p = ep->cache + ep->cids * ep->size;
594         for (i = 0; i < count; i++) {
595             do_blank(ep, p, id + i, 1);
596             if (do_write(ep, p, id + i, 1) < 0)
597                 return 0;
598         }
599     }
600     ep->fids = id + count;
601     return 1;
602 }
603
604 /*
605  * Initialize element ID for EP in BUF.
606  * FIXME pass buffer size!
607  */
608 void
609 ef_blank(int type, int id, void *buf)
610 {
611     struct empfile *ep;
612     struct emptypedstr *elt;
613
614     if (ef_check(type) < 0)
615         return;
616     ep = &empfile[type];
617     do_blank(ep, buf, id, 1);
618     if (ep->flags & EFF_TYPED) {
619         elt = buf;
620         elt->seqno = get_seqno(ep, elt->uid);
621     }
622 }
623
624 /*
625  * Initialize COUNT elements of EP in BUF, starting with element ID.
626  */
627 static void
628 do_blank(struct empfile *ep, void *buf, int id, int count)
629 {
630     int i;
631     struct emptypedstr *elt;
632
633     memset(buf, 0, count * ep->size);
634     if (ep->flags & EFF_TYPED) {
635         for (i = 0; i < count; i++) {
636             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
637             elt->ef_type = ep->uid;
638             elt->uid = id + i;
639         }
640     }
641 }
642
643 /*
644  * Truncate table TYPE to COUNT elements.
645  * Any pointers obtained from ef_ptr() become invalid.
646  * Return non-zero on success, zero on failure.
647  */
648 int
649 ef_truncate(int type, int count)
650 {
651     struct empfile *ep;
652     int need_sentinel;
653
654     if (ef_check(type) < 0)
655         return 0;
656     ep = &empfile[type];
657     if (CANT_HAPPEN(count < 0 || count > ep->fids))
658         return 0;
659
660     if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
661         if (ftruncate(ep->fd, count * ep->size) < 0) {
662             logerror("Can't truncate %s to %d elements (%s)",
663                      ep->file, count, strerror(errno));
664             return 0;
665         }
666     }
667     ep->fids = count;
668
669     if (ep->flags & EFF_MEM) {
670         need_sentinel = (ep->flags & EFF_SENTINEL) != 0;
671         if (!(ep->flags & EFF_STATIC)) {
672             if (!ef_realloc_cache(ep, count + need_sentinel)) {
673                 logerror("Can't shrink %s cache after truncate (%s)",
674                          ep->name, strerror(errno));
675                 /* continue with unshrunk cache */
676             }
677         }
678         if (need_sentinel)
679             memset(ep->cache + count * ep->size, 0, ep->size);
680         ep->cids = count;
681     } else {
682         if (ep->baseid >= count)
683             ep->cids = 0;
684         else if (ep->cids > count - ep->baseid)
685             ep->cids = count - ep->baseid;
686     }
687
688     return 1;
689 }
690
691 struct castr *
692 ef_cadef(int type)
693 {
694     return empfile[type].cadef;
695 }
696
697 int
698 ef_nelem(int type)
699 {
700     return empfile[type].fids;
701 }
702
703 int
704 ef_flags(int type)
705 {
706     return empfile[type].flags;
707 }
708
709 time_t
710 ef_mtime(int type)
711 {
712     if (empfile[type].fd <= 0)
713         return 0;
714     return fdate(empfile[type].fd);
715 }
716
717 /*
718  * Search for a table matching NAME, return its table type.
719  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
720  * several.
721  */
722 int
723 ef_byname(char *name)
724 {
725     return stmtch(name, empfile, offsetof(struct empfile, name),
726                   sizeof(empfile[0]));
727 }
728
729 /*
730  * Search CHOICES[] for a table type matching NAME, return it.
731  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
732  * several.
733  * CHOICES[] must be terminated with a negative value.
734  */
735 int
736 ef_byname_from(char *name, int choices[])
737 {
738     int res;
739     int *p;
740
741     res = M_NOTFOUND;
742     for (p = choices; *p >= 0; p++) {
743         if (ef_check(*p) < 0)
744             continue;
745         switch (mineq(name, empfile[*p].name)) {
746         case ME_MISMATCH:
747             break;
748         case ME_PARTIAL:
749             if (res >= 0)
750                 return M_NOTUNIQUE;
751             res = *p;
752             break;
753         case ME_EXACT:
754             return *p;
755         }
756     }
757     return res;
758 }
759
760 char *
761 ef_nameof(int type)
762 {
763     if (ef_check(type) < 0)
764         return "bad ef_type";
765     return empfile[type].name;
766 }
767
768 int
769 ef_check(int type)
770 {
771     if (CANT_HAPPEN((unsigned)type >= EF_MAX))
772         return -1;
773     return 0;
774 }
775
776 /*
777  * Ensure table contains element ID.
778  * If necessary, extend it in steps of COUNT elements.
779  * Return non-zero on success, zero on failure.
780  */
781 int
782 ef_ensure_space(int type, int id, int count)
783 {
784     if (ef_check(type) < 0)
785         return 0;
786     CANT_HAPPEN(id < 0);
787
788     while (id >= empfile[type].fids) {
789         if (!ef_extend(type, count))
790             return 0;
791     }
792     return 1;
793 }