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