]> git.pond.sub.org Git - empserver/blob - src/lib/common/file.c
Fix/improve logging in ef_close(), ef_extend(), ef_truncate()
[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 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         if (id + count > ep->csize) {
568             if (ep->flags & EFF_STATIC) {
569                 logerror("Can't extend %s beyond %d elements",
570                          ep->name, ep->csize);
571                 return 0;
572             }
573             if (!ef_realloc_cache(ep, id + count)) {
574                 logerror("Can't extend %s to %d elements (%s)",
575                          ep->name, id + count, strerror(errno));
576                 return 0;
577             }
578         }
579         p = ep->cache + id * ep->size;
580         do_blank(ep, p, id, count);
581         if (ep->fd >= 0) {
582             if (do_write(ep, p, id, count) < 0)
583                 return 0;
584         }
585         ep->cids += count;
586     } else {
587         /* need a buffer, steal last cache slot */
588         if (ep->cids == ep->csize)
589             ep->cids--;
590         p = ep->cache + ep->cids * ep->size;
591         for (i = 0; i < count; i++) {
592             do_blank(ep, p, id + i, 1);
593             if (do_write(ep, p, id + i, 1) < 0)
594                 return 0;
595         }
596     }
597     ep->fids += count;
598     return 1;
599 }
600
601 /*
602  * Initialize element ID for EP in BUF.
603  * FIXME pass buffer size!
604  */
605 void
606 ef_blank(int type, int id, void *buf)
607 {
608     struct empfile *ep;
609     struct emptypedstr *elt;
610
611     if (ef_check(type) < 0)
612         return;
613     ep = &empfile[type];
614     do_blank(ep, buf, id, 1);
615     if (ep->flags & EFF_TYPED) {
616         elt = buf;
617         elt->seqno = get_seqno(ep, elt->uid);
618     }
619 }
620
621 /*
622  * Initialize COUNT elements of EP in BUF, starting with element ID.
623  */
624 static void
625 do_blank(struct empfile *ep, void *buf, int id, int count)
626 {
627     int i;
628     struct emptypedstr *elt;
629
630     memset(buf, 0, count * ep->size);
631     if (ep->flags & EFF_TYPED) {
632         for (i = 0; i < count; i++) {
633             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
634             elt->ef_type = ep->uid;
635             elt->uid = id + i;
636         }
637     }
638 }
639
640 /*
641  * Truncate table TYPE to COUNT elements.
642  * Any pointers obtained from ef_ptr() become invalid.
643  * Return non-zero on success, zero on failure.
644  */
645 int
646 ef_truncate(int type, int count)
647 {
648     struct empfile *ep;
649
650     if (ef_check(type) < 0)
651         return 0;
652     ep = &empfile[type];
653     if (CANT_HAPPEN(count < 0 || count > ep->fids))
654         return 0;
655
656     if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
657         if (ftruncate(ep->fd, count * ep->size) < 0) {
658             logerror("Can't truncate %s to %d elements (%s)",
659                      ep->file, count, strerror(errno));
660             return 0;
661         }
662     }
663     ep->fids = count;
664
665     if (ep->flags & EFF_MEM) {
666         if (!(ep->flags & EFF_STATIC)) {
667             if (!ef_realloc_cache(ep, count)) {
668                 logerror("Can't shrink %s cache after truncate (%s)",
669                          ep->name, strerror(errno));
670                 /* continue with unshrunk cache */
671             }
672         }
673         ep->cids = count;
674     } else {
675         if (ep->baseid >= count)
676             ep->cids = 0;
677         else if (ep->cids > count - ep->baseid)
678             ep->cids = count - ep->baseid;
679     }
680
681     return 1;
682 }
683
684 struct castr *
685 ef_cadef(int type)
686 {
687     return empfile[type].cadef;
688 }
689
690 int
691 ef_nelem(int type)
692 {
693     return empfile[type].fids;
694 }
695
696 int
697 ef_flags(int type)
698 {
699     return empfile[type].flags;
700 }
701
702 time_t
703 ef_mtime(int type)
704 {
705     if (empfile[type].fd <= 0)
706         return 0;
707     return fdate(empfile[type].fd);
708 }
709
710 /*
711  * Search for a table matching NAME, return its table type.
712  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
713  * several.
714  */
715 int
716 ef_byname(char *name)
717 {
718     return stmtch(name, empfile, offsetof(struct empfile, name),
719                   sizeof(empfile[0]));
720 }
721
722 /*
723  * Search CHOICES[] for a table type matching NAME, return it.
724  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
725  * several.
726  * CHOICES[] must be terminated with a negative value.
727  */
728 int
729 ef_byname_from(char *name, int choices[])
730 {
731     int res;
732     int *p;
733
734     res = M_NOTFOUND;
735     for (p = choices; *p >= 0; p++) {
736         if (ef_check(*p) < 0)
737             continue;
738         switch (mineq(name, empfile[*p].name)) {
739         case ME_MISMATCH:
740             break;
741         case ME_PARTIAL:
742             if (res >= 0)
743                 return M_NOTUNIQUE;
744             res = *p;
745             break;
746         case ME_EXACT:
747             return *p;
748         }
749     }
750     return res;
751 }
752
753 char *
754 ef_nameof(int type)
755 {
756     if (ef_check(type) < 0)
757         return "bad ef_type";
758     return empfile[type].name;
759 }
760
761 int
762 ef_check(int type)
763 {
764     if (CANT_HAPPEN((unsigned)type >= EF_MAX))
765         return -1;
766     return 0;
767 }
768
769 /*
770  * Ensure table contains element ID.
771  * If necessary, extend it in steps of COUNT elements.
772  * Return non-zero on success, zero on failure.
773  */
774 int
775 ef_ensure_space(int type, int id, int count)
776 {
777     if (ef_check(type) < 0)
778         return 0;
779     CANT_HAPPEN(id < 0);
780
781     while (id >= empfile[type].fids) {
782         if (!ef_extend(type, count))
783             return 0;
784     }
785     return 1;
786 }