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