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