Using wrbuf rather than sprintf. Allow all syntaxes for ::data fetch.
[idzebra-moved-to-github.git] / index / retrieve.c
1 /* $Id: retrieve.c,v 1.58 2006-11-24 11:35:23 adam Exp $
2    Copyright (C) 1995-2006
3    Index Data ApS
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20
21 */
22
23 #include <stdio.h>
24 #include <assert.h>
25
26 #include <fcntl.h>
27 #ifdef WIN32
28 #include <io.h>
29 #include <process.h>
30 #endif
31 #if HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
34
35 #include "index.h"
36 #include <yaz/diagbib1.h>
37 #include <direntz.h>
38
39
40 #define ZEBRA_XML_HEADER_STR "<record xmlns=\"http://www.indexdata.com/zebra/\""
41
42 static int zebra_create_record_stream(ZebraHandle zh, 
43                                Record *rec,
44                                struct ZebraRecStream *stream){
45
46     RecordAttr *recordAttr = rec_init_attr(zh->reg->zei, *rec);
47
48     if ((*rec)->size[recInfo_storeData] > 0)
49         zebra_create_stream_mem(stream, (*rec)->info[recInfo_storeData],
50                                 (*rec)->size[recInfo_storeData]);
51     else
52     {
53         char full_rep[1024];
54         int fd;
55             
56         if (zh->path_reg && !yaz_is_abspath((*rec)->info[recInfo_filename])){
57             strcpy(full_rep, zh->path_reg);
58             strcat(full_rep, "/");
59             strcat(full_rep, (*rec)->info[recInfo_filename]);
60         }
61         else
62             strcpy(full_rep, (*rec)->info[recInfo_filename]);
63             
64         if ((fd = open (full_rep, O_BINARY|O_RDONLY)) == -1){
65             yaz_log (YLOG_WARN|YLOG_ERRNO, "Retrieve fail; missing file: %s",
66                      full_rep);
67             rec_free(rec);
68             return 14;
69         }
70         zebra_create_stream_fd(stream, fd, recordAttr->recordOffset);
71     }
72     return 0;
73 }
74     
75
76
77 static int parse_zebra_elem(const char *elem,
78                              const char **index, size_t *index_len,
79                              const char **type, size_t *type_len)
80 {
81     *index = 0;
82     *index_len = 0;
83
84     *type = 0;
85     *type_len = 0;
86
87     if (elem && *elem)
88     {
89         char *cp;
90         /* verify that '::' is in the beginning of *elem 
91            and something more follows */
92         if (':' != *elem
93             || !(elem +1) || ':' != *(elem +1)
94             || !(elem +2) || '\0' == *(elem +2))
95             return 0;
96  
97         /* pick out info from string after '::' */
98         elem = elem + 2;
99         cp = strchr(elem, ':');
100
101         if (!cp) /* index, no colon, no type */
102         {
103             *index = elem;
104             *index_len = strlen(elem);
105         }
106         else if (cp[1] == '\0') /* colon, but no following type */
107         {
108             return 0;
109         }
110         else  /* index, colon and type */
111         {
112             *index = elem;
113             *index_len = cp - elem;
114             *type = cp+1;
115             *type_len = strlen(cp+1);
116         }
117     }
118     return 1;
119 }
120
121
122 int zebra_special_index_fetch(ZebraHandle zh, zint sysno, ODR odr,
123                               Record rec,
124                               const char *elemsetname,
125                               oid_value input_format,
126                               oid_value *output_format,
127                               char **rec_bufp, int *rec_lenp)
128 {
129     const char *retrieval_index;
130     size_t retrieval_index_len; 
131     const char *retrieval_type;
132     size_t retrieval_type_len;
133     WRBUF wrbuf = 0;
134     zebra_rec_keys_t keys;
135     
136     /* set output variables before processing possible error states */
137     /* *rec_lenp = 0; */
138
139     /* only accept XML and SUTRS requests */
140     if (input_format != VAL_TEXT_XML
141         && input_format != VAL_SUTRS){
142         yaz_log(YLOG_WARN, "unsupported format for element set zebra::%s", 
143                 elemsetname);
144         *output_format = VAL_NONE;
145         return YAZ_BIB1_NO_SYNTAXES_AVAILABLE_FOR_THIS_REQUEST;
146     }
147
148     if (!parse_zebra_elem(elemsetname,
149                      &retrieval_index, &retrieval_index_len,
150                      &retrieval_type,  &retrieval_type_len))
151         return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
152
153     if (retrieval_type_len != 0 && retrieval_type_len != 1)
154     {
155         return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
156     }
157
158     if (retrieval_index_len)
159     {
160         char retrieval_index_cstr[256];
161
162         if (retrieval_index_len  < sizeof(retrieval_index_cstr) -1)
163         {
164             memcpy(retrieval_index_cstr, retrieval_index, retrieval_index_len);
165             retrieval_index_cstr[retrieval_index_len] = '\0';
166             
167             if (zebraExplain_lookup_attr_str(zh->reg->zei,
168                                              zinfo_index_category_index,
169                                              (retrieval_type_len == 0 ? -1 : 
170                                               retrieval_type[0]),
171                                              retrieval_index_cstr) == -1)
172                 return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
173         }
174     }
175
176     keys = zebra_rec_keys_open();
177     zebra_rec_keys_set_buf(keys, rec->info[recInfo_delKeys],
178                            rec->size[recInfo_delKeys], 0);
179
180     wrbuf = wrbuf_alloc();
181     if (zebra_rec_keys_rewind(keys)){
182         size_t slen;
183         const char *str;
184         struct it_key key_in;
185
186         if (input_format == VAL_TEXT_XML)
187         {
188             *output_format = VAL_TEXT_XML;
189             wrbuf_printf(wrbuf, ZEBRA_XML_HEADER_STR
190                          " sysno=\"" ZINT_FORMAT "\""
191                          " set=\"zebra::index%s/\">\n",
192                          sysno, elemsetname);
193         }
194         else if (input_format == VAL_SUTRS)
195             *output_format = VAL_SUTRS;
196
197         while(zebra_rec_keys_read(keys, &str, &slen, &key_in)){
198             int i;
199             int ord = CAST_ZINT_TO_INT(key_in.mem[0]);
200             int index_type;
201             const char *db = 0;
202             const char *string_index = 0;
203             size_t string_index_len;
204             char dst_buf[IT_MAX_WORD];
205             
206             zebraExplain_lookup_ord(zh->reg->zei, ord, &index_type, &db,
207                                     &string_index);
208             string_index_len = strlen(string_index);
209
210             /* process only if index is not defined, 
211                or if defined and matching */
212             if (retrieval_index == 0 
213                 || (string_index_len == retrieval_index_len 
214                     && !memcmp(string_index, retrieval_index,
215                                string_index_len))){
216                
217                 /* process only if type is not defined, or is matching */
218                 if (retrieval_type == 0 
219                     || (retrieval_type_len == 1 
220                         && retrieval_type[0] == index_type)){
221                     
222
223                     zebra_term_untrans(zh, index_type, dst_buf, str);
224                     if (strlen(dst_buf)){
225
226                         if (input_format == VAL_TEXT_XML){
227                             wrbuf_printf(wrbuf, "  <index name=\"%s\"", 
228                                          string_index);
229                             
230                             wrbuf_printf(wrbuf, " type=\"%c\"", index_type);
231                             
232                             wrbuf_printf(wrbuf, " seq=\"" ZINT_FORMAT "\">", 
233                                          key_in.mem[key_in.len -1]);
234                         
235                             wrbuf_xmlputs(wrbuf, dst_buf);
236                             wrbuf_printf(wrbuf, "</index>\n");
237                         }
238                         else if (input_format == VAL_SUTRS){
239                             wrbuf_printf(wrbuf, "%s ", string_index);
240                             
241                             wrbuf_printf(wrbuf, "%c", index_type);
242                             
243                             for (i = 1; i < key_in.len; i++)
244                                 wrbuf_printf(wrbuf, " " ZINT_FORMAT, 
245                                              key_in.mem[i]);
246
247                         /* zebra_term_untrans(zh, index_type, dst_buf, str); */
248                             wrbuf_printf(wrbuf, " %s", dst_buf);
249                         
250                             wrbuf_printf(wrbuf, "\n");
251                         }
252                     }
253                     
254                 }
255             }
256         }
257         if (input_format == VAL_TEXT_XML)
258             wrbuf_printf(wrbuf, "</record>\n");
259      }
260     *rec_lenp = wrbuf_len(wrbuf);
261     *rec_bufp = odr_malloc(odr, *rec_lenp);
262     memcpy(*rec_bufp, wrbuf_buf(wrbuf), *rec_lenp);
263     wrbuf_free(wrbuf, 1);
264     zebra_rec_keys_close(keys);
265     return 0;
266 }
267
268
269 static void retrieve_puts_attr(WRBUF wrbuf, const char *name,
270                                const char *value)
271 {
272     if (value)
273     {
274         wrbuf_printf(wrbuf, "%s=\"", name);
275         wrbuf_xmlputs(wrbuf, value);
276         wrbuf_printf(wrbuf, "\"\n");
277     }
278 }
279
280 static void retrieve_puts_str(WRBUF wrbuf, const char *name,
281                                const char *value)
282 {
283     if (value)
284         wrbuf_printf(wrbuf, "%s %s\n", name, value);
285 }
286
287 int zebra_special_fetch(ZebraHandle zh, zint sysno, int score, ODR odr,
288                            const char *elemsetname,
289                            oid_value input_format,
290                            oid_value *output_format,
291                            char **rec_bufp, int *rec_lenp)
292 {
293     Record rec;
294     
295     /* set output variables before processing possible error states */
296     /* *rec_lenp = 0; */
297
298
299
300     /* processing zebra::meta::sysno elemset without fetching binary data */
301     if (elemsetname && 0 == strcmp(elemsetname, "meta::sysno"))
302     {
303         int ret = 0;
304         WRBUF wrbuf = wrbuf_alloc();
305         if (input_format == VAL_SUTRS)
306         {
307             wrbuf_printf(wrbuf, ZINT_FORMAT, sysno);
308             *output_format = VAL_SUTRS;
309         } 
310         else if (input_format == VAL_TEXT_XML)
311         {
312             wrbuf_printf(wrbuf, ZEBRA_XML_HEADER_STR
313                          " sysno=\"" ZINT_FORMAT "\""
314                          " set=\"zebra::%s\"/>\n",
315                          sysno, elemsetname);
316             *output_format = VAL_TEXT_XML;
317         }
318         *rec_lenp = wrbuf_len(wrbuf);
319         if (*rec_lenp)
320             *rec_bufp = odr_strdup(odr, wrbuf_buf(wrbuf));
321         else
322             ret = YAZ_BIB1_NO_SYNTAXES_AVAILABLE_FOR_THIS_REQUEST;
323         wrbuf_free(wrbuf, 1);
324         return ret;
325     }
326
327     /* fetching binary record up for all other display elementsets */
328     rec = rec_get(zh->reg->records, sysno);
329     if (!rec)
330     {
331         yaz_log(YLOG_WARN, "rec_get fail on sysno=" ZINT_FORMAT, sysno);
332         return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
333     }
334
335     /* processing special elementsetnames zebra::data */    
336     if (elemsetname && 0 == strcmp(elemsetname, "data"))
337     {
338         struct ZebraRecStream stream;
339         RecordAttr *recordAttr = rec_init_attr(zh->reg->zei, rec); 
340         zebra_create_record_stream(zh, &rec, &stream);
341         *output_format = input_format;
342         *rec_lenp = recordAttr->recordSize;
343         *rec_bufp = (char *) odr_malloc(odr, *rec_lenp);
344         stream.readf(&stream, *rec_bufp, *rec_lenp);
345         stream.destroy(&stream);
346         rec_free(&rec);
347         return 0;
348     }
349
350     /* only accept XML and SUTRS requests from now */
351     if (input_format != VAL_TEXT_XML && input_format != VAL_SUTRS)
352     {
353         yaz_log(YLOG_WARN, "unsupported format for element set zebra::%s", 
354                 elemsetname);
355         return YAZ_BIB1_NO_SYNTAXES_AVAILABLE_FOR_THIS_REQUEST;
356     }
357     
358
359     /* processing special elementsetnames zebra::meta:: */
360     if (elemsetname && 0 == strcmp(elemsetname, "meta"))
361     {
362         int ret = 0;
363         WRBUF wrbuf = wrbuf_alloc();
364         RecordAttr *recordAttr = rec_init_attr(zh->reg->zei, rec); 
365
366         if (input_format == VAL_TEXT_XML)
367         {
368             *output_format = VAL_TEXT_XML;
369             
370             wrbuf_printf(
371                 wrbuf, ZEBRA_XML_HEADER_STR
372                 " sysno=\"" ZINT_FORMAT "\"", sysno);
373             retrieve_puts_attr(wrbuf, "base", rec->info[recInfo_databaseName]);
374             retrieve_puts_attr(wrbuf, "file", rec->info[recInfo_filename]);
375             retrieve_puts_attr(wrbuf, "type", rec->info[recInfo_fileType]);
376             
377             wrbuf_printf(
378                 wrbuf,
379                 " score=\"%i\""
380                 " rank=\"" ZINT_FORMAT "\""
381                 " size=\"%i\""
382                 " set=\"zebra::%s\"/>\n",
383                 score,
384                 recordAttr->staticrank,
385                 recordAttr->recordSize,
386                 elemsetname);
387         }
388         else if (input_format == VAL_SUTRS)
389         {
390             *output_format = VAL_SUTRS;
391             wrbuf_printf(wrbuf, "sysno " ZINT_FORMAT "\n", sysno);
392             retrieve_puts_str(wrbuf, "base", rec->info[recInfo_databaseName]);
393             retrieve_puts_str(wrbuf, "file", rec->info[recInfo_filename]);
394             retrieve_puts_str(wrbuf, "type", rec->info[recInfo_fileType]);
395
396             wrbuf_printf(wrbuf,
397                          "score %i\n"
398                          "rank " ZINT_FORMAT "\n"
399                          "size %i\n"
400                          "set zebra::%s\n",
401                          score,
402                          recordAttr->staticrank,
403                          recordAttr->recordSize,
404                          elemsetname);
405         }
406         *rec_lenp = wrbuf_len(wrbuf);
407         if (*rec_lenp)
408             *rec_bufp = odr_strdup(odr, wrbuf_buf(wrbuf));
409         else
410             ret = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
411
412         wrbuf_free(wrbuf, 1);
413         rec_free(&rec);
414         return ret;
415     }
416
417     /* processing special elementsetnames zebra::index:: */
418     if (elemsetname && 0 == strncmp(elemsetname, "index", 5)){
419         
420         int ret = zebra_special_index_fetch(zh, sysno, odr, rec,
421                                             elemsetname + 5,
422                                             input_format, output_format,
423                                             rec_bufp, rec_lenp);
424         
425         rec_free(&rec);
426         return ret;
427     }
428
429     if (rec)
430         rec_free(&rec);
431     return YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_;
432 }
433
434                           
435 int zebra_record_fetch(ZebraHandle zh, zint sysno, int score,
436                        zebra_snippets *hit_snippet, ODR odr,
437                        oid_value input_format, Z_RecordComposition *comp,
438                        oid_value *output_format,
439                        char **rec_bufp, int *rec_lenp, char **basenamep,
440                        char **addinfo)
441 {
442     Record rec;
443     char *fname, *file_type, *basename;
444     const char *elemsetname;
445     struct ZebraRecStream stream;
446     RecordAttr *recordAttr;
447     void *clientData;
448     int return_code = 0;
449
450     *basenamep = 0;
451     *addinfo = 0;
452     elemsetname = yaz_get_esn(comp);
453
454     /* processing zebra special elementset names of form 'zebra:: */
455     if (elemsetname && 0 == strncmp(elemsetname, "zebra::", 7))
456         return  zebra_special_fetch(zh, sysno, score, odr,
457                                     elemsetname + 7,
458                                     input_format, output_format,
459                                     rec_bufp, rec_lenp);
460
461
462     /* processing all other element set names */
463     rec = rec_get(zh->reg->records, sysno);
464     if (!rec)
465     {
466         yaz_log(YLOG_WARN, "rec_get fail on sysno=" ZINT_FORMAT, sysno);
467         *basenamep = 0;
468         return YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
469     }
470
471
472     recordAttr = rec_init_attr(zh->reg->zei, rec);
473
474     file_type = rec->info[recInfo_fileType];
475     fname = rec->info[recInfo_filename];
476     basename = rec->info[recInfo_databaseName];
477     *basenamep = (char *) odr_malloc (odr, strlen(basename)+1);
478     strcpy (*basenamep, basename);
479
480     yaz_log(YLOG_DEBUG, "retrieve localno=" ZINT_FORMAT " score=%d",
481             sysno, score);
482
483     zebra_create_record_stream(zh, &rec, &stream);
484     
485     {
486         /* snippets code */
487         zebra_snippets *snippet;
488         zebra_rec_keys_t reckeys = zebra_rec_keys_open();
489         RecType rt;
490         struct recRetrieveCtrl retrieveCtrl;
491
492         retrieveCtrl.stream = &stream;
493         retrieveCtrl.fname = fname;
494         retrieveCtrl.localno = sysno;
495         retrieveCtrl.staticrank = recordAttr->staticrank;
496         retrieveCtrl.score = score;
497         retrieveCtrl.recordSize = recordAttr->recordSize;
498         retrieveCtrl.odr = odr;
499         retrieveCtrl.input_format = retrieveCtrl.output_format = input_format;
500         retrieveCtrl.comp = comp;
501         retrieveCtrl.encoding = zh->record_encoding;
502         retrieveCtrl.diagnostic = 0;
503         retrieveCtrl.addinfo = 0;
504         retrieveCtrl.dh = zh->reg->dh;
505         retrieveCtrl.res = zh->res;
506         retrieveCtrl.rec_buf = 0;
507         retrieveCtrl.rec_len = -1;
508         retrieveCtrl.hit_snippet = hit_snippet;
509         retrieveCtrl.doc_snippet = zebra_snippets_create();
510
511         zebra_rec_keys_set_buf(reckeys,
512                                rec->info[recInfo_delKeys],
513                                rec->size[recInfo_delKeys], 
514                                0);
515         zebra_rec_keys_to_snippets(zh, reckeys, retrieveCtrl.doc_snippet);
516         zebra_rec_keys_close(reckeys);
517
518 #if 0
519         /* for debugging purposes */
520         yaz_log(YLOG_LOG, "DOC SNIPPET:");
521         zebra_snippets_log(retrieveCtrl.doc_snippet, YLOG_LOG);
522         yaz_log(YLOG_LOG, "HIT SNIPPET:");
523         zebra_snippets_log(retrieveCtrl.hit_snippet, YLOG_LOG);
524 #endif
525         snippet = zebra_snippets_window(retrieveCtrl.doc_snippet,
526                                         retrieveCtrl.hit_snippet,
527                                         10);
528 #if 0
529         /* for debugging purposes */
530         yaz_log(YLOG_LOG, "WINDOW SNIPPET:");
531         zebra_snippets_log(snippet, YLOG_LOG);
532 #endif
533
534         if (!(rt = recType_byName(zh->reg->recTypes, zh->res,
535                                   file_type, &clientData)))
536         {
537             return_code = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
538         }
539         else
540         {
541             (*rt->retrieve)(clientData, &retrieveCtrl);
542             return_code = retrieveCtrl.diagnostic;
543
544             *output_format = retrieveCtrl.output_format;
545             *rec_bufp = (char *) retrieveCtrl.rec_buf;
546             *rec_lenp = retrieveCtrl.rec_len;
547             *addinfo = retrieveCtrl.addinfo;
548         }
549
550         zebra_snippets_destroy(snippet);
551         zebra_snippets_destroy(retrieveCtrl.doc_snippet);
552      }
553
554     stream.destroy(&stream);
555     rec_free(&rec);
556
557     return return_code;
558 }
559
560 /*
561  * Local variables:
562  * c-basic-offset: 4
563  * indent-tabs-mode: nil
564  * End:
565  * vim: shiftwidth=4 tabstop=8 expandtab
566  */
567