Moved towards generic character mapping depending on "structure"
[idzebra-moved-to-github.git] / index / extract.c
1 /*
2  * Copyright (C) 1994-1997, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: extract.c,v $
7  * Revision 1.76  1997-10-27 14:33:04  adam
8  * Moved towards generic character mapping depending on "structure"
9  * field in abstract syntax file. Fixed a few memory leaks. Fixed
10  * bug with negative integers when doing searches with relational
11  * operators.
12  *
13  * Revision 1.75  1997/09/17 12:19:12  adam
14  * Zebra version corresponds to YAZ version 1.4.
15  * Changed Zebra server so that it doesn't depend on global common_resource.
16  *
17  * Revision 1.74  1997/09/09 13:38:06  adam
18  * Partial port to WIN95/NT.
19  *
20  * Revision 1.73  1997/09/04 13:57:20  adam
21  * New file extract/retrieve method tellf (added).
22  * Added O_BINARY for open calls.
23  *
24  * Revision 1.72  1997/07/15 16:32:29  adam
25  * Bug fix: Match handler didn't terminate the resulting string!
26  *
27  * Revision 1.71  1997/07/15 16:28:41  adam
28  * Bug fix: storeData didn't work with files with multiple records.
29  * Bug fix: fixed memory management with records; not really well
30  *  thought through.
31  *
32  * Revision 1.70  1997/07/01 13:00:42  adam
33  * Bug fix in routine searchRecordKey: uninitialized variables.
34  *
35  * Revision 1.69  1997/04/29 09:26:03  adam
36  * Bug fix: generic recordId handling didn't work for compressed internal
37  * keys.
38  *
39  * Revision 1.68  1997/02/12 20:39:45  adam
40  * Implemented options -f <n> that limits the log to the first <n>
41  * records.
42  * Changed some log messages also.
43  *
44  * Revision 1.67  1996/11/15 15:02:14  adam
45  * Minor changes regarding logging.
46  *
47  * Revision 1.66  1996/11/14  09:52:21  adam
48  * Strings in record keys bound by IT_MAX_WORD.
49  *
50  * Revision 1.65  1996/11/14  08:57:56  adam
51  * Reduction of storeKeys area.
52  *
53  * Revision 1.64  1996/11/08 11:10:16  adam
54  * Buffers used during file match got bigger.
55  * Compressed ISAM support everywhere.
56  * Bug fixes regarding masking characters in queries.
57  * Redesigned Regexp-2 queries.
58  *
59  * Revision 1.63  1996/10/29 14:09:39  adam
60  * Use of cisam system - enabled if setting isamc is 1.
61  *
62  * Revision 1.62  1996/10/11 10:57:01  adam
63  * New module recctrl. Used to manage records (extract/retrieval).
64  * Several files have been moved to the recctrl sub directory.
65  *
66  * Revision 1.61  1996/06/06 12:08:37  quinn
67  * Added showRecord function
68  *
69  * Revision 1.60  1996/06/04  10:18:12  adam
70  * Search/scan uses character mapping module.
71  *
72  * Revision 1.59  1996/05/14  15:47:07  adam
73  * Cleanup of various buffer size entities.
74  *
75  * Revision 1.58  1996/05/14  06:16:38  adam
76  * Compact use/set bytes used in search service.
77  *
78  * Revision 1.57  1996/05/13 14:23:04  adam
79  * Work on compaction of set/use bytes in dictionary.
80  *
81  * Revision 1.56  1996/05/09  09:54:42  adam
82  * Server supports maps from one logical attributes to a list of physical
83  * attributes.
84  * The extraction process doesn't make space consuming 'any' keys.
85  *
86  * Revision 1.55  1996/05/09  07:28:55  quinn
87  * Work towards phrases and multiple registers
88  *
89  * Revision 1.54  1996/05/01  13:46:35  adam
90  * First work on multiple records in one file.
91  * New option, -offset, to the "unread" command in the filter module.
92  *
93  * Revision 1.53  1996/04/26  12:09:43  adam
94  * Added a few comments.
95  *
96  * Revision 1.52  1996/04/25  13:27:57  adam
97  * Function recordExtract modified so that files with no keys (possibly empty)
98  * are ignored.
99  *
100  * Revision 1.51  1996/03/19  11:08:42  adam
101  * Bug fix: Log preamble wasn't always turned off after recordExtract.
102  *
103  * Revision 1.50  1996/02/12  18:45:36  adam
104  * New fileVerboseFlag in record group control.
105  *
106  * Revision 1.49  1996/02/05  12:29:57  adam
107  * Logging reduced a bit.
108  * The remaining running time is estimated during register merge.
109  *
110  * Revision 1.48  1996/02/01  20:53:26  adam
111  * The temporary per-record keys are compacted a little, and duplication
112  * of the per-records keys are avoided when they are saved in the record
113  * information buffer.
114  *
115  * Revision 1.47  1996/01/17  14:57:48  adam
116  * Prototype changed for reader functions in extract/retrieve. File
117  *  is identified by 'void *' instead of 'int.
118  *
119  * Revision 1.46  1995/12/15  14:57:16  adam
120  * Bug fix.
121  *
122  * Revision 1.45  1995/12/15  12:37:41  adam
123  * In addRecordKeyAny: Writes key only when attrSet != -1.
124  *
125  * Revision 1.44  1995/12/12  16:00:54  adam
126  * System call sync(2) used after update/commit.
127  * Locking (based on fcntl) uses F_EXLCK and F_SHLCK instead of F_WRLCK
128  * and F_RDLCK.
129  *
130  * Revision 1.43  1995/12/11  09:12:46  adam
131  * The rec_get function returns NULL if record doesn't exist - will
132  * happen in the server if the result set records have been deleted since
133  * the creation of the set (i.e. the search).
134  * The server saves a result temporarily if it is 'volatile', i.e. the
135  * set is register dependent.
136  *
137  * Revision 1.42  1995/12/07  17:38:46  adam
138  * Work locking mechanisms for concurrent updates/commit.
139  *
140  * Revision 1.41  1995/12/06  16:06:42  adam
141  * Better diagnostics. Work on 'real' dictionary deletion.
142  *
143  * Revision 1.40  1995/12/05  16:57:40  adam
144  * More work on regular patterns.
145  *
146  * Revision 1.39  1995/12/05  13:20:18  adam
147  * Bug fix: file_read sometimes returned early EOF.
148  *
149  * Revision 1.38  1995/12/04  17:59:21  adam
150  * More work on regular expression conversion.
151  *
152  * Revision 1.37  1995/12/04  14:22:27  adam
153  * Extra arg to recType_byName.
154  * Started work on new regular expression parsed input to
155  * structured records.
156  *
157  * Revision 1.36  1995/11/30  08:34:29  adam
158  * Started work on commit facility.
159  * Changed a few malloc/free to xmalloc/xfree.
160  *
161  * Revision 1.35  1995/11/28  14:26:21  adam
162  * Bug fix: recordId with constant wasn't right.
163  * Bug fix: recordId dictionary entry wasn't deleted when needed.
164  *
165  * Revision 1.34  1995/11/28  09:09:38  adam
166  * Zebra config renamed.
167  * Use setting 'recordId' to identify record now.
168  * Bug fix in recindex.c: rec_release_blocks was invokeded even
169  * though the blocks were already released.
170  * File traversal properly deletes records when needed.
171  *
172  * Revision 1.33  1995/11/27  09:56:20  adam
173  * Record info elements better enumerated. Internal store of records.
174  *
175  * Revision 1.32  1995/11/25  10:24:05  adam
176  * More record fields - they are enumerated now.
177  * New options: flagStoreData flagStoreKey.
178  *
179  * Revision 1.31  1995/11/24  11:31:35  adam
180  * Commands add & del read filenames from stdin if source directory is
181  * empty.
182  * Match criteria supports 'constant' strings.
183  *
184  * Revision 1.30  1995/11/22  17:19:16  adam
185  * Record management uses the bfile system.
186  *
187  * Revision 1.29  1995/11/21  15:01:14  adam
188  * New general match criteria implemented.
189  * New feature: document groups.
190  *
191  * Revision 1.28  1995/11/21  09:20:30  adam
192  * Yet more work on record match.
193  *
194  * Revision 1.27  1995/11/20  16:59:45  adam
195  * New update method: the 'old' keys are saved for each records.
196  *
197  * Revision 1.26  1995/11/20  11:56:24  adam
198  * Work on new traversal.
199  *
200  * Revision 1.25  1995/11/16  15:34:54  adam
201  * Uses new record management system in both indexer and server.
202  *
203  * Revision 1.24  1995/11/15  19:13:08  adam
204  * Work on record management.
205  *
206  * Revision 1.23  1995/10/27  14:00:10  adam
207  * Implemented detection of database availability.
208  *
209  * Revision 1.22  1995/10/17  18:02:07  adam
210  * New feature: databases. Implemented as prefix to words in dictionary.
211  *
212  * Revision 1.21  1995/10/10  12:24:38  adam
213  * Temporary sort files are compressed.
214  *
215  * Revision 1.20  1995/10/06  13:52:05  adam
216  * Bug fixes. Handler may abort further scanning.
217  *
218  * Revision 1.19  1995/10/04  12:55:16  adam
219  * Bug fix in ranked search. Use=Any keys inserted.
220  *
221  * Revision 1.18  1995/10/04  09:37:08  quinn
222  * Fixed bug.
223  *
224  * Revision 1.17  1995/10/03  14:28:57  adam
225  * Buffered read in extract works.
226  *
227  * Revision 1.16  1995/10/03  14:28:45  adam
228  * Work on more effecient read handler in extract.
229  *
230  * Revision 1.15  1995/10/02  15:42:53  adam
231  * Extract uses file descriptors instead of FILE pointers.
232  *
233  * Revision 1.14  1995/10/02  15:29:13  adam
234  * More logging in file_extract.
235  *
236  * Revision 1.13  1995/09/29  14:01:39  adam
237  * Bug fixes.
238  *
239  * Revision 1.12  1995/09/28  14:22:56  adam
240  * Sort uses smaller temporary files.
241  *
242  * Revision 1.11  1995/09/28  12:10:31  adam
243  * Bug fixes. Field prefix used in queries.
244  *
245  * Revision 1.10  1995/09/28  09:19:41  adam
246  * xfree/xmalloc used everywhere.
247  * Extract/retrieve method seems to work for text records.
248  *
249  * Revision 1.9  1995/09/27  12:22:28  adam
250  * More work on extract in record control.
251  * Field name is not in isam keys but in prefix in dictionary words.
252  *
253  * Revision 1.8  1995/09/14  07:48:22  adam
254  * Record control management.
255  *
256  * Revision 1.7  1995/09/11  13:09:32  adam
257  * More work on relevance feedback.
258  *
259  * Revision 1.6  1995/09/08  14:52:27  adam
260  * Minor changes. Dictionary is lower case now.
261  *
262  * Revision 1.5  1995/09/06  16:11:16  adam
263  * Option: only one word key per file.
264  *
265  * Revision 1.4  1995/09/05  15:28:39  adam
266  * More work on search engine.
267  *
268  * Revision 1.3  1995/09/04  12:33:41  adam
269  * Various cleanup. YAZ util used instead.
270  *
271  * Revision 1.2  1995/09/04  09:10:34  adam
272  * More work on index add/del/update.
273  * Merge sort implemented.
274  * Initial work on z39 server.
275  *
276  * Revision 1.1  1995/09/01  14:06:35  adam
277  * Split of work into more files.
278  *
279  */
280 #include <stdio.h>
281 #include <assert.h>
282 #ifdef WINDOWS
283 #include <io.h>
284 #else
285 #include <unistd.h>
286 #endif
287 #include <fcntl.h>
288
289 #include <recctrl.h>
290 #include "index.h"
291
292 #include "zinfo.h"
293
294 static Dict matchDict;
295
296 static Records records = NULL;
297
298 static char **key_buf;
299 static size_t ptr_top;
300 static size_t ptr_i;
301 static size_t key_buf_used;
302 static int key_file_no;
303
304 static int records_inserted = 0;
305 static int records_updated = 0;
306 static int records_deleted = 0;
307 static int records_processed = 0;
308
309 static ZebTargetInfo *zti = NULL;
310
311 static void logRecord (int showFlag)
312 {
313     if (!showFlag)
314         ++records_processed;
315     if (showFlag || !(records_processed % 1000))
316     {
317         logf (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
318               records_processed, records_inserted, records_updated,
319               records_deleted);
320     }
321 }
322
323 void key_open (BFiles bfs, int mem)
324 {
325     if (!mem)
326         mem = atoi(res_get_def (common_resource, "memMax", "4"))*1024*1024;
327     if (mem < 50000)
328         mem = 50000;
329     key_buf = xmalloc (mem);
330     ptr_top = mem/sizeof(char*);
331     ptr_i = 0;
332
333     key_buf_used = 0;
334     key_file_no = 0;
335
336     if (!(matchDict = dict_open (bfs, GMATCH_DICT, 50, 1)))
337     {
338         logf (LOG_FATAL, "dict_open fail of %s", GMATCH_DICT);
339         exit (1);
340     }
341     assert (!records);
342     records = rec_open (bfs, 1);
343 #if 1
344     zti = zebTargetInfo_open (records, 1);
345 #endif
346 }
347
348 struct encode_info {
349     int  sysno;
350     int  seqno;
351     char buf[768];
352 };
353
354 void encode_key_init (struct encode_info *i)
355 {
356     i->sysno = 0;
357     i->seqno = 0;
358 }
359
360 char *encode_key_int (int d, char *bp)
361 {
362     if (d <= 63)
363         *bp++ = d;
364     else if (d <= 16383)
365     {
366         *bp++ = 64 + (d>>8);
367         *bp++ = d  & 255;
368     }
369     else if (d <= 4194303)
370     {
371         *bp++ = 128 + (d>>16);
372         *bp++ = (d>>8) & 255;
373         *bp++ = d & 255;
374     }
375     else
376     {
377         *bp++ = 192 + (d>>24);
378         *bp++ = (d>>16) & 255;
379         *bp++ = (d>>8) & 255;
380         *bp++ = d & 255;
381     }
382     return bp;
383 }
384
385 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
386 {
387     struct it_key key;
388     char *bp = i->buf;
389
390     while ((*bp++ = *k++))
391         ;
392     memcpy (&key, k+1, sizeof(struct it_key));
393     bp = encode_key_int ( (key.sysno - i->sysno) * 2 + *k, bp);
394     if (i->sysno != key.sysno)
395     {
396         i->sysno = key.sysno;
397         i->seqno = 0;
398     }
399     bp = encode_key_int (key.seqno - i->seqno, bp);
400     i->seqno = key.seqno;
401     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
402     {
403         logf (LOG_FATAL|LOG_ERRNO, "fwrite");
404         exit (1);
405     }
406 }
407
408 #define SORT_EXTRA 0
409
410 #if SORT_EXTRA
411 static int key_y_len;
412
413 static int key_y_compare (const void *p1, const void *p2)
414 {
415     int r;
416
417     if ((r = key_compare (*(char**) p1 + key_y_len + 1,
418                           *(char**) p2 + key_y_len + 1)))
419          return r;
420     return *(*(char**) p1 + key_y_len) - *(*(char**) p2 + key_y_len);
421 }
422
423 static int key_x_compare (const void *p1, const void *p2)
424 {
425     return strcmp (*(char**) p1, *(char**) p2);
426 }
427 #endif
428
429 void key_flush (void)
430 {
431     FILE *outf;
432     char out_fname[200];
433     char *prevcp, *cp;
434     struct encode_info encode_info;
435 #if SORT_EXTRA
436     int i;
437 #endif
438     
439     if (ptr_i <= 0)
440         return;
441
442     key_file_no++;
443     logf (LOG_LOG, "sorting section %d", key_file_no);
444 #if !SORT_EXTRA
445     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_qsort_compare);
446     getFnameTmp (out_fname, key_file_no);
447
448     if (!(outf = fopen (out_fname, "w")))
449     {
450         logf (LOG_FATAL|LOG_ERRNO, "fopen (4) %s", out_fname);
451         exit (1);
452     }
453     logf (LOG_LOG, "writing section %d", key_file_no);
454     prevcp = cp = key_buf[ptr_top-ptr_i];
455     
456     encode_key_init (&encode_info);
457     encode_key_write (cp, &encode_info, outf);
458     while (--ptr_i > 0)
459     {
460         cp = key_buf[ptr_top-ptr_i];
461         if (strcmp (cp, prevcp))
462         {
463             encode_key_init (&encode_info);
464             encode_key_write (cp, &encode_info, outf);
465             prevcp = cp;
466         }
467         else
468             encode_key_write (cp + strlen(cp), &encode_info, outf);
469     }
470 #else
471     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_x_compare);
472     getFnameTmp (out_fname, key_file_no);
473
474     if (!(outf = fopen (out_fname, "w")))
475     {
476         logf (LOG_FATAL|LOG_ERRNO, "fopen (4) %s", out_fname);
477         exit (1);
478     }
479     logf (LOG_LOG, "writing section %d", key_file_no);
480     i = ptr_i;
481     prevcp =  key_buf[ptr_top-i];
482     while (1)
483         if (!--i || strcmp (prevcp, key_buf[ptr_top-i]))
484         {
485             key_y_len = strlen(prevcp)+1;
486 #if 0
487             logf (LOG_LOG, "key_y_len: %2d %02x %02x %s",
488                       key_y_len, prevcp[0], prevcp[1], 2+prevcp);
489 #endif
490             qsort (key_buf + ptr_top-ptr_i, ptr_i - i,
491                                    sizeof(char*), key_y_compare);
492             cp = key_buf[ptr_top-ptr_i];
493             --key_y_len;
494             encode_key_init (&encode_info);
495             encode_key_write (cp, &encode_info, outf);
496             while (--ptr_i > i)
497             {
498                 cp = key_buf[ptr_top-ptr_i];
499                 encode_key_write (cp+key_y_len, &encode_info, outf);
500             }
501             if (!i)
502                 break;
503             prevcp = key_buf[ptr_top-ptr_i];
504         }
505 #endif
506     if (fclose (outf))
507     {
508         logf (LOG_FATAL|LOG_ERRNO, "fclose %s", out_fname);
509         exit (1);
510     }
511     logf (LOG_LOG, "finished section %d", key_file_no);
512     ptr_i = 0;
513     key_buf_used = 0;
514 }
515
516 int key_close ()
517 {
518     key_flush ();
519     xfree (key_buf);
520 #if 1
521     zebTargetInfo_close (zti, 1);
522 #endif
523     rec_close (&records);
524     dict_close (matchDict);
525
526     logRecord (1);
527     return key_file_no;
528 }
529
530 static void wordInit (RecWord *p)
531 {
532     p->attrSet = 1;
533     p->attrUse = 1016;
534     p->reg_type = 'w';
535 }
536
537 struct recKeys {
538     int buf_used;
539     int buf_max;
540     char *buf;
541     char prevAttrSet;
542     short prevAttrUse;
543     int prevSeqNo;
544 } reckeys;
545
546 static void addRecordKey (const RecWord *p)
547 {
548     char *dst;
549     char attrSet;
550     short attrUse;
551     size_t i;
552     int lead = 0;
553     int diff = 0;
554
555     if (reckeys.buf_used+1024 > reckeys.buf_max)
556     {
557         char *b;
558
559         b = xmalloc (reckeys.buf_max += 128000);
560         if (reckeys.buf_used > 0)
561             memcpy (b, reckeys.buf, reckeys.buf_used);
562         xfree (reckeys.buf);
563         reckeys.buf = b;
564     }
565     dst = reckeys.buf + reckeys.buf_used;
566
567     attrSet = p->attrSet;
568     if (reckeys.buf_used > 0 && reckeys.prevAttrSet == attrSet)
569         lead |= 1;
570     else
571         reckeys.prevAttrSet = attrSet;
572     attrUse = p->attrUse;
573     if (reckeys.buf_used > 0 && reckeys.prevAttrUse == attrUse)
574         lead |= 2;
575     else
576         reckeys.prevAttrUse = attrUse;
577 #if 1
578     diff = 1 + p->seqno - reckeys.prevSeqNo;
579     if (diff >= 1 && diff <= 15)
580         lead |= (diff << 2);
581     else
582         diff = 0;
583 #endif
584     reckeys.prevSeqNo = p->seqno;
585
586     *dst++ = lead;
587
588     if (!(lead & 1))
589     {
590         memcpy (dst, &attrSet, sizeof(attrSet));
591         dst += sizeof(attrSet);
592     }
593     if (!(lead & 2))
594     {
595         memcpy (dst, &attrUse, sizeof(attrUse));
596         dst += sizeof(attrUse);
597     }
598     *dst++ = p->reg_type;
599     for (i = 0; p->string[i] && i < IT_MAX_WORD-3; i++)
600         *dst++ = p->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         extractCtrl.dh = rGroup->dh;
989
990         reckeys.buf_used = 0;
991         reckeys.prevAttrUse = -1;
992         reckeys.prevAttrSet = -1;
993         reckeys.prevSeqNo = 0;
994
995         recordOffset = fi->file_moffset;
996         extractCtrl.offset = recordOffset;
997         extractCtrl.readf = file_read;
998         extractCtrl.seekf = file_seek;
999         extractCtrl.tellf = file_tell;
1000         extractCtrl.endf = file_end;
1001         extractCtrl.zebra_maps = rGroup->zebra_maps;
1002         extractCtrl.flagShowRecords = rGroup->flagShowRecords;
1003         if (rGroup->flagShowRecords)
1004             printf ("File: %s %ld\n", fname, (long) recordOffset);
1005
1006         logInfo.fname = fname;
1007         logInfo.recordOffset = recordOffset;
1008         logInfo.rGroup = rGroup;
1009         log_event_start (recordLogPreamble, &logInfo);
1010
1011         r = (*recType->extract)(&extractCtrl);
1012
1013         log_event_start (NULL, NULL);
1014
1015         if (r)      
1016         {
1017             /* error occured during extraction ... */
1018             if (!rGroup->flagShowRecords &&
1019                     records_processed < rGroup->fileVerboseLimit)
1020             {
1021                 logf (LOG_WARN, "fail %s %s %ld code = %d", rGroup->recordType,
1022                       fname, (long) recordOffset, r);
1023             }
1024             return 0;
1025         }
1026         if (reckeys.buf_used == 0)
1027         {
1028             /* the extraction process returned no information - the record
1029                is probably empty - unless flagShowRecords is in use */
1030             if (rGroup->flagShowRecords)
1031                 return 1;
1032             logf (LOG_WARN, "No keys generated for file %s", fname);
1033             logf (LOG_WARN, " The file is probably empty");
1034             return 0;
1035         }
1036     }
1037
1038     /* perform match if sysno not known and if match criteria is specified */
1039        
1040     matchStr = NULL;
1041     if (!sysno) 
1042     {
1043         sysnotmp = 0;
1044         sysno = &sysnotmp;
1045         if (rGroup->recordId && *rGroup->recordId)
1046         {
1047             char *rinfo;
1048         
1049             matchStr = fileMatchStr (&reckeys, rGroup, fname, 
1050                                      rGroup->recordId);
1051             if (matchStr)
1052             {
1053                 rinfo = dict_lookup (matchDict, matchStr);
1054                 if (rinfo)
1055                     memcpy (sysno, rinfo+1, sizeof(*sysno));
1056             }
1057             else
1058             {
1059                 logf (LOG_WARN, "Bad match criteria");
1060                 return 0;
1061             }
1062         }
1063     }
1064
1065     if (! *sysno)
1066     {
1067         /* new record */
1068         if (deleteFlag)
1069         {
1070             logf (LOG_LOG, "Cannot delete new record");
1071             return 1;
1072         }
1073         if (records_processed < rGroup->fileVerboseLimit)
1074             logf (LOG_LOG, "add %s %s %ld", rGroup->recordType,
1075                   fname, (long) recordOffset);
1076         rec = rec_new (records);
1077         *sysno = rec->sysno;
1078
1079         if (matchStr)
1080         {
1081             dict_insert (matchDict, matchStr, sizeof(*sysno), sysno);
1082         }
1083         flushRecordKeys (*sysno, 1, &reckeys, rGroup->databaseName);
1084
1085         records_inserted++;
1086     }
1087     else
1088     {
1089         /* record already exists */
1090         struct recKeys delkeys;
1091
1092         rec = rec_get (records, *sysno);
1093         assert (rec);
1094         delkeys.buf_used = rec->size[recInfo_delKeys];
1095         delkeys.buf = rec->info[recInfo_delKeys];
1096         flushRecordKeys (*sysno, 0, &delkeys, rec->info[recInfo_databaseName]);
1097         if (deleteFlag)
1098         {
1099             /* record going to be deleted */
1100             if (!delkeys.buf_used)
1101             {
1102                 logf (LOG_LOG, "delete %s %s %ld", rGroup->recordType,
1103                       fname, (long) recordOffset);
1104                 logf (LOG_WARN, "cannot delete file above, storeKeys false");
1105             }
1106             else
1107             {
1108                 if (records_processed < rGroup->fileVerboseLimit)
1109                     logf (LOG_LOG, "delete %s %s %ld", rGroup->recordType,
1110                           fname, (long) recordOffset);
1111                 records_deleted++;
1112                 if (matchStr)
1113                     dict_delete (matchDict, matchStr);
1114                 rec_del (records, &rec);
1115             }
1116             logRecord (0);
1117             return 1;
1118         }
1119         else
1120         {
1121             /* record going to be updated */
1122             if (!delkeys.buf_used)
1123             {
1124                 logf (LOG_LOG, "update %s %s %ld", rGroup->recordType,
1125                       fname, (long) recordOffset);
1126                 logf (LOG_WARN, "cannot update file above, storeKeys false");
1127             }
1128             else
1129             {
1130                 if (records_processed < rGroup->fileVerboseLimit)
1131                     logf (LOG_LOG, "update %s %s %ld", rGroup->recordType,
1132                           fname, (long) recordOffset);
1133                 flushRecordKeys (*sysno, 1, &reckeys, rGroup->databaseName); 
1134                 records_updated++;
1135             }
1136         }
1137     }
1138     /* update file type */
1139     xfree (rec->info[recInfo_fileType]);
1140     rec->info[recInfo_fileType] =
1141         rec_strdup (rGroup->recordType, &rec->size[recInfo_fileType]);
1142
1143     /* update filename */
1144     xfree (rec->info[recInfo_filename]);
1145     rec->info[recInfo_filename] =
1146         rec_strdup (fname, &rec->size[recInfo_filename]);
1147
1148     /* update delete keys */
1149     xfree (rec->info[recInfo_delKeys]);
1150     if (reckeys.buf_used > 0 && rGroup->flagStoreKeys == 1)
1151     {
1152 #if 1
1153         rec->size[recInfo_delKeys] = reckeys.buf_used;
1154         rec->info[recInfo_delKeys] = reckeys.buf;
1155         reckeys.buf = NULL;
1156         reckeys.buf_max = 0;
1157 #else
1158         rec->info[recInfo_delKeys] = xmalloc (reckeys.buf_used);
1159         rec->size[recInfo_delKeys] = reckeys.buf_used;
1160         memcpy (rec->info[recInfo_delKeys], reckeys.buf,
1161                 rec->size[recInfo_delKeys]);
1162 #endif
1163     }
1164     else
1165     {
1166         rec->info[recInfo_delKeys] = NULL;
1167         rec->size[recInfo_delKeys] = 0;
1168     }
1169
1170     /* update store data */
1171     xfree (rec->info[recInfo_storeData]);
1172     if (rGroup->flagStoreData == 1)
1173     {
1174         int size = fi->file_moffset - recordOffset; 
1175         if (!size)
1176             size = fi->file_max - recordOffset;
1177         rec->size[recInfo_storeData] = size;
1178         rec->info[recInfo_storeData] = xmalloc (size);
1179         if (lseek (fi->fd, recordOffset, SEEK_SET) < 0)
1180         {
1181             logf (LOG_ERRNO|LOG_FATAL, "seek to %ld in %s", fname,
1182                   (long) recordOffset);
1183             exit (1);
1184         }
1185         if (read (fi->fd, rec->info[recInfo_storeData], size) < size)
1186         {
1187             logf (LOG_ERRNO|LOG_FATAL, "read %d bytes of %s",
1188                   fi->file_max, fname);
1189             exit (1);
1190         }
1191     }
1192     else
1193     {
1194         rec->info[recInfo_storeData] = NULL;
1195         rec->size[recInfo_storeData] = 0;
1196     }
1197     /* update database name */
1198     xfree (rec->info[recInfo_databaseName]);
1199     rec->info[recInfo_databaseName] =
1200         rec_strdup (rGroup->databaseName, &rec->size[recInfo_databaseName]); 
1201
1202     /* update offset */
1203     xfree (rec->info[recInfo_offset]);
1204
1205     rec->size[recInfo_offset] = sizeof(recordOffset);
1206     rec->info[recInfo_offset] = xmalloc (sizeof(recordOffset));
1207     memcpy (rec->info[recInfo_offset], &recordOffset, sizeof(recordOffset));
1208     
1209     /* commit this record */
1210     rec_put (records, &rec);
1211     logRecord (0);
1212     return 1;
1213 }
1214
1215 int fileExtract (SYSNO *sysno, const char *fname, 
1216                  const struct recordGroup *rGroupP, int deleteFlag)
1217 {
1218     int r, i, fd;
1219     char gprefix[128];
1220     char ext[128];
1221     char ext_res[128];
1222     char subType[128];
1223     RecType recType;
1224     struct recordGroup rGroupM;
1225     struct recordGroup *rGroup = &rGroupM;
1226     struct file_read_info *fi;
1227
1228     memcpy (rGroup, rGroupP, sizeof(*rGroupP));
1229    
1230     if (!rGroup->groupName || !*rGroup->groupName)
1231         *gprefix = '\0';
1232     else
1233         sprintf (gprefix, "%s.", rGroup->groupName);
1234
1235     logf (LOG_DEBUG, "fileExtract %s", fname);
1236
1237     /* determine file extension */
1238     for (i = strlen(fname); --i >= 0; )
1239         if (fname[i] == '/')
1240         {
1241             strcpy (ext, "");
1242             break;
1243         }
1244         else if (fname[i] == '.')
1245         {
1246             strcpy (ext, fname+i+1);
1247             break;
1248         }
1249     /* determine file type - depending on extension */
1250     if (!rGroup->recordType)
1251     {
1252         sprintf (ext_res, "%srecordType.%s", gprefix, ext);
1253         if (!(rGroup->recordType = res_get (common_resource, ext_res)))
1254         {
1255             sprintf (ext_res, "%srecordType", gprefix);
1256             if (!(rGroup->recordType = res_get (common_resource, ext_res)))
1257             {
1258                 if (records_processed < rGroup->fileVerboseLimit)
1259                     logf (LOG_LOG, "? %s", fname);
1260                 return 0;
1261             }
1262         }
1263     }
1264     if (!rGroup->recordType)
1265     {
1266         if (records_processed < rGroup->fileVerboseLimit)
1267             logf (LOG_LOG, "? record %s", fname);
1268         return 0;
1269     }
1270     if (!(recType = recType_byName (rGroup->recordType, subType)))
1271     {
1272         logf (LOG_WARN, "No such record type: %s", rGroup->recordType);
1273         return 0;
1274     }
1275
1276     /* determine match criteria */
1277     if (!rGroup->recordId)
1278     {
1279         sprintf (ext_res, "%srecordId.%s", gprefix, ext);
1280         rGroup->recordId = res_get (common_resource, ext_res);
1281     }
1282
1283     /* determine database name */
1284     if (!rGroup->databaseName)
1285     {
1286         sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
1287         if (!(rGroup->databaseName = res_get (common_resource, ext_res)))
1288         {
1289             sprintf (ext_res, "%sdatabase", gprefix);
1290             rGroup->databaseName = res_get (common_resource, ext_res);
1291         }
1292     }
1293     if (!rGroup->databaseName)
1294         rGroup->databaseName = "Default";
1295
1296     if (rGroup->flagStoreData == -1)
1297     {
1298         const char *sval;
1299         sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
1300         if (!(sval = res_get (common_resource, ext_res)))
1301         {
1302             sprintf (ext_res, "%sstoreData", gprefix);
1303             sval = res_get (common_resource, ext_res);
1304         }
1305         if (sval)
1306             rGroup->flagStoreData = atoi (sval);
1307     }
1308     if (rGroup->flagStoreData == -1)
1309         rGroup->flagStoreData = 0;
1310
1311     if (rGroup->flagStoreKeys == -1)
1312     {
1313         const char *sval;
1314
1315         sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
1316         if (!(sval = res_get (common_resource, ext_res)))
1317         {
1318             sprintf (ext_res, "%sstoreKeys", gprefix);
1319             sval = res_get (common_resource, ext_res);
1320         }
1321         if (sval)
1322             rGroup->flagStoreKeys = atoi (sval);
1323     }
1324     if (rGroup->flagStoreKeys == -1)
1325         rGroup->flagStoreKeys = 0;
1326
1327     if (sysno && deleteFlag)
1328         fd = -1;
1329     else
1330     {
1331         if ((fd = open (fname, O_BINARY|O_RDONLY)) == -1)
1332         {
1333             logf (LOG_WARN|LOG_ERRNO, "open %s", fname);
1334             return 0;
1335         }
1336     }
1337     fi = file_read_start (fd);
1338     do
1339     {
1340         file_begin (fi);
1341         r = recordExtract (sysno, fname, rGroup, deleteFlag, fi,
1342                            recType, subType);
1343     } while (r && !sysno && fi->file_more);
1344     file_read_stop (fi);
1345     if (fd != -1)
1346         close (fd);
1347     return r;
1348 }
1349