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