]> git.pond.sub.org Git - empserver/blob - src/lib/common/file.c
empfile's init callback is now unused, remove
[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-2006
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  * 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         return do_write(ep, ep->cache, ep->baseid, ep->cids) >= 0;
235
236     return 1;
237 }
238
239 /*
240  * Return pointer to element ID in table TYPE if it exists, else NULL.
241  * The table must be fully cached, i.e. flags & EFF_MEM.
242  * The caller is responsible for flushing changes he makes.
243  */
244 void *
245 ef_ptr(int type, int id)
246 {
247     struct empfile *ep;
248
249     if (ef_check(type) < 0)
250         return NULL;
251     ep = &empfile[type];
252     if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
253         return NULL;
254     if (id < 0 || id >= ep->fids)
255         return NULL;
256     return ep->cache + ep->size * id;
257 }
258
259 /*
260  * Read element ID from table TYPE into buffer INTO.
261  * FIXME pass buffer size!
262  * Return non-zero on success, zero on failure.
263  */
264 int
265 ef_read(int type, int id, void *into)
266 {
267     struct empfile *ep;
268     void *from;
269
270     if (ef_check(type) < 0)
271         return 0;
272     ep = &empfile[type];
273     if (CANT_HAPPEN(!ep->cache))
274         return 0;
275     if (id < 0 || id >= ep->fids)
276         return 0;
277
278     if (ep->flags & EFF_MEM) {
279         from = ep->cache + id * ep->size;
280     } else {
281         if (ep->baseid + ep->cids <= id || ep->baseid > id) {
282             if (fillcache(ep, id) < 1)
283                 return 0;
284         }
285         from = ep->cache + (id - ep->baseid) * ep->size;
286     }
287     memcpy(into, from, ep->size);
288
289     if (ep->postread)
290         ep->postread(id, into);
291     return 1;
292 }
293
294 /*
295  * Fill cache of EP with elements starting at ID.
296  * If any were read, return their number.
297  * Else return -1 and leave the cache unchanged.
298  */
299 static int
300 fillcache(struct empfile *ep, int start)
301 {
302     int n, ret;
303     char *p;
304
305     if (CANT_HAPPEN(ep->fd < 0 || !ep->cache))
306         return -1;
307
308     if (lseek(ep->fd, start * ep->size, SEEK_SET) == (off_t)-1) {
309         logerror("Error seeking %s (%s)", ep->file, strerror(errno));
310         return -1;
311     }
312
313     p = ep->cache;
314     n = ep->csize * ep->size;
315     while (n > 0) {
316         ret = read(ep->fd, p, n);
317         if (ret < 0) {
318             if (errno != EAGAIN) {
319                 logerror("Error reading %s (%s)", ep->file, strerror(errno));
320                 break;
321             }
322         } else if (ret == 0) {
323             break;
324         } else {
325             p += ret;
326             n -= ret;
327         }
328     }
329
330     if (p == ep->cache)
331         return -1;              /* nothing read, old cache still ok */
332
333     ep->baseid = start;
334     ep->cids = (p - ep->cache) / ep->size;
335     return ep->cids;
336 }
337
338 /*
339  * Write COUNT elements from BUF to EP, starting at ID.
340  * Return 0 on success, -1 on error.
341  */
342 static int
343 do_write(struct empfile *ep, void *buf, int id, int count)
344 {
345     int n, ret;
346     char *p;
347
348     if (CANT_HAPPEN(ep->fd < 0 || (ep->flags & EFF_PRIVATE)
349                     || id < 0 || count < 0))
350         return -1;
351
352     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
353         logerror("Error seeking %s (%s)", ep->file, strerror(errno));
354         return -1;
355     }
356
357     p = buf;
358     n = count * ep->size;
359     while (n > 0) {
360         ret = write(ep->fd, p, n);
361         if (ret < 0) {
362             if (errno != EAGAIN) {
363                 logerror("Error writing %s (%s)", ep->file, strerror(errno));
364                 /* FIXME if this extended file, truncate back to old size */
365                 return -1;
366             }
367         } else {
368             p += ret;
369             n -= ret;
370         }
371     }
372
373     return 0;
374 }
375
376 /*
377  * Write element ID into table TYPE from buffer FROM.
378  * FIXME pass buffer size!
379  * If table is file-backed and not privately mapped, write through
380  * cache straight to disk.
381  * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
382  * Can write at the end of partially cached table.
383  * Return non-zero on success, zero on failure.
384  */
385 int
386 ef_write(int type, int id, void *from)
387 {
388     struct empfile *ep;
389     char *to;
390
391     if (ef_check(type) < 0)
392         return 0;
393     ep = &empfile[type];
394     if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
395         return 0;
396     if (ep->prewrite)
397         ep->prewrite(id, from);
398     if (CANT_HAPPEN((ep->flags & EFF_MEM) ? id >= ep->fids : id > ep->fids))
399         return 0;               /* not implemented */
400     if (!(ep->flags & EFF_PRIVATE)) {
401         if (do_write(ep, from, id, 1) < 0)
402             return 0;
403     }
404     if (id >= ep->baseid && id < ep->baseid + ep->cids) {
405         /* update the cache if necessary */
406         to = ep->cache + (id - ep->baseid) * ep->size;
407         if (to != from)
408             memcpy(to, from, ep->size);
409     }
410     if (id >= ep->fids) {
411         /* write beyond end of file extends it, take note */
412         ep->fids = id + 1;
413     }
414     return 1;
415 }
416
417 /*
418  * Extend table TYPE by COUNT elements.
419  * Any pointers obtained from ef_ptr() become invalid.
420  * Return non-zero on success, zero on failure.
421  */
422 int
423 ef_extend(int type, int count)
424 {
425     struct empfile *ep;
426     char *p;
427     int i, id;
428
429     if (ef_check(type) < 0)
430         return 0;
431     ep = &empfile[type];
432     if (CANT_HAPPEN(count < 0))
433         return 0;
434
435     id = ep->fids;
436     if (ep->flags & EFF_MEM) {
437         if (id + count > ep->csize) {
438             if (ep->flags & EFF_STATIC) {
439                 logerror("Can't extend %s beyond %d elements",
440                          ep->file, ep->csize);
441                 return 0;
442             }
443             if (!ef_realloc_cache(ep, id + count)) {
444                 logerror("Can't extend %s to %d elements (%s)",
445                          ep->file, id + count, strerror(errno));
446                 return 0;
447             }
448         }
449         p = ep->cache + id * ep->size;
450         do_blank(ep, p, id, count);
451         if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
452             if (do_write(ep, p, id, count) < 0)
453                 return 0;
454         }
455         ep->cids += count;
456     } else {
457         /* need a buffer, steal last cache slot */
458         if (ep->cids == ep->csize)
459             ep->cids--;
460         p = ep->cache + ep->cids * ep->size;
461         for (i = 0; i < count; i++) {
462             do_blank(ep, p, id + i, 1);
463             if (do_write(ep, p, id + i, 1) < 0)
464                 return 0;
465         }
466     }
467     ep->fids += count;
468     return 1;
469 }
470
471 /*
472  * Initialize COUNT elements of EP in BUF, starting with element ID.
473  */
474 static void
475 do_blank(struct empfile *ep, void *buf, int id, int count)
476 {
477     int i;
478     struct emptypedstr *elt;
479
480     memset(buf, 0, count * ep->size);
481     if (ep->flags & EFF_TYPED) {
482         for (i = 0; i < count; i++) {
483             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
484             elt->ef_type = ep->uid;
485             elt->uid = id + i;
486         }
487     }
488 }
489
490 struct castr *
491 ef_cadef(int type)
492 {
493     return empfile[type].cadef;
494 }
495
496 int
497 ef_nelem(int type)
498 {
499     return empfile[type].fids;
500 }
501
502 int
503 ef_flags(int type)
504 {
505     return empfile[type].flags;
506 }
507
508 time_t
509 ef_mtime(int type)
510 {
511     if (empfile[type].fd <= 0)
512         return 0;
513     return fdate(empfile[type].fd);
514 }
515
516 /*
517  * Search for a table matching NAME, return its table type.
518  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
519  * several.
520  */
521 int
522 ef_byname(char *name)
523 {
524     return stmtch(name, empfile, offsetof(struct empfile, name),
525                   sizeof(empfile[0]));
526 }
527
528 /*
529  * Search CHOICES[] for a table type matching NAME, return it.
530  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
531  * several.
532  * CHOICES[] must be terminated with a negative value.
533  */
534 int
535 ef_byname_from(char *name, int choices[])
536 {
537     int res;
538     int *p;
539
540     res = M_NOTFOUND;
541     for (p = choices; *p >= 0; p++) {
542         if (ef_check(*p) < 0)
543             continue;
544         switch (mineq(name, empfile[*p].name)) {
545         case ME_MISMATCH:
546             break;
547         case ME_PARTIAL:
548             if (res >= 0)
549                 return M_NOTUNIQUE;
550             res = *p;
551             break;
552         case ME_EXACT:
553             return *p;
554         }
555     }
556     return res;
557 }
558
559 char *
560 ef_nameof(int type)
561 {
562     if (ef_check(type) < 0)
563         return "bad ef_type";
564     return empfile[type].name;
565 }
566
567 int
568 ef_check(int type)
569 {
570     if (CANT_HAPPEN((unsigned)type >= EF_MAX))
571         return -1;
572     return 0;
573 }
574
575 /*
576  * Ensure file-backed table contains ID.
577  * If necessary, extend it in steps of COUNT elements.
578  * Return non-zero on success, zero on failure.
579  */
580 int
581 ef_ensure_space(int type, int id, int count)
582 {
583     if (ef_check(type) < 0)
584         return 0;
585     CANT_HAPPEN(id < 0);
586
587     while (id >= empfile[type].fids) {
588         if (!ef_extend(type, count))
589             return 0;
590     }
591     return 1;
592 }