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