Commands add & del read filenames from stdin if source directory is
[idzebra-moved-to-github.git] / index / extract.c
1 /*
2  * Copyright (C) 1994-1995, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: extract.c,v $
7  * Revision 1.31  1995-11-24 11:31:35  adam
8  * Commands add & del read filenames from stdin if source directory is
9  * empty.
10  * Match criteria supports 'constant' strings.
11  *
12  * Revision 1.30  1995/11/22  17:19:16  adam
13  * Record management uses the bfile system.
14  *
15  * Revision 1.29  1995/11/21  15:01:14  adam
16  * New general match criteria implemented.
17  * New feature: document groups.
18  *
19  * Revision 1.28  1995/11/21  09:20:30  adam
20  * Yet more work on record match.
21  *
22  * Revision 1.27  1995/11/20  16:59:45  adam
23  * New update method: the 'old' keys are saved for each records.
24  *
25  * Revision 1.26  1995/11/20  11:56:24  adam
26  * Work on new traversal.
27  *
28  * Revision 1.25  1995/11/16  15:34:54  adam
29  * Uses new record management system in both indexer and server.
30  *
31  * Revision 1.24  1995/11/15  19:13:08  adam
32  * Work on record management.
33  *
34  * Revision 1.23  1995/10/27  14:00:10  adam
35  * Implemented detection of database availability.
36  *
37  * Revision 1.22  1995/10/17  18:02:07  adam
38  * New feature: databases. Implemented as prefix to words in dictionary.
39  *
40  * Revision 1.21  1995/10/10  12:24:38  adam
41  * Temporary sort files are compressed.
42  *
43  * Revision 1.20  1995/10/06  13:52:05  adam
44  * Bug fixes. Handler may abort further scanning.
45  *
46  * Revision 1.19  1995/10/04  12:55:16  adam
47  * Bug fix in ranked search. Use=Any keys inserted.
48  *
49  * Revision 1.18  1995/10/04  09:37:08  quinn
50  * Fixed bug.
51  *
52  * Revision 1.17  1995/10/03  14:28:57  adam
53  * Buffered read in extract works.
54  *
55  * Revision 1.16  1995/10/03  14:28:45  adam
56  * Work on more effecient read handler in extract.
57  *
58  * Revision 1.15  1995/10/02  15:42:53  adam
59  * Extract uses file descriptors instead of FILE pointers.
60  *
61  * Revision 1.14  1995/10/02  15:29:13  adam
62  * More logging in file_extract.
63  *
64  * Revision 1.13  1995/09/29  14:01:39  adam
65  * Bug fixes.
66  *
67  * Revision 1.12  1995/09/28  14:22:56  adam
68  * Sort uses smaller temporary files.
69  *
70  * Revision 1.11  1995/09/28  12:10:31  adam
71  * Bug fixes. Field prefix used in queries.
72  *
73  * Revision 1.10  1995/09/28  09:19:41  adam
74  * xfree/xmalloc used everywhere.
75  * Extract/retrieve method seems to work for text records.
76  *
77  * Revision 1.9  1995/09/27  12:22:28  adam
78  * More work on extract in record control.
79  * Field name is not in isam keys but in prefix in dictionary words.
80  *
81  * Revision 1.8  1995/09/14  07:48:22  adam
82  * Record control management.
83  *
84  * Revision 1.7  1995/09/11  13:09:32  adam
85  * More work on relevance feedback.
86  *
87  * Revision 1.6  1995/09/08  14:52:27  adam
88  * Minor changes. Dictionary is lower case now.
89  *
90  * Revision 1.5  1995/09/06  16:11:16  adam
91  * Option: only one word key per file.
92  *
93  * Revision 1.4  1995/09/05  15:28:39  adam
94  * More work on search engine.
95  *
96  * Revision 1.3  1995/09/04  12:33:41  adam
97  * Various cleanup. YAZ util used instead.
98  *
99  * Revision 1.2  1995/09/04  09:10:34  adam
100  * More work on index add/del/update.
101  * Merge sort implemented.
102  * Initial work on z39 server.
103  *
104  * Revision 1.1  1995/09/01  14:06:35  adam
105  * Split of work into more files.
106  *
107  */
108 #include <stdio.h>
109 #include <assert.h>
110 #include <unistd.h>
111 #include <fcntl.h>
112 #include <ctype.h>
113
114 #include <alexutil.h>
115 #include <recctrl.h>
116 #include "index.h"
117
118 #include "recindex.h"
119
120 static Dict matchDict;
121
122 static Records records = NULL;
123
124 static char **key_buf;
125 static size_t ptr_top;
126 static size_t ptr_i;
127 static size_t key_buf_used;
128 static int key_file_no;
129
130 static int records_inserted = 0;
131 static int records_updated = 0;
132 static int records_deleted = 0;
133
134 #define MATCH_DICT "match"
135
136 void key_open (int mem)
137 {
138     if (mem < 50000)
139         mem = 50000;
140     key_buf = xmalloc (mem);
141     ptr_top = mem/sizeof(char*);
142     ptr_i = 0;
143
144     key_buf_used = 0;
145     key_file_no = 0;
146
147     if (!(matchDict = dict_open (MATCH_DICT, 20, 1)))
148     {
149         logf (LOG_FATAL, "dict_open fail of %s", MATCH_DICT);
150         exit (1);
151     }
152     assert (!records);
153     records = rec_open (1);
154 }
155
156 struct encode_info {
157     int  sysno;
158     int  seqno;
159     char buf[512];
160 };
161
162 void encode_key_init (struct encode_info *i)
163 {
164     i->sysno = 0;
165     i->seqno = 0;
166 }
167
168 char *encode_key_int (int d, char *bp)
169 {
170     if (d <= 63)
171         *bp++ = d;
172     else if (d <= 16383)
173     {
174         *bp++ = 64 + (d>>8);
175         *bp++ = d  & 255;
176     }
177     else if (d <= 4194303)
178     {
179         *bp++ = 128 + (d>>16);
180         *bp++ = (d>>8) & 255;
181         *bp++ = d & 255;
182     }
183     else
184     {
185         *bp++ = 192 + (d>>24);
186         *bp++ = (d>>16) & 255;
187         *bp++ = (d>>8) & 255;
188         *bp++ = d & 255;
189     }
190     return bp;
191 }
192
193 void encode_key_write (char *k, struct encode_info *i, FILE *outf)
194 {
195     struct it_key key;
196     char *bp = i->buf;
197
198     while ((*bp++ = *k++))
199         ;
200     memcpy (&key, k+1, sizeof(struct it_key));
201     bp = encode_key_int ( (key.sysno - i->sysno) * 2 + *k, bp);
202     if (i->sysno != key.sysno)
203     {
204         i->sysno = key.sysno;
205         i->seqno = 0;
206     }
207     bp = encode_key_int (key.seqno - i->seqno, bp);
208     i->seqno = key.seqno;
209     if (fwrite (i->buf, bp - i->buf, 1, outf) != 1)
210     {
211         logf (LOG_FATAL|LOG_ERRNO, "fwrite");
212         exit (1);
213     }
214 }
215
216 void key_flush (void)
217 {
218     FILE *outf;
219     char out_fname[200];
220     char *prevcp, *cp;
221     struct encode_info encode_info;
222     
223     if (ptr_i <= 0)
224         return;
225
226     key_file_no++;
227     logf (LOG_LOG, "sorting section %d", key_file_no);
228     qsort (key_buf + ptr_top-ptr_i, ptr_i, sizeof(char*), key_qsort_compare);
229     sprintf (out_fname, TEMP_FNAME, key_file_no);
230
231     if (!(outf = fopen (out_fname, "w")))
232     {
233         logf (LOG_FATAL|LOG_ERRNO, "fopen (4) %s", out_fname);
234         exit (1);
235     }
236     logf (LOG_LOG, "writing section %d", key_file_no);
237     prevcp = cp = key_buf[ptr_top-ptr_i];
238     
239     encode_key_init (&encode_info);
240     encode_key_write (cp, &encode_info, outf);
241     while (--ptr_i > 0)
242     {
243         cp = key_buf[ptr_top-ptr_i];
244         if (strcmp (cp, prevcp))
245         {
246             encode_key_init (&encode_info);
247             encode_key_write (cp, &encode_info, outf);
248             prevcp = cp;
249         }
250         else
251             encode_key_write (cp + strlen(cp), &encode_info, outf);
252     }
253     if (fclose (outf))
254     {
255         logf (LOG_FATAL|LOG_ERRNO, "fclose %s", out_fname);
256         exit (1);
257     }
258     logf (LOG_LOG, "finished section %d", key_file_no);
259     ptr_i = 0;
260     key_buf_used = 0;
261 }
262
263 int key_close (void)
264 {
265     key_flush ();
266     xfree (key_buf);
267     rec_close (&records);
268     dict_close (matchDict);
269
270     logf (LOG_LOG, "Records inserted %6d", records_inserted);
271     logf (LOG_LOG, "Records updated  %6d", records_updated);
272     logf (LOG_LOG, "Records deleted  %6d", records_deleted);
273     return key_file_no;
274 }
275
276 static void wordInit (RecWord *p)
277 {
278     p->attrSet = 1;
279     p->attrUse = 1016;
280     p->which = Word_String;
281 }
282
283 struct recKeys {
284     int buf_used;
285     int buf_max;
286     char *buf;
287 } reckeys;
288
289 static void addRecordKey (const RecWord *p)
290 {
291     char *dst;
292     char attrSet;
293     short attrUse;
294     size_t i;
295
296     if (reckeys.buf_used+1024 > reckeys.buf_max)
297     {
298         char *b;
299
300         b = malloc (reckeys.buf_max += 65000);
301         if (reckeys.buf_used > 0)
302             memcpy (b, reckeys.buf, reckeys.buf_used);
303         free (reckeys.buf);
304         reckeys.buf = b;
305     }
306     dst = reckeys.buf + reckeys.buf_used;
307     switch (p->which)
308     {
309     case Word_String:
310         attrSet = p->attrSet;
311         memcpy (dst, &attrSet, sizeof(attrSet));
312         dst += sizeof(attrSet);
313
314         attrUse = p->attrUse;
315         memcpy (dst, &attrUse, sizeof(attrUse));
316         dst += sizeof(attrUse);
317         
318         for (i = 0; p->u.string[i]; i++)
319             *dst++ = p->u.string[i];
320         *dst++ = '\0';
321
322         memcpy (dst, &p->seqno, sizeof(p->seqno));
323         dst += sizeof(p->seqno);
324
325         break;
326     default:
327         return;
328     }
329     reckeys.buf_used = dst - reckeys.buf;
330 }
331
332 static void flushRecordKeys (SYSNO sysno, int cmd, struct recKeys *reckeys, 
333                              const char *databaseName)
334 {
335     int off = 0;
336     while (off < reckeys->buf_used)
337     {
338         const char *src = reckeys->buf + off;
339         char attrSet;
340         short attrUse;
341         struct it_key key;
342         
343         memcpy (&attrSet, src, sizeof(attrSet));
344         src += sizeof(attrSet);
345
346         memcpy (&attrUse, src, sizeof(attrUse));
347         src += sizeof(attrUse);
348
349         if (key_buf_used + 1024 > (ptr_top-ptr_i)*sizeof(char*))
350             key_flush ();
351         ++ptr_i;
352         key_buf[ptr_top-ptr_i] = (char*)key_buf + key_buf_used;
353         key_buf_used += index_word_prefix ((char*)key_buf + key_buf_used,
354                                            attrSet, attrUse, databaseName);
355         while (*src)
356             ((char*)key_buf) [key_buf_used++] = index_char_cvt (*src++);
357         src++;
358         ((char*)key_buf) [key_buf_used++] = '\0';
359         
360         ((char*) key_buf)[key_buf_used++] = cmd;
361
362         memcpy (&key.seqno, src, sizeof(key.seqno));
363         src += sizeof(key.seqno);
364         key.sysno = sysno;
365         memcpy ((char*)key_buf + key_buf_used, &key, sizeof(key));
366         key_buf_used += sizeof(key);
367         off = src - reckeys->buf;
368     }
369     assert (off == reckeys->buf_used);
370 }
371
372 static const char **searchRecordKey (struct recKeys *reckeys,
373                                int attrSetS, int attrUseS)
374 {
375     static const char *ws[32];
376     int off = 0;
377     int startSeq = -1;
378     int i;
379
380     for (i = 0; i<32; i++)
381         ws[i] = NULL;
382     
383     while (off < reckeys->buf_used)
384     {
385         const char *src = reckeys->buf + off;
386         char attrSet;
387         short attrUse;
388         int seqno;
389         const char *wstart;
390         
391         memcpy (&attrSet, src, sizeof(attrSet));
392         src += sizeof(attrSet);
393
394         memcpy (&attrUse, src, sizeof(attrUse));
395         src += sizeof(attrUse);
396
397         wstart = src;
398         while (*src++)
399             ;
400
401         memcpy (&seqno, src, sizeof(seqno));
402         src += sizeof(seqno);
403
404 #if 0
405         logf (LOG_LOG, "(%d,%d) %d %s", attrSet, attrUse, seqno, wstart);
406 #endif
407         if (attrUseS == attrUse && attrSetS == attrSet)
408         {
409             int woff;
410
411
412             if (startSeq == -1)
413                 startSeq = seqno;
414             woff = seqno - startSeq;
415             if (woff >= 0 && woff < 31)
416                 ws[woff] = wstart;
417         }
418
419         off = src - reckeys->buf;
420     }
421     assert (off == reckeys->buf_used);
422     return ws;
423 }
424
425 static void addRecordKeyAny (const RecWord *p)
426 {
427     if (p->attrSet != 1 || p->attrUse != 1016)
428     {
429         RecWord w;
430
431         memcpy (&w, p, sizeof(w));
432         w.attrSet = 1;
433         w.attrUse = 1016;
434         addRecordKey (&w);
435     }
436     addRecordKey (p);
437 }
438
439 static char *file_buf;
440 static int file_offset;
441 static int file_bufsize;
442
443 static void file_read_start (int fd)
444 {
445     file_offset = 0;
446     file_buf = xmalloc (4096);
447     file_bufsize = read (fd, file_buf, 4096);
448 }
449
450 static void file_read_stop (int fd)
451 {
452     xfree (file_buf);
453 }
454
455 static int file_read (int fd, char *buf, size_t count)
456 {
457     int l = file_bufsize - file_offset;
458
459     if (count > l)
460     {
461         int r;
462         if (l > 0)
463             memcpy (buf, file_buf + file_offset, l);
464         count = count-l;
465         if (count > file_bufsize)
466         {
467             if ((r = read (fd, buf + l, count)) == -1)
468             {
469                 logf (LOG_FATAL|LOG_ERRNO, "read");
470                 exit (1);
471             }
472             file_bufsize = 0;
473             file_offset = 0;
474             return r;
475         }
476         file_bufsize = r = read (fd, file_buf, 4096);
477         if (r == -1)
478         {
479             logf (LOG_FATAL|LOG_ERRNO, "read");
480             exit (1);
481         }
482         else if (r <= count)
483         {
484             file_offset = r;
485             memcpy (buf + l, file_buf, r);
486             return l + r;
487         }
488         else
489         {
490             file_offset = count;
491             memcpy (buf + l, file_buf, count - l);
492             return count;
493         }
494     }
495     memcpy (buf, file_buf + file_offset, count);
496     file_offset += count;
497     return count;
498 }
499
500 static int atois (const char **s)
501 {
502     int val = 0, c;
503     while ( (c=**s) >= '0' && c <= '9')
504     {
505         val = val*10 + c - '0';
506         ++(*s);
507     }
508     return val;
509 }
510
511 static char *fileMatchStr (struct recKeys *reckeys, struct recordGroup *rGroup,
512                            const char *fname,
513                            const char *recordType,
514                            const char *spec)
515 {
516     static char dstBuf[2048];
517     char *dst = dstBuf;
518     const char *s = spec;
519     static const char **w;
520     int i;
521
522     while (1)
523     {
524         while (*s == ' ' || *s == '\t')
525             s++;
526         if (!*s)
527             break;
528         if (*s == '(')
529         {
530             char matchFlag[32];
531             int attrSet, attrUse;
532             int first = 1;
533
534             s++;
535             attrSet = atois (&s);
536             if (*s != ',')
537             {
538                 logf (LOG_WARN, "Missing , in match criteria %s in group %s",
539                       spec, rGroup->groupName ? rGroup->groupName : "none");
540                 return NULL;
541             }
542             s++;
543             attrUse = atois (&s);
544             w = searchRecordKey (reckeys, attrSet, attrUse);
545             assert (w);
546
547             if (*s == ')')
548             {
549                 for (i = 0; i<32; i++)
550                     matchFlag[i] = 1;
551             }
552             else
553             {
554                 logf (LOG_WARN, "Missing ) in match criteria %s in group %s",
555                       spec, rGroup->groupName ? rGroup->groupName : "none");
556                 return NULL;
557             }
558             s++;
559
560             for (i = 0; i<32; i++)
561                 if (matchFlag[i] && w[i])
562                 {
563                     if (first)
564                     {
565                         *dst++ = ' ';
566                         first = 0;
567                     }
568                     strcpy (dst, w[i]);
569                     dst += strlen(w[i]);
570                 }
571             if (first)
572             {
573                 logf (LOG_WARN, "Record in file %s didn't contain match"
574                       " fields in (%d,%d)", fname, attrSet, attrUse);
575                 return NULL;
576             }
577         }
578         else if (*s == '$')
579         {
580             int spec_len;
581             char special[64];
582             const char *spec_src = NULL;
583             const char *s1 = ++s;
584             while (*s1 && *s1 != ' ' && *s1 != '\t')
585                 s1++;
586
587             spec_len = s1 - s;
588             if (spec_len > 63)
589                 spec_len = 63;
590             memcpy (special, s, spec_len);
591             special[spec_len] = '\0';
592             s = s1;
593
594             if (strcmp (special, "group"))
595                 spec_src = rGroup->groupName;
596             else if (strcmp (special, "database"))
597                 spec_src = rGroup->databaseName;
598             else if (strcmp (special, "filename"))
599                 spec_src = fname;
600             else if (strcmp (special, "type"))
601                 spec_src = recordType;
602             else 
603                 spec_src = NULL;
604             if (spec_src)
605             {
606                 strcpy (dst, spec_src);
607                 dst += strlen (spec_src);
608             }
609         }
610         else if (*s == '\"' || *s == '\'')
611         {
612             int stopMarker = *s++;
613             char tmpString[64];
614             int i = 0;
615
616             while (*s && *s != stopMarker)
617             {
618                 if (i < 63)
619                     tmpString[i++] = *s;
620             }
621             if (*s)
622                 s++;
623             tmpString[i] = '\0';
624             strcpy (dst, tmpString);
625             dst += strlen (tmpString);
626         }
627         else
628         {
629             logf (LOG_WARN, "Syntax error in match criteria %s in group %s",
630                   spec, rGroup->groupName ? rGroup->groupName : "none");
631             return NULL;
632         }
633         *dst++ = 1;
634     }
635     if (dst == dstBuf)
636     {
637         logf (LOG_WARN, "No match criteria for record %s in group %s",
638               fname, rGroup->groupName ? rGroup->groupName : "none");
639         return NULL;
640     }
641     return dstBuf;
642 }
643
644 int fileExtract (SYSNO *sysno, const char *fname, struct recordGroup *rGroup,
645                  int deleteFlag)
646 {
647     SYSNO sysnotmp;
648     int i, r;
649     char gprefix[128];
650     char ext[128];
651     char ext_res[128];
652     const char *file_type;
653     const char *file_match;
654     struct recExtractCtrl extractCtrl;
655     RecType recType;
656     Record rec;
657     char *matchStr;
658
659     if (!rGroup->groupName || !*rGroup->groupName)
660         *gprefix = '\0';
661     else
662         sprintf (gprefix, "%s.", rGroup->groupName);
663
664     logf (LOG_DEBUG, "fileExtract %s", fname);
665
666     /* determine file extension */
667     for (i = strlen(fname); --i >= 0; )
668         if (fname[i] == '/')
669         {
670             strcpy (ext, "");
671             break;
672         }
673         else if (fname[i] == '.')
674         {
675             strcpy (ext, fname+i+1);
676             break;
677         }
678     /* determine file type - depending on extension */
679     sprintf (ext_res, "%sfileExtension.%s", gprefix, ext);
680     if (!(file_type = res_get (common_resource, ext_res)))
681         return 0;
682     if (!(recType = recType_byName (file_type)))
683         return 0;
684
685     /* determine match criteria */
686     sprintf (ext_res, "%sfileMatch.%s", gprefix, ext);
687     file_match = res_get (common_resource, ext_res);
688     if (!file_match)
689     {
690         sprintf (ext_res, "%sfileMatch", gprefix);
691         file_match = res_get (common_resource, ext_res);
692     }
693
694     /* determine database name */
695     if (!rGroup->databaseName)
696     {
697         sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
698         if (!(rGroup->databaseName = res_get (common_resource, ext_res)))
699         {
700             sprintf (ext_res, "%sdatabase", gprefix);
701             rGroup->databaseName = res_get (common_resource, ext_res);
702         }
703     }
704     if (!rGroup->databaseName)
705         rGroup->databaseName = "Default";
706
707     /* open input file */
708     if ((extractCtrl.fd = open (fname, O_RDONLY)) == -1)
709     {
710         logf (LOG_WARN|LOG_ERRNO, "open %s", fname);
711         return 0;
712     }
713
714     /* extract keys */
715     extractCtrl.subType = "";
716     extractCtrl.init = wordInit;
717     extractCtrl.add = addRecordKeyAny;
718
719     reckeys.buf_used = 0;
720     file_read_start (extractCtrl.fd);
721     extractCtrl.readf = file_read;
722     r = (*recType->extract)(&extractCtrl);
723     file_read_stop (extractCtrl.fd);
724     close (extractCtrl.fd);
725   
726     if (r)      
727     {
728         logf (LOG_WARN, "Couldn't extract file %s, code %d", fname, r);
729         return 0;
730     }
731
732     /* perform match if sysno not known and if match criteria is specified */
733        
734     matchStr = NULL;
735     if (!sysno) 
736     {
737         sysnotmp = 0;
738         sysno = &sysnotmp;
739         if (file_match)
740         {
741             char *rinfo;
742         
743             matchStr = fileMatchStr(&reckeys, rGroup, fname, file_type,
744                                     file_match);
745             if (matchStr)
746             {
747                 rinfo = dict_lookup (matchDict, matchStr);
748                 if (rinfo)
749                     memcpy (sysno, rinfo+1, sizeof(*sysno));
750             }
751             else
752             {
753                 logf (LOG_WARN, "Record not inserted");
754                 return 0;
755             }
756         }
757     }
758
759     /* new record ? */
760     if (! *sysno)
761     {
762         if (deleteFlag)
763         {
764             logf (LOG_LOG, "? record %s", fname);
765             return 1;
766         }
767         logf (LOG_LOG, "add record %s", fname);
768         rec = rec_new (records);
769         *sysno = rec->sysno;
770
771         if (matchStr)
772             dict_insert (matchDict, matchStr, sizeof(*sysno), sysno);
773         flushRecordKeys (*sysno, 1, &reckeys, rGroup->databaseName);
774
775         records_inserted++;
776     }
777     else
778     {
779         struct recKeys delkeys;
780
781         rec = rec_get (records, *sysno);
782
783         delkeys.buf_used = rec->size[2];
784         delkeys.buf = rec->info[2];
785         flushRecordKeys (*sysno, 0, &delkeys, rec->info[3]);
786         if (deleteFlag)
787         {
788             logf (LOG_LOG, "delete record %s", fname);
789             records_deleted++;
790             rec_del (records, &rec);
791             return 1;
792         }
793         else
794         {
795             logf (LOG_LOG, "update record %s", fname);
796             flushRecordKeys (*sysno, 1, &reckeys, rGroup->databaseName); 
797             records_updated++;
798         }
799     }
800     free (rec->info[0]);
801     rec->info[0] = rec_strdup (file_type, &rec->size[0]);
802
803     free (rec->info[1]);
804     rec->info[1] = rec_strdup (fname, &rec->size[1]);
805
806     free (rec->info[2]);
807     if (reckeys.buf_used > 0)
808     {
809         rec->info[2] = malloc (reckeys.buf_used);
810         rec->size[2] = reckeys.buf_used;
811         memcpy (rec->info[2], reckeys.buf, rec->size[2]);
812     }
813     else
814     {
815         rec->info[2] = NULL;
816         rec->size[2] = 0;
817     }
818     free (rec->info[3]);
819     rec->info[3] = rec_strdup (rGroup->databaseName, &rec->size[3]); 
820
821     rec_put (records, &rec);
822     return 1;
823 }