6ca60158870cc7f2d771e6efaaf1995f261f897c
[metaproxy-moved-to-github.git] / src / filter_zoom.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2012 Index Data
3
4 Metaproxy is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17 */
18
19 #include "config.hpp"
20
21 #include <stdlib.h>
22 #include <sys/types.h>
23 #include "filter_zoom.hpp"
24 #include <metaproxy/package.hpp>
25 #include <metaproxy/util.hpp>
26 #include <metaproxy/xmlutil.hpp>
27 #include "torus.hpp"
28
29 #include <libxslt/xsltutils.h>
30 #include <libxslt/transform.h>
31
32 #include <boost/thread/mutex.hpp>
33 #include <boost/thread/condition.hpp>
34
35 #include <yaz/yaz-version.h>
36 #include <yaz/tpath.h>
37 #include <yaz/srw.h>
38 #include <yaz/ccl_xml.h>
39 #include <yaz/ccl.h>
40 #include <yaz/rpn2cql.h>
41 #include <yaz/rpn2solr.h>
42 #include <yaz/pquery.h>
43 #include <yaz/cql.h>
44 #include <yaz/oid_db.h>
45 #include <yaz/diagbib1.h>
46 #include <yaz/log.h>
47 #include <yaz/zgdu.h>
48 #include <yaz/querytowrbuf.h>
49 #include <yaz/sortspec.h>
50 #include <yaz/tokenizer.h>
51 #include <yaz/zoom.h>
52
53 namespace mp = metaproxy_1;
54 namespace yf = mp::filter;
55
56 namespace metaproxy_1 {
57     namespace filter {
58         class Zoom::Searchable : boost::noncopyable {
59           public:
60             std::string authentication;
61             std::string cfAuth;
62             std::string cfProxy;
63             std::string cfSubDB;
64             std::string udb;
65             std::string target;
66             std::string query_encoding;
67             std::string sru;
68             std::string sru_version;
69             std::string request_syntax;
70             std::string element_set;
71             std::string record_encoding;
72             std::string transform_xsl_fname;
73             std::string transform_xsl_content;
74             std::string urlRecipe;
75             std::string contentConnector;
76             std::string sortStrategy;
77             bool use_turbomarc;
78             bool piggyback;
79             CCL_bibset ccl_bibset;
80             std::map<std::string, std::string> sortmap;
81             Searchable(CCL_bibset base);
82             ~Searchable();
83         };
84         class Zoom::Backend : boost::noncopyable {
85             friend class Impl;
86             friend class Frontend;
87             std::string zurl;
88             WRBUF m_apdu_wrbuf;
89             ZOOM_connection m_connection;
90             ZOOM_resultset m_resultset;
91             std::string m_frontend_database;
92             SearchablePtr sptr;
93             xsltStylesheetPtr xsp;
94             std::string content_session_id;
95             bool enable_cproxy;
96             bool enable_explain;
97             xmlDoc *explain_doc;
98         public:
99             Backend();
100             ~Backend();
101             void connect(std::string zurl, int *error, char **addinfo,
102                          ODR odr);
103             void search(ZOOM_query q, Odr_int *hits,
104                         int *error, char **addinfo, ODR odr);
105             void present(Odr_int start, Odr_int number, ZOOM_record *recs,
106                          int *error, char **addinfo, ODR odr);
107             void set_option(const char *name, const char *value);
108             void set_option(const char *name, std::string value);
109             const char *get_option(const char *name);
110             void get_zoom_error(int *error, char **addinfo, ODR odr);
111         };
112         class Zoom::Frontend : boost::noncopyable {
113             friend class Impl;
114             Impl *m_p;
115             bool m_is_virtual;
116             bool m_in_use;
117             yazpp_1::GDU m_init_gdu;
118             BackendPtr m_backend;
119             void handle_package(mp::Package &package);
120             void handle_search(mp::Package &package);
121
122             BackendPtr explain_search(mp::Package &package,
123                                       std::string &database,
124                                       int *error,
125                                       char **addinfo,
126                                       mp::odr &odr,
127                                       std::string &torus_db,
128                                       std::string &realm);
129             void handle_present(mp::Package &package);
130             BackendPtr get_backend_from_databases(mp::Package &package,
131                                                   std::string &database,
132                                                   int *error,
133                                                   char **addinfo,
134                                                   mp::odr &odr,
135                                                   int *proxy_step);
136
137             bool create_content_session(mp::Package &package,
138                                         BackendPtr b,
139                                         int *error,
140                                         char **addinfo,
141                                         ODR odr,
142                                         std::string authentication,
143                                         std::string proxy,
144                                         std::string realm);
145             
146             void prepare_elements(BackendPtr b,
147                                   Odr_oid *preferredRecordSyntax,
148                                   const char *element_set_name,
149                                   bool &enable_pz2_retrieval,
150                                   bool &enable_pz2_transform,
151                                   bool &enable_record_transform,
152                                   bool &assume_marc8_charset);
153
154             Z_Records *get_records(Package &package,
155                                    Odr_int start,
156                                    Odr_int number_to_present,
157                                    int *error,
158                                    char **addinfo,
159                                    Odr_int *number_of_records_returned,
160                                    ODR odr, BackendPtr b,
161                                    Odr_oid *preferredRecordSyntax,
162                                    const char *element_set_name);
163             Z_Records *get_explain_records(Package &package,
164                                            Odr_int start,
165                                            Odr_int number_to_present,
166                                            int *error,
167                                            char **addinfo,
168                                            Odr_int *number_of_records_returned,
169                                            ODR odr, BackendPtr b,
170                                            Odr_oid *preferredRecordSyntax,
171                                            const char *element_set_name);
172
173             void log_diagnostic(mp::Package &package,
174                                 int error, const char *addinfo);
175         public:
176             Frontend(Impl *impl);
177             ~Frontend();
178         };
179         class Zoom::Impl {
180             friend class Frontend;
181         public:
182             Impl();
183             ~Impl();
184             void process(metaproxy_1::Package & package);
185             void configure(const xmlNode * ptr, bool test_only,
186                            const char *path);
187         private:
188             void configure_local_records(const xmlNode * ptr, bool test_only);
189             FrontendPtr get_frontend(mp::Package &package);
190             void release_frontend(mp::Package &package);
191             SearchablePtr parse_torus_record(const xmlNode *ptr);
192             struct cql_node *convert_cql_fields(struct cql_node *cn, ODR odr);
193             std::map<mp::Session, FrontendPtr> m_clients;            
194             boost::mutex m_mutex;
195             boost::condition m_cond_session_ready;
196             std::string torus_searchable_url;
197             std::string torus_content_url;
198             std::string default_realm;
199             std::map<std::string,std::string> fieldmap;
200             std::string xsldir;
201             std::string file_path;
202             std::string content_proxy_server;
203             std::string content_tmp_file;
204             bool apdu_log;
205             CCL_bibset bibset;
206             std::string element_transform;
207             std::string element_raw;
208             std::string proxy;
209             xsltStylesheetPtr explain_xsp;
210             xsltStylesheetPtr record_xsp;
211             std::map<std::string,SearchablePtr> s_map;
212             std::string zoom_timeout;
213         };
214     }
215 }
216
217
218 static xmlNode *xml_node_search(xmlNode *ptr, int *num, int m)
219 {
220     while (ptr)
221     {
222         if (ptr->type == XML_ELEMENT_NODE &&
223             !strcmp((const char *) ptr->name, "recordData"))
224         {
225             (*num)++;
226             if (m == *num)
227                 return ptr;
228         }
229         else  // else: we don't want to find nested nodes
230         {   
231             xmlNode *ret_node = xml_node_search(ptr->children, num, m);
232             if (ret_node)
233                 return ret_node;
234         }
235         ptr = ptr->next;
236     }
237     return 0;
238 }
239
240 // define Pimpl wrapper forwarding to Impl
241  
242 yf::Zoom::Zoom() : m_p(new Impl)
243 {
244 }
245
246 yf::Zoom::~Zoom()
247 {  // must have a destructor because of boost::scoped_ptr
248 }
249
250 void yf::Zoom::configure(const xmlNode *xmlnode, bool test_only,
251                          const char *path)
252 {
253     m_p->configure(xmlnode, test_only, path);
254 }
255
256 void yf::Zoom::process(mp::Package &package) const
257 {
258     m_p->process(package);
259 }
260
261
262 // define Implementation stuff
263
264 yf::Zoom::Backend::Backend()
265 {
266     m_apdu_wrbuf = wrbuf_alloc();
267     m_connection = ZOOM_connection_create(0);
268     ZOOM_connection_save_apdu_wrbuf(m_connection, m_apdu_wrbuf);
269     m_resultset = 0;
270     xsp = 0;
271     enable_cproxy = true;
272     enable_explain = false;
273     explain_doc = 0;
274 }
275
276 yf::Zoom::Backend::~Backend()
277 {
278     if (xsp)
279         xsltFreeStylesheet(xsp);
280     if (explain_doc)
281         xmlFreeDoc(explain_doc);
282     ZOOM_connection_destroy(m_connection);
283     ZOOM_resultset_destroy(m_resultset);
284     wrbuf_destroy(m_apdu_wrbuf);
285 }
286
287
288 void yf::Zoom::Backend::get_zoom_error(int *error, char **addinfo,
289                                        ODR odr)
290 {
291     const char *msg = 0;
292     const char *zoom_addinfo = 0;
293     const char *dset = 0;
294     int error0 = ZOOM_connection_error_x(m_connection, &msg,
295                                          &zoom_addinfo, &dset);
296     if (error0)
297     {
298         if (!dset)
299             dset = "Unknown";
300         
301         if (!strcmp(dset, "info:srw/diagnostic/1"))
302             *error = yaz_diag_srw_to_bib1(error0);
303         else if (!strcmp(dset, "Bib-1"))
304             *error = error0;
305         else
306             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
307         
308         *addinfo = (char *) odr_malloc(
309             odr, 30 + strlen(dset) + strlen(msg) +
310             (zoom_addinfo ? strlen(zoom_addinfo) : 0));
311         **addinfo = '\0';
312         if (zoom_addinfo && *zoom_addinfo)
313         {
314             strcpy(*addinfo, zoom_addinfo);
315             strcat(*addinfo, " ");
316         }
317         sprintf(*addinfo + strlen(*addinfo), "(%s %d %s)", dset, error0, msg);
318     }
319 }
320
321 void yf::Zoom::Backend::connect(std::string zurl,
322                                 int *error, char **addinfo,
323                                 ODR odr)
324 {
325     ZOOM_connection_connect(m_connection, zurl.c_str(), 0);
326     get_zoom_error(error, addinfo, odr);
327 }
328
329 void yf::Zoom::Backend::search(ZOOM_query q, Odr_int *hits,
330                                int *error, char **addinfo, ODR odr)
331 {
332     ZOOM_resultset_destroy(m_resultset);
333     m_resultset = ZOOM_connection_search(m_connection, q);
334     get_zoom_error(error, addinfo, odr);
335     if (*error == 0)
336         *hits = ZOOM_resultset_size(m_resultset);
337     else
338         *hits = 0;
339 }
340
341 void yf::Zoom::Backend::present(Odr_int start, Odr_int number,
342                                 ZOOM_record *recs,
343                                 int *error, char **addinfo, ODR odr)
344 {
345     ZOOM_resultset_records(m_resultset, recs, start, number);
346     get_zoom_error(error, addinfo, odr);
347 }
348
349 void yf::Zoom::Backend::set_option(const char *name, const char *value)
350 {
351     ZOOM_connection_option_set(m_connection, name, value);
352     if (m_resultset)
353         ZOOM_resultset_option_set(m_resultset, name, value);
354 }
355
356 void yf::Zoom::Backend::set_option(const char *name, std::string value)
357 {
358     set_option(name, value.c_str());
359 }
360
361 const char *yf::Zoom::Backend::get_option(const char *name)
362 {
363     return ZOOM_connection_option_get(m_connection, name);
364 }
365
366 yf::Zoom::Searchable::Searchable(CCL_bibset base)
367 {
368     piggyback = true;
369     use_turbomarc = true;
370     sortStrategy = "embed";
371     urlRecipe = "${md-electronic-url}";
372     ccl_bibset = ccl_qual_dup(base);
373 }
374
375 yf::Zoom::Searchable::~Searchable()
376 {
377     ccl_qual_rm(&ccl_bibset);
378 }
379
380 yf::Zoom::Frontend::Frontend(Impl *impl) : 
381     m_p(impl), m_is_virtual(false), m_in_use(true)
382 {
383 }
384
385 yf::Zoom::Frontend::~Frontend()
386 {
387 }
388
389 yf::Zoom::FrontendPtr yf::Zoom::Impl::get_frontend(mp::Package &package)
390 {
391     boost::mutex::scoped_lock lock(m_mutex);
392
393     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
394     
395     while(true)
396     {
397         it = m_clients.find(package.session());
398         if (it == m_clients.end())
399             break;
400         
401         if (!it->second->m_in_use)
402         {
403             it->second->m_in_use = true;
404             return it->second;
405         }
406         m_cond_session_ready.wait(lock);
407     }
408     FrontendPtr f(new Frontend(this));
409     m_clients[package.session()] = f;
410     f->m_in_use = true;
411     return f;
412 }
413
414 void yf::Zoom::Impl::release_frontend(mp::Package &package)
415 {
416     boost::mutex::scoped_lock lock(m_mutex);
417     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
418     
419     it = m_clients.find(package.session());
420     if (it != m_clients.end())
421     {
422         if (package.session().is_closed())
423         {
424             m_clients.erase(it);
425         }
426         else
427         {
428             it->second->m_in_use = false;
429         }
430         m_cond_session_ready.notify_all();
431     }
432 }
433
434 yf::Zoom::Impl::Impl() :
435     apdu_log(false), element_transform("pz2") , element_raw("raw"),
436     zoom_timeout("40")
437 {
438     bibset = ccl_qual_mk();
439
440     explain_xsp = 0;
441     record_xsp = 0;
442     srand((unsigned int) time(0));
443 }
444
445 yf::Zoom::Impl::~Impl()
446 {
447     if (explain_xsp)
448         xsltFreeStylesheet(explain_xsp);
449     ccl_qual_rm(&bibset);
450 }
451
452 yf::Zoom::SearchablePtr yf::Zoom::Impl::parse_torus_record(const xmlNode *ptr)
453 {
454     Zoom::SearchablePtr s(new Searchable(bibset));
455     
456     for (ptr = ptr->children; ptr; ptr = ptr->next)
457     {
458         if (ptr->type != XML_ELEMENT_NODE)
459             continue;
460         if (!strcmp((const char *) ptr->name, "layer"))
461             ptr = ptr->children;
462         else if (!strcmp((const char *) ptr->name,
463                          "authentication"))
464         {
465             s->authentication = mp::xml::get_text(ptr);
466         }
467         else if (!strcmp((const char *) ptr->name,
468                          "cfAuth"))
469         {
470             s->cfAuth = mp::xml::get_text(ptr);
471         } 
472         else if (!strcmp((const char *) ptr->name,
473                          "cfProxy"))
474         {
475             s->cfProxy = mp::xml::get_text(ptr);
476         }  
477         else if (!strcmp((const char *) ptr->name,
478                          "cfSubDB"))
479         {
480             s->cfSubDB = mp::xml::get_text(ptr);
481         }  
482         else if (!strcmp((const char *) ptr->name,
483                          "contentConnector"))
484         {
485             s->contentConnector = mp::xml::get_text(ptr);
486         }  
487         else if (!strcmp((const char *) ptr->name, "udb"))
488         {
489             s->udb = mp::xml::get_text(ptr);
490         }
491         else if (!strcmp((const char *) ptr->name, "zurl"))
492         {
493             s->target = mp::xml::get_text(ptr);
494         }
495         else if (!strcmp((const char *) ptr->name, "sru"))
496         {
497             s->sru = mp::xml::get_text(ptr);
498         }
499         else if (!strcmp((const char *) ptr->name, "SRUVersion") ||
500                  !strcmp((const char *) ptr->name, "sruVersion"))
501         {
502             s->sru_version = mp::xml::get_text(ptr);
503         }
504         else if (!strcmp((const char *) ptr->name,
505                          "queryEncoding"))
506         {
507             s->query_encoding = mp::xml::get_text(ptr);
508         }
509         else if (!strcmp((const char *) ptr->name,
510                          "piggyback"))
511         {
512             s->piggyback = mp::xml::get_bool(ptr, true);
513         }
514         else if (!strcmp((const char *) ptr->name,
515                          "requestSyntax"))
516         {
517             s->request_syntax = mp::xml::get_text(ptr);
518         }
519         else if (!strcmp((const char *) ptr->name,
520                          "elementSet"))
521         {
522             s->element_set = mp::xml::get_text(ptr);
523         }
524         else if (!strcmp((const char *) ptr->name,
525                          "recordEncoding"))
526         {
527             s->record_encoding = mp::xml::get_text(ptr);
528         }
529         else if (!strcmp((const char *) ptr->name,
530                          "transform"))
531         {
532             s->transform_xsl_fname = mp::xml::get_text(ptr);
533         }
534         else if (!strcmp((const char *) ptr->name,
535                          "literalTransform"))
536         {
537             s->transform_xsl_content = mp::xml::get_text(ptr);
538         }
539         else if (!strcmp((const char *) ptr->name,
540                          "urlRecipe"))
541         {
542             s->urlRecipe = mp::xml::get_text(ptr);
543         }
544         else if (!strcmp((const char *) ptr->name,
545                          "useTurboMarc"))
546         {
547             ; // useTurboMarc is ignored
548         }
549         else if (!strncmp((const char *) ptr->name,
550                           "cclmap_", 7))
551         {
552             std::string value = mp::xml::get_text(ptr);
553             if (value.length() > 0)
554             {
555                 ccl_qual_fitem(s->ccl_bibset, value.c_str(),
556                                (const char *) ptr->name + 7);
557             }
558         }
559         else if (!strncmp((const char *) ptr->name,
560                           "sortmap_", 8))
561         {
562             std::string value = mp::xml::get_text(ptr);
563             s->sortmap[(const char *) ptr->name + 8] = value;
564         }
565         else if (!strcmp((const char *) ptr->name,
566                           "sortStrategy"))
567         {
568             s->sortStrategy = mp::xml::get_text(ptr);
569         }
570     }
571     return s;
572 }
573
574 void yf::Zoom::Impl::configure_local_records(const xmlNode *ptr, bool test_only)
575 {
576     while (ptr && ptr->type != XML_ELEMENT_NODE)
577         ptr = ptr->next;
578     
579     if (ptr)
580     {
581         if (!strcmp((const char *) ptr->name, "records"))
582         {
583             for (ptr = ptr->children; ptr; ptr = ptr->next)
584             {
585                 if (ptr->type != XML_ELEMENT_NODE)
586                     continue;
587                 if (!strcmp((const char *) ptr->name, "record"))
588                 {
589                     SearchablePtr s = parse_torus_record(ptr);
590                     if (s)
591                     {
592                         std::string udb = s->udb;
593                         if (udb.length())
594                             s_map[s->udb] = s;
595                         else
596                         {
597                             throw mp::filter::FilterException
598                                 ("No udb for local torus record");
599                         }
600                     }
601                 }
602                 else
603                 {
604                     throw mp::filter::FilterException
605                         ("Bad element " 
606                          + std::string((const char *) ptr->name)
607                          + " in zoom filter inside element "
608                          "<torus><records>");
609                 }
610             }
611         }
612         else
613         {
614             throw mp::filter::FilterException
615                 ("Bad element " 
616                  + std::string((const char *) ptr->name)
617                  + " in zoom filter inside element <torus>");
618         }
619     }
620 }
621
622 void yf::Zoom::Impl::configure(const xmlNode *ptr, bool test_only,
623                                const char *path)
624 {
625     std::string explain_xslt_fname;
626     std::string record_xslt_fname;
627
628     content_tmp_file = "/tmp/cf.XXXXXX.p";
629     if (path && *path)
630     {
631         file_path = path;
632     }
633     for (ptr = ptr->children; ptr; ptr = ptr->next)
634     {
635         if (ptr->type != XML_ELEMENT_NODE)
636             continue;
637         else if (!strcmp((const char *) ptr->name, "torus"))
638         {
639             const struct _xmlAttr *attr;
640             for (attr = ptr->properties; attr; attr = attr->next)
641             {
642                 if (!strcmp((const char *) attr->name, "url"))
643                     torus_searchable_url = mp::xml::get_text(attr->children);
644                 else if (!strcmp((const char *) attr->name, "content_url"))
645                     torus_content_url = mp::xml::get_text(attr->children);
646                 else if (!strcmp((const char *) attr->name, "realm"))
647                     default_realm = mp::xml::get_text(attr->children);
648                 else if (!strcmp((const char *) attr->name, "xsldir"))
649                     xsldir = mp::xml::get_text(attr->children);
650                 else if (!strcmp((const char *) attr->name, "element_transform"))
651                     element_transform = mp::xml::get_text(attr->children);
652                 else if (!strcmp((const char *) attr->name, "element_raw"))
653                     element_raw = mp::xml::get_text(attr->children);
654                 else if (!strcmp((const char *) attr->name, "proxy"))
655                     proxy = mp::xml::get_text(attr->children);
656                 else if (!strcmp((const char *) attr->name, "explain_xsl"))
657                     explain_xslt_fname = mp::xml::get_text(attr->children);
658                 else if (!strcmp((const char *) attr->name, "record_xsl"))
659                     record_xslt_fname = mp::xml::get_text(attr->children);
660                 else
661                     throw mp::filter::FilterException(
662                         "Bad attribute " + std::string((const char *)
663                                                        attr->name));
664             }
665             // If content_url is not given, use value of searchable, to
666             // ensure backwards compatibility
667             if (!torus_content_url.length())
668                 torus_content_url = torus_searchable_url;
669             configure_local_records(ptr->children, test_only);
670         }
671         else if (!strcmp((const char *) ptr->name, "cclmap"))
672         {
673             const char *addinfo = 0;
674             ccl_xml_config(bibset, ptr, &addinfo);
675         }
676         else if (!strcmp((const char *) ptr->name, "fieldmap"))
677         {
678             const struct _xmlAttr *attr;
679             std::string ccl_field;
680             std::string cql_field;
681             for (attr = ptr->properties; attr; attr = attr->next)
682             {
683                 if (!strcmp((const char *) attr->name, "ccl"))
684                     ccl_field = mp::xml::get_text(attr->children);
685                 else if (!strcmp((const char *) attr->name, "cql"))
686                     cql_field = mp::xml::get_text(attr->children);
687                 else
688                     throw mp::filter::FilterException(
689                         "Bad attribute " + std::string((const char *)
690                                                        attr->name));
691             }
692             if (cql_field.length())
693                 fieldmap[cql_field] = ccl_field;
694         }
695         else if (!strcmp((const char *) ptr->name, "contentProxy"))
696         {
697             const struct _xmlAttr *attr;
698             for (attr = ptr->properties; attr; attr = attr->next)
699             {
700                 if (!strcmp((const char *) attr->name, "server"))
701                     content_proxy_server = mp::xml::get_text(attr->children);
702                 else if (!strcmp((const char *) attr->name, "tmp_file"))
703                     content_tmp_file = mp::xml::get_text(attr->children);
704                 else
705                     throw mp::filter::FilterException(
706                         "Bad attribute " + std::string((const char *)
707                                                        attr->name));
708             }
709         }
710         else if (!strcmp((const char *) ptr->name, "log"))
711         { 
712             const struct _xmlAttr *attr;
713             for (attr = ptr->properties; attr; attr = attr->next)
714             {
715                 if (!strcmp((const char *) attr->name, "apdu"))
716                     apdu_log = mp::xml::get_bool(attr->children, false);
717                 else
718                     throw mp::filter::FilterException(
719                         "Bad attribute " + std::string((const char *)
720                                                        attr->name));
721             }
722         }
723         else if (!strcmp((const char *) ptr->name, "zoom"))
724         {
725             const struct _xmlAttr *attr;
726             for (attr = ptr->properties; attr; attr = attr->next)
727             {
728                 if (!strcmp((const char *) attr->name, "timeout"))
729                     zoom_timeout = mp::xml::get_text(attr->children);
730                 else
731                     throw mp::filter::FilterException(
732                         "Bad attribute " + std::string((const char *)
733                                                        attr->name));
734             }
735         }
736         else
737         {
738             throw mp::filter::FilterException
739                 ("Bad element " 
740                  + std::string((const char *) ptr->name)
741                  + " in zoom filter");
742         }
743     }
744
745     if (explain_xslt_fname.length())
746     {
747         const char *path = 0;
748         
749         if (xsldir.length())
750             path = xsldir.c_str();
751         else
752             path = file_path.c_str();
753         
754         char fullpath[1024];
755         char *cp = yaz_filepath_resolve(explain_xslt_fname.c_str(),
756                                         path, 0, fullpath);
757         if (!cp)
758         {
759             throw mp::filter::FilterException
760                 ("Cannot read XSLT " + explain_xslt_fname);
761         }
762
763         xmlDoc *xsp_doc = xmlParseFile(cp);
764         if (!xsp_doc)
765         {
766             throw mp::filter::FilterException
767                 ("Cannot parse XSLT " + explain_xslt_fname);
768         }
769
770         explain_xsp = xsltParseStylesheetDoc(xsp_doc);
771         if (!explain_xsp)
772         {
773             xmlFreeDoc(xsp_doc);
774             throw mp::filter::FilterException
775                 ("Cannot parse XSLT " + explain_xslt_fname);
776             
777         }
778     }
779
780     if (record_xslt_fname.length())
781     {
782         const char *path = 0;
783         
784         if (xsldir.length())
785             path = xsldir.c_str();
786         else
787             path = file_path.c_str();
788         
789         char fullpath[1024];
790         char *cp = yaz_filepath_resolve(record_xslt_fname.c_str(),
791                                         path, 0, fullpath);
792         if (!cp)
793         {
794             throw mp::filter::FilterException
795                 ("Cannot read XSLT " + record_xslt_fname);
796         }
797
798         xmlDoc *xsp_doc = xmlParseFile(cp);
799         if (!xsp_doc)
800         {
801             throw mp::filter::FilterException
802                 ("Cannot parse XSLT " + record_xslt_fname);
803         }
804
805         record_xsp = xsltParseStylesheetDoc(xsp_doc);
806         if (!record_xsp)
807         {
808             xmlFreeDoc(xsp_doc);
809             throw mp::filter::FilterException
810                 ("Cannot parse XSLT " + record_xslt_fname);
811             
812         }
813     }
814 }
815
816 bool yf::Zoom::Frontend::create_content_session(mp::Package &package,
817                                                 BackendPtr b,
818                                                 int *error, char **addinfo,
819                                                 ODR odr,
820                                                 std::string authentication,
821                                                 std::string proxy,
822                                                 std::string realm)
823 {
824     if (b->sptr->contentConnector.length())
825     {
826         char *fname = (char *) xmalloc(m_p->content_tmp_file.length() + 8);
827         strcpy(fname, m_p->content_tmp_file.c_str());
828         char *xx = strstr(fname, "XXXXXX");
829         if (!xx)
830         {
831             xx = fname + strlen(fname);
832             strcat(fname, "XXXXXX");
833         }
834         char tmp_char = xx[6];
835         sprintf(xx, "%06d", ((unsigned) rand()) % 1000000);
836         xx[6] = tmp_char;
837
838         FILE *file = fopen(fname, "w");
839         if (!file)
840         {
841             package.log("zoom", YLOG_WARN|YLOG_ERRNO, "create %s", fname);
842             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
843             *addinfo = (char *)  odr_malloc(odr, 40 + strlen(fname));
844             sprintf(*addinfo, "Could not create %s", fname);
845             xfree(fname);
846             return false;
847         }
848         b->content_session_id.assign(xx, 6);
849         WRBUF w = wrbuf_alloc();
850         wrbuf_puts(w, "#content_proxy\n");
851         wrbuf_printf(w, "connector: %s\n", b->sptr->contentConnector.c_str());
852         if (authentication.length())
853             wrbuf_printf(w, "auth: %s\n", authentication.c_str());
854         if (proxy.length())
855             wrbuf_printf(w, "proxy: %s\n", proxy.c_str());
856         if (realm.length())
857             wrbuf_printf(w, "realm: %s\n", realm.c_str());
858
859         fwrite(wrbuf_buf(w), 1, wrbuf_len(w), file);
860         fclose(file);
861         package.log("zoom", YLOG_LOG, "content file: %s", fname);
862         xfree(fname);
863         wrbuf_destroy(w);
864     }
865     return true;
866 }
867
868 yf::Zoom::BackendPtr yf::Zoom::Frontend::get_backend_from_databases(
869     mp::Package &package,
870     std::string &database, int *error, char **addinfo, mp::odr &odr,
871     int *proxy_step)
872 {
873     std::list<BackendPtr>::const_iterator map_it;
874     if (m_backend && !m_backend->enable_explain && 
875         m_backend->m_frontend_database == database)
876         return m_backend;
877
878     std::string input_args;
879     std::string torus_db;
880     size_t db_arg_pos = database.find(',');
881     if (db_arg_pos != std::string::npos)
882     {
883         torus_db = database.substr(0, db_arg_pos);
884         input_args = database.substr(db_arg_pos + 1);
885     }
886     else
887         torus_db = database;
888
889     std::string authentication;
890     std::string content_authentication;
891     std::string proxy;
892     std::string content_proxy;
893     std::string realm = m_p->default_realm;
894
895     const char *param_user = 0;
896     const char *param_password = 0;
897     const char *param_content_user = 0;
898     const char *param_content_password = 0;
899     const char *param_nocproxy = 0;
900     int no_parms = 0;
901
902     char **names;
903     char **values;
904     int no_out_args = 0;
905     if (input_args.length())
906         no_parms = yaz_uri_to_array(input_args.c_str(),
907                                     odr, &names, &values);
908     // adding 10 because we'll be adding other URL args
909     const char **out_names = (const char **)
910         odr_malloc(odr, (10 + no_parms) * sizeof(*out_names));
911     const char **out_values = (const char **)
912         odr_malloc(odr, (10 + no_parms) * sizeof(*out_values));
913     
914     // may be changed if it's a content connection
915     std::string torus_url = m_p->torus_searchable_url;
916     int i;
917     for (i = 0; i < no_parms; i++)
918     {
919         const char *name = names[i];
920         const char *value = values[i];
921         assert(name);
922         assert(value);
923         if (!strcmp(name, "user"))
924             param_user = value;
925         else if (!strcmp(name, "password"))
926             param_password = value;
927         else if (!strcmp(name, "content-user"))
928             param_content_user = value;
929         else if (!strcmp(name, "content-password"))
930             param_content_password = value;
931         else if (!strcmp(name, "content-proxy"))
932             content_proxy = value;
933         else if (!strcmp(name, "nocproxy"))
934             param_nocproxy = value;
935         else if (!strcmp(name, "proxy"))
936         {
937             char **dstr;
938             int dnum = 0;
939             nmem_strsplit(((ODR) odr)->mem, ",", value, &dstr, &dnum);
940             if (*proxy_step >= dnum)
941                 *proxy_step = 0;
942             else
943             {
944                 proxy = dstr[*proxy_step];
945                 
946                 (*proxy_step)++;
947                 if (*proxy_step == dnum)
948                     *proxy_step = 0;
949             }
950         }
951         else if (!strcmp(name, "cproxysession"))
952         {
953             out_names[no_out_args] = name;
954             out_values[no_out_args++] = value;
955             torus_url = m_p->torus_content_url;
956         }
957         else if (!strcmp(name, "realm"))
958             realm = value;
959         else if (name[0] == 'x' && name[1] == '-')
960         {
961             out_names[no_out_args] = name;
962             out_values[no_out_args++] = value;
963         }
964         else
965         {
966             BackendPtr notfound;
967             char *msg = (char*) odr_malloc(odr, strlen(name) + 30);
968             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
969             sprintf(msg, "Bad database argument: %s", name);
970             *addinfo = msg;
971             return notfound;
972         }
973     }
974     if (param_user)
975     {
976         authentication = std::string(param_user);
977         if (param_password)
978             authentication += "/" + std::string(param_password);
979     }
980     if (param_content_user)
981     {
982         content_authentication = std::string(param_content_user);
983         if (param_content_password)
984             content_authentication += "/" + std::string(param_content_password);
985     }
986
987     if (torus_db.compare("IR-Explain---1") == 0)
988         return explain_search(package, database, error, addinfo, odr, torus_db,
989             realm);
990     
991     SearchablePtr sptr;
992
993     std::map<std::string,SearchablePtr>::iterator it;
994     it = m_p->s_map.find(torus_db);
995     if (it != m_p->s_map.end())
996         sptr = it->second;
997     else if (torus_url.length() > 0)
998     {
999         std::string torus_query = "udb==" + torus_db;
1000         xmlDoc *doc = mp::get_searchable(package,torus_url, torus_db,
1001                                          torus_query,
1002                                          realm, m_p->proxy);
1003         if (!doc)
1004         {
1005             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1006             *addinfo = odr_strdup(odr, database.c_str());
1007             BackendPtr b;
1008             return b;
1009         }
1010         const xmlNode *ptr = xmlDocGetRootElement(doc);
1011         if (ptr)
1012         {   // presumably ptr is a records element node
1013             // parse first record in document
1014             for (ptr = ptr->children; ptr; ptr = ptr->next)
1015             {
1016                 if (ptr->type == XML_ELEMENT_NODE
1017                     && !strcmp((const char *) ptr->name, "record"))
1018                 {
1019                     if (sptr)
1020                     {
1021                         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1022                         *addinfo = (char*) odr_malloc(odr, 40 + database.length()),
1023                         sprintf(*addinfo, "multiple records for udb=%s",
1024                                  database.c_str());
1025                         xmlFreeDoc(doc);
1026                         BackendPtr b;
1027                         return b;
1028                     }
1029                     sptr = m_p->parse_torus_record(ptr);
1030                 }
1031             }
1032         }
1033         xmlFreeDoc(doc);
1034     }
1035
1036     if (!sptr)
1037     {
1038         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1039         *addinfo = odr_strdup(odr, database.c_str());
1040         BackendPtr b;
1041         return b;
1042     }
1043         
1044     xsltStylesheetPtr xsp = 0;
1045     if (sptr->transform_xsl_content.length())
1046     {
1047         xmlDoc *xsp_doc = xmlParseMemory(sptr->transform_xsl_content.c_str(),
1048                                          sptr->transform_xsl_content.length());
1049         if (!xsp_doc)
1050         {
1051             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1052             *addinfo = (char *) odr_malloc(odr, 40);
1053             sprintf(*addinfo, "xmlParseMemory failed");
1054             BackendPtr b;
1055             return b;
1056         }
1057         xsp = xsltParseStylesheetDoc(xsp_doc);
1058         if (!xsp)
1059         {
1060             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1061             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
1062             BackendPtr b;
1063             xmlFreeDoc(xsp_doc);
1064             return b;
1065         }
1066     }
1067     else if (sptr->transform_xsl_fname.length())
1068     {
1069         const char *path = 0;
1070
1071         if (m_p->xsldir.length())
1072             path = m_p->xsldir.c_str();
1073         else
1074             path = m_p->file_path.c_str();
1075         std::string fname;
1076
1077         char fullpath[1024];
1078         char *cp = yaz_filepath_resolve(sptr->transform_xsl_fname.c_str(),
1079                                         path, 0, fullpath);
1080         if (cp)
1081             fname.assign(cp);
1082         else
1083         {
1084             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1085             *addinfo = (char *)
1086                 odr_malloc(odr, 40 + sptr->transform_xsl_fname.length());
1087             sprintf(*addinfo, "File could not be read: %s", 
1088                     sptr->transform_xsl_fname.c_str());
1089             BackendPtr b;
1090             return b;
1091         }
1092         xmlDoc *xsp_doc = xmlParseFile(fname.c_str());
1093         if (!xsp_doc)
1094         {
1095             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1096             *addinfo = (char *) odr_malloc(odr, 40 + fname.length());
1097             sprintf(*addinfo, "xmlParseFile failed. File: %s", fname.c_str());
1098             BackendPtr b;
1099             return b;
1100         }
1101         xsp = xsltParseStylesheetDoc(xsp_doc);
1102         if (!xsp)
1103         {
1104             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1105             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
1106             BackendPtr b;
1107             xmlFreeDoc(xsp_doc);
1108             return b;
1109         }
1110     }
1111
1112     m_backend.reset();
1113
1114     BackendPtr b(new Backend);
1115
1116     b->sptr = sptr;
1117     b->xsp = xsp;
1118     b->m_frontend_database = database;
1119     b->enable_cproxy = param_nocproxy ? false : true;
1120
1121     if (sptr->query_encoding.length())
1122         b->set_option("rpnCharset", sptr->query_encoding);
1123
1124     b->set_option("timeout", m_p->zoom_timeout.c_str());
1125     
1126     if (m_p->apdu_log) 
1127         b->set_option("apdulog", "1");
1128
1129     if (sptr->piggyback && sptr->sru.length())
1130         b->set_option("count", "1"); /* some SRU servers INSIST on getting
1131                                         maximumRecords > 0 */
1132     b->set_option("piggyback", sptr->piggyback ? "1" : "0");
1133
1134     if (authentication.length() == 0)
1135         authentication = sptr->authentication;
1136
1137     if (proxy.length() == 0)
1138         proxy = sptr->cfProxy;
1139     
1140     if (sptr->cfAuth.length())
1141     {
1142         // A CF target
1143         b->set_option("user", sptr->cfAuth);
1144         if (authentication.length())
1145         {
1146             size_t found = authentication.find('/');
1147             if (found != std::string::npos)
1148             {
1149                 out_names[no_out_args] = "user";
1150                 out_values[no_out_args++] =
1151                     odr_strdup(odr, authentication.substr(0, found).c_str());
1152
1153                 out_names[no_out_args] = "password";
1154                 out_values[no_out_args++] =
1155                     odr_strdup(odr, authentication.substr(found+1).c_str());
1156             }
1157             else
1158             {
1159                 out_names[no_out_args] = "user";
1160                 out_values[no_out_args++] =
1161                     odr_strdup(odr, authentication.c_str());
1162             }                
1163         }
1164         if (proxy.length())
1165         {
1166             out_names[no_out_args] = "proxy";
1167             out_values[no_out_args++] = odr_strdup(odr, proxy.c_str());
1168         }
1169         if (sptr->cfSubDB.length())
1170         {
1171             out_names[no_out_args] = "subdatabase";
1172             out_values[no_out_args++] = odr_strdup(odr, sptr->cfSubDB.c_str());
1173         }
1174         if (param_nocproxy)
1175         {
1176             out_names[no_out_args] = "nocproxy";
1177             out_values[no_out_args++] = odr_strdup(odr, param_nocproxy);
1178         }
1179     }
1180     else
1181     {
1182         size_t found = authentication.find('/');
1183         
1184         if (sptr->sru.length() && found != std::string::npos)
1185         {
1186             b->set_option("user", authentication.substr(0, found));
1187             b->set_option("password", authentication.substr(found+1));
1188         }
1189         else
1190             b->set_option("user", authentication);
1191
1192         if (proxy.length())
1193             b->set_option("proxy", proxy);
1194     }
1195     if (proxy.length())
1196         package.log("zoom", YLOG_LOG, "proxy: %s", proxy.c_str());
1197                 
1198     std::string url;
1199     if (sptr->sru.length())
1200     {
1201         url = "http://" + sptr->target;
1202         b->set_option("sru", sptr->sru);
1203
1204         if (sptr->sru_version.length())
1205             b->set_option("sru_version", sptr->sru_version);
1206     }
1207     else
1208     {
1209         url = sptr->target;
1210     }
1211     if (no_out_args)
1212     {
1213         char *x_args = 0;
1214         out_names[no_out_args] = 0; // terminate list
1215         
1216         yaz_array_to_uri(&x_args, odr, (char **) out_names,
1217                          (char **) out_values);
1218         url += "," + std::string(x_args);
1219     }
1220     package.log("zoom", YLOG_LOG, "url: %s", url.c_str());
1221     b->connect(url, error, addinfo, odr);
1222     if (*error == 0 && b->enable_cproxy)
1223         create_content_session(package, b, error, addinfo, odr,
1224                                content_authentication.length() ?
1225                                content_authentication : authentication,
1226                                content_proxy.length() ? content_proxy : proxy,
1227                                realm);
1228     if (*error == 0)
1229         m_backend = b;
1230     return b;
1231 }
1232
1233 void yf::Zoom::Frontend::prepare_elements(BackendPtr b,
1234                                           Odr_oid *preferredRecordSyntax,
1235                                           const char *element_set_name,
1236                                           bool &enable_pz2_retrieval,
1237                                           bool &enable_pz2_transform,
1238                                           bool &enable_record_transform,
1239                                           bool &assume_marc8_charset)
1240 {
1241     char oid_name_str[OID_STR_MAX];
1242     const char *syntax_name = 0;
1243     
1244     if (preferredRecordSyntax &&
1245         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
1246         && element_set_name)
1247     {
1248         if (!strcmp(element_set_name, m_p->element_transform.c_str()))
1249         {
1250             enable_pz2_retrieval = true;
1251             enable_pz2_transform = true;
1252         }
1253         else if (!strcmp(element_set_name, m_p->element_raw.c_str()))
1254         {
1255             enable_pz2_retrieval = true;
1256         }
1257         else
1258         {
1259             enable_pz2_retrieval = true;
1260             enable_pz2_transform = true;
1261             enable_record_transform = true;
1262         }
1263     }
1264     
1265     if (enable_pz2_retrieval)
1266     {
1267         std::string configured_request_syntax = b->sptr->request_syntax;
1268         if (configured_request_syntax.length())
1269         {
1270             syntax_name = configured_request_syntax.c_str();
1271             const Odr_oid *syntax_oid = 
1272                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
1273             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
1274                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
1275                 assume_marc8_charset = true;
1276         }
1277     }
1278     else if (preferredRecordSyntax)
1279         syntax_name =
1280             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
1281
1282     if (b->sptr->sru.length())
1283         syntax_name = "XML";
1284
1285     b->set_option("preferredRecordSyntax", syntax_name);
1286
1287     if (enable_pz2_retrieval)
1288     {
1289         element_set_name = 0;
1290         if (b->sptr->element_set.length())
1291             element_set_name = b->sptr->element_set.c_str();
1292     }
1293
1294     b->set_option("elementSetName", element_set_name);
1295     if (b->sptr->sru.length() && element_set_name)
1296         b->set_option("schema", element_set_name);
1297 }
1298
1299 Z_Records *yf::Zoom::Frontend::get_explain_records(
1300     Package &package,
1301     Odr_int start,
1302     Odr_int number_to_present,
1303     int *error,
1304     char **addinfo,
1305     Odr_int *number_of_records_returned,
1306     ODR odr,
1307     BackendPtr b,
1308     Odr_oid *preferredRecordSyntax,
1309     const char *element_set_name)
1310 {
1311     Odr_int i;
1312     Z_Records *records = 0;
1313
1314     if (!b->explain_doc)
1315     {
1316         return records;
1317     }
1318     if (number_to_present > 10000)
1319         number_to_present = 10000;
1320
1321     xmlNode *ptr = xmlDocGetRootElement(b->explain_doc);
1322     
1323     Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1324         odr_malloc(odr, sizeof(*npl));
1325     npl->records = (Z_NamePlusRecord **)
1326         odr_malloc(odr, number_to_present * sizeof(*npl->records));
1327     
1328     for (i = 0; i < number_to_present; i++)
1329     {
1330         int num = 0;
1331         xmlNode *res = xml_node_search(ptr, &num, start + i + 1);
1332         if (!res)
1333             break;
1334         xmlBufferPtr xml_buf = xmlBufferCreate();
1335         xmlNode *tmp_node = xmlCopyNode(res->children, 1);
1336         xmlNodeDump(xml_buf, tmp_node->doc, tmp_node, 0, 0);
1337
1338         Z_NamePlusRecord *npr =
1339             (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1340         npr->databaseName = odr_strdup(odr, b->m_frontend_database.c_str());
1341         npr->which = Z_NamePlusRecord_databaseRecord;
1342         npr->u.databaseRecord =
1343             z_ext_record_xml(odr,
1344                              (const char *) xml_buf->content, xml_buf->use);
1345         npl->records[i] = npr;
1346         xmlFreeNode(tmp_node);
1347         xmlBufferFree(xml_buf);
1348     }
1349     records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1350     records->which = Z_Records_DBOSD;
1351     records->u.databaseOrSurDiagnostics = npl;
1352
1353     npl->num_records = i;
1354     *number_of_records_returned = i;
1355     return records;
1356 }
1357
1358
1359 Z_Records *yf::Zoom::Frontend::get_records(Package &package,
1360                                            Odr_int start,
1361                                            Odr_int number_to_present,
1362                                            int *error,
1363                                            char **addinfo,
1364                                            Odr_int *number_of_records_returned,
1365                                            ODR odr,
1366                                            BackendPtr b,
1367                                            Odr_oid *preferredRecordSyntax,
1368                                            const char *element_set_name)
1369 {
1370     *number_of_records_returned = 0;
1371     Z_Records *records = 0;
1372     bool enable_pz2_retrieval = false; // whether target profile is used
1373     bool enable_pz2_transform = false; // whether XSLT is used as well
1374     bool assume_marc8_charset = false;
1375     bool enable_record_transform = false;
1376
1377     prepare_elements(b, preferredRecordSyntax,
1378                      element_set_name,
1379                      enable_pz2_retrieval,
1380                      enable_pz2_transform,
1381                      enable_record_transform,
1382                      assume_marc8_charset);
1383
1384     package.log("zoom", YLOG_LOG, "pz2_retrieval: %s . pz2_transform: %s",
1385                 enable_pz2_retrieval ? "yes" : "no",
1386                 enable_pz2_transform ? "yes" : "no");
1387
1388     if (start < 0 || number_to_present <=0)
1389         return records;
1390     
1391     if (number_to_present > 10000)
1392         number_to_present = 10000;
1393
1394     ZOOM_record *recs = (ZOOM_record *)
1395         odr_malloc(odr, (size_t) number_to_present * sizeof(*recs));
1396
1397     b->present(start, number_to_present, recs, error, addinfo, odr);
1398
1399     int i = 0;
1400     if (!*error)
1401     {
1402         for (i = 0; i < number_to_present; i++)
1403             if (!recs[i])
1404                 break;
1405     }
1406     if (i > 0)
1407     {  // only return records if no error and at least one record
1408
1409         const char *xsl_parms[3];
1410         char cproxy_host[1024];
1411
1412         if (b->enable_cproxy && b->content_session_id.length())
1413         {
1414             sprintf(cproxy_host, "%s.%s/",
1415                     b->content_session_id.c_str(),
1416                     m_p->content_proxy_server.c_str());
1417             
1418             char *q_cproxy_host = (char *) 
1419                 odr_malloc(odr, strlen(cproxy_host) + 3);
1420             strcpy(q_cproxy_host, "\"");
1421             strcat(q_cproxy_host, cproxy_host);
1422             strcat(q_cproxy_host, "\"");
1423
1424             xsl_parms[0] = "cproxyhost";
1425             xsl_parms[1] = q_cproxy_host;
1426             xsl_parms[2] = 0;
1427         }
1428         else
1429         {
1430             xsl_parms[0] = 0;
1431             *cproxy_host = '\0';
1432         }
1433
1434         char *odr_database = odr_strdup(odr,
1435                                         b->m_frontend_database.c_str());
1436         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1437             odr_malloc(odr, sizeof(*npl));
1438         *number_of_records_returned = i;
1439         npl->num_records = i;
1440         npl->records = (Z_NamePlusRecord **)
1441             odr_malloc(odr, i * sizeof(*npl->records));
1442         for (i = 0; i < number_to_present; i++)
1443         {
1444             Z_NamePlusRecord *npr = 0;
1445             const char *addinfo;
1446
1447             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1448                                               &addinfo, 0 /* diagset */);
1449                 
1450             if (sur_error)
1451             {
1452                 log_diagnostic(package, sur_error, addinfo);
1453                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1454                                             addinfo);
1455             }
1456             else if (enable_pz2_retrieval)
1457             {
1458                 char rec_type_str[100];
1459                 const char *record_encoding = 0;
1460
1461                 if (b->sptr->record_encoding.length())
1462                     record_encoding = b->sptr->record_encoding.c_str();
1463                 else if (assume_marc8_charset)
1464                     record_encoding = "marc8";
1465
1466                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1467                 if (record_encoding)
1468                 {
1469                     strcat(rec_type_str, "; charset=");
1470                     strcat(rec_type_str, record_encoding);
1471                 }
1472
1473                 package.log("zoom", YLOG_LOG, "Getting record of type %s",
1474                             rec_type_str);
1475                 int rec_len;
1476                 xmlChar *xmlrec_buf = 0;
1477                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1478                                                       &rec_len);
1479                 if (!rec_buf && !npr)
1480                 {
1481                     std::string addinfo("ZOOM_record_get failed for type ");
1482
1483                     int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1484                     addinfo += rec_type_str;
1485                     log_diagnostic(package, error, addinfo.c_str());
1486                     npr = zget_surrogateDiagRec(odr, odr_database,
1487                                                 error, addinfo.c_str());
1488                 }
1489                 else
1490                 {
1491                     package.log_write(rec_buf, rec_len);
1492                     package.log_write("\r\n", 2);
1493                 }
1494
1495                 if (rec_buf && b->xsp && enable_pz2_transform)
1496                 {
1497                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1498                     if (!rec_doc)
1499                     {
1500                         const char *addinfo = "xml parse failed for record";
1501                         int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1502                         log_diagnostic(package, error, addinfo);
1503                         npr = zget_surrogateDiagRec(
1504                             odr, odr_database, error, addinfo);
1505                     }
1506                     else
1507                     { 
1508                         xsltStylesheetPtr xsp = b->xsp;
1509                         xmlDoc *rec_res = xsltApplyStylesheet(xsp, rec_doc,
1510                                                               xsl_parms);
1511                         if (rec_res && m_p->record_xsp &&
1512                             enable_record_transform)
1513                         {
1514                             xmlDoc *tmp_doc = rec_res;
1515
1516                             xsp = m_p->record_xsp;
1517                             rec_res = xsltApplyStylesheet(xsp, tmp_doc,
1518                                                           xsl_parms);
1519                             xmlFreeDoc(tmp_doc);
1520                         }
1521                         if (rec_res)
1522                         {
1523                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1524                                                    rec_res, xsp);
1525                             rec_buf = (const char *) xmlrec_buf;
1526                             package.log("zoom", YLOG_LOG, "xslt successful");
1527                             package.log_write(rec_buf, rec_len);
1528
1529                             xmlFreeDoc(rec_res);
1530                         }
1531                         if (!rec_buf)
1532                         {
1533                             std::string addinfo;
1534                             int error =
1535                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1536
1537                             addinfo = "xslt apply failed for "
1538                                 + b->sptr->transform_xsl_fname;
1539                             log_diagnostic(package, error, addinfo.c_str());
1540                             npr = zget_surrogateDiagRec(
1541                                 odr, odr_database, error, addinfo.c_str());
1542                         }
1543                         xmlFreeDoc(rec_doc);
1544                     }
1545                 }
1546
1547                 if (rec_buf)
1548                 {
1549                     xmlDoc *doc = xmlParseMemory(rec_buf, rec_len);
1550                     std::string res = 
1551                         mp::xml::url_recipe_handle(doc, b->sptr->urlRecipe);
1552                     if (res.length() && *cproxy_host)
1553                     {
1554                         size_t off = res.find_first_of("://");
1555                         if (off != std::string::npos)
1556                             res.insert(off + 3, cproxy_host);
1557                     }
1558                     if (res.length())
1559                     {
1560                         xmlNode *ptr = xmlDocGetRootElement(doc);
1561                         while (ptr && ptr->type != XML_ELEMENT_NODE)
1562                             ptr = ptr->next;
1563                         xmlNode *c = 
1564                             xmlNewChild(ptr, 0, BAD_CAST "metadata", 0);
1565                         xmlNewProp(c, BAD_CAST "type", BAD_CAST
1566                                    "generated-url");
1567                         xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1568                         xmlAddChild(c, t);
1569
1570                         if (xmlrec_buf)
1571                             xmlFree(xmlrec_buf);
1572
1573                         xmlDocDumpMemory(doc, &xmlrec_buf, &rec_len);
1574                         rec_buf = (const char *) xmlrec_buf;
1575                     }
1576                     xmlFreeDoc(doc);
1577                 }
1578                 if (!npr)
1579                 {
1580                     if (!rec_buf)
1581                         npr = zget_surrogateDiagRec(
1582                             odr, odr_database, 
1583                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1584                             rec_type_str);
1585                     else
1586                     {
1587                         npr = (Z_NamePlusRecord *)
1588                             odr_malloc(odr, sizeof(*npr));
1589                         npr->databaseName = odr_database;
1590                         npr->which = Z_NamePlusRecord_databaseRecord;
1591                         npr->u.databaseRecord =
1592                             z_ext_record_xml(odr, rec_buf, rec_len);
1593                     }
1594                 }
1595                 if (xmlrec_buf)
1596                     xmlFree(xmlrec_buf);
1597             }
1598             else
1599             {
1600                 Z_External *ext =
1601                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1602                 if (ext)
1603                 {
1604                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1605                     npr->databaseName = odr_database;
1606                     npr->which = Z_NamePlusRecord_databaseRecord;
1607                     npr->u.databaseRecord = ext;
1608                 }
1609                 else
1610                 {
1611                     npr = zget_surrogateDiagRec(
1612                         odr, odr_database, 
1613                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1614                         "ZOOM_record, type ext");
1615                 }
1616             }
1617             npl->records[i] = npr;
1618         }
1619         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1620         records->which = Z_Records_DBOSD;
1621         records->u.databaseOrSurDiagnostics = npl;
1622     }
1623     return records;
1624 }
1625
1626 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1627                                                     ODR odr)
1628 {
1629     struct cql_node *r = 0;
1630     if (!cn)
1631         return 0;
1632     switch (cn->which)
1633     {
1634     case CQL_NODE_ST:
1635         if (cn->u.st.index)
1636         {
1637             std::map<std::string,std::string>::const_iterator it;
1638             it = fieldmap.find(cn->u.st.index);
1639             if (it == fieldmap.end())
1640                 return cn;
1641             if (it->second.length())
1642                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1643             else
1644                 cn->u.st.index = 0;
1645         }
1646         break;
1647     case CQL_NODE_BOOL:
1648         r = convert_cql_fields(cn->u.boolean.left, odr);
1649         if (!r)
1650             r = convert_cql_fields(cn->u.boolean.right, odr);
1651         break;
1652     case CQL_NODE_SORT:
1653         r = convert_cql_fields(cn->u.sort.search, odr);
1654         break;
1655     }
1656     return r;
1657 }
1658
1659 void yf::Zoom::Frontend::log_diagnostic(mp::Package &package,
1660                                         int error, const char *addinfo)
1661 {
1662     const char *err_msg = yaz_diag_bib1_str(error);
1663     if (addinfo)
1664         package.log("zoom", YLOG_WARN, "Diagnostic %d %s: %s",
1665                     error, err_msg, addinfo);
1666     else
1667         package.log("zoom", YLOG_WARN, "Diagnostic %d %s:",
1668                     error, err_msg);
1669 }
1670
1671 yf::Zoom::BackendPtr yf::Zoom::Frontend::explain_search(mp::Package &package,
1672                                                         std::string &database,
1673                                                         int *error,
1674                                                         char **addinfo,
1675                                                         mp::odr &odr,
1676                                                         std::string &torus_db,
1677                                                         std::string &realm)
1678 {
1679     m_backend.reset();
1680
1681     BackendPtr b(new Backend);
1682
1683     b->m_frontend_database = database;
1684     b->enable_explain = true;
1685    
1686     Z_GDU *gdu = package.request().get();
1687     Z_APDU *apdu_req = gdu->u.z3950;
1688     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1689     Z_Query *query = sr->query;
1690
1691     if (!m_p->explain_xsp)
1692     {
1693         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1694         *addinfo =
1695             odr_strdup(odr, "IR-Explain---1 unsupported. "
1696                        "Torus explain_xsl not defined");
1697         return m_backend;
1698     }
1699     else if (query->which == Z_Query_type_104 &&
1700         query->u.type_104->which == Z_External_CQL)
1701     {
1702         std::string torus_url = m_p->torus_searchable_url;
1703         std::string torus_query(query->u.type_104->u.cql);
1704         xmlDoc *doc = mp::get_searchable(package, torus_url, "",
1705                                          torus_query,
1706                                          realm, m_p->proxy);
1707         if (m_p->explain_xsp)
1708         {
1709             xmlDoc *rec_res =  xsltApplyStylesheet(m_p->explain_xsp, doc, 0);
1710
1711             xmlFreeDoc(doc);
1712             doc = rec_res;
1713         }
1714         if (!doc)
1715         {
1716             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1717             *addinfo = odr_strdup(odr, "IR-Explain---1 problem. " 
1718                                   "Could not obtain Torus records for Explain");
1719         }
1720         else
1721         {
1722             xmlNode *ptr = xmlDocGetRootElement(doc);
1723             int hits = 0;
1724             
1725             xml_node_search(ptr, &hits, 0);
1726
1727             Z_APDU *apdu_res = odr.create_searchResponse(apdu_req, 0, 0);
1728             apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1729             package.response() = apdu_res;
1730             m_backend = b;
1731         }
1732         if (b->explain_doc)
1733             xmlFreeDoc(b->explain_doc);
1734         b->explain_doc = doc;
1735         return m_backend;
1736     }
1737     else
1738     {
1739         *error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
1740         *addinfo = odr_strdup(odr, "IR-Explain---1 only supports CQL");
1741         return m_backend;
1742     }
1743 }
1744
1745 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1746 {
1747     Z_GDU *gdu = package.request().get();
1748     Z_APDU *apdu_req = gdu->u.z3950;
1749     Z_APDU *apdu_res = 0;
1750     mp::odr odr;
1751     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1752     if (sr->num_databaseNames != 1)
1753     {
1754         int error = YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED;
1755         log_diagnostic(package, error, 0);
1756         apdu_res = odr.create_searchResponse(apdu_req, error, 0);
1757         package.response() = apdu_res;
1758         return;
1759     }
1760     int proxy_step = 0;
1761
1762 next_proxy:
1763
1764     int error = 0;
1765     char *addinfo = 0;
1766     std::string db(sr->databaseNames[0]);
1767
1768     BackendPtr b = get_backend_from_databases(package, db, &error,
1769                                               &addinfo, odr, &proxy_step);
1770     if (error && proxy_step)
1771     {
1772         package.log("zoom", YLOG_WARN,
1773                     "create backend failed: trying next proxy");
1774         goto next_proxy;
1775     }
1776     if (error)
1777     {
1778         log_diagnostic(package, error, addinfo);
1779         apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1780         package.response() = apdu_res;
1781         return;
1782     }
1783     if (!b || b->enable_explain)
1784         return;
1785
1786     b->set_option("setname", "default");
1787
1788     bool enable_pz2_retrieval = false;
1789     bool enable_pz2_transform = false;
1790     bool enable_record_transform = false;
1791     bool assume_marc8_charset = false;
1792     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
1793                      enable_pz2_retrieval,
1794                      enable_pz2_transform,
1795                      enable_record_transform,
1796                      assume_marc8_charset);
1797
1798     Odr_int hits = 0;
1799     Z_Query *query = sr->query;
1800     WRBUF ccl_wrbuf = 0;
1801     WRBUF pqf_wrbuf = 0;
1802     std::string sortkeys;
1803
1804     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1805     {
1806         // RPN
1807         pqf_wrbuf = wrbuf_alloc();
1808         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1809     }
1810     else if (query->which == Z_Query_type_2)
1811     {
1812         // CCL
1813         ccl_wrbuf = wrbuf_alloc();
1814         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1815                     query->u.type_2->len);
1816     }
1817     else if (query->which == Z_Query_type_104 &&
1818              query->u.type_104->which == Z_External_CQL)
1819     {
1820         // CQL
1821         const char *cql = query->u.type_104->u.cql;
1822         CQL_parser cp = cql_parser_create();
1823         int r = cql_parser_string(cp, cql);
1824         package.log("zoom", YLOG_LOG, "CQL: %s", cql);
1825         if (r)
1826         {
1827             cql_parser_destroy(cp);
1828             error = YAZ_BIB1_MALFORMED_QUERY;
1829             const char *addinfo = "CQL syntax error";
1830             log_diagnostic(package, error, addinfo);
1831             apdu_res = 
1832                 odr.create_searchResponse(apdu_req, error, addinfo);
1833             package.response() = apdu_res;
1834             return;
1835         }
1836         struct cql_node *cn = cql_parser_result(cp);
1837         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1838         if (cn_error)
1839         {
1840             // hopefully we are getting a ptr to a index+relation+term node
1841             error = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1842             addinfo = 0;
1843             if (cn_error->which == CQL_NODE_ST)
1844                 addinfo = cn_error->u.st.index;
1845             
1846             log_diagnostic(package, error, addinfo);
1847             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1848             package.response() = apdu_res;
1849             cql_parser_destroy(cp);
1850             return;
1851         }
1852         char ccl_buf[1024];
1853         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1854         if (r)
1855         {
1856             error = YAZ_BIB1_MALFORMED_QUERY;
1857             const char *addinfo = "CQL to CCL conversion error";
1858
1859             log_diagnostic(package, error, addinfo);
1860             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1861             package.response() = apdu_res;
1862             cql_parser_destroy(cp);
1863             return;
1864         }
1865
1866         WRBUF sru_sortkeys_wrbuf = wrbuf_alloc();
1867         if (cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf))
1868         {
1869             error = YAZ_BIB1_ILLEGAL_SORT_RELATION;
1870             const char *addinfo = "CQL to CCL sortby conversion";
1871
1872             log_diagnostic(package, error, addinfo);
1873             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1874             package.response() = apdu_res;
1875             wrbuf_destroy(sru_sortkeys_wrbuf);
1876             cql_parser_destroy(cp);
1877             return;
1878         }
1879         WRBUF sort_spec_wrbuf = wrbuf_alloc();
1880         yaz_srw_sortkeys_to_sort_spec(wrbuf_cstr(sru_sortkeys_wrbuf),
1881                                       sort_spec_wrbuf);
1882         wrbuf_destroy(sru_sortkeys_wrbuf);
1883
1884         ccl_wrbuf = wrbuf_alloc();
1885         wrbuf_puts(ccl_wrbuf, ccl_buf);
1886         
1887         yaz_tok_cfg_t tc = yaz_tok_cfg_create();
1888         yaz_tok_parse_t tp =
1889             yaz_tok_parse_buf(tc, wrbuf_cstr(sort_spec_wrbuf));
1890         yaz_tok_cfg_destroy(tc);
1891         
1892         /* go through sortspec and map fields */
1893         int token = yaz_tok_move(tp);
1894         while (token != YAZ_TOK_EOF)
1895         {
1896             if (token == YAZ_TOK_STRING)
1897             {
1898                 const char *field = yaz_tok_parse_string(tp);
1899                 std::map<std::string,std::string>::iterator it;
1900                 it = b->sptr->sortmap.find(field);
1901                 if (it != b->sptr->sortmap.end())
1902                     sortkeys += it->second;
1903                 else
1904                     sortkeys += field;
1905             }
1906             sortkeys += " ";
1907             token = yaz_tok_move(tp);
1908             if (token == YAZ_TOK_STRING)
1909             {
1910                 sortkeys += yaz_tok_parse_string(tp);
1911             }
1912             if (token != YAZ_TOK_EOF)
1913             {
1914                 sortkeys += " ";
1915                 token = yaz_tok_move(tp);
1916             }
1917         }
1918         yaz_tok_parse_destroy(tp);
1919         wrbuf_destroy(sort_spec_wrbuf);
1920
1921         cql_parser_destroy(cp);
1922     }
1923     else
1924     {
1925         error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
1926         const char *addinfo = 0;
1927         log_diagnostic(package, error, addinfo);
1928         apdu_res =  odr.create_searchResponse(apdu_req, error, addinfo);
1929         package.response() = apdu_res;
1930         return;
1931     }
1932
1933     if (ccl_wrbuf)
1934     {
1935         // CCL to PQF
1936         assert(pqf_wrbuf == 0);
1937         int cerror, cpos;
1938         struct ccl_rpn_node *cn;
1939         package.log("zoom", YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1940         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1941                           &cerror, &cpos);
1942         wrbuf_destroy(ccl_wrbuf);
1943         if (!cn)
1944         {
1945             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1946             error = YAZ_BIB1_MALFORMED_QUERY;
1947
1948             switch (cerror)
1949             {
1950             case CCL_ERR_UNKNOWN_QUAL:
1951             case CCL_ERR_TRUNC_NOT_LEFT: 
1952             case CCL_ERR_TRUNC_NOT_RIGHT:
1953             case CCL_ERR_TRUNC_NOT_BOTH:
1954 #ifdef CCL_ERR_TRUNC_NOT_EMBED
1955             case CCL_ERR_TRUNC_NOT_EMBED:
1956 #endif
1957 #ifdef CCL_ERR_TRUNC_NOT_SINGLE
1958             case CCL_ERR_TRUNC_NOT_SINGLE:
1959 #endif
1960                 error = YAZ_BIB1_UNSUPP_SEARCH;
1961                 break;
1962             }
1963             log_diagnostic(package, error, addinfo);
1964             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1965             package.response() = apdu_res;
1966             return;
1967         }
1968         pqf_wrbuf = wrbuf_alloc();
1969         ccl_pquery(pqf_wrbuf, cn);
1970         package.log("zoom", YLOG_LOG, "RPN: %s", wrbuf_cstr(pqf_wrbuf));
1971         ccl_rpn_delete(cn);
1972     }
1973     
1974     assert(pqf_wrbuf);
1975
1976     ZOOM_query q = ZOOM_query_create();
1977     ZOOM_query_sortby2(q, b->sptr->sortStrategy.c_str(), sortkeys.c_str());
1978
1979     if (b->get_option("sru"))
1980     {
1981         int status = 0;
1982         Z_RPNQuery *zquery;
1983         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1984         WRBUF wrb = wrbuf_alloc();
1985             
1986         if (!strcmp(b->get_option("sru"), "solr"))
1987         {
1988             solr_transform_t cqlt = solr_transform_create();
1989             
1990             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1991             
1992             solr_transform_close(cqlt);
1993         }
1994         else
1995         {
1996             cql_transform_t cqlt = cql_transform_create();
1997             
1998             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1999             
2000             cql_transform_close(cqlt);
2001         }
2002         if (status == 0)
2003         {
2004             ZOOM_query_cql(q, wrbuf_cstr(wrb));
2005             package.log("zoom", YLOG_LOG, "CQL: %s", wrbuf_cstr(wrb));
2006             b->search(q, &hits, &error, &addinfo, odr);
2007         }
2008         ZOOM_query_destroy(q);
2009         
2010         wrbuf_destroy(wrb);
2011         wrbuf_destroy(pqf_wrbuf);
2012         if (status)
2013         {
2014             error = YAZ_BIB1_MALFORMED_QUERY;
2015             const char *addinfo = "can not convert from RPN to CQL/SOLR";
2016             log_diagnostic(package, error, addinfo);
2017             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2018             package.response() = apdu_res;
2019             return;
2020         }
2021     }
2022     else
2023     {
2024         ZOOM_query_prefix(q, wrbuf_cstr(pqf_wrbuf));
2025         package.log("zoom", YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
2026         b->search(q, &hits, &error, &addinfo, odr);
2027         ZOOM_query_destroy(q);
2028         wrbuf_destroy(pqf_wrbuf);
2029     }
2030
2031     if (error && proxy_step)
2032     {
2033         // reset below prevent reuse in get_backend_from_databases
2034         m_backend.reset();
2035         package.log("zoom", YLOG_WARN, "search failed: trying next proxy");
2036         goto next_proxy;
2037     }
2038
2039     const char *element_set_name = 0;
2040     Odr_int number_to_present = 0;
2041     if (!error)
2042         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
2043     
2044     Odr_int number_of_records_returned = 0;
2045     Z_Records *records = get_records(
2046         package,
2047         0, number_to_present, &error, &addinfo,
2048         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
2049         element_set_name);
2050     if (error)
2051         log_diagnostic(package, error, addinfo);
2052     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2053     if (records)
2054     {
2055         apdu_res->u.searchResponse->records = records;
2056         apdu_res->u.searchResponse->numberOfRecordsReturned =
2057             odr_intdup(odr, number_of_records_returned);
2058     }
2059     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
2060     package.response() = apdu_res;
2061 }
2062
2063 void yf::Zoom::Frontend::handle_present(mp::Package &package)
2064 {
2065     Z_GDU *gdu = package.request().get();
2066     Z_APDU *apdu_req = gdu->u.z3950;
2067     Z_APDU *apdu_res = 0;
2068     Z_PresentRequest *pr = apdu_req->u.presentRequest;
2069
2070     mp::odr odr;
2071     if (!m_backend)
2072     {
2073         package.response() = odr.create_presentResponse(
2074             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
2075         return;
2076     }
2077     const char *element_set_name = 0;
2078     Z_RecordComposition *comp = pr->recordComposition;
2079     if (comp && comp->which != Z_RecordComp_simple)
2080     {
2081         package.response() = odr.create_presentResponse(
2082             apdu_req, 
2083             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
2084         return;
2085     }
2086     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
2087         element_set_name = comp->u.simple->u.generic;
2088     Odr_int number_of_records_returned = 0;
2089     int error = 0;
2090     char *addinfo = 0;
2091
2092     if (m_backend->enable_explain)
2093     {
2094         Z_Records *records =
2095             get_explain_records(
2096                 package,
2097                 *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2098                 &error, &addinfo, &number_of_records_returned, odr, m_backend,
2099                 pr->preferredRecordSyntax, element_set_name);
2100         
2101         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2102         if (records)
2103         {
2104             apdu_res->u.presentResponse->records = records;
2105             apdu_res->u.presentResponse->numberOfRecordsReturned =
2106                 odr_intdup(odr, number_of_records_returned);
2107         }
2108         package.response() = apdu_res;
2109     }
2110     else
2111     {
2112         Z_Records *records =
2113             get_records(package,
2114                         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2115                         &error, &addinfo, &number_of_records_returned, odr, m_backend,
2116                         pr->preferredRecordSyntax, element_set_name);
2117         
2118         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2119         if (records)
2120         {
2121             apdu_res->u.presentResponse->records = records;
2122             apdu_res->u.presentResponse->numberOfRecordsReturned =
2123                 odr_intdup(odr, number_of_records_returned);
2124         }
2125         package.response() = apdu_res;
2126     }
2127 }
2128
2129 void yf::Zoom::Frontend::handle_package(mp::Package &package)
2130 {
2131     Z_GDU *gdu = package.request().get();
2132     if (!gdu)
2133         ;
2134     else if (gdu->which == Z_GDU_Z3950)
2135     {
2136         Z_APDU *apdu_req = gdu->u.z3950;
2137
2138         if (m_backend)
2139             wrbuf_rewind(m_backend->m_apdu_wrbuf);
2140         if (apdu_req->which == Z_APDU_initRequest)
2141         {
2142             mp::odr odr;
2143             package.response() = odr.create_close(
2144                 apdu_req,
2145                 Z_Close_protocolError,
2146                 "double init");
2147         }
2148         else if (apdu_req->which == Z_APDU_searchRequest)
2149         {
2150             handle_search(package);
2151         }
2152         else if (apdu_req->which == Z_APDU_presentRequest)
2153         {
2154             handle_present(package);
2155         }
2156         else
2157         {
2158             mp::odr odr;
2159             package.response() = odr.create_close(
2160                 apdu_req,
2161                 Z_Close_protocolError,
2162                 "zoom filter cannot handle this APDU");
2163             package.session().close();
2164         }
2165         if (m_backend)
2166         {
2167             WRBUF w = m_backend->m_apdu_wrbuf;
2168             package.log_write(wrbuf_buf(w), wrbuf_len(w));
2169         }
2170     }
2171     else
2172     {
2173         package.session().close();
2174     }
2175 }
2176
2177 void yf::Zoom::Impl::process(mp::Package &package)
2178 {
2179     FrontendPtr f = get_frontend(package);
2180     Z_GDU *gdu = package.request().get();
2181
2182     if (f->m_is_virtual)
2183     {
2184         f->handle_package(package);
2185     }
2186     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
2187              Z_APDU_initRequest)
2188     {
2189         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
2190         f->m_init_gdu = gdu;
2191         
2192         mp::odr odr;
2193         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
2194         Z_InitResponse *resp = apdu->u.initResponse;
2195         
2196         int i;
2197         static const int masks[] = {
2198             Z_Options_search,
2199             Z_Options_present,
2200             -1 
2201         };
2202         for (i = 0; masks[i] != -1; i++)
2203             if (ODR_MASK_GET(req->options, masks[i]))
2204                 ODR_MASK_SET(resp->options, masks[i]);
2205         
2206         static const int versions[] = {
2207             Z_ProtocolVersion_1,
2208             Z_ProtocolVersion_2,
2209             Z_ProtocolVersion_3,
2210             -1
2211         };
2212         for (i = 0; versions[i] != -1; i++)
2213             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
2214                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
2215             else
2216                 break;
2217         
2218         *resp->preferredMessageSize = *req->preferredMessageSize;
2219         *resp->maximumRecordSize = *req->maximumRecordSize;
2220         
2221         package.response() = apdu;
2222         f->m_is_virtual = true;
2223     }
2224     else
2225         package.move();
2226
2227     release_frontend(package);
2228 }
2229
2230
2231 static mp::filter::Base* filter_creator()
2232 {
2233     return new mp::filter::Zoom;
2234 }
2235
2236 extern "C" {
2237     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
2238         0,
2239         "zoom",
2240         filter_creator
2241     };
2242 }
2243
2244
2245 /*
2246  * Local variables:
2247  * c-basic-offset: 4
2248  * c-file-style: "Stroustrup"
2249  * indent-tabs-mode: nil
2250  * End:
2251  * vim: shiftwidth=4 tabstop=8 expandtab
2252  */
2253