]> git.pond.sub.org Git - empserver/blob - src/lib/common/file.c
Make server check game state file sizes on startup
[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_write(struct empfile *, void *, int, int, time_t);
52 static void do_blank(struct empfile *, void *, int, int);
53
54 /*
55  * Open the file-backed table TYPE (EF_SECTOR, ...).
56  * HOW are flags to control operation.  Naturally, immutable flags are
57  * not permitted.
58  * If NELT is non-negative, the table must have that many elements.
59  * Return non-zero on success, zero on failure.
60  * You must call ef_close() before the next ef_open().
61  */
62 int
63 ef_open(int type, int how, int nelt)
64 {
65     struct empfile *ep;
66     struct flock lock;
67     int oflags, fd, fsiz, nslots;
68
69     if (ef_check(type) < 0)
70         return 0;
71     if (CANT_HAPPEN(how & EFF_IMMUTABLE))
72         how &= ~EFF_IMMUTABLE;
73
74     /* open file */
75     ep = &empfile[type];
76     if (CANT_HAPPEN(ep->fd >= 0))
77         return 0;
78     oflags = O_RDWR;
79     if (how & EFF_PRIVATE)
80         oflags = O_RDONLY;
81     if (how & EFF_CREATE)
82         oflags |= O_CREAT | O_TRUNC;
83 #if defined(_WIN32)
84     oflags |= O_BINARY;
85 #endif
86     if ((fd = open(ep->file, oflags, S_IRWUG)) < 0) {
87         logerror("Can't open %s (%s)", ep->file, strerror(errno));
88         return 0;
89     }
90
91     lock.l_type = how & EFF_PRIVATE ? F_RDLCK : F_WRLCK;
92     lock.l_whence = SEEK_SET;
93     lock.l_start = lock.l_len = 0;
94     if (fcntl(fd, F_SETLK, &lock) == -1) {
95         logerror("Can't lock %s (%s)", ep->file, strerror(errno));
96         close(fd);
97         return 0;
98     }
99
100     /* get file size */
101     fsiz = fsize(fd);
102     if (fsiz % ep->size) {
103         logerror("Can't open %s (file size not a multiple of record size %d)",
104                  ep->file, ep->size);
105         close(fd);
106         return 0;
107     }
108     ep->fids = fsiz / ep->size;
109     if (nelt >= 0 && nelt != ep->fids) {
110         logerror("Can't open %s (got %d records instead of %d)",
111                  ep->file, ep->fids, nelt);
112         close(fd);
113         return 0;
114     }
115
116     /* allocate cache */
117     if (ep->flags & EFF_STATIC) {
118         /* ep->cache already points to space for ep->csize elements */
119         if (how & EFF_MEM) {
120             if (ep->fids > ep->csize) {
121                 logerror("Can't open %s: file larger than %d bytes",
122                          ep->file, ep->fids * ep->size);
123                 close(fd);
124                 return 0;
125             }
126         }
127     } else {
128         if (CANT_HAPPEN(ep->cache))
129             free(ep->cache);
130         if (how & EFF_MEM)
131             nslots = ep->fids;
132         else
133             nslots = blksize(fd) / ep->size;
134         if (!ef_realloc_cache(ep, nslots)) {
135             logerror("Can't map %s (%s)", ep->file, strerror(errno));
136             close(fd);
137             return 0;
138         }
139     }
140     ep->baseid = 0;
141     ep->cids = 0;
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) && ep->fids) {
147         if (fillcache(ep, 0) != ep->fids) {
148             ep->cids = 0;       /* prevent cache flush */
149             ep->flags &= EFF_IMMUTABLE; /* maintain invariant */
150             ef_close(type);
151             return 0;
152         }
153     }
154
155     return 1;
156 }
157
158 /*
159  * Reallocate cache for table EP to hold COUNT slots.
160  * The table must not be allocated statically.
161  * The cache may still be unmapped.
162  * If reallocation succeeds, any pointers obtained from ef_ptr()
163  * become invalid.
164  * If it fails, the cache is unchanged, and errno is set.
165  * Return non-zero on success, zero on failure.
166  */
167 static int
168 ef_realloc_cache(struct empfile *ep, int count)
169 {
170     void *cache;
171
172     if (CANT_HAPPEN(ep->flags & EFF_STATIC))
173         return 0;
174     if (CANT_HAPPEN(count < 0))
175         count = 0;
176
177     /*
178      * Avoid zero slots, because that can lead to null cache, which
179      * would be interpreted as unmapped cache.
180      */
181     if (count == 0)
182         count++;
183     cache = realloc(ep->cache, count * ep->size);
184     if (!cache)
185         return 0;
186
187     ep->cache = cache;
188     ep->csize = count;
189     return 1;
190 }
191
192 /*
193  * Close the file-backed table TYPE (EF_SECTOR, ...).
194  * Return non-zero on success, zero on failure.
195  */
196 int
197 ef_close(int type)
198 {
199     struct empfile *ep;
200     int retval;
201
202     retval = ef_flush(type);
203     ep = &empfile[type];
204     ep->flags &= EFF_IMMUTABLE;
205     if (!(ep->flags & EFF_STATIC)) {
206         free(ep->cache);
207         ep->cache = NULL;
208     }
209     if (close(ep->fd) < 0) {
210         logerror("Error closing %s (%s)", ep->name, strerror(errno));
211         retval = 0;
212     }
213     ep->fd = -1;
214     return retval;
215 }
216
217 /*
218  * Flush table TYPE (EF_SECTOR, ...) to disk.
219  * Does nothing if the table is privately mapped.
220  * Return non-zero on success, zero on failure.
221  */
222 int
223 ef_flush(int type)
224 {
225     struct empfile *ep;
226
227     if (ef_check(type) < 0)
228         return 0;
229     ep = &empfile[type];
230     if (ep->flags & EFF_PRIVATE)
231         return 1;               /* nothing to do */
232     if (CANT_HAPPEN(ep->fd < 0))
233         return 0;
234     /*
235      * We don't know which cache entries are dirty.  ef_write() writes
236      * through, but direct updates through ef_ptr() don't.  They are
237      * allowed only with EFF_MEM.  Assume the whole cash is dirty
238      * then.
239      */
240     if (ep->flags & EFF_MEM) {
241         if (do_write(ep, ep->cache, ep->baseid, ep->cids, time(NULL)) < 0)
242             return 0;
243     }
244
245     return 1;
246 }
247
248 /*
249  * Return pointer to element ID in table TYPE if it exists, else NULL.
250  * The table must be fully cached, i.e. flags & EFF_MEM.
251  * The caller is responsible for flushing changes he makes.
252  */
253 void *
254 ef_ptr(int type, int id)
255 {
256     struct empfile *ep;
257
258     if (ef_check(type) < 0)
259         return NULL;
260     ep = &empfile[type];
261     if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
262         return NULL;
263     if (id < 0 || id >= ep->fids)
264         return NULL;
265     return ep->cache + ep->size * id;
266 }
267
268 /*
269  * Read element ID from table TYPE into buffer INTO.
270  * FIXME pass buffer size!
271  * Return non-zero on success, zero on failure.
272  */
273 int
274 ef_read(int type, int id, void *into)
275 {
276     struct empfile *ep;
277     void *from;
278
279     if (ef_check(type) < 0)
280         return 0;
281     ep = &empfile[type];
282     if (CANT_HAPPEN(!ep->cache))
283         return 0;
284     if (id < 0 || id >= ep->fids)
285         return 0;
286
287     if (ep->flags & EFF_MEM) {
288         from = ep->cache + id * ep->size;
289     } else {
290         if (ep->baseid + ep->cids <= id || ep->baseid > id) {
291             if (fillcache(ep, id) < 1)
292                 return 0;
293         }
294         from = ep->cache + (id - ep->baseid) * ep->size;
295     }
296     memcpy(into, from, ep->size);
297
298     if (ep->postread)
299         ep->postread(id, into);
300     return 1;
301 }
302
303 /*
304  * Fill cache of file-backed EP with elements starting at ID.
305  * If any were read, return their number.
306  * Else return -1 and leave the cache unchanged.
307  */
308 static int
309 fillcache(struct empfile *ep, int id)
310 {
311     int n, ret;
312     char *p;
313
314     if (CANT_HAPPEN(ep->fd < 0 || !ep->cache))
315         return -1;
316
317     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
318         logerror("Error seeking %s to elt %d (%s)",
319                  ep->file, id, strerror(errno));
320         return -1;
321     }
322
323     p = ep->cache;
324     n = MIN(ep->csize, ep->fids - id) * ep->size;
325     while (n > 0) {
326         ret = read(ep->fd, p, n);
327         if (ret < 0) {
328             if (errno != EINTR) {
329                 logerror("Error reading %s elt %d (%s)",
330                          ep->file,
331                          id + (int)((p - ep->cache) / ep->size),
332                          strerror(errno));
333                 break;
334             }
335         } else if (ret == 0) {
336             logerror("Unexpected EOF reading %s elt %d",
337                      ep->file, id + (int)((p - ep->cache) / ep->size));
338             break;
339         } else {
340             p += ret;
341             n -= ret;
342         }
343     }
344
345     if (p == ep->cache)
346         return -1;              /* nothing read, old cache still ok */
347
348     ep->baseid = id;
349     ep->cids = (p - ep->cache) / ep->size;
350     return ep->cids;
351 }
352
353 /*
354  * Write COUNT elements starting at ID from BUF to file-backed EP.
355  * Set the timestamp to NOW if the table has those.
356  * Return 0 on success, -1 on error (file may be corrupt then).
357  */
358 static int
359 do_write(struct empfile *ep, void *buf, int id, int count, time_t now)
360 {
361     int i, n, ret;
362     char *p;
363     struct emptypedstr *elt;
364
365     if (CANT_HAPPEN(ep->fd < 0 || (ep->flags & EFF_PRIVATE)
366                     || id < 0 || count < 0))
367         return -1;
368
369     if (ep->flags & EFF_TYPED) {
370         for (i = 0; i < count; i++) {
371             /*
372              * TODO Oopses here could be due to bad data corruption.
373              * Fail instead of attempting to recover?
374              */
375             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
376             if (CANT_HAPPEN(elt->ef_type != ep->uid))
377                 elt->ef_type = ep->uid;
378             if (CANT_HAPPEN(elt->uid != id + i))
379                 elt->uid = id + i;
380             elt->timestamp = now;
381         }
382     }
383
384     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
385         logerror("Error seeking %s to elt %d (%s)",
386                  ep->file, id, strerror(errno));
387         return -1;
388     }
389
390     p = buf;
391     n = count * ep->size;
392     while (n > 0) {
393         ret = write(ep->fd, p, n);
394         if (ret < 0) {
395             if (errno != EINTR) {
396                 logerror("Error writing %s elt %d (%s)",
397                          ep->file,
398                          id + (int)((p - (char *)buf) / ep->size),
399                          strerror(errno));
400                 return -1;
401             }
402         } else {
403             p += ret;
404             n -= ret;
405         }
406     }
407
408     return 0;
409 }
410
411 /*
412  * Write element ID into table TYPE from buffer FROM.
413  * FIXME pass buffer size!
414  * If table is file-backed and not privately mapped, write through
415  * cache straight to disk.
416  * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
417  * Can write at the end of partially cached table.
418  * Return non-zero on success, zero on failure.
419  */
420 int
421 ef_write(int type, int id, void *from)
422 {
423     struct empfile *ep;
424     char *to;
425
426     if (ef_check(type) < 0)
427         return 0;
428     ep = &empfile[type];
429     if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
430         return 0;
431     if (ep->prewrite)
432         ep->prewrite(id, from);
433     if (CANT_HAPPEN((ep->flags & EFF_MEM) ? id >= ep->fids : id > ep->fids))
434         return 0;               /* not implemented */
435     if (!(ep->flags & EFF_PRIVATE)) {
436         if (do_write(ep, from, id, 1, time(NULL)) < 0)
437             return 0;
438     }
439     if (id >= ep->baseid && id < ep->baseid + ep->cids) {
440         /* update the cache if necessary */
441         to = ep->cache + (id - ep->baseid) * ep->size;
442         if (to != from)
443             memcpy(to, from, ep->size);
444     }
445     if (id >= ep->fids) {
446         /* write beyond end of file extends it, take note */
447         ep->fids = id + 1;
448     }
449     return 1;
450 }
451
452 /*
453  * Extend table TYPE by COUNT elements.
454  * Any pointers obtained from ef_ptr() become invalid.
455  * Return non-zero on success, zero on failure.
456  */
457 int
458 ef_extend(int type, int count)
459 {
460     struct empfile *ep;
461     char *p;
462     int i, id;
463     time_t now = time(NULL);
464
465     if (ef_check(type) < 0)
466         return 0;
467     ep = &empfile[type];
468     if (CANT_HAPPEN(count < 0))
469         return 0;
470
471     id = ep->fids;
472     if (ep->flags & EFF_MEM) {
473         if (id + count > ep->csize) {
474             if (ep->flags & EFF_STATIC) {
475                 logerror("Can't extend %s beyond %d elements",
476                          ep->file, ep->csize);
477                 return 0;
478             }
479             if (!ef_realloc_cache(ep, id + count)) {
480                 logerror("Can't extend %s to %d elements (%s)",
481                          ep->file, id + count, strerror(errno));
482                 return 0;
483             }
484         }
485         p = ep->cache + id * ep->size;
486         do_blank(ep, p, id, count);
487         if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
488             if (do_write(ep, p, id, count, now) < 0)
489                 return 0;
490         }
491         ep->cids += count;
492     } else {
493         /* need a buffer, steal last cache slot */
494         if (ep->cids == ep->csize)
495             ep->cids--;
496         p = ep->cache + ep->cids * ep->size;
497         for (i = 0; i < count; i++) {
498             do_blank(ep, p, id + i, 1);
499             if (do_write(ep, p, id + i, 1, now) < 0)
500                 return 0;
501         }
502     }
503     ep->fids += count;
504     return 1;
505 }
506
507 /*
508  * Initialize element ID for EP in BUF.
509  * FIXME pass buffer size!
510  */
511 void
512 ef_blank(int type, int id, void *buf)
513 {
514     if (ef_check(type) < 0)
515         return;
516     do_blank(&empfile[type], buf, id, 1);
517 }
518
519 /*
520  * Initialize COUNT elements of EP in BUF, starting with element ID.
521  */
522 static void
523 do_blank(struct empfile *ep, void *buf, int id, int count)
524 {
525     int i;
526     struct emptypedstr *elt;
527
528     memset(buf, 0, count * ep->size);
529     if (ep->flags & EFF_TYPED) {
530         for (i = 0; i < count; i++) {
531             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
532             elt->ef_type = ep->uid;
533             elt->uid = id + i;
534         }
535     }
536 }
537
538 /*
539  * Truncate table TYPE to COUNT elements.
540  * Any pointers obtained from ef_ptr() become invalid.
541  * Return non-zero on success, zero on failure.
542  */
543 int
544 ef_truncate(int type, int count)
545 {
546     struct empfile *ep;
547
548     if (ef_check(type) < 0)
549         return 0;
550     ep = &empfile[type];
551     if (CANT_HAPPEN(count < 0 || count > ep->fids))
552         return 0;
553
554     if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
555         if (ftruncate(ep->fd, count * ep->size) < 0) {
556             logerror("Can't truncate %s to %d elements (%s)",
557                      ep->file, count, strerror(errno));
558             return 0;
559         }
560     }
561     ep->fids = count;
562
563     if (ep->flags & EFF_MEM) {
564         if (!(ep->flags & EFF_STATIC)) {
565             if (!ef_realloc_cache(ep, count)) {
566                 logerror("Can't shrink cache after truncate");
567                 /* continue with unshrunk cache */
568             }
569         }
570         ep->cids = count;
571     } else {
572         if (ep->baseid >= count)
573             ep->cids = 0;
574         else if (ep->cids > count - ep->baseid)
575             ep->cids = count - ep->baseid;
576     }
577
578     return 1;
579 }
580
581 struct castr *
582 ef_cadef(int type)
583 {
584     return empfile[type].cadef;
585 }
586
587 int
588 ef_nelem(int type)
589 {
590     return empfile[type].fids;
591 }
592
593 int
594 ef_flags(int type)
595 {
596     return empfile[type].flags;
597 }
598
599 time_t
600 ef_mtime(int type)
601 {
602     if (empfile[type].fd <= 0)
603         return 0;
604     return fdate(empfile[type].fd);
605 }
606
607 /*
608  * Search for a table matching NAME, return its table type.
609  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
610  * several.
611  */
612 int
613 ef_byname(char *name)
614 {
615     return stmtch(name, empfile, offsetof(struct empfile, name),
616                   sizeof(empfile[0]));
617 }
618
619 /*
620  * Search CHOICES[] for a table type matching NAME, return it.
621  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
622  * several.
623  * CHOICES[] must be terminated with a negative value.
624  */
625 int
626 ef_byname_from(char *name, int choices[])
627 {
628     int res;
629     int *p;
630
631     res = M_NOTFOUND;
632     for (p = choices; *p >= 0; p++) {
633         if (ef_check(*p) < 0)
634             continue;
635         switch (mineq(name, empfile[*p].name)) {
636         case ME_MISMATCH:
637             break;
638         case ME_PARTIAL:
639             if (res >= 0)
640                 return M_NOTUNIQUE;
641             res = *p;
642             break;
643         case ME_EXACT:
644             return *p;
645         }
646     }
647     return res;
648 }
649
650 char *
651 ef_nameof(int type)
652 {
653     if (ef_check(type) < 0)
654         return "bad ef_type";
655     return empfile[type].name;
656 }
657
658 int
659 ef_check(int type)
660 {
661     if (CANT_HAPPEN((unsigned)type >= EF_MAX))
662         return -1;
663     return 0;
664 }
665
666 /*
667  * Ensure file-backed table contains ID.
668  * If necessary, extend it in steps of COUNT elements.
669  * Return non-zero on success, zero on failure.
670  */
671 int
672 ef_ensure_space(int type, int id, int count)
673 {
674     if (ef_check(type) < 0)
675         return 0;
676     CANT_HAPPEN(id < 0);
677
678     while (id >= empfile[type].fids) {
679         if (!ef_extend(type, count))
680             return 0;
681     }
682     return 1;
683 }