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