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