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