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