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