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