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