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