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