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