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