]> git.pond.sub.org Git - empserver/blob - src/lib/common/file.c
New ef_truncate()
[empserver] / src / lib / common / file.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2008, 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-2006
34  */
35
36 #include <config.h>
37
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <unistd.h>
43 #include "file.h"
44 #include "match.h"
45 #include "misc.h"
46 #include "nsc.h"
47 #include "prototypes.h"
48
49 static int ef_realloc_cache(struct empfile *, int);
50 static int fillcache(struct empfile *, int);
51 static int do_write(struct empfile *, void *, int, int);
52 static void do_blank(struct empfile *, void *, int, int);
53
54 /*
55  * Open the file-backed table TYPE (EF_SECTOR, ...).
56  * HOW are flags to control operation.  Naturally, immutable flags are
57  * not permitted.
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     struct flock lock;
66     int oflags, fd, fsiz, nslots;
67
68     if (ef_check(type) < 0)
69         return 0;
70     if (CANT_HAPPEN(how & EFF_IMMUTABLE))
71         how &= ~EFF_IMMUTABLE;
72
73     /* open file */
74     ep = &empfile[type];
75     if (CANT_HAPPEN(ep->fd >= 0))
76         return 0;
77     oflags = O_RDWR;
78     if (how & EFF_PRIVATE)
79         oflags = O_RDONLY;
80     if (how & EFF_CREATE)
81         oflags |= O_CREAT | O_TRUNC;
82 #if defined(_WIN32)
83     oflags |= O_BINARY;
84 #endif
85     if ((fd = open(ep->file, oflags, S_IRWUG)) < 0) {
86         logerror("Can't open %s (%s)", ep->file, strerror(errno));
87         return 0;
88     }
89
90     lock.l_type = how & EFF_PRIVATE ? F_RDLCK : F_WRLCK;
91     lock.l_whence = SEEK_SET;
92     lock.l_start = lock.l_len = 0;
93     if (fcntl(fd, F_SETLK, &lock) == -1) {
94         logerror("Can't lock %s (%s)", ep->file, strerror(errno));
95         close(fd);
96         return 0;
97     }
98
99     /* get file size */
100     fsiz = fsize(fd);
101     if (fsiz % ep->size) {
102         logerror("Can't open %s (file size not a multiple of record size %d)",
103                  ep->file, ep->size);
104         close(fd);
105         return 0;
106     }
107     ep->fids = fsiz / ep->size;
108
109     /* allocate cache */
110     if (ep->flags & EFF_STATIC) {
111         /* ep->cache already points to space for ep->csize elements */
112         if (how & EFF_MEM) {
113             if (ep->fids > ep->csize) {
114                 logerror("Can't open %s: file larger than %d bytes",
115                          ep->file, ep->fids * ep->size);
116                 close(fd);
117                 return 0;
118             }
119         }
120     } else {
121         if (CANT_HAPPEN(ep->cache))
122             free(ep->cache);
123         if (how & EFF_MEM)
124             nslots = ep->fids;
125         else
126             nslots = blksize(fd) / ep->size;
127         if (!ef_realloc_cache(ep, nslots)) {
128             logerror("Can't map %s (%s)", ep->file, strerror(errno));
129             close(fd);
130             return 0;
131         }
132     }
133     ep->baseid = 0;
134     ep->cids = 0;
135     ep->flags = (ep->flags & EFF_IMMUTABLE) | (how & ~EFF_CREATE);
136     ep->fd = fd;
137
138     /* map file into cache */
139     if ((how & EFF_MEM) && ep->fids) {
140         if (fillcache(ep, 0) != ep->fids) {
141             ep->cids = 0;       /* prevent cache flush */
142             ep->flags &= EFF_IMMUTABLE; /* maintain invariant */
143             ef_close(type);
144             return 0;
145         }
146     }
147
148     return 1;
149 }
150
151 /*
152  * Reallocate cache for table EP to hold COUNT slots.
153  * The table must not be allocated statically.
154  * The cache may still be unmapped.
155  * If reallocation succeeds, any pointers obtained from ef_ptr()
156  * become invalid.
157  * If it fails, the cache is unchanged, and errno is set.
158  * Return non-zero on success, zero on failure.
159  */
160 static int
161 ef_realloc_cache(struct empfile *ep, int count)
162 {
163     void *cache;
164
165     if (CANT_HAPPEN(ep->flags & EFF_STATIC))
166         return 0;
167     if (CANT_HAPPEN(count < 0))
168         count = 0;
169
170     /*
171      * Avoid zero slots, because that can lead to null cache, which
172      * would be interpreted as unmapped cache.
173      */
174     if (count == 0)
175         count++;
176     cache = realloc(ep->cache, count * ep->size);
177     if (!cache)
178         return 0;
179
180     ep->cache = cache;
181     ep->csize = count;
182     return 1;
183 }
184
185 /*
186  * Close the file-backed table TYPE (EF_SECTOR, ...).
187  * Return non-zero on success, zero on failure.
188  */
189 int
190 ef_close(int type)
191 {
192     struct empfile *ep;
193     int retval;
194
195     retval = ef_flush(type);
196     ep = &empfile[type];
197     ep->flags &= EFF_IMMUTABLE;
198     if (!(ep->flags & EFF_STATIC)) {
199         free(ep->cache);
200         ep->cache = NULL;
201     }
202     if (close(ep->fd) < 0) {
203         logerror("Error closing %s (%s)", ep->name, strerror(errno));
204         retval = 0;
205     }
206     ep->fd = -1;
207     return retval;
208 }
209
210 /*
211  * Flush table TYPE (EF_SECTOR, ...) to disk.
212  * Does nothing if the table is privately mapped.
213  * Return non-zero on success, zero on failure.
214  */
215 int
216 ef_flush(int type)
217 {
218     struct empfile *ep;
219
220     if (ef_check(type) < 0)
221         return 0;
222     ep = &empfile[type];
223     if (ep->flags & EFF_PRIVATE)
224         return 1;               /* nothing to do */
225     if (CANT_HAPPEN(ep->fd < 0))
226         return 0;
227     /*
228      * We don't know which cache entries are dirty.  ef_write() writes
229      * through, but direct updates through ef_ptr() don't.  They are
230      * allowed only with EFF_MEM.  Assume the whole cash is dirty
231      * then.
232      */
233     if (ep->flags & EFF_MEM)
234         return do_write(ep, ep->cache, ep->baseid, ep->cids) >= 0;
235
236     return 1;
237 }
238
239 /*
240  * Return pointer to element ID in table TYPE if it exists, else NULL.
241  * The table must be fully cached, i.e. flags & EFF_MEM.
242  * The caller is responsible for flushing changes he makes.
243  */
244 void *
245 ef_ptr(int type, int id)
246 {
247     struct empfile *ep;
248
249     if (ef_check(type) < 0)
250         return NULL;
251     ep = &empfile[type];
252     if (CANT_HAPPEN(!(ep->flags & EFF_MEM) || !ep->cache))
253         return NULL;
254     if (id < 0 || id >= ep->fids)
255         return NULL;
256     return ep->cache + ep->size * id;
257 }
258
259 /*
260  * Read element ID from table TYPE into buffer INTO.
261  * FIXME pass buffer size!
262  * Return non-zero on success, zero on failure.
263  */
264 int
265 ef_read(int type, int id, void *into)
266 {
267     struct empfile *ep;
268     void *from;
269
270     if (ef_check(type) < 0)
271         return 0;
272     ep = &empfile[type];
273     if (CANT_HAPPEN(!ep->cache))
274         return 0;
275     if (id < 0 || id >= ep->fids)
276         return 0;
277
278     if (ep->flags & EFF_MEM) {
279         from = ep->cache + id * ep->size;
280     } else {
281         if (ep->baseid + ep->cids <= id || ep->baseid > id) {
282             if (fillcache(ep, id) < 1)
283                 return 0;
284         }
285         from = ep->cache + (id - ep->baseid) * ep->size;
286     }
287     memcpy(into, from, ep->size);
288
289     if (ep->postread)
290         ep->postread(id, into);
291     return 1;
292 }
293
294 /*
295  * Fill cache of EP with elements starting at ID.
296  * If any were read, return their number.
297  * Else return -1 and leave the cache unchanged.
298  */
299 static int
300 fillcache(struct empfile *ep, int start)
301 {
302     int n, ret;
303     char *p;
304
305     if (CANT_HAPPEN(ep->fd < 0 || !ep->cache))
306         return -1;
307
308     if (lseek(ep->fd, start * ep->size, SEEK_SET) == (off_t)-1) {
309         logerror("Error seeking %s (%s)", ep->file, strerror(errno));
310         return -1;
311     }
312
313     p = ep->cache;
314     n = ep->csize * ep->size;
315     while (n > 0) {
316         ret = read(ep->fd, p, n);
317         if (ret < 0) {
318             if (errno != EAGAIN) {
319                 logerror("Error reading %s (%s)", ep->file, strerror(errno));
320                 break;
321             }
322         } else if (ret == 0) {
323             break;
324         } else {
325             p += ret;
326             n -= ret;
327         }
328     }
329
330     if (p == ep->cache)
331         return -1;              /* nothing read, old cache still ok */
332
333     ep->baseid = start;
334     ep->cids = (p - ep->cache) / ep->size;
335     return ep->cids;
336 }
337
338 /*
339  * Write COUNT elements from BUF to EP, starting at ID.
340  * Return 0 on success, -1 on error.
341  */
342 static int
343 do_write(struct empfile *ep, void *buf, int id, int count)
344 {
345     int i, n, ret;
346     char *p;
347     struct emptypedstr *elt;
348
349     if (CANT_HAPPEN(ep->fd < 0 || (ep->flags & EFF_PRIVATE)
350                     || id < 0 || count < 0))
351         return -1;
352
353     if (ep->flags & EFF_TYPED) {
354         for (i = 0; i < count; i++) {
355             /*
356              * TODO Oopses here could be due to bad data corruption.
357              * Fail instead of attempting to recover?
358              */
359             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
360             if (CANT_HAPPEN(elt->ef_type != ep->uid))
361                 elt->ef_type = ep->uid;
362             if (CANT_HAPPEN(elt->uid != id + i))
363                 elt->uid = id + i;
364         }
365     }
366
367     if (lseek(ep->fd, id * ep->size, SEEK_SET) == (off_t)-1) {
368         logerror("Error seeking %s (%s)", ep->file, strerror(errno));
369         return -1;
370     }
371
372     p = buf;
373     n = count * ep->size;
374     while (n > 0) {
375         ret = write(ep->fd, p, n);
376         if (ret < 0) {
377             if (errno != EAGAIN) {
378                 logerror("Error writing %s (%s)", ep->file, strerror(errno));
379                 /* FIXME if this extended file, truncate back to old size */
380                 return -1;
381             }
382         } else {
383             p += ret;
384             n -= ret;
385         }
386     }
387
388     return 0;
389 }
390
391 /*
392  * Write element ID into table TYPE from buffer FROM.
393  * FIXME pass buffer size!
394  * If table is file-backed and not privately mapped, write through
395  * cache straight to disk.
396  * Cannot write beyond the end of fully cached table (flags & EFF_MEM).
397  * Can write at the end of partially cached table.
398  * Return non-zero on success, zero on failure.
399  */
400 int
401 ef_write(int type, int id, void *from)
402 {
403     struct empfile *ep;
404     char *to;
405
406     if (ef_check(type) < 0)
407         return 0;
408     ep = &empfile[type];
409     if (CANT_HAPPEN((ep->flags & (EFF_MEM | EFF_PRIVATE)) == EFF_PRIVATE))
410         return 0;
411     if (ep->prewrite)
412         ep->prewrite(id, from);
413     if (CANT_HAPPEN((ep->flags & EFF_MEM) ? id >= ep->fids : id > ep->fids))
414         return 0;               /* not implemented */
415     if (!(ep->flags & EFF_PRIVATE)) {
416         if (do_write(ep, from, id, 1) < 0)
417             return 0;
418     }
419     if (id >= ep->baseid && id < ep->baseid + ep->cids) {
420         /* update the cache if necessary */
421         to = ep->cache + (id - ep->baseid) * ep->size;
422         if (to != from)
423             memcpy(to, from, ep->size);
424     }
425     if (id >= ep->fids) {
426         /* write beyond end of file extends it, take note */
427         ep->fids = id + 1;
428     }
429     return 1;
430 }
431
432 /*
433  * Extend table TYPE by COUNT elements.
434  * Any pointers obtained from ef_ptr() become invalid.
435  * Return non-zero on success, zero on failure.
436  */
437 int
438 ef_extend(int type, int count)
439 {
440     struct empfile *ep;
441     char *p;
442     int i, id;
443
444     if (ef_check(type) < 0)
445         return 0;
446     ep = &empfile[type];
447     if (CANT_HAPPEN(count < 0))
448         return 0;
449
450     id = ep->fids;
451     if (ep->flags & EFF_MEM) {
452         if (id + count > ep->csize) {
453             if (ep->flags & EFF_STATIC) {
454                 logerror("Can't extend %s beyond %d elements",
455                          ep->file, ep->csize);
456                 return 0;
457             }
458             if (!ef_realloc_cache(ep, id + count)) {
459                 logerror("Can't extend %s to %d elements (%s)",
460                          ep->file, id + count, strerror(errno));
461                 return 0;
462             }
463         }
464         p = ep->cache + id * ep->size;
465         do_blank(ep, p, id, count);
466         if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
467             if (do_write(ep, p, id, count) < 0)
468                 return 0;
469         }
470         ep->cids += count;
471     } else {
472         /* need a buffer, steal last cache slot */
473         if (ep->cids == ep->csize)
474             ep->cids--;
475         p = ep->cache + ep->cids * ep->size;
476         for (i = 0; i < count; i++) {
477             do_blank(ep, p, id + i, 1);
478             if (do_write(ep, p, id + i, 1) < 0)
479                 return 0;
480         }
481     }
482     ep->fids += count;
483     return 1;
484 }
485
486 /*
487  * Initialize element ID for EP in BUF.
488  * FIXME pass buffer size!
489  */
490 void
491 ef_blank(int type, int id, void *buf)
492 {
493     if (ef_check(type) < 0)
494         return;
495     do_blank(&empfile[type], buf, id, 1);
496 }
497
498 /*
499  * Initialize COUNT elements of EP in BUF, starting with element ID.
500  */
501 static void
502 do_blank(struct empfile *ep, void *buf, int id, int count)
503 {
504     int i;
505     struct emptypedstr *elt;
506
507     memset(buf, 0, count * ep->size);
508     if (ep->flags & EFF_TYPED) {
509         for (i = 0; i < count; i++) {
510             elt = (struct emptypedstr *)((char *)buf + i * ep->size);
511             elt->ef_type = ep->uid;
512             elt->uid = id + i;
513         }
514     }
515 }
516
517 /*
518  * Truncate table TYPE to COUNT elements.
519  * Any pointers obtained from ef_ptr() become invalid.
520  * Return non-zero on success, zero on failure.
521  */
522 int
523 ef_truncate(int type, int count)
524 {
525     struct empfile *ep;
526
527     if (ef_check(type) < 0)
528         return 0;
529     ep = &empfile[type];
530     if (CANT_HAPPEN(count < 0 || count > ep->fids))
531         return 0;
532
533     if (ep->fd >= 0 && !(ep->flags & EFF_PRIVATE)) {
534         if (ftruncate(ep->fd, count * ep->size) < 0) {
535             logerror("Can't truncate %s to %d elements (%s)",
536                      ep->file, count, strerror(errno));
537             return 0;
538         }
539     }
540     ep->fids = count;
541
542     if (ep->flags & EFF_MEM) {
543         if (!(ep->flags & EFF_STATIC)) {
544             if (!ef_realloc_cache(ep, count)) {
545                 logerror("Can't shrink cache after truncate");
546                 /* continue with unshrunk cache */
547             }
548         }
549         ep->cids = count;
550     } else {
551         if (ep->baseid >= count)
552             ep->cids = 0;
553         else if (ep->cids > count - ep->baseid)
554             ep->cids = count - ep->baseid;
555     }
556
557     return 1;
558 }
559
560 struct castr *
561 ef_cadef(int type)
562 {
563     return empfile[type].cadef;
564 }
565
566 int
567 ef_nelem(int type)
568 {
569     return empfile[type].fids;
570 }
571
572 int
573 ef_flags(int type)
574 {
575     return empfile[type].flags;
576 }
577
578 time_t
579 ef_mtime(int type)
580 {
581     if (empfile[type].fd <= 0)
582         return 0;
583     return fdate(empfile[type].fd);
584 }
585
586 /*
587  * Search for a table matching NAME, return its table type.
588  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
589  * several.
590  */
591 int
592 ef_byname(char *name)
593 {
594     return stmtch(name, empfile, offsetof(struct empfile, name),
595                   sizeof(empfile[0]));
596 }
597
598 /*
599  * Search CHOICES[] for a table type matching NAME, return it.
600  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
601  * several.
602  * CHOICES[] must be terminated with a negative value.
603  */
604 int
605 ef_byname_from(char *name, int choices[])
606 {
607     int res;
608     int *p;
609
610     res = M_NOTFOUND;
611     for (p = choices; *p >= 0; p++) {
612         if (ef_check(*p) < 0)
613             continue;
614         switch (mineq(name, empfile[*p].name)) {
615         case ME_MISMATCH:
616             break;
617         case ME_PARTIAL:
618             if (res >= 0)
619                 return M_NOTUNIQUE;
620             res = *p;
621             break;
622         case ME_EXACT:
623             return *p;
624         }
625     }
626     return res;
627 }
628
629 char *
630 ef_nameof(int type)
631 {
632     if (ef_check(type) < 0)
633         return "bad ef_type";
634     return empfile[type].name;
635 }
636
637 int
638 ef_check(int type)
639 {
640     if (CANT_HAPPEN((unsigned)type >= EF_MAX))
641         return -1;
642     return 0;
643 }
644
645 /*
646  * Ensure file-backed table contains ID.
647  * If necessary, extend it in steps of COUNT elements.
648  * Return non-zero on success, zero on failure.
649  */
650 int
651 ef_ensure_space(int type, int id, int count)
652 {
653     if (ef_check(type) < 0)
654         return 0;
655     CANT_HAPPEN(id < 0);
656
657     while (id >= empfile[type].fids) {
658         if (!ef_extend(type, count))
659             return 0;
660     }
661     return 1;
662 }