Added O_BINARY to open calls.
[idzebra-moved-to-github.git] / bfile / mfile.c
1 /*
2  * Copyright (C) 1994, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: mfile.c,v $
7  * Revision 1.22  1997-09-04 13:56:39  adam
8  * Added O_BINARY to open calls.
9  *
10  * Revision 1.21  1996/10/29 13:56:18  adam
11  * Include of zebrautl.h instead of alexutil.h.
12  *
13  * Revision 1.20  1996/05/14 12:10:16  quinn
14  * Bad areadef scan
15  *
16  * Revision 1.19  1996/05/01  07:16:30  quinn
17  * Fixed ancient bug.
18  *
19  * Revision 1.18  1996/04/09  06:47:30  adam
20  * Function scan_areadef doesn't use sscanf (%n fails on this Linux).
21  *
22  * Revision 1.17  1996/03/20 13:29:11  quinn
23  * Bug-fix
24  *
25  * Revision 1.16  1995/12/12  15:57:57  adam
26  * Implemented mf_unlink. cf_unlink uses mf_unlink.
27  *
28  * Revision 1.15  1995/12/08  16:21:14  adam
29  * Work on commit/update.
30  *
31  * Revision 1.14  1995/12/05  13:12:37  quinn
32  * Added <errno.h>
33  *
34  * Revision 1.13  1995/11/30  17:00:50  adam
35  * Several bug fixes. Commit system runs now.
36  *
37  * Revision 1.12  1995/11/24  17:26:11  quinn
38  * Mostly about making some ISAM stuff in the config file optional.
39  *
40  * Revision 1.11  1995/11/13  09:32:43  quinn
41  * Comment work.
42  *
43  * Revision 1.10  1995/09/04  12:33:22  adam
44  * Various cleanup. YAZ util used instead.
45  *
46  * Revision 1.9  1994/11/04  14:26:39  quinn
47  * bug-fix.
48  *
49  * Revision 1.8  1994/10/05  16:56:42  quinn
50  * Minor.
51  *
52  * Revision 1.7  1994/09/19  14:12:37  quinn
53  * dunno.
54  *
55  * Revision 1.6  1994/09/14  13:10:15  quinn
56  * Corrected some bugs in the init-phase
57  *
58  * Revision 1.5  1994/09/12  08:01:51  quinn
59  * Small
60  *
61  * Revision 1.4  1994/09/01  14:51:07  quinn
62  * Allowed mf_write to write beyond eof+1.
63  *
64  * Revision 1.3  1994/08/24  09:37:17  quinn
65  * Changed reaction to read return values.
66  *
67  * Revision 1.2  1994/08/23  14:50:48  quinn
68  * Fixed mf_close().
69  *
70  * Revision 1.1  1994/08/23  14:41:33  quinn
71  * First functional version.
72  *
73  */
74
75
76  /*
77   * TODO: The size estimates in init may not be accurate due to
78   * only partially written final blocks.
79   */
80
81 #include <sys/types.h>
82 #include <fcntl.h>
83 #include <unistd.h>
84 #include <dirent.h>
85 #include <stdlib.h>
86 #include <stdio.h>
87 #include <assert.h>
88 #include <errno.h>
89
90 #include <zebrautl.h>
91 #include <mfile.h>
92
93 static MFile_area_struct *open_areas = 0;
94 static MFile_area_struct *default_area = 0;
95
96 static int scan_areadef(MFile_area ma, const char *name)
97 {
98     /*
99      * If no definition is given, use current directory, unlimited.
100      */
101     const char *ad = res_get_def(common_resource, name, ".:-1b");
102     char dirname[FILENAME_MAX+1]; 
103     mf_dir **dp = &ma->dirs, *dir = *dp;
104
105     if (!ad)
106     {
107         logf (LOG_FATAL, "Could not find resource '%s'", name);
108         return -1;
109     }
110     for (;;)
111     {
112         const char *ad0 = ad;
113         int i = 0, fact = 1, multi, size = 0;
114
115         while (*ad == ' ' || *ad == '\t')
116             ad++;
117         if (!*ad)
118             break;
119         while (*ad && *ad != ':')
120         {
121             if (i < FILENAME_MAX)
122                 dirname[i++] = *ad;
123             ad++;
124         }
125         dirname[i] = '\0';
126         if (*ad++ != ':')
127         {
128             logf (LOG_FATAL, "Missing colon after path: %s", ad0);
129             return -1;
130         }
131         if (i == 0)
132         {
133             logf (LOG_FATAL, "Empty path: %s", ad0);
134             return -1;
135         }
136         while (*ad == ' ' || *ad == '\t')
137             ad++;
138         if (*ad == '-')
139         {
140             fact = -1;
141             ad++;
142         }
143         else if (*ad == '+')
144             ad++;
145         size = 0;
146         if (*ad < '0' || *ad > '9')
147         {
148             logf (LOG_FATAL, "Missing size after path: %s", ad0);
149             return -1;
150         }
151         size = 0;
152         while (*ad >= '0' && *ad <= '9')
153             size = size*10 + (*ad++ - '0');
154         switch (*ad)
155         {
156             case 'B': case 'b': multi = 1; break;
157             case 'K': case 'k': multi = 1024; break;
158             case 'M': case 'm': multi = 1048576; break;
159             case '\0':
160                 logf (LOG_FATAL, "Missing unit: %s", ad0);
161                 return -1;
162             default:
163                 logf (LOG_FATAL, "Illegal unit: %c in %s", *ad, ad0);
164                 return -1;
165         }
166         ad++;
167         *dp = dir = xmalloc(sizeof(mf_dir));
168         dir->next = 0;
169         strcpy(dir->name, dirname);
170         dir->max_bytes = dir->avail_bytes = fact * size * multi;
171         dp = &dir->next;
172     }
173     return 0;
174 }
175
176 static int file_position(MFile mf, int pos, int offset)
177 {
178     int off = 0, c = mf->cur_file, ps;
179
180     if ((c > 0 && pos <= mf->files[c-1].top) ||
181         (c < mf->no_files -1 && pos > mf->files[c].top))
182     {
183         c = 0;
184         while (c + 1 < mf->no_files && mf->files[c].top < pos)
185         {
186             off += mf->files[c].blocks;
187             c++;
188         }
189         assert(c < mf->no_files);
190     }
191     else
192         off = c ? (mf->files[c-1].top + 1) : 0;
193     if (mf->files[c].fd < 0 && (mf->files[c].fd = open(mf->files[c].path,
194         mf->wr ? (O_BINARY|O_RDWR|O_CREAT) : (O_BINARY|O_RDONLY), 0666)) < 0)
195     {
196         if (!mf->wr && errno == ENOENT && off == 0)
197             return -2;
198         logf (LOG_FATAL|LOG_ERRNO, "Failed to open %s", mf->files[c].path);
199         return -1;
200     }
201     if (lseek(mf->files[c].fd, (ps = pos - off) * mf->blocksize + offset,
202         SEEK_SET) < 0)
203     {
204         logf (LOG_FATAL|LOG_ERRNO, "Failed to seek in %s", mf->files[c].path);
205         return -1;
206     }
207     mf->cur_file = c;
208     return ps;
209 }
210
211 static int cmp_part_file(const void *p1, const void *p2)
212 {
213     return ((part_file *)p1)->number - ((part_file *)p2)->number;
214 }
215
216 /*
217  * Create a new area, cotaining metafiles in directories.
218  * Find the part-files in each directory, and inventory the existing metafiles.
219  */
220 MFile_area mf_init(const char *name)
221 {
222     MFile_area ma = xmalloc(sizeof(MFile_area_struct)), mp;
223     mf_dir *dirp;
224     meta_file *meta_f;
225     part_file *part_f = 0;
226     DIR *dd;
227     struct dirent *dent;
228     int fd, number;
229     char metaname[FILENAME_MAX+1], tmpnam[FILENAME_MAX+1];
230
231     logf (LOG_DEBUG, "mf_init(%s)", name);
232     for (mp = open_areas; mp; mp = mp->next)
233         if (!strcmp(name, mp->name))
234             return mp;
235     ma = xmalloc(sizeof(MFile_area_struct));
236     strcpy(ma->name, name);
237     ma->next = open_areas;
238     open_areas = ma;
239     ma->mfiles = 0;
240     ma->dirs = 0;
241     if (scan_areadef(ma, name) < 0)
242     {
243         logf (LOG_FATAL, "Failed to access description of '%s'", name);
244         return 0;
245     }
246     /* look at each directory */
247     for (dirp = ma->dirs; dirp; dirp = dirp->next)
248     {
249         if (!(dd = opendir(dirp->name)))
250         {
251             logf (LOG_FATAL|LOG_ERRNO, "Failed to open %s", dirp->name);
252             return 0;
253         }
254         /* look at each file */
255         while ((dent = readdir(dd)))
256         {
257             if (*dent->d_name == '.')
258                 continue;
259             if (sscanf(dent->d_name, "%[^.].mf.%d", metaname, &number) != 2)
260             {
261                 logf (LOG_DEBUG, "bf: %s is not a part-file.", dent->d_name);
262                 continue;
263             }
264             for (meta_f = ma->mfiles; meta_f; meta_f = meta_f->next)
265             {
266                 /* known metafile */
267                 if (!strcmp(meta_f->name, metaname))
268                 {
269                     part_f = &meta_f->files[meta_f->no_files++];
270                     break;
271                 }
272             }
273             /* new metafile */
274             if (!meta_f)
275             {
276                 meta_f = xmalloc(sizeof(*meta_f));
277                 meta_f->ma = ma;
278                 meta_f->next = ma->mfiles;
279                 meta_f->open = 0;
280                 meta_f->cur_file = -1;
281                 ma->mfiles = meta_f;
282                 strcpy(meta_f->name, metaname);
283                 part_f = &meta_f->files[0];
284                 meta_f->no_files = 1;
285             }
286             part_f->number = number;
287             part_f->dir = dirp;
288             part_f->fd = -1;
289             sprintf(tmpnam, "%s/%s", dirp->name, dent->d_name);
290             part_f->path = xstrdup(tmpnam);
291             /* get size */
292             if ((fd = open(part_f->path, O_BINARY|O_RDONLY)) < 0)
293             {
294                 logf (LOG_FATAL|LOG_ERRNO, "Failed to access %s",
295                       dent->d_name);
296                 return 0;
297             }
298             if ((part_f->bytes = lseek(fd, 0, SEEK_END)) < 0)
299             {
300                 logf (LOG_FATAL|LOG_ERRNO, "Failed to seek in %s",
301                       dent->d_name);
302                 return 0;
303             }
304             close(fd);
305             if (dirp->max_bytes >= 0)
306                 dirp->avail_bytes -= part_f->bytes;
307         }
308         closedir(dd);
309     }
310     for (meta_f = ma->mfiles; meta_f; meta_f = meta_f->next)
311     {
312         logf (LOG_DEBUG, "mf_init: %s consists of %d part(s)", meta_f->name,
313               meta_f->no_files);
314         qsort(meta_f->files, meta_f->no_files, sizeof(part_file),
315               cmp_part_file);
316     }
317     return ma;
318 }
319
320 /*
321  * Open a metafile.
322  * If !ma, Use MF_DEFAULT_AREA.
323  */
324 MFile mf_open(MFile_area ma, const char *name, int block_size, int wflag)
325 {
326     struct meta_file *new;
327     int i;
328     char tmp[FILENAME_MAX+1];
329     mf_dir *dp;
330
331     logf(LOG_DEBUG, "mf_open(%s bs=%d, %s)", name, block_size,
332          wflag ? "RW" : "RDONLY");
333     if (!ma)
334     {
335         if (!default_area && !(default_area = mf_init(MF_DEFAULT_AREA)))
336         {
337             logf (LOG_FATAL, "Failed to open default area.");
338             return 0;
339         }
340         ma = default_area;
341     }
342     for (new = ma->mfiles; new; new = new->next)
343         if (!strcmp(name, new->name))
344             if (new->open)
345                 abort();
346             else
347                 break;
348     if (!new)
349     {
350         new = xmalloc(sizeof(*new));
351         strcpy(new->name, name);
352         /* allocate one, empty file */
353         new->no_files = 1;
354         new->files[0].bytes = new->files[0].blocks = 0;
355         new->files[0].top = -1;
356         new->files[0].number = 0;
357         new->files[0].fd = -1;
358         new->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
359         for (dp = ma->dirs; dp && dp->max_bytes >= 0 && dp->avail_bytes <
360             new->min_bytes_creat; dp = dp->next);
361         if (!dp)
362         {
363             logf (LOG_FATAL, "Insufficient space for new mfile.");
364             return 0;
365         }
366         new->files[0].dir = dp;
367         sprintf(tmp, "%s/%s.mf.%d", dp->name, new->name, 0);
368         new->files[0].path = xstrdup(tmp);
369         new->ma = ma;
370     }
371     else
372     {
373         for (i = 0; i < new->no_files; i++)
374         {
375             if (new->files[i].bytes % block_size)
376                 new->files[i].bytes += block_size - new->files[i].bytes %
377                     block_size;
378             new->files[i].blocks = new->files[i].bytes / block_size;
379         }
380         assert(!new->open);
381     }
382     new->blocksize = block_size;
383     new->min_bytes_creat = MF_MIN_BLOCKS_CREAT * block_size;
384     new->wr=wflag;
385     new->cur_file = 0;
386     new->open = 1;
387
388     for (i = 0; i < new->no_files; i++)
389     {
390         new->files[i].blocks = new->files[i].bytes / new->blocksize;
391         if (i == new->no_files - 1)
392             new->files[i].top = -1;
393         else
394             new->files[i].top = i ? (new->files[i-1].top + new->files[i].blocks)
395                 : (new->files[i].blocks - 1);
396     }
397     return new;
398 }
399
400 /*
401  * Close a metafile.
402  */
403 int mf_close(MFile mf)
404 {
405     int i;
406
407     logf (LOG_DEBUG, "mf_close(%s)", mf->name);
408     assert(mf->open);
409     for (i = 0; i < mf->no_files; i++)
410         if (mf->files[i].fd >= 0)
411         {
412             close(mf->files[i].fd);
413             mf->files[i].fd = -1;
414         }
415     mf->open = 0;
416     return 0;
417 }
418
419 /*
420  * Read one block from a metafile. Interface mirrors bfile.
421  */
422 int mf_read(MFile mf, int no, int offset, int num, void *buf)
423 {
424     int rd, toread;
425
426     if ((rd = file_position(mf, no, offset)) < 0)
427         if (rd == -2)
428             return 0;
429         else
430             exit(1);
431     toread = num ? num : mf->blocksize;
432     if ((rd = read(mf->files[mf->cur_file].fd, buf, toread)) < 0)
433     {
434         logf (LOG_FATAL|LOG_ERRNO, "mf_read: Read failed (%s)",
435               mf->files[mf->cur_file].path);
436         exit(1);
437     }
438     else if (rd < toread)
439         return 0;
440     else
441         return 1;
442 }
443
444 /*
445  * Write.
446  */
447 int mf_write(MFile mf, int no, int offset, int num, const void *buf)
448 {
449     int ps, nblocks, towrite;
450     mf_dir *dp;
451     char tmp[FILENAME_MAX+1];
452     unsigned char dummych = '\xff';
453
454     if ((ps = file_position(mf, no, offset)) < 0)
455         exit(1);
456     /* file needs to grow */
457     while (ps >= mf->files[mf->cur_file].blocks)
458     {
459         /* file overflow - allocate new file */
460         if (mf->files[mf->cur_file].dir->max_bytes >= 0 &&
461             (ps - mf->files[mf->cur_file].blocks + 1) * mf->blocksize >
462             mf->files[mf->cur_file].dir->avail_bytes)
463         {
464             /* cap off file? */
465             if ((nblocks = mf->files[mf->cur_file].dir->avail_bytes /
466                 mf->blocksize) > 0)
467             {
468                 logf (LOG_DEBUG, "Capping off file %s at pos %d",
469                     mf->files[mf->cur_file].path, nblocks);
470                 if ((ps = file_position(mf,
471                     (mf->cur_file ? mf->files[mf->cur_file-1].top : 0) +
472                     mf->files[mf->cur_file].blocks + nblocks, 0)) < 0)
473                         exit(1);
474                 if (write(mf->files[mf->cur_file].fd, &dummych, 1) < 1)
475                 {
476                     logf (LOG_ERRNO|LOG_FATAL, "write dummy");
477                     exit(1);
478                 }
479                 mf->files[mf->cur_file].blocks += nblocks;
480                 mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
481                 mf->files[mf->cur_file].dir->avail_bytes -= nblocks *
482                     mf->blocksize;
483             }
484             /* get other bit */
485             logf (LOG_DEBUG, "Creating new file.");
486             for (dp = mf->ma->dirs; dp && dp->max_bytes >= 0 &&
487                 dp->avail_bytes < mf->min_bytes_creat; dp = dp->next);
488             if (!dp)
489             {
490                 logf (LOG_FATAL, "Cannot allocate more space for %s",
491                       mf->name);
492                 exit(1);
493             }
494             mf->files[mf->cur_file].top = (mf->cur_file ?
495                 mf->files[mf->cur_file-1].top : -1) +
496                 mf->files[mf->cur_file].blocks;
497             mf->files[++(mf->cur_file)].top = -1;
498             mf->files[mf->cur_file].dir = dp;
499             mf->files[mf->cur_file].number =
500                 mf->files[mf->cur_file-1].number + 1;
501             mf->files[mf->cur_file].blocks =
502                 mf->files[mf->cur_file].bytes = 0;
503             mf->files[mf->cur_file].fd = -1;
504             sprintf(tmp, "%s/%s.mf.%d", dp->name, mf->name,
505                 mf->files[mf->cur_file].number);
506             mf->files[mf->cur_file].path = xstrdup(tmp);
507             mf->no_files++;
508             /* open new file and position at beginning */
509             if ((ps = file_position(mf, no, offset)) < 0)
510                 exit(1);
511         }
512         else
513         {
514             nblocks = ps - mf->files[mf->cur_file].blocks + 1;
515             mf->files[mf->cur_file].blocks += nblocks;
516             mf->files[mf->cur_file].bytes += nblocks * mf->blocksize;
517             if (mf->files[mf->cur_file].dir->max_bytes >= 0)
518                 mf->files[mf->cur_file].dir->avail_bytes -=
519                 nblocks * mf->blocksize;
520         }
521     }
522     towrite = num ? num : mf->blocksize;
523     if (write(mf->files[mf->cur_file].fd, buf, towrite) < towrite)
524     {
525         logf (LOG_FATAL|LOG_ERRNO, "Write failed");
526         exit(1);
527     }
528     return 0;
529 }
530
531 /*
532  * Destroy a metafile, unlinking component files. File must be open.
533  */
534 int mf_unlink(MFile mf)
535 {
536     int i;
537
538     for (i = 0; i < mf->no_files; i++)
539         unlink (mf->files[i].path);
540     return 0;
541 }
542
543 /*
544  * Unlink the file by name, rather than MFile-handle. File should be closed.
545  */
546 int mf_unlink_name(MFile_area ma, const char *name)
547 {
548     abort();
549     return 0;
550 }