]> git.pond.sub.org Git - empserver/blob - src/lib/common/file.c
Update timestamps in privately mapped tables, too
[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  * Do nothing if the table is privately mapped.
220  * Update timestamps of written elements if table is EFF_TYPED.
221  * Return non-zero on success, zero on failure.
222  */
223 int
224 ef_flush(int type)
225 {
226     struct empfile *ep;
227
228     if (ef_check(type) < 0)
229         return 0;
230     ep = &empfile[type];
231     if (ep->flags & EFF_PRIVATE)
232         return 1;               /* nothing to do */
233     if (CANT_HAPPEN(ep->fd < 0))
234         return 0;
235     /*
236      * We don't know which cache entries are dirty.  ef_write() writes
237      * through, but direct updates through ef_ptr() don't.  They are
238      * allowed only with EFF_MEM.  Assume the whole cash is dirty
239      * then.
240      */
241     if (ep->flags & EFF_MEM) {
242         if (do_write(ep, ep->cache, ep->baseid, ep->cids, time(NULL)) < 0)
243             return 0;
244     }
245
246     return 1;
247 }
248
249 /*
250  * Return pointer to element ID in table TYPE if it exists, else NULL.
251  * The table must be fully cached, i.e. flags & EFF_MEM.
252  * The caller is responsible for flushing changes he makes.
253  */
254 void *
255 ef_ptr(int type, int id)
256 {
257     struct empfile *ep;
258
259     if (ef_check(type) < 0)
260         return NULL;
261     ep = &empfile[type];
262     if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
263         return NULL;
264     if (id < 0 || id >= ep->fids)
265         return NULL;
266     return ep->cache + ep->size * id;
267 }
268
269 /*
270  * Read element ID from table TYPE into buffer INTO.
271  * FIXME pass buffer size!
272  * Return non-zero on success, zero on failure.
273  */
274 int
275 ef_read(int type, int id, void *into)
276 {
277     struct empfile *ep;
278     void *from;
279
280     if (ef_check(type) < 0)
281         return 0;
282     ep = &empfile[type];
283     if (CANT_HAPPEN(!ep->cache))
284         return 0;
285     if (id < 0 || id >= ep->fids)
286         return 0;
287
288     if (ep->flags & EFF_MEM) {
289         from = ep->cache + id * ep->size;
290     } else {
291         if (ep->baseid + ep->cids <= id || ep->baseid > id) {
292             if (fillcache(ep, id) < 1)
293                 return 0;
294         }
295         from = ep->cache + (id - ep->baseid) * ep->size;
296     }
297     memcpy(into, from, ep->size);
298
299     if (ep->postread)
300         ep->postread(id, into);
301     return 1;
302 }
303
304 /*
305  * Fill cache of file-backed EP with elements starting at ID.
306  * If any were read, return their number.
307  * Else return -1 and leave the cache unchanged.
308  */
309 static int
310 fillcache(struct empfile *ep, int id)
311 {
312     int n, ret;
313     char *p;
314
315     if (CANT_HAPPEN(ep->fd < 0 || !ep->cache))
316         return -1;
317
318     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
319         logerror("Error seeking %s to elt %d (%s)",
320                  ep->file, id, strerror(errno));
321         return -1;
322     }
323
324     p = ep->cache;
325     n = MIN(ep->csize, ep->fids - id) * ep->size;
326     while (n > 0) {
327         ret = read(ep->fd, p, n);
328         if (ret < 0) {
329             if (errno != EINTR) {
330                 logerror("Error reading %s elt %d (%s)",
331                          ep->file,
332                          id + (int)((p - ep->cache) / ep->size),
333                          strerror(errno));
334                 break;
335             }
336         } else if (ret == 0) {
337             logerror("Unexpected EOF reading %s elt %d",
338                      ep->file, id + (int)((p - ep->cache) / ep->size));
339             break;
340         } else {
341             p += ret;
342             n -= ret;
343         }
344     }
345
346     if (p == ep->cache)
347         return -1;              /* nothing read, old cache still ok */
348
349     ep->baseid = id;
350     ep->cids = (p - ep->cache) / ep->size;
351     return ep->cids;
352 }
353
354 /*
355  * Write COUNT elements starting at ID from BUF to file-backed EP.
356  * Set the timestamp to NOW if the table is EFF_TYPED.
357  * Don't actually write if table is privately mapped.
358  * Return 0 on success, -1 on error (file may be corrupt then).
359  */
360 static int
361 do_write(struct empfile *ep, void *buf, int id, int count, time_t now)
362 {
363     int i, n, ret;
364     char *p;
365     struct emptypedstr *elt;
366
367     if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
368         return -1;
369
370     if (ep->flags & EFF_TYPED) {
371         for (i = 0; i < count; i++) {
372             /*
373              * TODO Oopses here could be due to bad data corruption.
374              * Fail instead of attempting to recover?
375              */
376             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
377             if (CANT_HAPPEN(elt->ef_type != ep->uid))
378                 elt->ef_type = ep->uid;
379             if (CANT_HAPPEN(elt->uid != id + i))
380                 elt->uid = id + i;
381             elt->timestamp = now;
382         }
383     }
384
385     if (ep->flags & EFF_PRIVATE)
386         return 0;
387
388     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
389         logerror("Error seeking %s to elt %d (%s)",
390                  ep->file, id, strerror(errno));
391         return -1;
392     }
393
394     p = buf;
395     n = count * ep->size;
396     while (n > 0) {
397         ret = write(ep->fd, p, n);
398         if (ret < 0) {
399             if (errno != EINTR) {
400                 logerror("Error writing %s elt %d (%s)",
401                          ep->file,
402                          id + (int)((p - (char *)buf) / ep->size),
403                          strerror(errno));
404                 return -1;
405             }
406         } else {
407             p += ret;
408             n -= ret;
409         }
410     }
411
412     return 0;
413 }
414
415 /*
416  * Write element ID into table TYPE from buffer FROM.
417  * FIXME pass buffer size!
418  * Update timestamp in FROM if table is EFF_TYPED.
419  * If table is file-backed and not privately mapped, write through
420  * cache straight to disk.
421  * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
422  * Can write at the end of partially cached table.
423  * Return non-zero on success, zero on failure.
424  */
425 int
426 ef_write(int type, int id, void *from)
427 {
428     struct empfile *ep;
429     char *to;
430
431     if (ef_check(type) < 0)
432         return 0;
433     ep = &empfile[type];
434     if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
435         return 0;
436     if (ep->prewrite)
437         ep->prewrite(id, from);
438     if (CANT_HAPPEN((ep->flags & EFF_MEM) ? id >= ep->fids : id > ep->fids))
439         return 0;               /* not implemented */
440     if (ep->fd >= 0) {
441         if (do_write(ep, from, id, 1, time(NULL)) < 0)
442             return 0;
443     }
444     if (id >= ep->baseid && id < ep->baseid + ep->cids) {
445         /* update the cache if necessary */
446         to = ep->cache + (id - ep->baseid) * ep->size;
447         if (to != from)
448             memcpy(to, from, ep->size);
449     }
450     if (id >= ep->fids) {
451         /* write beyond end of file extends it, take note */
452         ep->fids = id + 1;
453     }
454     return 1;
455 }
456
457 /*
458  * Extend table TYPE by COUNT elements.
459  * Any pointers obtained from ef_ptr() become invalid.
460  * Return non-zero on success, zero on failure.
461  */
462 int
463 ef_extend(int type, int count)
464 {
465     struct empfile *ep;
466     char *p;
467     int i, id;
468     time_t now = time(NULL);
469
470     if (ef_check(type) < 0)
471         return 0;
472     ep = &empfile[type];
473     if (CANT_HAPPEN(count < 0))
474         return 0;
475
476     id = ep->fids;
477     if (ep->flags & EFF_MEM) {
478         if (id + count > ep->csize) {
479             if (ep->flags & EFF_STATIC) {
480                 logerror("Can't extend %s beyond %d elements",
481                          ep->file, ep->csize);
482                 return 0;
483             }
484             if (!ef_realloc_cache(ep, id + count)) {
485                 logerror("Can't extend %s to %d elements (%s)",
486                          ep->file, id + count, strerror(errno));
487                 return 0;
488             }
489         }
490         p = ep->cache + id * ep->size;
491         do_blank(ep, p, id, count);
492         if (ep->fd >= 0) {
493             if (do_write(ep, p, id, count, now) < 0)
494                 return 0;
495         }
496         ep->cids += count;
497     } else {
498         /* need a buffer, steal last cache slot */
499         if (ep->cids == ep->csize)
500             ep->cids--;
501         p = ep->cache + ep->cids * ep->size;
502         for (i = 0; i < count; i++) {
503             do_blank(ep, p, id + i, 1);
504             if (do_write(ep, p, id + i, 1, now) < 0)
505                 return 0;
506         }
507     }
508     ep->fids += count;
509     return 1;
510 }
511
512 /*
513  * Initialize element ID for EP in BUF.
514  * FIXME pass buffer size!
515  */
516 void
517 ef_blank(int type, int id, void *buf)
518 {
519     if (ef_check(type) < 0)
520         return;
521     do_blank(&empfile[type], buf, id, 1);
522 }
523
524 /*
525  * Initialize COUNT elements of EP in BUF, starting with element ID.
526  */
527 static void
528 do_blank(struct empfile *ep, void *buf, int id, int count)
529 {
530     int i;
531     struct emptypedstr *elt;
532
533     memset(buf, 0, count * ep->size);
534     if (ep->flags & EFF_TYPED) {
535         for (i = 0; i < count; i++) {
536             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
537             elt->ef_type = ep->uid;
538             elt->uid = id + i;
539         }
540     }
541 }
542
543 /*
544  * Truncate table TYPE to COUNT elements.
545  * Any pointers obtained from ef_ptr() become invalid.
546  * Return non-zero on success, zero on failure.
547  */
548 int
549 ef_truncate(int type, int count)
550 {
551     struct empfile *ep;
552
553     if (ef_check(type) < 0)
554         return 0;
555     ep = &empfile[type];
556     if (CANT_HAPPEN(count < 0 || count > ep->fids))
557         return 0;
558
559     if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
560         if (ftruncate(ep->fd, count * ep->size) < 0) {
561             logerror("Can't truncate %s to %d elements (%s)",
562                      ep->file, count, strerror(errno));
563             return 0;
564         }
565     }
566     ep->fids = count;
567
568     if (ep->flags & EFF_MEM) {
569         if (!(ep->flags & EFF_STATIC)) {
570             if (!ef_realloc_cache(ep, count)) {
571                 logerror("Can't shrink cache after truncate");
572                 /* continue with unshrunk cache */
573             }
574         }
575         ep->cids = count;
576     } else {
577         if (ep->baseid >= count)
578             ep->cids = 0;
579         else if (ep->cids > count - ep->baseid)
580             ep->cids = count - ep->baseid;
581     }
582
583     return 1;
584 }
585
586 struct castr *
587 ef_cadef(int type)
588 {
589     return empfile[type].cadef;
590 }
591
592 int
593 ef_nelem(int type)
594 {
595     return empfile[type].fids;
596 }
597
598 int
599 ef_flags(int type)
600 {
601     return empfile[type].flags;
602 }
603
604 time_t
605 ef_mtime(int type)
606 {
607     if (empfile[type].fd <= 0)
608         return 0;
609     return fdate(empfile[type].fd);
610 }
611
612 /*
613  * Search for a table matching NAME, return its table type.
614  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
615  * several.
616  */
617 int
618 ef_byname(char *name)
619 {
620     return stmtch(name, empfile, offsetof(struct empfile, name),
621                   sizeof(empfile[0]));
622 }
623
624 /*
625  * Search CHOICES[] for a table type matching NAME, return it.
626  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
627  * several.
628  * CHOICES[] must be terminated with a negative value.
629  */
630 int
631 ef_byname_from(char *name, int choices[])
632 {
633     int res;
634     int *p;
635
636     res = M_NOTFOUND;
637     for (p = choices; *p >= 0; p++) {
638         if (ef_check(*p) < 0)
639             continue;
640         switch (mineq(name, empfile[*p].name)) {
641         case ME_MISMATCH:
642             break;
643         case ME_PARTIAL:
644             if (res >= 0)
645                 return M_NOTUNIQUE;
646             res = *p;
647             break;
648         case ME_EXACT:
649             return *p;
650         }
651     }
652     return res;
653 }
654
655 char *
656 ef_nameof(int type)
657 {
658     if (ef_check(type) < 0)
659         return "bad ef_type";
660     return empfile[type].name;
661 }
662
663 int
664 ef_check(int type)
665 {
666     if (CANT_HAPPEN((unsigned)type >= EF_MAX))
667         return -1;
668     return 0;
669 }
670
671 /*
672  * Ensure file-backed table contains ID.
673  * If necessary, extend it in steps of COUNT elements.
674  * Return non-zero on success, zero on failure.
675  */
676 int
677 ef_ensure_space(int type, int id, int count)
678 {
679     if (ef_check(type) < 0)
680         return 0;
681     CANT_HAPPEN(id < 0);
682
683     while (id >= empfile[type].fids) {
684         if (!ef_extend(type, count))
685             return 0;
686     }
687     return 1;
688 }