]> git.pond.sub.org Git - empserver/blob - src/lib/common/file.c
b1ebfb13d873d592dbd8db46d6263ed91965049d
[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);
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) < 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  * Update the timestamp 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)
362 {
363     int i, n, ret;
364     char *p;
365     struct emptypedstr *elt;
366     time_t now;
367
368     if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
369         return -1;
370
371     if (ep->flags & EFF_TYPED) {
372         now = time(NULL);
373         for (i = 0; i < count; i++) {
374             /*
375              * TODO Oopses here could be due to bad data corruption.
376              * Fail instead of attempting to recover?
377              */
378             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
379             if (CANT_HAPPEN(elt->ef_type != ep->uid))
380                 elt->ef_type = ep->uid;
381             if (CANT_HAPPEN(elt->uid != id + i))
382                 elt->uid = id + i;
383             elt->timestamp = now;
384         }
385     }
386
387     if (ep->flags & EFF_PRIVATE)
388         return 0;
389
390     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
391         logerror("Error seeking %s to elt %d (%s)",
392                  ep->file, id, strerror(errno));
393         return -1;
394     }
395
396     p = buf;
397     n = count * ep->size;
398     while (n > 0) {
399         ret = write(ep->fd, p, n);
400         if (ret < 0) {
401             if (errno != EINTR) {
402                 logerror("Error writing %s elt %d (%s)",
403                          ep->file,
404                          id + (int)((p - (char *)buf) / ep->size),
405                          strerror(errno));
406                 return -1;
407             }
408         } else {
409             p += ret;
410             n -= ret;
411         }
412     }
413
414     return 0;
415 }
416
417 /*
418  * Write element ID into table TYPE from buffer FROM.
419  * FIXME pass buffer size!
420  * Update timestamp in FROM if table is EFF_TYPED.
421  * If table is file-backed and not privately mapped, write through
422  * cache straight to disk.
423  * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
424  * Can write at the end of partially cached table.
425  * Return non-zero on success, zero on failure.
426  */
427 int
428 ef_write(int type, int id, void *from)
429 {
430     struct empfile *ep;
431     char *to;
432
433     if (ef_check(type) < 0)
434         return 0;
435     ep = &empfile[type];
436     if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
437         return 0;
438     if (ep->prewrite)
439         ep->prewrite(id, from);
440     if (CANT_HAPPEN((ep->flags & EFF_MEM) ? id >= ep->fids : id > ep->fids))
441         return 0;               /* not implemented */
442     if (ep->fd >= 0) {
443         if (do_write(ep, from, id, 1) < 0)
444             return 0;
445     }
446     if (id >= ep->baseid && id < ep->baseid + ep->cids) {
447         /* update the cache if necessary */
448         to = ep->cache + (id - ep->baseid) * ep->size;
449         if (to != from)
450             memcpy(to, from, ep->size);
451     }
452     if (id >= ep->fids) {
453         /* write beyond end of file extends it, take note */
454         ep->fids = id + 1;
455     }
456     return 1;
457 }
458
459 /*
460  * Extend table TYPE by COUNT elements.
461  * Any pointers obtained from ef_ptr() become invalid.
462  * Return non-zero on success, zero on failure.
463  */
464 int
465 ef_extend(int type, int count)
466 {
467     struct empfile *ep;
468     char *p;
469     int i, id;
470
471     if (ef_check(type) < 0)
472         return 0;
473     ep = &empfile[type];
474     if (CANT_HAPPEN(count < 0))
475         return 0;
476
477     id = ep->fids;
478     if (ep->flags & EFF_MEM) {
479         if (id + count > ep->csize) {
480             if (ep->flags & EFF_STATIC) {
481                 logerror("Can't extend %s beyond %d elements",
482                          ep->file, ep->csize);
483                 return 0;
484             }
485             if (!ef_realloc_cache(ep, id + count)) {
486                 logerror("Can't extend %s to %d elements (%s)",
487                          ep->file, id + count, strerror(errno));
488                 return 0;
489             }
490         }
491         p = ep->cache + id * ep->size;
492         do_blank(ep, p, id, count);
493         if (ep->fd >= 0) {
494             if (do_write(ep, p, id, count) < 0)
495                 return 0;
496         }
497         ep->cids += count;
498     } else {
499         /* need a buffer, steal last cache slot */
500         if (ep->cids == ep->csize)
501             ep->cids--;
502         p = ep->cache + ep->cids * ep->size;
503         for (i = 0; i < count; i++) {
504             do_blank(ep, p, id + i, 1);
505             if (do_write(ep, p, id + i, 1) < 0)
506                 return 0;
507         }
508     }
509     ep->fids += count;
510     return 1;
511 }
512
513 /*
514  * Initialize element ID for EP in BUF.
515  * FIXME pass buffer size!
516  */
517 void
518 ef_blank(int type, int id, void *buf)
519 {
520     if (ef_check(type) < 0)
521         return;
522     do_blank(&empfile[type], buf, id, 1);
523 }
524
525 /*
526  * Initialize COUNT elements of EP in BUF, starting with element ID.
527  */
528 static void
529 do_blank(struct empfile *ep, void *buf, int id, int count)
530 {
531     int i;
532     struct emptypedstr *elt;
533
534     memset(buf, 0, count * ep->size);
535     if (ep->flags & EFF_TYPED) {
536         for (i = 0; i < count; i++) {
537             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
538             elt->ef_type = ep->uid;
539             elt->uid = id + i;
540         }
541     }
542 }
543
544 /*
545  * Truncate table TYPE to COUNT elements.
546  * Any pointers obtained from ef_ptr() become invalid.
547  * Return non-zero on success, zero on failure.
548  */
549 int
550 ef_truncate(int type, int count)
551 {
552     struct empfile *ep;
553
554     if (ef_check(type) < 0)
555         return 0;
556     ep = &empfile[type];
557     if (CANT_HAPPEN(count < 0 || count > ep->fids))
558         return 0;
559
560     if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
561         if (ftruncate(ep->fd, count * ep->size) < 0) {
562             logerror("Can't truncate %s to %d elements (%s)",
563                      ep->file, count, strerror(errno));
564             return 0;
565         }
566     }
567     ep->fids = count;
568
569     if (ep->flags & EFF_MEM) {
570         if (!(ep->flags & EFF_STATIC)) {
571             if (!ef_realloc_cache(ep, count)) {
572                 logerror("Can't shrink cache after truncate");
573                 /* continue with unshrunk cache */
574             }
575         }
576         ep->cids = count;
577     } else {
578         if (ep->baseid >= count)
579             ep->cids = 0;
580         else if (ep->cids > count - ep->baseid)
581             ep->cids = count - ep->baseid;
582     }
583
584     return 1;
585 }
586
587 struct castr *
588 ef_cadef(int type)
589 {
590     return empfile[type].cadef;
591 }
592
593 int
594 ef_nelem(int type)
595 {
596     return empfile[type].fids;
597 }
598
599 int
600 ef_flags(int type)
601 {
602     return empfile[type].flags;
603 }
604
605 time_t
606 ef_mtime(int type)
607 {
608     if (empfile[type].fd <= 0)
609         return 0;
610     return fdate(empfile[type].fd);
611 }
612
613 /*
614  * Search for a table matching NAME, return its table type.
615  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
616  * several.
617  */
618 int
619 ef_byname(char *name)
620 {
621     return stmtch(name, empfile, offsetof(struct empfile, name),
622                   sizeof(empfile[0]));
623 }
624
625 /*
626  * Search CHOICES[] for a table type matching NAME, return it.
627  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
628  * several.
629  * CHOICES[] must be terminated with a negative value.
630  */
631 int
632 ef_byname_from(char *name, int choices[])
633 {
634     int res;
635     int *p;
636
637     res = M_NOTFOUND;
638     for (p = choices; *p >= 0; p++) {
639         if (ef_check(*p) < 0)
640             continue;
641         switch (mineq(name, empfile[*p].name)) {
642         case ME_MISMATCH:
643             break;
644         case ME_PARTIAL:
645             if (res >= 0)
646                 return M_NOTUNIQUE;
647             res = *p;
648             break;
649         case ME_EXACT:
650             return *p;
651         }
652     }
653     return res;
654 }
655
656 char *
657 ef_nameof(int type)
658 {
659     if (ef_check(type) < 0)
660         return "bad ef_type";
661     return empfile[type].name;
662 }
663
664 int
665 ef_check(int type)
666 {
667     if (CANT_HAPPEN((unsigned)type >= EF_MAX))
668         return -1;
669     return 0;
670 }
671
672 /*
673  * Ensure file-backed table contains ID.
674  * If necessary, extend it in steps of COUNT elements.
675  * Return non-zero on success, zero on failure.
676  */
677 int
678 ef_ensure_space(int type, int id, int count)
679 {
680     if (ef_check(type) < 0)
681         return 0;
682     CANT_HAPPEN(id < 0);
683
684     while (id >= empfile[type].fids) {
685         if (!ef_extend(type, count))
686             return 0;
687     }
688     return 1;
689 }