Search/scan uses character mapping module.
[idzebra-moved-to-github.git] / index / extract.c
1 /*
2  * Copyright (C) 1994-1996, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: extract.c,v $
7  * Revision 1.60  1996-06-04 10:18:12  adam
8  * Search/scan uses character mapping module.
9  *
10  * Revision 1.59  1996/05/14  15:47:07  adam
11  * Cleanup of various buffer size entities.
12  *
13  * Revision 1.58  1996/05/14  06:16:38  adam
14  * Compact use/set bytes used in search service.
15  *
16  * Revision 1.57  1996/05/13 14:23:04  adam
17  * Work on compaction of set/use bytes in dictionary.
18  *
19  * Revision 1.56  1996/05/09  09:54:42  adam
20  * Server supports maps from one logical attributes to a list of physical
21  * attributes.
22  * The extraction process doesn't make space consuming 'any' keys.
23  *
24  * Revision 1.55  1996/05/09  07:28:55  quinn
25  * Work towards phrases and multiple registers
26  *
27  * Revision 1.54  1996/05/01  13:46:35  adam
28  * First work on multiple records in one file.
29  * New option, -offset, to the "unread" command in the filter module.
30  *
31  * Revision 1.53  1996/04/26  12:09:43  adam
32  * Added a few comments.
33  *
34  * Revision 1.52  1996/04/25  13:27:57  adam
35  * Function recordExtract modified so that files with no keys (possibly empty)
36  * are ignored.
37  *
38  * Revision 1.51  1996/03/19  11:08:42  adam
39  * Bug fix: Log preamble wasn't always turned off after recordExtract.
40  *
41  * Revision 1.50  1996/02/12  18:45:36  adam
42  * New fileVerboseFlag in record group control.
43  *
44  * Revision 1.49  1996/02/05  12:29:57  adam
45  * Logging reduced a bit.
46  * The remaining running time is estimated during register merge.
47  *
48  * Revision 1.48  1996/02/01  20:53:26  adam
49  * The temporary per-record keys are compacted a little, and duplication
50  * of the per-records keys are avoided when they are saved in the record
51  * information buffer.
52  *
53  * Revision 1.47  1996/01/17  14:57:48  adam
54  * Prototype changed for reader functions in extract/retrieve. File
55  *  is identified by 'void *' instead of 'int.
56  *
57  * Revision 1.46  1995/12/15  14:57:16  adam
58  * Bug fix.
59  *
60  * Revision 1.45  1995/12/15  12:37:41  adam
61  * In addRecordKeyAny: Writes key only when attrSet != -1.
62  *
63  * Revision 1.44  1995/12/12  16:00:54  adam
64  * System call sync(2) used after update/commit.
65  * Locking (based on fcntl) uses F_EXLCK and F_SHLCK instead of F_WRLCK
66  * and F_RDLCK.
67  *
68  * Revision 1.43  1995/12/11  09:12:46  adam
69  * The rec_get function returns NULL if record doesn't exist - will
70  * happen in the server if the result set records have been deleted since
71  * the creation of the set (i.e. the search).
72  * The server saves a result temporarily if it is 'volatile', i.e. the
73  * set is register dependent.
74  *
75  * Revision 1.42  1995/12/07  17:38:46  adam
76  * Work locking mechanisms for concurrent updates/commit.
77  *
78  * Revision 1.41  1995/12/06  16:06:42  adam
79  * Better diagnostics. Work on 'real' dictionary deletion.
80  *
81  * Revision 1.40  1995/12/05  16:57:40  adam
82  * More work on regular patterns.
83  *
84  * Revision 1.39  1995/12/05  13:20:18  adam
85  * Bug fix: file_read sometimes returned early EOF.
86  *
87  * Revision 1.38  1995/12/04  17:59:21  adam
88  * More work on regular expression conversion.
89  *
90  * Revision 1.37  1995/12/04  14:22:27  adam
91  * Extra arg to recType_byName.
92  * Started work on new regular expression parsed input to
93  * structured records.
94  *
95  * Revision 1.36  1995/11/30  08:34:29  adam
96  * Started work on commit facility.
97  * Changed a few malloc/free to xmalloc/xfree.
98  *
99  * Revision 1.35  1995/11/28  14:26:21  adam
100  * Bug fix: recordId with constant wasn't right.
101  * Bug fix: recordId dictionary entry wasn't deleted when needed.
102  *
103  * Revision 1.34  1995/11/28  09:09:38  adam
104  * Zebra config renamed.
105  * Use setting 'recordId' to identify record now.
106  * Bug fix in recindex.c: rec_release_blocks was invokeded even
107  * though the blocks were already released.
108  * File traversal properly deletes records when needed.
109  *
110  * Revision 1.33  1995/11/27  09:56:20  adam
111  * Record info elements better enumerated. Internal store of records.
112  *
113  * Revision 1.32  1995/11/25  10:24:05  adam
114  * More record fields - they are enumerated now.
115  * New options: flagStoreData flagStoreKey.
116  *
117  * Revision 1.31  1995/11/24  11:31:35  adam
118  * Commands add & del read filenames from stdin if source directory is
119  * empty.
120  * Match criteria supports 'constant' strings.
121  *
122  * Revision 1.30  1995/11/22  17:19:16  adam
123  * Record management uses the bfile system.
124  *
125  * Revision 1.29  1995/11/21  15:01:14  adam
126  * New general match criteria implemented.
127  * New feature: document groups.
128  *
129  * Revision 1.28  1995/11/21  09:20:30  adam
130  * Yet more work on record match.
131  *
132  * Revision 1.27  1995/11/20  16:59:45  adam
133  * New update method: the 'old' keys are saved for each records.
134  *
135  * Revision 1.26  1995/11/20  11:56:24  adam
136  * Work on new traversal.
137  *
138  * Revision 1.25  1995/11/16  15:34:54  adam
139  * Uses new record management system in both indexer and server.
140  *
141  * Revision 1.24  1995/11/15  19:13:08  adam
142  * Work on record management.
143  *
144  * Revision 1.23  1995/10/27  14:00:10  adam
145  * Implemented detection of database availability.
146  *
147  * Revision 1.22  1995/10/17  18:02:07  adam
148  * New feature: databases. Implemented as prefix to words in dictionary.
149  *
150  * Revision 1.21  1995/10/10  12:24:38  adam
151  * Temporary sort files are compressed.
152  *
153  * Revision 1.20  1995/10/06  13:52:05  adam
154  * Bug fixes. Handler may abort further scanning.
155  *
156  * Revision 1.19  1995/10/04  12:55:16  adam
157  * Bug fix in ranked search. Use=Any keys inserted.
158  *
159  * Revision 1.18  1995/10/04  09:37:08  quinn
160  * Fixed bug.
161  *
162  * Revision 1.17  1995/10/03  14:28:57  adam
163  * Buffered read in extract works.
164  *
165  * Revision 1.16  1995/10/03  14:28:45  adam
166  * Work on more effecient read handler in extract.
167  *
168  * Revision 1.15  1995/10/02  15:42:53  adam
169  * Extract uses file descriptors instead of FILE pointers.
170  *
171  * Revision 1.14  1995/10/02  15:29:13  adam
172  * More logging in file_extract.
173  *
174  * Revision 1.13  1995/09/29  14:01:39  adam
175  * Bug fixes.
176  *
177  * Revision 1.12  1995/09/28  14:22:56  adam
178  * Sort uses smaller temporary files.
179  *
180  * Revision 1.11  1995/09/28  12:10:31  adam
181  * Bug fixes. Field prefix used in queries.
182  *
183  * Revision 1.10  1995/09/28  09:19:41  adam
184  * xfree/xmalloc used everywhere.
185  * Extract/retrieve method seems to work for text records.
186  *
187  * Revision 1.9  1995/09/27  12:22:28  adam
188  * More work on extract in record control.
189  * Field name is not in isam keys but in prefix in dictionary words.
190  *
191  * Revision 1.8  1995/09/14  07:48:22  adam
192  * Record control management.
193  *
194  * Revision 1.7  1995/09/11  13:09:32  adam
195  * More work on relevance feedback.
196  *
197  * Revision 1.6  1995/09/08  14:52:27  adam
198  * Minor changes. Dictionary is lower case now.
199  *
200  * Revision 1.5  1995/09/06  16:11:16  adam
201  * Option: only one word key per file.
202  *
203  * Revision 1.4  1995/09/05  15:28:39  adam
204  * More work on search engine.
205  *
206  * Revision 1.3  1995/09/04  12:33:41  adam
207  * Various cleanup. YAZ util used instead.
208  *
209  * Revision 1.2  1995/09/04  09:10:34  adam
210  * More work on index add/del/update.
211  * Merge sort implemented.
212  * Initial work on z39 server.
213  *
214  * Revision 1.1  1995/09/01  14:06:35  adam
215  * Split of work into more files.
216  *
217  */
218 #include <stdio.h>
219 #include <assert.h>
220 #include <unistd.h>
221 #include <fcntl.h>
222
223 #include <alexutil.h>
224 #include <recctrl.h>
225 #include "index.h"
226
227 #include "zinfo.h"
228
229 static Dict matchDict;
230
231 static Records records = NULL;
232
233 static char **key_buf;
234 static size_t ptr_top;
235 static size_t ptr_i;
236 static size_t key_buf_used;
237 static int key_file_no;
238
239 static int records_inserted = 0;
240 static int records_updated = 0;
241 static int records_deleted = 0;
242 static int records_processed = 0;
243
244 static ZebTargetInfo *zti = NULL;
245
246 static void logRecord (int showFlag)
247 {
248     if (!showFlag)
249         ++records_processed;
250     if (showFlag || !(records_processed % 1000))
251     {
252         logf (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
253               records_processed, records_inserted, records_updated,
254               records_deleted);
255     }
256 }
257
258 void key_open (int mem)
259 {
260     if (mem < 50000)
261         mem = 50000;
262     key_buf = xmalloc (mem);
263     ptr_top = mem/sizeof(char*);
264     ptr_i = 0;
265
266     key_buf_used = 0;
267     key_file_no = 0;
268
269     if (!(matchDict = dict_open (GMATCH_DICT, 50, 1)))
270     {
271         logf (LOG_FATAL, "dict_open fail of %s", GMATCH_DICT);
272         exit (1);
273     }
274     assert (!records);
275     records = rec_open (1);
276 #if 1
277     zti = zebTargetInfo_open (records, 1);
278 #endif
279 }
280
281 struct encode_info {
282     int  sysno;
283     int  seqno;
284     char buf[768];
285 };
286
287 void encode_key_init (struct encode_info *i)
288 {
289     i->sysno = 0;
290     i->seqno = 0;
291 }
292
293 char *encode_key_int (int d, char *bp)
294 {
295     if (d <= 63)
296         *bp++ = d;
297     else if (d <= 16383)
298     {
299         *bp++ = 64 + (d>>8);
300         *bp++ = d  & 255;
301     }
302     else if (d <= 4194303)
303     {
304         *bp++ = 128 + (d>>16);
305         *bp++ = (d>>8) & 255;
306         *bp++ = d & 255;
307     }
308     else
309     {
310         *bp++ = 192 + (d>>24);
311         *bp++ = (d>>16) & 255;
312         *bp++ = (d>>8) & 255;
313         *bp++ = d & 255;
314     }
315     return bp;
316 }
317
318 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
319 {
320     struct it_key key;
321     char *bp = i->buf;
322
323     while ((*bp++ = *k++))
324         ;
325     memcpy (&key, k+1, sizeof(struct it_key));
326     bp = encode_key_int ( (key.sysno - i->sysno) * 2 + *k, bp);
327     if (i->sysno != key.sysno)
328     {
329         i->sysno = key.sysno;
330         i->seqno = 0;
331     }
332     bp = encode_key_int (key.seqno - i->seqno, bp);
333     i->seqno = key.seqno;
334     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
335     {
336         logf (LOG_FATAL|LOG_ERRNO, "fwrite");
337         exit (1);
338     }
339 }
340
341 void key_flush (void)
342 {
343     FILE *outf;
344     char out_fname[200];
345     char *prevcp, *cp;
346     struct encode_info encode_info;
347     
348     if (ptr_i <= 0)
349         return;
350
351     key_file_no++;
352     logf (LOG_LOG, "sorting section %d", key_file_no);
353     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_qsort_compare);
354     sprintf (out_fname, TEMP_FNAME, key_file_no);
355
356     if (!(outf = fopen (out_fname, "w")))
357     {
358         logf (LOG_FATAL|LOG_ERRNO, "fopen (4) %s", out_fname);
359         exit (1);
360     }
361     logf (LOG_LOG, "writing section %d", key_file_no);
362     prevcp = cp = key_buf[ptr_top-ptr_i];
363     
364     encode_key_init (&encode_info);
365     encode_key_write (cp, &encode_info, outf);
366     while (--ptr_i > 0)
367     {
368         cp = key_buf[ptr_top-ptr_i];
369         if (strcmp (cp, prevcp))
370         {
371             encode_key_init (&encode_info);
372             encode_key_write (cp, &encode_info, outf);
373             prevcp = cp;
374         }
375         else
376             encode_key_write (cp + strlen(cp), &encode_info, outf);
377     }
378     if (fclose (outf))
379     {
380         logf (LOG_FATAL|LOG_ERRNO, "fclose %s", out_fname);
381         exit (1);
382     }
383     logf (LOG_LOG, "finished section %d", key_file_no);
384     ptr_i = 0;
385     key_buf_used = 0;
386 }
387
388 int key_close (void)
389 {
390     key_flush ();
391     xfree (key_buf);
392 #if 1
393     zebTargetInfo_close (zti, 1);
394 #endif
395     rec_close (&records);
396     dict_close (matchDict);
397
398     logRecord (1);
399     return key_file_no;
400 }
401
402 static void wordInit (RecWord *p)
403 {
404     p->attrSet = 1;
405     p->attrUse = 1016;
406     p->which = Word_String;
407 }
408
409 struct recKeys {
410     int buf_used;
411     int buf_max;
412     char *buf;
413     char prevAttrSet;
414     short prevAttrUse;
415 } reckeys;
416
417 static void addRecordKey (const RecWord *p)
418 {
419     char *dst;
420     char attrSet;
421     short attrUse;
422     size_t i;
423     int lead = 0;
424
425     if (reckeys.buf_used+1024 > reckeys.buf_max)
426     {
427         char *b;
428
429         b = xmalloc (reckeys.buf_max += 128000);
430         if (reckeys.buf_used > 0)
431             memcpy (b, reckeys.buf, reckeys.buf_used);
432         xfree (reckeys.buf);
433         reckeys.buf = b;
434     }
435     dst = reckeys.buf + reckeys.buf_used;
436
437     attrSet = p->attrSet;
438     if (reckeys.buf_used > 0 && reckeys.prevAttrSet == attrSet)
439         lead |= 1;
440     else
441         reckeys.prevAttrSet = attrSet;
442     attrUse = p->attrUse;
443     if (reckeys.buf_used > 0 && reckeys.prevAttrUse == attrUse)
444         lead |= 2;
445     else
446         reckeys.prevAttrUse = attrUse;
447
448     *dst++ = lead;
449
450     if (!(lead & 1))
451     {
452         memcpy (dst, &attrSet, sizeof(attrSet));
453         dst += sizeof(attrSet);
454     }
455     if (!(lead & 2))
456     {
457         memcpy (dst, &attrUse, sizeof(attrUse));
458         dst += sizeof(attrUse);
459     }
460     switch (p->which)
461     {
462         case Word_String:
463             *dst++ = 'w';
464             break;
465         case Word_Phrase:
466             *dst++ = 'p';
467             break;
468         case Word_Numeric:
469             *dst++ = 'n';
470     }
471     for (i = 0; p->u.string[i]; i++)
472         *dst++ = p->u.string[i];
473     *dst++ = '\0';
474
475     memcpy (dst, &p->seqno, sizeof(p->seqno));
476     dst += sizeof(p->seqno);
477     reckeys.buf_used = dst - reckeys.buf;
478 }
479
480 static void flushRecordKeys (SYSNO sysno, int cmd, struct recKeys *reckeys, 
481                              const char *databaseName)
482 {
483     char attrSet = -1;
484     short attrUse = -1;
485     int off = 0;
486
487     if (zebTargetInfo_curDatabase (zti, databaseName))
488     {
489         if (zebTargetInfo_newDatabase (zti, databaseName))
490             abort ();
491     }
492     while (off < reckeys->buf_used)
493     {
494         const char *src = reckeys->buf + off;
495         struct it_key key;
496         int lead;
497     
498         lead = *src++;
499
500         if (!(lead & 1))
501         {
502             memcpy (&attrSet, src, sizeof(attrSet));
503             src += sizeof(attrSet);
504         }
505         if (!(lead & 2))
506         {
507             memcpy (&attrUse, src, sizeof(attrUse));
508             src += sizeof(attrUse);
509         }
510         if (key_buf_used + 1024 > (ptr_top-ptr_i)*sizeof(char*))
511             key_flush ();
512         ++ptr_i;
513         key_buf[ptr_top-ptr_i] = (char*)key_buf + key_buf_used;
514
515         lead = zebTargetInfo_lookupSU (zti, attrSet, attrUse);
516         if (lead < 0)
517             lead = zebTargetInfo_addSU (zti, attrSet, attrUse);
518         assert (lead > 0);
519         ((char*) key_buf) [key_buf_used++] = lead;
520         while (*src)
521             ((char*)key_buf) [key_buf_used++] = *src++;
522         src++;
523         ((char*)key_buf) [key_buf_used++] = '\0';
524         
525         ((char*) key_buf)[key_buf_used++] = cmd;
526
527         memcpy (&key.seqno, src, sizeof(key.seqno));
528         src += sizeof(key.seqno);
529         key.sysno = sysno;
530         memcpy ((char*)key_buf + key_buf_used, &key, sizeof(key));
531         key_buf_used += sizeof(key);
532         off = src - reckeys->buf;
533     }
534     assert (off == reckeys->buf_used);
535 }
536
537 static const char **searchRecordKey (struct recKeys *reckeys,
538                                int attrSetS, int attrUseS)
539 {
540     static const char *ws[32];
541     int off = 0;
542     int startSeq = -1;
543     int i;
544
545     for (i = 0; i<32; i++)
546         ws[i] = NULL;
547     
548     while (off < reckeys->buf_used)
549     {
550         const char *src = reckeys->buf + off;
551         char attrSet;
552         short attrUse;
553         int seqno;
554         const char *wstart;
555         
556         memcpy (&attrSet, src, sizeof(attrSet));
557         src += sizeof(attrSet);
558
559         memcpy (&attrUse, src, sizeof(attrUse));
560         src += sizeof(attrUse);
561
562         wstart = src;
563         while (*src++)
564             ;
565
566         memcpy (&seqno, src, sizeof(seqno));
567         src += sizeof(seqno);
568
569 #if 0
570         logf (LOG_LOG, "(%d,%d) %d %s", attrSet, attrUse, seqno, wstart);
571 #endif
572         if (attrUseS == attrUse && attrSetS == attrSet)
573         {
574             int woff;
575
576
577             if (startSeq == -1)
578                 startSeq = seqno;
579             woff = seqno - startSeq;
580             if (woff >= 0 && woff < 31)
581                 ws[woff] = wstart;
582         }
583
584         off = src - reckeys->buf;
585     }
586     assert (off == reckeys->buf_used);
587     return ws;
588 }
589
590 struct file_read_info {
591     off_t file_max;
592     off_t file_offset;
593     off_t file_moffset;
594     int file_more;
595     int fd;
596 };
597
598 static struct file_read_info *file_read_start (int fd)
599 {
600     struct file_read_info *fi = xmalloc (sizeof(*fi));
601
602     fi->fd = fd;
603     fi->file_max = 0;
604     fi->file_moffset = 0;
605     return fi;
606 }
607
608 static void file_read_stop (struct file_read_info *fi)
609 {
610     assert (fi);
611     xfree (fi);
612 }
613
614 static off_t file_seek (void *handle, off_t offset)
615 {
616     struct file_read_info *p = handle;
617     p->file_offset = offset;
618     return lseek (p->fd, offset, SEEK_SET);
619 }
620
621 static int file_read (void *handle, char *buf, size_t count)
622 {
623     struct file_read_info *p = handle;
624     int fd = p->fd;
625     int r;
626     r = read (fd, buf, count);
627     if (r > 0)
628     {
629         p->file_offset += r;
630         if (p->file_offset > p->file_max)
631             p->file_max = p->file_offset;
632     }
633     return r;
634 }
635
636 static void file_begin (void *handle)
637 {
638     struct file_read_info *p = handle;
639
640     p->file_offset = p->file_moffset;
641     if (p->file_moffset)
642         lseek (p->fd, p->file_moffset, SEEK_SET);
643     p->file_more = 0;
644 }
645
646 static void file_end (void *handle, off_t offset)
647 {
648     struct file_read_info *p = handle;
649
650     assert (p->file_more == 0);
651     p->file_more = 1;
652     p->file_moffset = offset;
653 }
654
655 static int atois (const char **s)
656 {
657     int val = 0, c;
658     while ( (c=**s) >= '0' && c <= '9')
659     {
660         val = val*10 + c - '0';
661         ++(*s);
662     }
663     return val;
664 }
665
666 static char *fileMatchStr (struct recKeys *reckeys, struct recordGroup *rGroup,
667                            const char *fname,
668                            const char *spec)
669 {
670     static char dstBuf[2048];
671     char *dst = dstBuf;
672     const char *s = spec;
673     static const char **w;
674     int i;
675
676     while (1)
677     {
678         while (*s == ' ' || *s == '\t')
679             s++;
680         if (!*s)
681             break;
682         if (*s == '(')
683         {
684             char matchFlag[32];
685             int attrSet, attrUse;
686             int first = 1;
687
688             s++;
689             attrSet = atois (&s);
690             if (*s != ',')
691             {
692                 logf (LOG_WARN, "Missing , in match criteria %s in group %s",
693                       spec, rGroup->groupName ? rGroup->groupName : "none");
694                 return NULL;
695             }
696             s++;
697             attrUse = atois (&s);
698             w = searchRecordKey (reckeys, attrSet, attrUse);
699             assert (w);
700
701             if (*s == ')')
702             {
703                 for (i = 0; i<32; i++)
704                     matchFlag[i] = 1;
705             }
706             else
707             {
708                 logf (LOG_WARN, "Missing ) in match criteria %s in group %s",
709                       spec, rGroup->groupName ? rGroup->groupName : "none");
710                 return NULL;
711             }
712             s++;
713
714             for (i = 0; i<32; i++)
715                 if (matchFlag[i] && w[i])
716                 {
717                     if (first)
718                     {
719                         *dst++ = ' ';
720                         first = 0;
721                     }
722                     strcpy (dst, w[i]);
723                     dst += strlen(w[i]);
724                 }
725             if (first)
726             {
727                 logf (LOG_WARN, "Record didn't contain match"
728                       " fields in (%d,%d)", attrSet, attrUse);
729                 return NULL;
730             }
731         }
732         else if (*s == '$')
733         {
734             int spec_len;
735             char special[64];
736             const char *spec_src = NULL;
737             const char *s1 = ++s;
738             while (*s1 && *s1 != ' ' && *s1 != '\t')
739                 s1++;
740
741             spec_len = s1 - s;
742             if (spec_len > 63)
743                 spec_len = 63;
744             memcpy (special, s, spec_len);
745             special[spec_len] = '\0';
746             s = s1;
747
748             if (!strcmp (special, "group"))
749                 spec_src = rGroup->groupName;
750             else if (!strcmp (special, "database"))
751                 spec_src = rGroup->databaseName;
752             else if (!strcmp (special, "filename"))
753                 spec_src = fname;
754             else if (!strcmp (special, "type"))
755                 spec_src = rGroup->recordType;
756             else 
757                 spec_src = NULL;
758             if (spec_src)
759             {
760                 strcpy (dst, spec_src);
761                 dst += strlen (spec_src);
762             }
763         }
764         else if (*s == '\"' || *s == '\'')
765         {
766             int stopMarker = *s++;
767             char tmpString[64];
768             int i = 0;
769
770             while (*s && *s != stopMarker)
771             {
772                 if (i < 63)
773                     tmpString[i++] = *s++;
774             }
775             if (*s)
776                 s++;
777             tmpString[i] = '\0';
778             strcpy (dst, tmpString);
779             dst += strlen (tmpString);
780         }
781         else
782         {
783             logf (LOG_WARN, "Syntax error in match criteria %s in group %s",
784                   spec, rGroup->groupName ? rGroup->groupName : "none");
785             return NULL;
786         }
787         *dst++ = 1;
788     }
789     if (dst == dstBuf)
790     {
791         logf (LOG_WARN, "No match criteria for record %s in group %s",
792               fname, rGroup->groupName ? rGroup->groupName : "none");
793         return NULL;
794     }
795     return dstBuf;
796 }
797
798 struct recordLogInfo {
799     const char *fname;
800     char *op;
801     struct recordGroup *rGroup;
802 };
803      
804 static void recordLogPreamble (int level, const char *msg, void *info)
805 {
806     struct recordLogInfo *p = info;
807     FILE *outf = log_file ();
808
809     if (level & LOG_LOG)
810         return ;
811     if (p->op) 
812         fprintf (outf, "%s of ", p->op);
813     fprintf (outf, "%s type %s\n", p->rGroup->recordType, p->fname);
814     log_event_start (NULL, NULL);
815 }
816
817 static int recordExtract (SYSNO *sysno, const char *fname,
818                           struct recordGroup *rGroup, int deleteFlag,
819                           struct file_read_info *fi, RecType recType,
820                           char *subType)
821 {
822     struct recExtractCtrl extractCtrl;
823     int r;
824     char *matchStr;
825     SYSNO sysnotmp;
826     off_t recordOffset = 0;
827     Record rec;
828     struct recordLogInfo logInfo;
829
830     logInfo.fname = fname;
831     logInfo.op = NULL;
832     logInfo.rGroup = rGroup;
833     log_event_start (recordLogPreamble, &logInfo);
834     
835     if (fi->fd != -1)
836     {
837         /* we are going to read from a file, so prepare the extraction */
838         extractCtrl.fh = fi;
839         extractCtrl.subType = subType;
840         extractCtrl.init = wordInit;
841         extractCtrl.add = addRecordKey;
842
843         reckeys.buf_used = 0;
844         reckeys.prevAttrUse = -1;
845         reckeys.prevAttrSet = -1;
846
847         recordOffset = fi->file_moffset;
848         extractCtrl.offset = recordOffset;
849         extractCtrl.readf = file_read;
850         extractCtrl.seekf = file_seek;
851         extractCtrl.endf = file_end;
852         r = (*recType->extract)(&extractCtrl);
853
854         if (r)      
855         {
856             /* error occured during extraction ... */
857             logf (LOG_WARN, "Couldn't extract file %s, code %d", fname, r);
858             return 0;
859         }
860         if (reckeys.buf_used == 0)
861         {
862             /* the extraction process returned no information - the record
863                is probably empty */
864             logf (LOG_WARN, "Empty file %s", fname);
865             return 0;
866         }
867     }
868
869     /* perform match if sysno not known and if match criteria is specified */
870        
871     matchStr = NULL;
872     if (!sysno) 
873     {
874         sysnotmp = 0;
875         sysno = &sysnotmp;
876         if (rGroup->recordId && *rGroup->recordId)
877         {
878             char *rinfo;
879         
880             matchStr = fileMatchStr (&reckeys, rGroup, fname, 
881                                      rGroup->recordId);
882             if (matchStr)
883             {
884                 rinfo = dict_lookup (matchDict, matchStr);
885                 if (rinfo)
886                     memcpy (sysno, rinfo+1, sizeof(*sysno));
887             }
888             else
889             {
890                 logf (LOG_WARN, "Bad match criteria");
891                 return 0;
892             }
893         }
894     }
895
896     if (! *sysno)
897     {
898         /* new record */
899         if (deleteFlag)
900         {
901             logf (LOG_LOG, "Cannot delete new record");
902             return 1;
903         }
904         logInfo.op = "add";
905         if (rGroup->fileVerboseFlag)
906             logf (LOG_LOG, "add %s %s+%ld", rGroup->recordType,
907                   fname, (long) recordOffset);
908         rec = rec_new (records);
909         *sysno = rec->sysno;
910
911         if (matchStr)
912         {
913             dict_insert (matchDict, matchStr, sizeof(*sysno), sysno);
914         }
915         flushRecordKeys (*sysno, 1, &reckeys, rGroup->databaseName);
916
917         records_inserted++;
918     }
919     else
920     {
921         /* record already exists */
922         struct recKeys delkeys;
923
924         rec = rec_get (records, *sysno);
925         assert (rec);
926         delkeys.buf_used = rec->size[recInfo_delKeys];
927         delkeys.buf = rec->info[recInfo_delKeys];
928         flushRecordKeys (*sysno, 0, &delkeys, rec->info[recInfo_databaseName]);
929         if (deleteFlag)
930         {
931             /* record going to be deleted */
932             logInfo.op = "delete";
933             if (!delkeys.buf_used)
934             {
935                 logf (LOG_WARN, "cannot delete; storeKeys false");
936             }
937             else
938             {
939                 if (rGroup->fileVerboseFlag)
940                     logf (LOG_LOG, "delete %s %s %ld", rGroup->recordType,
941                           fname, (long) recordOffset);
942                 records_deleted++;
943                 if (matchStr)
944                     dict_delete (matchDict, matchStr);
945                 rec_del (records, &rec);
946             }
947             logRecord (0);
948             return 1;
949         }
950         else
951         {
952             /* record going to be updated */
953             logInfo.op = "update";
954             if (!delkeys.buf_used)
955             {
956                 logf (LOG_WARN, "cannot update; storeKeys false");
957             }
958             else
959             {
960                 if (rGroup->fileVerboseFlag)
961                     logf (LOG_LOG, "update %s %s %ld", rGroup->recordType,
962                           fname, (long) recordOffset);
963                 flushRecordKeys (*sysno, 1, &reckeys, rGroup->databaseName); 
964                 records_updated++;
965             }
966         }
967     }
968     /* update file type */
969     xfree (rec->info[recInfo_fileType]);
970     rec->info[recInfo_fileType] =
971         rec_strdup (rGroup->recordType, &rec->size[recInfo_fileType]);
972
973     /* update filename */
974     xfree (rec->info[recInfo_filename]);
975     rec->info[recInfo_filename] =
976         rec_strdup (fname, &rec->size[recInfo_filename]);
977
978     /* update delete keys */
979     xfree (rec->info[recInfo_delKeys]);
980     if (reckeys.buf_used > 0 && rGroup->flagStoreKeys == 1)
981     {
982 #if 1
983         rec->size[recInfo_delKeys] = reckeys.buf_used;
984         rec->info[recInfo_delKeys] = reckeys.buf;
985         reckeys.buf = NULL;
986         reckeys.buf_max = 0;
987 #else
988         rec->info[recInfo_delKeys] = xmalloc (reckeys.buf_used);
989         rec->size[recInfo_delKeys] = reckeys.buf_used;
990         memcpy (rec->info[recInfo_delKeys], reckeys.buf,
991                 rec->size[recInfo_delKeys]);
992 #endif
993     }
994     else
995     {
996         rec->info[recInfo_delKeys] = NULL;
997         rec->size[recInfo_delKeys] = 0;
998     }
999
1000     /* update store data */
1001     xfree (rec->info[recInfo_storeData]);
1002     if (rGroup->flagStoreData == 1)
1003     {
1004         rec->size[recInfo_storeData] = fi->file_max;
1005         rec->info[recInfo_storeData] = xmalloc (fi->file_max);
1006         if (lseek (fi->fd, recordOffset, SEEK_SET) < 0)
1007         {
1008             logf (LOG_ERRNO|LOG_FATAL, "seek to %ld in %s", fname,
1009                   (long) recordOffset);
1010             exit (1);
1011         }
1012         if (read (fi->fd, rec->info[recInfo_storeData], fi->file_max)
1013             < fi->file_max)
1014         {
1015             logf (LOG_ERRNO|LOG_FATAL, "read %d bytes of %s",
1016                   fi->file_max, fname);
1017             exit (1);
1018         }
1019     }
1020     else
1021     {
1022         rec->info[recInfo_storeData] = NULL;
1023         rec->size[recInfo_storeData] = 0;
1024     }
1025     /* update database name */
1026     xfree (rec->info[recInfo_databaseName]);
1027     rec->info[recInfo_databaseName] =
1028         rec_strdup (rGroup->databaseName, &rec->size[recInfo_databaseName]); 
1029
1030     /* update offset */
1031     xfree (rec->info[recInfo_offset]);
1032
1033     rec->size[recInfo_offset] = sizeof(recordOffset);
1034     rec->info[recInfo_offset] = xmalloc (sizeof(recordOffset));
1035     memcpy (rec->info[recInfo_offset], &recordOffset, sizeof(recordOffset));
1036     
1037     /* commit this record */
1038     rec_put (records, &rec);
1039     logRecord (0);
1040     return 1;
1041 }
1042
1043 int fileExtract (SYSNO *sysno, const char *fname, 
1044                  const struct recordGroup *rGroupP, int deleteFlag)
1045 {
1046     int r, i, fd;
1047     char gprefix[128];
1048     char ext[128];
1049     char ext_res[128];
1050     char subType[128];
1051     RecType recType;
1052     struct recordGroup rGroupM;
1053     struct recordGroup *rGroup = &rGroupM;
1054     struct file_read_info *fi;
1055
1056     memcpy (rGroup, rGroupP, sizeof(*rGroupP));
1057    
1058     if (!rGroup->groupName || !*rGroup->groupName)
1059         *gprefix = '\0';
1060     else
1061         sprintf (gprefix, "%s.", rGroup->groupName);
1062
1063     logf (LOG_DEBUG, "fileExtract %s", fname);
1064
1065     /* determine file extension */
1066     for (i = strlen(fname); --i >= 0; )
1067         if (fname[i] == '/')
1068         {
1069             strcpy (ext, "");
1070             break;
1071         }
1072         else if (fname[i] == '.')
1073         {
1074             strcpy (ext, fname+i+1);
1075             break;
1076         }
1077     /* determine file type - depending on extension */
1078     if (!rGroup->recordType)
1079     {
1080         sprintf (ext_res, "%srecordType.%s", gprefix, ext);
1081         if (!(rGroup->recordType = res_get (common_resource, ext_res)))
1082         {
1083             sprintf (ext_res, "%srecordType", gprefix);
1084             if (!(rGroup->recordType = res_get (common_resource, ext_res)))
1085             {
1086                 if (rGroup->fileVerboseFlag)
1087                     logf (LOG_LOG, "? %s", fname);
1088                 return 0;
1089             }
1090         }
1091     }
1092     if (!rGroup->recordType)
1093     {
1094         if (rGroup->fileVerboseFlag)
1095             logf (LOG_LOG, "? record %s", fname);
1096         return 0;
1097     }
1098     if (!(recType = recType_byName (rGroup->recordType, subType)))
1099     {
1100         logf (LOG_WARN, "No such record type: %s", rGroup->recordType);
1101         return 0;
1102     }
1103
1104     /* determine match criteria */
1105     if (!rGroup->recordId)
1106     {
1107         sprintf (ext_res, "%srecordId.%s", gprefix, ext);
1108         rGroup->recordId = res_get (common_resource, ext_res);
1109     }
1110
1111     /* determine database name */
1112     if (!rGroup->databaseName)
1113     {
1114         sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
1115         if (!(rGroup->databaseName = res_get (common_resource, ext_res)))
1116         {
1117             sprintf (ext_res, "%sdatabase", gprefix);
1118             rGroup->databaseName = res_get (common_resource, ext_res);
1119         }
1120     }
1121     if (!rGroup->databaseName)
1122         rGroup->databaseName = "Default";
1123
1124     if (rGroup->flagStoreData == -1)
1125     {
1126         const char *sval;
1127         sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
1128         if (!(sval = res_get (common_resource, ext_res)))
1129         {
1130             sprintf (ext_res, "%sstoreData", gprefix);
1131             sval = res_get (common_resource, ext_res);
1132         }
1133         if (sval)
1134             rGroup->flagStoreData = atoi (sval);
1135     }
1136     if (rGroup->flagStoreData == -1)
1137         rGroup->flagStoreData = 0;
1138
1139     if (rGroup->flagStoreKeys == -1)
1140     {
1141         const char *sval;
1142
1143         sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
1144         if (!(sval = res_get (common_resource, ext_res)))
1145         {
1146             sprintf (ext_res, "%sstoreKeys", gprefix);
1147             sval = res_get (common_resource, ext_res);
1148         }
1149         if (sval)
1150             rGroup->flagStoreKeys = atoi (sval);
1151     }
1152     if (rGroup->flagStoreKeys == -1)
1153         rGroup->flagStoreKeys = 0;
1154
1155     if (sysno && deleteFlag)
1156         fd = -1;
1157     else
1158     {
1159         if ((fd = open (fname, O_RDONLY)) == -1)
1160         {
1161             logf (LOG_WARN|LOG_ERRNO, "open %s", fname);
1162             return 0;
1163         }
1164     }
1165     fi = file_read_start (fd);
1166     do
1167     {
1168         file_begin (fi);
1169         r = recordExtract (sysno, fname, rGroup, deleteFlag, fi,
1170                            recType, subType);
1171     } while (r && !sysno && fi->file_more);
1172     log_event_start (NULL, NULL);
1173     file_read_stop (fi);
1174     if (fd != -1)
1175         close (fd);
1176     return r;
1177 }
1178