]> git.pond.sub.org Git - empserver/blob - src/lib/common/file.c
[_WIN32, __GNUC__]: Reorganize the include files for WIN32 to
[empserver] / src / lib / common / file.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2006, 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
34  */
35
36 #include <config.h>
37
38 #include <errno.h>
39 #if defined(_WIN32) && !defined(__GNUC__)
40 #include <io.h>
41 #endif
42 #include <fcntl.h>
43 #include <signal.h>
44 #include <sys/types.h>
45 #if !defined(_WIN32)
46 #include <unistd.h>
47 #endif
48 #include "file.h"
49 #include "match.h"
50 #include "misc.h"
51 #include "nsc.h"
52 #include "optlist.h"
53 #include "prototypes.h"
54
55 static int fillcache(struct empfile *, int);
56 static int do_write(struct empfile *, void *, int, int);
57
58 /*
59  * Open the file-backed table TYPE (EF_SECTOR, ...).
60  * HOW are flags to control operation.  Naturally, immutable flags are
61  * not permitted.
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)
67 {
68     struct empfile *ep;
69     int oflags, fd, fsiz, size;
70
71     if (ef_check(type) < 0)
72         return 0;
73     if (CANT_HAPPEN(how & EFF_IMMUTABLE))
74         how &= ~EFF_IMMUTABLE;
75
76     /* open file */
77     ep = &empfile[type];
78     if (CANT_HAPPEN(ep->fd >= 0))
79         return 0;
80     oflags = O_RDWR;
81     if (how & EFF_RDONLY)
82         oflags = O_RDONLY;
83     if (how & EFF_CREATE)
84         oflags |= O_CREAT | O_TRUNC;
85 #if defined(_WIN32)
86     oflags |= O_BINARY;
87 #endif
88     if ((fd = open(ep->file, oflags, 0660)) < 0) {
89         logerror("Can't open %s (%s)", ep->file, strerror(errno));
90         return 0;
91     }
92
93     /* get file size */
94     fsiz = fsize(fd);
95     if (fsiz % ep->size) {
96         logerror("Can't open %s (file size not a multiple of record size %d)",
97                  ep->file, ep->size);
98         close(fd);
99         return 0;
100     }
101     ep->fids = fsiz / ep->size;
102
103     /* allocate cache */
104     if (ep->flags & EFF_STATIC) {
105         /* ep->cache already points to space for ep->csize elements */
106         if (how & EFF_MEM) {
107             if (ep->fids > ep->csize) {
108                 logerror("Can't open %s: file larger than %d bytes",
109                          ep->file, ep->fids * ep->size);
110                 close(fd);
111                 return 0;
112             }
113         }
114     } else {
115         if (how & EFF_MEM)
116             ep->csize = ep->fids;
117         else
118             ep->csize = blksize(fd) / ep->size;
119         /* 0 could lead to null cache, which confuses assertions */
120         if (!ep->csize)
121             ep->csize++;
122         size = ep->csize * ep->size;
123         if (CANT_HAPPEN(ep->cache))
124             free(ep->cache);
125         ep->cache = malloc(size);
126         if (ep->cache == NULL) {
127             logerror("Can't open %s: out of memory", ep->file);
128             close(fd);
129             return 0;
130         }
131     }
132     ep->baseid = 0;
133     ep->cids = 0;
134     ep->flags = (ep->flags & EFF_IMMUTABLE) | (how & ~EFF_CREATE);
135     ep->fd = fd;
136
137     /* map file into cache */
138     if ((how & EFF_MEM) && ep->fids) {
139         if (fillcache(ep, 0) != ep->fids) {
140             ep->cids = 0;       /* prevent cache flush */
141             ep->flags &= EFF_IMMUTABLE; /* maintain invariant */
142             ef_close(type);
143             return 0;
144         }
145     }
146
147     /*
148      * Could close fd if both EFF_RDONLY and EFF_MEM, but that doesn't
149      * happen, so don't bother.
150      */
151
152     return 1;
153 }
154
155 /*
156  * Close the file-backed table TYPE (EF_SECTOR, ...).
157  * Return non-zero on success, zero on failure.
158  */
159 int
160 ef_close(int type)
161 {
162     struct empfile *ep;
163     int retval;
164
165     retval = ef_flush(type);
166     ep = &empfile[type];
167     ep->flags &= EFF_IMMUTABLE;
168     if (!(ep->flags & EFF_STATIC)) {
169         free(ep->cache);
170         ep->cache = NULL;
171     }
172     if (close(ep->fd) < 0) {
173         logerror("Error closing %s (%s)", ep->name, strerror(errno));
174         retval = 0;
175     }
176     ep->fd = -1;
177     return retval;
178 }
179
180 /*
181  * Flush file-backed table TYPE (EF_SECTOR, ...) to disk.
182  * Return non-zero on success, zero on failure.
183  */
184 int
185 ef_flush(int type)
186 {
187     struct empfile *ep;
188
189     if (ef_check(type) < 0)
190         return 0;
191     ep = &empfile[type];
192     if (CANT_HAPPEN(ep->fd < 0))
193         return 0;
194     /*
195      * We don't know which cache entries are dirty.  ef_write() writes
196      * through, but direct updates through ef_ptr() don't.  They are
197      * allowed only with EFF_MEM.  Assume the whole cash is dirty
198      * then.
199      */
200     if (!(ep->flags & EFF_RDONLY) && (ep->flags & EFF_MEM))
201         return do_write(ep, ep->cache, ep->baseid, ep->cids) >= 0;
202
203     return 1;
204 }
205
206 /*
207  * Return pointer to element ID in table TYPE if it exists, else NULL.
208  * The table must be fully cached, i.e. flags & EFF_MEM.
209  * The caller is responsible for flushing changes he makes.
210  */
211 void *
212 ef_ptr(int type, int id)
213 {
214     struct empfile *ep;
215
216     if (ef_check(type) < 0)
217         return NULL;
218     ep = &empfile[type];
219     if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
220         return NULL;
221     if (id < 0 || id >= ep->fids)
222         return NULL;
223     return ep->cache + ep->size * id;
224 }
225
226 /*
227  * Read element ID from table TYPE into buffer INTO.
228  * FIXME pass buffer size!
229  * Return non-zero on success, zero on failure.
230  */
231 int
232 ef_read(int type, int id, void *into)
233 {
234     struct empfile *ep;
235     void *from;
236
237     if (ef_check(type) < 0)
238         return 0;
239     ep = &empfile[type];
240     if (CANT_HAPPEN(!ep->cache))
241         return 0;
242     if (id < 0 || id >= ep->fids)
243         return 0;
244
245     if (ep->flags & EFF_MEM) {
246         from = ep->cache + id * ep->size;
247     } else {
248         if (ep->baseid + ep->cids <= id || ep->baseid > id) {
249             if (fillcache(ep, id) < 1)
250                 return 0;
251         }
252         from = ep->cache + (id - ep->baseid) * ep->size;
253     }
254     memcpy(into, from, ep->size);
255
256     if (ep->postread)
257         ep->postread(id, into);
258     return 1;
259 }
260
261 /*
262  * Fill cache of EP with elements starting at ID.
263  * If any were read, return their number.
264  * Else return -1 and leave the cache unchanged.
265  */
266 static int
267 fillcache(struct empfile *ep, int start)
268 {
269     int n, ret;
270     char *p;
271
272     if (CANT_HAPPEN(ep->fd < 0 || !ep->cache))
273         return -1;
274
275     if (lseek(ep->fd, start * ep->size, SEEK_SET) == (off_t)-1) {
276         logerror("Error seeking %s (%s)", ep->file, strerror(errno));
277         return -1;
278     }
279
280     p = ep->cache;
281     n = ep->csize * ep->size;
282     while (n > 0) {
283         ret = read(ep->fd, p, n);
284         if (ret < 0) {
285             if (errno != EAGAIN) {
286                 logerror("Error reading %s (%s)", ep->file, strerror(errno));
287                 break;
288             }
289         } else if (ret == 0) {
290             break;
291         } else {
292             p += ret;
293             n -= ret;
294         }
295     }
296
297     if (p == ep->cache)
298         return -1;              /* nothing read, old cache still ok */
299
300     ep->baseid = start;
301     ep->cids = (p - ep->cache) / ep->size;
302     return ep->cids;
303 }
304
305 /*
306  * Write COUNT elements from BUF to EP, starting at ID.
307  * Return 0 on success, -1 on error.
308  */
309 static int
310 do_write(struct empfile *ep, void *buf, int id, int count)
311 {
312     int n, ret;
313     char *p;
314
315     if (CANT_HAPPEN(ep->fd < 0 || id < 0 || count < 0))
316         return -1;
317
318     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
319         logerror("Error seeking %s (%s)", ep->file, strerror(errno));
320         return -1;
321     }
322
323     p = buf;
324     n = count * ep->size;
325     while (n > 0) {
326         ret = write(ep->fd, p, n);
327         if (ret < 0) {
328             if (errno != EAGAIN) {
329                 logerror("Error writing %s (%s)", ep->file, strerror(errno));
330                 /* FIXME if this extended file, truncate back to old size */
331                 return -1;
332             }
333         } else {
334             p += ret;
335             n -= ret;
336         }
337     }
338
339     return 0;
340 }
341
342 /*
343  * Write element ID into file-backed table TYPE from buffer FROM.
344  * FIXME pass buffer size!
345  * Write through cache straight to disk.
346  * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
347  * Can write at the end of partially cached table.
348  * Return non-zero on success, zero on failure.
349  */
350 int
351 ef_write(int type, int id, void *from)
352 {
353     struct empfile *ep;
354     char *to;
355
356     if (ef_check(type) < 0)
357         return 0;
358     ep = &empfile[type];
359     if (ep->prewrite)
360         ep->prewrite(id, from);
361     if (CANT_HAPPEN((ep->flags & EFF_MEM) ? id >= ep->fids : id > ep->fids))
362         return 0;               /* not implemented */
363     if (do_write(ep, from, id, 1) < 0)
364         return 0;
365     if (id >= ep->baseid && id < ep->baseid + ep->cids) {
366         /* update the cache if necessary */
367         to = ep->cache + (id - ep->baseid) * ep->size;
368         if (to != from)
369             memcpy(to, from, ep->size);
370     }
371     if (id >= ep->fids) {
372         /* write beyond end of file extends it, take note */
373         ep->fids = id + 1;
374     }
375     return 1;
376 }
377
378 /*
379  * Extend the file-backed table TYPE by COUNT elements.
380  * Return non-zero on success, zero on failure.
381  */
382 int
383 ef_extend(int type, int count)
384 {
385     struct empfile *ep;
386     void *tmpobj;
387     int id, i, how;
388
389     if (ef_check(type) < 0)
390         return 0;
391     ep = &empfile[type];
392     if (CANT_HAPPEN(ep->fd < 0 || count < 0))
393         return 0;
394
395     tmpobj = calloc(1, ep->size);
396     id = ep->fids;
397     for (i = 0; i < count; i++) {
398         if (ep->init)
399             ep->init(id + i, tmpobj);
400         if (do_write(ep, tmpobj, id + i, 1) < 0)
401             break;
402     }
403     free(tmpobj);
404
405     if (ep->flags & EFF_MEM) {
406         /* FIXME lazy bastards...  do this right */
407         /* XXX this will cause problems if there are ef_ptrs (to the
408          * old allocated structure) active when we do the re-open */
409         how = ep->flags & ~EFF_IMMUTABLE;
410         ef_close(type);
411         ef_open(type, how);
412     } else {
413         ep->fids += i;
414     }
415
416     return i == count;
417 }
418
419 struct castr *
420 ef_cadef(int type)
421 {
422     return empfile[type].cadef;
423 }
424
425 int
426 ef_nelem(int type)
427 {
428     return empfile[type].fids;
429 }
430
431 int
432 ef_flags(int type)
433 {
434     return empfile[type].flags;
435 }
436
437 time_t
438 ef_mtime(int type)
439 {
440     if (empfile[type].fd <= 0)
441         return 0;
442     return fdate(empfile[type].fd);
443 }
444
445 /*
446  * Search for a table matching NAME, return its table type.
447  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
448  * several.
449  */
450 int
451 ef_byname(char *name)
452 {
453     return stmtch(name, empfile, offsetof(struct empfile, name),
454                   sizeof(empfile[0]));
455 }
456
457 /*
458  * Search CHOICES[] for a table type matching NAME, return it.
459  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
460  * several.
461  * CHOICES[] must be terminated with a negative value.
462  */
463 int
464 ef_byname_from(char *name, int choices[])
465 {
466     int res;
467     int *p;
468
469     res = M_NOTFOUND;
470     for (p = choices; *p >= 0; p++) {
471         if (ef_check(*p) < 0)
472             continue;
473         switch (mineq(name, empfile[*p].name)) {
474         case ME_MISMATCH:
475             break;
476         case ME_PARTIAL:
477             if (res >= 0)
478                 return M_NOTUNIQUE;
479             res = *p;
480             break;
481         case ME_EXACT:
482             return *p;
483         }
484     }
485     return res;
486 }
487
488 char *
489 ef_nameof(int type)
490 {
491     if (ef_check(type) < 0)
492         return "bad ef_type";
493     return empfile[type].name;
494 }
495
496 int
497 ef_check(int type)
498 {
499     if (CANT_HAPPEN((unsigned)type >= EF_MAX))
500         return -1;
501     return 0;
502 }
503
504 /*
505  * Ensure file-backed table contains ID.
506  * If necessary, extend it in steps of COUNT elements.
507  * Return non-zero on success, zero on failure.
508  */
509 int
510 ef_ensure_space(int type, int id, int count)
511 {
512     if (ef_check(type) < 0)
513         return 0;
514     CANT_HAPPEN(id < 0);
515
516     while (id >= empfile[type].fids) {
517         if (!ef_extend(type, count))
518             return 0;
519     }
520     return 1;
521 }
522
523 static void
524 ef_fix_size(struct empfile *ep, int n)
525 {
526     ep->cids = ep->fids = n;
527     ep->csize = n + 1;
528 }
529
530 /*
531  * Initialize Empire tables.
532  * Must be called once, before using anything else from this module.
533  */
534 void
535 ef_init(void)
536 {
537     struct castr *ca;
538     struct empfile *ep;
539     struct symbol *lup;
540     int i;
541
542     empfile[EF_MAP].size = empfile[EF_BMAP].size = (WORLD_X * WORLD_Y) / 2;
543
544     ca = (struct castr *)empfile[EF_META].cache;
545     for (i = 0; ca[i].ca_name; i++) ;
546     ef_fix_size(&empfile[EF_META], i);
547
548     for (ep = empfile; ep->uid >= 0; ep++) {
549         if (ep->cadef == symbol_ca) {
550             lup = (struct symbol *)ep->cache;
551             for (i = 0; lup[i].name; i++) ;
552             ef_fix_size(ep, i);
553         }
554     }
555 }