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