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