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