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