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