zoom: allow Torus record wrapped in single "record" elem
[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 && ptr->type == XML_ELEMENT_NODE)
1168         {
1169             if (!strcmp((const char *) ptr->name, "record"))
1170             {
1171                 sptr = m_p->parse_torus_record(ptr);
1172             }
1173             else if (!strcmp((const char *) ptr->name, "records"))
1174             {
1175                 for (ptr = ptr->children; ptr; ptr = ptr->next)
1176                 {
1177                     if (ptr->type == XML_ELEMENT_NODE
1178                         && !strcmp((const char *) ptr->name, "record"))
1179                     {
1180                         if (sptr)
1181                         {
1182                             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1183                             *addinfo = (char*)
1184                                 odr_malloc(odr, 40 + torus_db.length());
1185                             sprintf(*addinfo, "multiple records for udb=%s",
1186                                     database.c_str());
1187                             xmlFreeDoc(doc);
1188                             BackendPtr b;
1189                             return b;
1190                         }
1191                         sptr = m_p->parse_torus_record(ptr);
1192                     }
1193                 }
1194             }
1195             else
1196             {
1197                 *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1198                 *addinfo = (char*) odr_malloc(
1199                     odr, 40 + strlen((const char *) ptr->name));
1200                 sprintf(*addinfo, "bad root element for torus: %s", ptr->name);
1201                 xmlFreeDoc(doc);
1202                 BackendPtr b;
1203                 return b;
1204             }
1205         }
1206         xmlFreeDoc(doc);
1207     }
1208
1209     if (!sptr)
1210     {
1211         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1212         *addinfo = odr_strdup(odr, torus_db.c_str());
1213         BackendPtr b;
1214         return b;
1215     }
1216         
1217     xsltStylesheetPtr xsp = 0;
1218     if (sptr->transform_xsl_content.length())
1219     {
1220         xmlDoc *xsp_doc = xmlParseMemory(sptr->transform_xsl_content.c_str(),
1221                                          sptr->transform_xsl_content.length());
1222         if (!xsp_doc)
1223         {
1224             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1225             *addinfo = (char *) odr_malloc(odr, 40);
1226             sprintf(*addinfo, "xmlParseMemory failed");
1227             BackendPtr b;
1228             return b;
1229         }
1230         xsp = xsltParseStylesheetDoc(xsp_doc);
1231         if (!xsp)
1232         {
1233             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1234             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
1235             BackendPtr b;
1236             xmlFreeDoc(xsp_doc);
1237             return b;
1238         }
1239     }
1240     else if (sptr->transform_xsl_fname.length())
1241     {
1242         const char *path = 0;
1243
1244         if (m_p->xsldir.length())
1245             path = m_p->xsldir.c_str();
1246         else
1247             path = m_p->file_path.c_str();
1248         std::string fname;
1249
1250         char fullpath[1024];
1251         char *cp = yaz_filepath_resolve(sptr->transform_xsl_fname.c_str(),
1252                                         path, 0, fullpath);
1253         if (cp)
1254             fname.assign(cp);
1255         else
1256         {
1257             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1258             *addinfo = (char *)
1259                 odr_malloc(odr, 40 + sptr->transform_xsl_fname.length());
1260             sprintf(*addinfo, "File could not be read: %s", 
1261                     sptr->transform_xsl_fname.c_str());
1262             BackendPtr b;
1263             return b;
1264         }
1265         xmlDoc *xsp_doc = xmlParseFile(fname.c_str());
1266         if (!xsp_doc)
1267         {
1268             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1269             *addinfo = (char *) odr_malloc(odr, 40 + fname.length());
1270             sprintf(*addinfo, "xmlParseFile failed. File: %s", fname.c_str());
1271             BackendPtr b;
1272             return b;
1273         }
1274         xsp = xsltParseStylesheetDoc(xsp_doc);
1275         if (!xsp)
1276         {
1277             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1278             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
1279             BackendPtr b;
1280             xmlFreeDoc(xsp_doc);
1281             return b;
1282         }
1283     }
1284
1285     cql_transform_t cqlt = 0;
1286     if (sptr->rpn2cql_fname.length())
1287     {
1288         char fullpath[1024];
1289         char *cp = yaz_filepath_resolve(sptr->rpn2cql_fname.c_str(),
1290                                         m_p->file_path.c_str(), 0, fullpath);
1291         if (cp)
1292             cqlt = cql_transform_open_fname(fullpath);
1293     }
1294     else
1295         cqlt = cql_transform_create();
1296
1297     if (!cqlt)
1298     {
1299         *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1300         *addinfo = odr_strdup(odr, "Missing/invalid cql2rpn file");
1301         BackendPtr b;
1302         xsltFreeStylesheet(xsp);
1303         return b;
1304     }
1305
1306     m_backend.reset();
1307
1308     BackendPtr b(new Backend);
1309
1310     b->cqlt = cqlt;
1311     b->sptr = sptr;
1312     b->xsp = xsp;
1313     b->m_frontend_database = database;
1314     b->enable_cproxy = param_nocproxy ? false : true;
1315
1316     if (sptr->query_encoding.length())
1317         b->set_option("rpnCharset", sptr->query_encoding);
1318
1319     b->set_option("timeout", m_p->zoom_timeout.c_str());
1320     
1321     if (m_p->apdu_log) 
1322         b->set_option("apdulog", "1");
1323
1324     if (sptr->piggyback && sptr->sru.length())
1325         b->set_option("count", "1"); /* some SRU servers INSIST on getting
1326                                         maximumRecords > 0 */
1327     b->set_option("piggyback", sptr->piggyback ? "1" : "0");
1328
1329     if (authentication.length() == 0)
1330         authentication = sptr->authentication;
1331
1332     if (proxy.length() == 0)
1333         proxy = sptr->cfProxy;
1334     b->m_proxy = proxy;
1335     
1336     if (sptr->cfAuth.length())
1337     {
1338         // A CF target
1339         b->set_option("user", sptr->cfAuth);
1340         if (authentication.length())
1341         {
1342             size_t found = authentication.find('/');
1343             if (found != std::string::npos)
1344             {
1345                 out_names[no_out_args] = "user";
1346                 out_values[no_out_args++] =
1347                     odr_strdup(odr, authentication.substr(0, found).c_str());
1348
1349                 out_names[no_out_args] = "password";
1350                 out_values[no_out_args++] =
1351                     odr_strdup(odr, authentication.substr(found+1).c_str());
1352             }
1353             else
1354             {
1355                 out_names[no_out_args] = "user";
1356                 out_values[no_out_args++] =
1357                     odr_strdup(odr, authentication.c_str());
1358             }                
1359         }
1360         if (proxy.length())
1361         {
1362             out_names[no_out_args] = "proxy";
1363             out_values[no_out_args++] = odr_strdup(odr, proxy.c_str());
1364         }
1365         if (sptr->cfSubDB.length())
1366         {
1367             out_names[no_out_args] = "subdatabase";
1368             out_values[no_out_args++] = odr_strdup(odr, sptr->cfSubDB.c_str());
1369         }
1370         if (param_nocproxy)
1371         {
1372             out_names[no_out_args] = "nocproxy";
1373             out_values[no_out_args++] = odr_strdup(odr, param_nocproxy);
1374         }
1375     }
1376     else
1377     {
1378         size_t found = authentication.find('/');
1379         
1380         if (sptr->sru.length() && found != std::string::npos)
1381         {
1382             b->set_option("user", authentication.substr(0, found));
1383             b->set_option("password", authentication.substr(found+1));
1384         }
1385         else
1386             b->set_option("user", authentication);
1387
1388         if (proxy.length())
1389             b->set_option("proxy", proxy);
1390     }
1391     std::string url;
1392     if (sptr->sru.length())
1393     {
1394         url = "http://" + sptr->target;
1395         b->set_option("sru", sptr->sru);
1396
1397         if (sptr->sru_version.length())
1398             b->set_option("sru_version", sptr->sru_version);
1399     }
1400     else
1401     {
1402         url = sptr->target;
1403     }
1404     if (no_out_args)
1405     {
1406         char *x_args = 0;
1407         out_names[no_out_args] = 0; // terminate list
1408         
1409         yaz_array_to_uri(&x_args, odr, (char **) out_names,
1410                          (char **) out_values);
1411         url += "," + std::string(x_args);
1412     }
1413     package.log("zoom", YLOG_LOG, "url: %s", url.c_str());
1414     b->connect(url, error, addinfo, odr);
1415     if (*error == 0 && b->enable_cproxy)
1416         create_content_session(package, b, error, addinfo, odr,
1417                                content_authentication.length() ?
1418                                content_authentication : authentication,
1419                                content_proxy.length() ? content_proxy : proxy,
1420                                realm);
1421     if (*error == 0)
1422         m_backend = b;
1423     return b;
1424 }
1425
1426 void yf::Zoom::Frontend::prepare_elements(BackendPtr b,
1427                                           Odr_oid *preferredRecordSyntax,
1428                                           const char *element_set_name,
1429                                           bool &enable_pz2_retrieval,
1430                                           bool &enable_pz2_transform,
1431                                           bool &enable_record_transform,
1432                                           bool &assume_marc8_charset)
1433 {
1434     char oid_name_str[OID_STR_MAX];
1435     const char *syntax_name = 0;
1436     
1437     if (preferredRecordSyntax &&
1438         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml))
1439     {
1440         if (element_set_name &&
1441             !strcmp(element_set_name, m_p->element_transform.c_str()))
1442         {
1443             enable_pz2_retrieval = true;
1444             enable_pz2_transform = true;
1445         }
1446         else if (element_set_name && 
1447                  !strcmp(element_set_name, m_p->element_raw.c_str()))
1448         {
1449             enable_pz2_retrieval = true;
1450         }
1451         else if (m_p->record_xsp)
1452         {
1453             enable_pz2_retrieval = true;
1454             enable_pz2_transform = true;
1455             enable_record_transform = true;
1456         }
1457     }
1458     
1459     if (enable_pz2_retrieval)
1460     {
1461         std::string configured_request_syntax = b->sptr->request_syntax;
1462         if (configured_request_syntax.length())
1463         {
1464             syntax_name = configured_request_syntax.c_str();
1465             const Odr_oid *syntax_oid = 
1466                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
1467             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
1468                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
1469                 assume_marc8_charset = true;
1470         }
1471     }
1472     else if (preferredRecordSyntax)
1473         syntax_name =
1474             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
1475
1476     if (b->sptr->sru.length())
1477         syntax_name = "XML";
1478
1479     b->set_option("preferredRecordSyntax", syntax_name);
1480
1481     if (enable_pz2_retrieval)
1482     {
1483         element_set_name = 0;
1484         if (b->sptr->element_set.length())
1485             element_set_name = b->sptr->element_set.c_str();
1486     }
1487
1488     b->set_option("elementSetName", element_set_name);
1489     if (b->sptr->sru.length() && element_set_name)
1490         b->set_option("schema", element_set_name);
1491 }
1492
1493 Z_Records *yf::Zoom::Frontend::get_explain_records(
1494     mp::Package &package,
1495     Odr_int start,
1496     Odr_int number_to_present,
1497     int *error,
1498     char **addinfo,
1499     Odr_int *number_of_records_returned,
1500     ODR odr,
1501     BackendPtr b,
1502     Odr_oid *preferredRecordSyntax,
1503     const char *element_set_name)
1504 {
1505     Odr_int i;
1506     Z_Records *records = 0;
1507
1508     if (!b->explain_doc)
1509     {
1510         return records;
1511     }
1512     if (number_to_present > 10000)
1513         number_to_present = 10000;
1514
1515     xmlNode *ptr = xmlDocGetRootElement(b->explain_doc);
1516     
1517     Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1518         odr_malloc(odr, sizeof(*npl));
1519     npl->records = (Z_NamePlusRecord **)
1520         odr_malloc(odr, number_to_present * sizeof(*npl->records));
1521     
1522     for (i = 0; i < number_to_present; i++)
1523     {
1524         int num = 0;
1525         xmlNode *res = xml_node_search(ptr, &num, start + i + 1);
1526         if (!res)
1527             break;
1528         xmlBufferPtr xml_buf = xmlBufferCreate();
1529         xmlNode *tmp_node = xmlCopyNode(res->children, 1);
1530         xmlNodeDump(xml_buf, tmp_node->doc, tmp_node, 0, 0);
1531
1532         Z_NamePlusRecord *npr =
1533             (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1534         npr->databaseName = odr_strdup(odr, b->m_frontend_database.c_str());
1535         npr->which = Z_NamePlusRecord_databaseRecord;
1536         npr->u.databaseRecord =
1537             z_ext_record_xml(odr,
1538                              (const char *) xml_buf->content, xml_buf->use);
1539         npl->records[i] = npr;
1540         xmlFreeNode(tmp_node);
1541         xmlBufferFree(xml_buf);
1542     }
1543     records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1544     records->which = Z_Records_DBOSD;
1545     records->u.databaseOrSurDiagnostics = npl;
1546
1547     npl->num_records = i;
1548     *number_of_records_returned = i;
1549     return records;
1550 }
1551
1552
1553 Z_Records *yf::Zoom::Frontend::get_records(mp::Package &package,
1554                                            Odr_int start,
1555                                            Odr_int number_to_present,
1556                                            int *error,
1557                                            char **addinfo,
1558                                            Odr_int *number_of_records_returned,
1559                                            ODR odr,
1560                                            BackendPtr b,
1561                                            Odr_oid *preferredRecordSyntax,
1562                                            const char *element_set_name)
1563 {
1564     *number_of_records_returned = 0;
1565     Z_Records *records = 0;
1566     bool enable_pz2_retrieval = false; // whether target profile is used
1567     bool enable_pz2_transform = false; // whether XSLT is used as well
1568     bool assume_marc8_charset = false;
1569     bool enable_record_transform = false;
1570
1571     prepare_elements(b, preferredRecordSyntax,
1572                      element_set_name,
1573                      enable_pz2_retrieval,
1574                      enable_pz2_transform,
1575                      enable_record_transform,
1576                      assume_marc8_charset);
1577
1578     package.log("zoom", YLOG_LOG, "pz2_retrieval: %s . pz2_transform: %s",
1579                 enable_pz2_retrieval ? "yes" : "no",
1580                 enable_pz2_transform ? "yes" : "no");
1581
1582     if (start < 0 || number_to_present <=0)
1583         return records;
1584     
1585     if (number_to_present > 10000)
1586         number_to_present = 10000;
1587
1588     ZOOM_record *recs = (ZOOM_record *)
1589         odr_malloc(odr, (size_t) number_to_present * sizeof(*recs));
1590
1591     b->present(start, number_to_present, recs, error, addinfo, odr);
1592
1593     int i = 0;
1594     if (!*error)
1595     {
1596         for (i = 0; i < number_to_present; i++)
1597             if (!recs[i])
1598                 break;
1599     }
1600     if (i > 0)
1601     {  // only return records if no error and at least one record
1602
1603         const char *xsl_parms[3];
1604         mp::wrbuf cproxy_host;
1605         
1606         if (b->enable_cproxy && b->cproxy_host.length())
1607         {
1608             wrbuf_puts(cproxy_host, "\"");
1609             wrbuf_puts(cproxy_host, b->cproxy_host.c_str());
1610             wrbuf_puts(cproxy_host, "/\"");
1611
1612             xsl_parms[0] = "cproxyhost";
1613             xsl_parms[1] = wrbuf_cstr(cproxy_host);
1614             xsl_parms[2] = 0;
1615         }
1616         else
1617         {
1618             xsl_parms[0] = 0;
1619         }
1620
1621         char *odr_database = odr_strdup(odr,
1622                                         b->m_frontend_database.c_str());
1623         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1624             odr_malloc(odr, sizeof(*npl));
1625         *number_of_records_returned = i;
1626         npl->num_records = i;
1627         npl->records = (Z_NamePlusRecord **)
1628             odr_malloc(odr, i * sizeof(*npl->records));
1629         for (i = 0; i < number_to_present; i++)
1630         {
1631             Z_NamePlusRecord *npr = 0;
1632             const char *addinfo;
1633
1634             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1635                                               &addinfo, 0 /* diagset */);
1636                 
1637             if (sur_error)
1638             {
1639                 log_diagnostic(package, sur_error, addinfo);
1640                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1641                                             addinfo);
1642             }
1643             else if (enable_pz2_retrieval)
1644             {
1645                 char rec_type_str[100];
1646                 const char *record_encoding = 0;
1647
1648                 if (b->sptr->record_encoding.length())
1649                     record_encoding = b->sptr->record_encoding.c_str();
1650                 else if (assume_marc8_charset)
1651                     record_encoding = "marc8";
1652
1653                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1654                 if (record_encoding)
1655                 {
1656                     strcat(rec_type_str, "; charset=");
1657                     strcat(rec_type_str, record_encoding);
1658                 }
1659
1660                 package.log("zoom", YLOG_LOG, "Getting record of type %s",
1661                             rec_type_str);
1662                 int rec_len;
1663                 xmlChar *xmlrec_buf = 0;
1664                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1665                                                       &rec_len);
1666                 if (!rec_buf && !npr)
1667                 {
1668                     std::string addinfo("ZOOM_record_get failed for type ");
1669
1670                     int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1671                     addinfo += rec_type_str;
1672                     log_diagnostic(package, error, addinfo.c_str());
1673                     npr = zget_surrogateDiagRec(odr, odr_database,
1674                                                 error, addinfo.c_str());
1675                 }
1676                 else
1677                 {
1678                     package.log_write(rec_buf, rec_len);
1679                     package.log_write("\r\n", 2);
1680                 }
1681
1682                 if (rec_buf && b->xsp && enable_pz2_transform)
1683                 {
1684                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1685                     if (!rec_doc)
1686                     {
1687                         const char *addinfo = "xml parse failed for record";
1688                         int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1689                         log_diagnostic(package, error, addinfo);
1690                         npr = zget_surrogateDiagRec(
1691                             odr, odr_database, error, addinfo);
1692                     }
1693                     else
1694                     { 
1695                         // first stage XSLT - per target
1696                         xsltStylesheetPtr xsp = b->xsp;
1697                         xmlDoc *rec_res = xsltApplyStylesheet(xsp, rec_doc,
1698                                                               xsl_parms);
1699                         // insert generated-url
1700                         if (rec_res)
1701                         {
1702                             std::string res = 
1703                                 mp::xml::url_recipe_handle(rec_res,
1704                                                            b->sptr->urlRecipe);
1705                             if (res.length())
1706                             {
1707                                 xmlNode *ptr = xmlDocGetRootElement(rec_res);
1708                                 while (ptr && ptr->type != XML_ELEMENT_NODE)
1709                                     ptr = ptr->next;
1710                                 xmlNode *c = 
1711                                     xmlNewChild(ptr, 0, BAD_CAST "metadata", 0);
1712                                 xmlNewProp(c, BAD_CAST "type", BAD_CAST
1713                                            "generated-url");
1714                                 xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1715                                 xmlAddChild(c, t);
1716                             }
1717                         }
1718                         // second stage XSLT - common
1719                         if (rec_res && m_p->record_xsp &&
1720                             enable_record_transform)
1721                         {
1722                             xmlDoc *tmp_doc = rec_res;
1723
1724                             xsp = m_p->record_xsp;
1725                             rec_res = xsltApplyStylesheet(xsp, tmp_doc,
1726                                                           xsl_parms);
1727                             xmlFreeDoc(tmp_doc);
1728                         }
1729                         // get result out of it
1730                         if (rec_res)
1731                         {
1732                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1733                                                    rec_res, xsp);
1734                             rec_buf = (const char *) xmlrec_buf;
1735                             package.log_write(rec_buf, rec_len);
1736
1737                             xmlFreeDoc(rec_res);
1738                         }
1739                         if (!rec_buf)
1740                         {
1741                             std::string addinfo;
1742                             int error =
1743                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1744
1745                             addinfo = "xslt apply failed for "
1746                                 + b->sptr->transform_xsl_fname;
1747                             log_diagnostic(package, error, addinfo.c_str());
1748                             npr = zget_surrogateDiagRec(
1749                                 odr, odr_database, error, addinfo.c_str());
1750                         }
1751                         xmlFreeDoc(rec_doc);
1752                     }
1753                 }
1754
1755                 if (!npr)
1756                 {
1757                     if (!rec_buf)
1758                         npr = zget_surrogateDiagRec(
1759                             odr, odr_database, 
1760                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1761                             rec_type_str);
1762                     else
1763                     {
1764                         npr = (Z_NamePlusRecord *)
1765                             odr_malloc(odr, sizeof(*npr));
1766                         npr->databaseName = odr_database;
1767                         npr->which = Z_NamePlusRecord_databaseRecord;
1768                         npr->u.databaseRecord =
1769                             z_ext_record_xml(odr, rec_buf, rec_len);
1770                     }
1771                 }
1772                 if (xmlrec_buf)
1773                     xmlFree(xmlrec_buf);
1774             }
1775             else
1776             {
1777                 Z_External *ext =
1778                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1779                 if (ext)
1780                 {
1781                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1782                     npr->databaseName = odr_database;
1783                     npr->which = Z_NamePlusRecord_databaseRecord;
1784                     npr->u.databaseRecord = ext;
1785                 }
1786                 else
1787                 {
1788                     npr = zget_surrogateDiagRec(
1789                         odr, odr_database, 
1790                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1791                         "ZOOM_record, type ext");
1792                 }
1793             }
1794             npl->records[i] = npr;
1795         }
1796         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1797         records->which = Z_Records_DBOSD;
1798         records->u.databaseOrSurDiagnostics = npl;
1799     }
1800     return records;
1801 }
1802
1803 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1804                                                     ODR odr)
1805 {
1806     struct cql_node *r = 0;
1807     if (!cn)
1808         return 0;
1809     switch (cn->which)
1810     {
1811     case CQL_NODE_ST:
1812         if (cn->u.st.index)
1813         {
1814             std::map<std::string,std::string>::const_iterator it;
1815             it = fieldmap.find(cn->u.st.index);
1816             if (it == fieldmap.end())
1817                 return cn;
1818             if (it->second.length())
1819                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1820             else
1821                 cn->u.st.index = 0;
1822         }
1823         break;
1824     case CQL_NODE_BOOL:
1825         r = convert_cql_fields(cn->u.boolean.left, odr);
1826         if (!r)
1827             r = convert_cql_fields(cn->u.boolean.right, odr);
1828         break;
1829     case CQL_NODE_SORT:
1830         r = convert_cql_fields(cn->u.sort.search, odr);
1831         break;
1832     }
1833     return r;
1834 }
1835
1836 void yf::Zoom::Frontend::log_diagnostic(mp::Package &package,
1837                                         int error, const char *addinfo)
1838 {
1839     const char *err_msg = yaz_diag_bib1_str(error);
1840     if (addinfo)
1841         package.log("zoom", YLOG_WARN, "Diagnostic %d %s: %s",
1842                     error, err_msg, addinfo);
1843     else
1844         package.log("zoom", YLOG_WARN, "Diagnostic %d %s:",
1845                     error, err_msg);
1846 }
1847
1848 yf::Zoom::BackendPtr yf::Zoom::Frontend::explain_search(mp::Package &package,
1849                                                         std::string &database,
1850                                                         int *error,
1851                                                         char **addinfo,
1852                                                         mp::odr &odr,
1853                                                         std::string torus_url,
1854                                                         std::string &torus_db,
1855                                                         std::string &realm)
1856 {
1857     m_backend.reset();
1858
1859     BackendPtr b(new Backend);
1860
1861     b->m_frontend_database = database;
1862     b->enable_explain = true;
1863    
1864     Z_GDU *gdu = package.request().get();
1865     Z_APDU *apdu_req = gdu->u.z3950;
1866     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1867     Z_Query *query = sr->query;
1868
1869     if (!m_p->explain_xsp)
1870     {
1871         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1872         *addinfo =
1873             odr_strdup(odr, "IR-Explain---1 unsupported. "
1874                        "Torus explain_xsl not defined");
1875         return m_backend;
1876     }
1877     else if (query->which == Z_Query_type_104 &&
1878         query->u.type_104->which == Z_External_CQL)
1879     {
1880         std::string torus_query(query->u.type_104->u.cql);
1881         xmlDoc *doc = mp::get_searchable(package, torus_url, "",
1882                                          torus_query,
1883                                          realm, m_p->proxy);
1884         if (m_p->explain_xsp)
1885         {
1886             xmlDoc *rec_res =  xsltApplyStylesheet(m_p->explain_xsp, doc, 0);
1887
1888             xmlFreeDoc(doc);
1889             doc = rec_res;
1890         }
1891         if (!doc)
1892         {
1893             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1894             *addinfo = odr_strdup(odr, "Torus server unavailable or "
1895                                   "incorrectly configured");
1896         }
1897         else
1898         {
1899             xmlNode *ptr = xmlDocGetRootElement(doc);
1900             int hits = 0;
1901             
1902             xml_node_search(ptr, &hits, 0);
1903
1904             Z_APDU *apdu_res = odr.create_searchResponse(apdu_req, 0, 0);
1905             apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1906             package.response() = apdu_res;
1907             m_backend = b;
1908         }
1909         if (b->explain_doc)
1910             xmlFreeDoc(b->explain_doc);
1911         b->explain_doc = doc;
1912         return m_backend;
1913     }
1914     else
1915     {
1916         *error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
1917         *addinfo = odr_strdup(odr, "IR-Explain---1 only supports CQL");
1918         return m_backend;
1919     }
1920 }
1921
1922 static bool wait_conn(COMSTACK cs, int secs)
1923 {
1924     struct yaz_poll_fd pfd;
1925
1926     yaz_poll_add(pfd.input_mask, yaz_poll_except);
1927     if (cs->io_pending && CS_WANT_WRITE)
1928         yaz_poll_add(pfd.input_mask, yaz_poll_write);
1929     if (cs->io_pending & CS_WANT_READ)
1930         yaz_poll_add(pfd.input_mask, yaz_poll_read);
1931
1932     pfd.fd = cs_fileno(cs);
1933     pfd.client_data = 0;
1934     
1935     int ret = yaz_poll(&pfd, 1, secs, 0);
1936     return ret > 0;
1937 }
1938
1939 bool yf::Zoom::Impl::check_proxy(const char *proxy)
1940 {
1941     COMSTACK conn = 0;
1942     const char *uri = "http://localhost/";
1943     void *add;
1944     mp::odr odr;
1945     bool outcome = false;
1946     conn = cs_create_host_proxy(uri, 0, &add, proxy);
1947
1948     if (!conn)
1949         return false;
1950
1951     Z_GDU *gdu = z_get_HTTP_Request_uri(odr, uri, 0, 1);
1952     gdu->u.HTTP_Request->method = odr_strdup(odr, "GET");
1953     
1954     if (z_GDU(odr, &gdu, 0, 0))
1955     {
1956         int len;
1957         char *buf = odr_getbuf(odr, &len, 0);
1958         
1959         int ret = cs_connect(conn, add);
1960         if (ret > 0 || (ret == 0 && wait_conn(conn, 1)))
1961         {
1962             while (1)
1963             {
1964                 ret = cs_put(conn, buf, len);
1965                 if (ret != 1)
1966                     break;
1967                 if (!wait_conn(conn, proxy_timeout))
1968                     break;
1969             }
1970             if (ret == 0)
1971                 outcome = true;
1972         }
1973     }
1974     cs_close(conn);
1975     return outcome;
1976 }
1977
1978 bool yf::Zoom::Frontend::retry(mp::Package &package,
1979                                mp::odr &odr,
1980                                BackendPtr b, 
1981                                int &error, char **addinfo,
1982                                int &proxy_step, int &same_retries,
1983                                int &proxy_retries)
1984 {
1985     if (b && b->m_proxy.length() && !m_p->check_proxy(b->m_proxy.c_str()))
1986     {
1987         log_diagnostic(package, error, *addinfo);
1988         package.log("zoom", YLOG_LOG, "proxy %s fails", b->m_proxy.c_str());
1989         m_backend.reset();
1990         if (proxy_step) // there is a failover
1991         {
1992             proxy_retries++;
1993             package.log("zoom", YLOG_WARN, "search failed: trying next proxy");
1994             return true;
1995         }
1996         error = YAZ_BIB1_PROXY_FAILURE;
1997         *addinfo = odr_strdup(odr, b->m_proxy.c_str());
1998     }
1999     else if (same_retries == 0 && proxy_retries == 0)
2000     {
2001         log_diagnostic(package, error, *addinfo);
2002         same_retries++;
2003         package.log("zoom", YLOG_WARN, "search failed: retry");
2004         m_backend.reset();
2005         proxy_step = 0;
2006         return true;
2007     }
2008     return false;
2009 }
2010
2011 void yf::Zoom::Frontend::handle_search(mp::Package &package)
2012 {
2013     Z_GDU *gdu = package.request().get();
2014     Z_APDU *apdu_req = gdu->u.z3950;
2015     Z_APDU *apdu_res = 0;
2016     mp::odr odr;
2017     Z_SearchRequest *sr = apdu_req->u.searchRequest;
2018     if (sr->num_databaseNames != 1)
2019     {
2020         int error = YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED;
2021         log_diagnostic(package, error, 0);
2022         apdu_res = odr.create_searchResponse(apdu_req, error, 0);
2023         package.response() = apdu_res;
2024         return;
2025     }
2026     int proxy_step = 0;
2027     int same_retries = 0;
2028     int proxy_retries = 0;
2029
2030 next_proxy:
2031
2032     int error = 0;
2033     char *addinfo = 0;
2034     std::string db(sr->databaseNames[0]);
2035
2036     BackendPtr b = get_backend_from_databases(package, db, &error,
2037                                               &addinfo, odr, &proxy_step);
2038     if (error)
2039     {
2040         if (retry(package, odr, b, error, &addinfo, proxy_step,
2041                   same_retries, proxy_retries))
2042             goto next_proxy;
2043     }
2044     if (error)
2045     {
2046         log_diagnostic(package, error, addinfo);
2047         apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2048         package.response() = apdu_res;
2049         return;
2050     }
2051     if (!b || b->enable_explain)
2052         return;
2053
2054     b->set_option("setname", "default");
2055
2056     bool enable_pz2_retrieval = false;
2057     bool enable_pz2_transform = false;
2058     bool enable_record_transform = false;
2059     bool assume_marc8_charset = false;
2060     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
2061                      enable_pz2_retrieval,
2062                      enable_pz2_transform,
2063                      enable_record_transform,
2064                      assume_marc8_charset);
2065
2066     Odr_int hits = 0;
2067     Z_Query *query = sr->query;
2068     mp::wrbuf ccl_wrbuf;
2069     mp::wrbuf pqf_wrbuf;
2070     std::string sortkeys;
2071
2072     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
2073     {
2074         // RPN
2075         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
2076     }
2077     else if (query->which == Z_Query_type_2)
2078     {
2079         // CCL
2080         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
2081                     query->u.type_2->len);
2082     }
2083     else if (query->which == Z_Query_type_104 &&
2084              query->u.type_104->which == Z_External_CQL)
2085     {
2086         // CQL
2087         const char *cql = query->u.type_104->u.cql;
2088         CQL_parser cp = cql_parser_create();
2089         int r = cql_parser_string(cp, cql);
2090         package.log("zoom", YLOG_LOG, "CQL: %s", cql);
2091         if (r)
2092         {
2093             cql_parser_destroy(cp);
2094             error = YAZ_BIB1_MALFORMED_QUERY;
2095             const char *addinfo = "CQL syntax error";
2096             log_diagnostic(package, error, addinfo);
2097             apdu_res = 
2098                 odr.create_searchResponse(apdu_req, error, addinfo);
2099             package.response() = apdu_res;
2100             return;
2101         }
2102         struct cql_node *cn = cql_parser_result(cp);
2103         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
2104         if (cn_error)
2105         {
2106             // hopefully we are getting a ptr to a index+relation+term node
2107             error = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
2108             addinfo = 0;
2109             if (cn_error->which == CQL_NODE_ST)
2110                 addinfo = cn_error->u.st.index;
2111             
2112             log_diagnostic(package, error, addinfo);
2113             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2114             package.response() = apdu_res;
2115             cql_parser_destroy(cp);
2116             return;
2117         }
2118         r = cql_to_ccl(cn, wrbuf_vp_puts,  ccl_wrbuf);
2119         if (r)
2120         {
2121             error = YAZ_BIB1_MALFORMED_QUERY;
2122             const char *addinfo = "CQL to CCL conversion error";
2123
2124             log_diagnostic(package, error, addinfo);
2125             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2126             package.response() = apdu_res;
2127             cql_parser_destroy(cp);
2128             return;
2129         }
2130
2131         mp::wrbuf sru_sortkeys_wrbuf;
2132         if (cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf))
2133         {
2134             error = YAZ_BIB1_ILLEGAL_SORT_RELATION;
2135             const char *addinfo = "CQL to CCL sortby conversion";
2136
2137             log_diagnostic(package, error, addinfo);
2138             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2139             package.response() = apdu_res;
2140             cql_parser_destroy(cp);
2141             return;
2142         }
2143         mp::wrbuf sort_spec_wrbuf;
2144         yaz_srw_sortkeys_to_sort_spec(wrbuf_cstr(sru_sortkeys_wrbuf),
2145                                       sort_spec_wrbuf);
2146         yaz_tok_cfg_t tc = yaz_tok_cfg_create();
2147         yaz_tok_parse_t tp =
2148             yaz_tok_parse_buf(tc, wrbuf_cstr(sort_spec_wrbuf));
2149         yaz_tok_cfg_destroy(tc);
2150         
2151         /* go through sortspec and map fields */
2152         int token = yaz_tok_move(tp);
2153         while (token != YAZ_TOK_EOF)
2154         {
2155             if (token == YAZ_TOK_STRING)
2156             {
2157                 const char *field = yaz_tok_parse_string(tp);
2158                 std::map<std::string,std::string>::iterator it;
2159                 it = b->sptr->sortmap.find(field);
2160                 if (it != b->sptr->sortmap.end())
2161                     sortkeys += it->second;
2162                 else
2163                     sortkeys += field;
2164             }
2165             sortkeys += " ";
2166             token = yaz_tok_move(tp);
2167             if (token == YAZ_TOK_STRING)
2168             {
2169                 sortkeys += yaz_tok_parse_string(tp);
2170             }
2171             if (token != YAZ_TOK_EOF)
2172             {
2173                 sortkeys += " ";
2174                 token = yaz_tok_move(tp);
2175             }
2176         }
2177         yaz_tok_parse_destroy(tp);
2178         cql_parser_destroy(cp);
2179     }
2180     else
2181     {
2182         error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
2183         const char *addinfo = 0;
2184         log_diagnostic(package, error, addinfo);
2185         apdu_res =  odr.create_searchResponse(apdu_req, error, addinfo);
2186         package.response() = apdu_res;
2187         return;
2188     }
2189
2190     if (ccl_wrbuf.len())
2191     {
2192         // CCL to PQF
2193         assert(pqf_wrbuf.len() == 0);
2194         int cerror, cpos;
2195         struct ccl_rpn_node *cn;
2196         package.log("zoom", YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
2197         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
2198                           &cerror, &cpos);
2199         if (!cn)
2200         {
2201             char *addinfo = odr_strdup_null(odr, ccl_err_msg(cerror));
2202             error = YAZ_BIB1_MALFORMED_QUERY;
2203
2204             switch (cerror)
2205             {
2206             case CCL_ERR_UNKNOWN_QUAL:
2207             case CCL_ERR_TRUNC_NOT_LEFT: 
2208             case CCL_ERR_TRUNC_NOT_RIGHT:
2209             case CCL_ERR_TRUNC_NOT_BOTH:
2210 #ifdef CCL_ERR_TRUNC_NOT_EMBED
2211             case CCL_ERR_TRUNC_NOT_EMBED:
2212 #endif
2213 #ifdef CCL_ERR_TRUNC_NOT_SINGLE
2214             case CCL_ERR_TRUNC_NOT_SINGLE:
2215 #endif
2216                 error = YAZ_BIB1_UNSUPP_SEARCH;
2217                 break;
2218             }
2219             log_diagnostic(package, error, addinfo);
2220             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2221             package.response() = apdu_res;
2222             return;
2223         }
2224         ccl_pquery(pqf_wrbuf, cn);
2225         package.log("zoom", YLOG_LOG, "RPN: %s", wrbuf_cstr(pqf_wrbuf));
2226         ccl_rpn_delete(cn);
2227     }
2228     
2229     assert(pqf_wrbuf.len());
2230
2231     ZOOM_query q = ZOOM_query_create();
2232     ZOOM_query_sortby2(q, b->sptr->sortStrategy.c_str(), sortkeys.c_str());
2233
2234     if (b->get_option("sru"))
2235     {
2236         int status = 0;
2237         Z_RPNQuery *zquery;
2238         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
2239         mp::wrbuf wrb;
2240             
2241         if (!strcmp(b->get_option("sru"), "solr"))
2242         {
2243             solr_transform_t cqlt = solr_transform_create();
2244             
2245             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
2246             
2247             solr_transform_close(cqlt);
2248         }
2249         else
2250         {
2251             status = cql_transform_rpn2cql_wrbuf(b->cqlt, wrb, zquery);
2252         }
2253         if (status == 0)
2254         {
2255             ZOOM_query_cql(q, wrbuf_cstr(wrb));
2256             package.log("zoom", YLOG_LOG, "CQL: %s", wrbuf_cstr(wrb));
2257             b->search(q, &hits, &error, &addinfo, odr);
2258         }
2259         ZOOM_query_destroy(q);
2260         
2261         if (status)
2262         {
2263             error = YAZ_BIB1_MALFORMED_QUERY;
2264             const char *addinfo = "can not convert from RPN to CQL/SOLR";
2265             log_diagnostic(package, error, addinfo);
2266             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2267             package.response() = apdu_res;
2268             return;
2269         }
2270     }
2271     else
2272     {
2273         ZOOM_query_prefix(q, wrbuf_cstr(pqf_wrbuf));
2274         package.log("zoom", YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
2275         b->search(q, &hits, &error, &addinfo, odr);
2276         ZOOM_query_destroy(q);
2277     }
2278
2279     if (error)
2280     {
2281         if (retry(package, odr, b, error, &addinfo, proxy_step,
2282                   same_retries, proxy_retries))
2283             goto next_proxy;
2284     }
2285
2286     const char *element_set_name = 0;
2287     Odr_int number_to_present = 0;
2288     if (!error)
2289         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
2290     
2291     Odr_int number_of_records_returned = 0;
2292     Z_Records *records = get_records(
2293         package,
2294         0, number_to_present, &error, &addinfo,
2295         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
2296         element_set_name);
2297     if (error)
2298         log_diagnostic(package, error, addinfo);
2299     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2300     if (records)
2301     {
2302         apdu_res->u.searchResponse->records = records;
2303         apdu_res->u.searchResponse->numberOfRecordsReturned =
2304             odr_intdup(odr, number_of_records_returned);
2305     }
2306     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
2307     package.response() = apdu_res;
2308 }
2309
2310 void yf::Zoom::Frontend::handle_present(mp::Package &package)
2311 {
2312     Z_GDU *gdu = package.request().get();
2313     Z_APDU *apdu_req = gdu->u.z3950;
2314     Z_APDU *apdu_res = 0;
2315     Z_PresentRequest *pr = apdu_req->u.presentRequest;
2316
2317     mp::odr odr;
2318     if (!m_backend)
2319     {
2320         package.response() = odr.create_presentResponse(
2321             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
2322         return;
2323     }
2324     const char *element_set_name = 0;
2325     Z_RecordComposition *comp = pr->recordComposition;
2326     if (comp && comp->which != Z_RecordComp_simple)
2327     {
2328         package.response() = odr.create_presentResponse(
2329             apdu_req, 
2330             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
2331         return;
2332     }
2333     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
2334         element_set_name = comp->u.simple->u.generic;
2335     Odr_int number_of_records_returned = 0;
2336     int error = 0;
2337     char *addinfo = 0;
2338
2339     if (m_backend->enable_explain)
2340     {
2341         Z_Records *records =
2342             get_explain_records(
2343                 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     else
2358     {
2359         Z_Records *records =
2360             get_records(package,
2361                         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2362                         &error, &addinfo, &number_of_records_returned, odr, m_backend,
2363                         pr->preferredRecordSyntax, element_set_name);
2364         
2365         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2366         if (records)
2367         {
2368             apdu_res->u.presentResponse->records = records;
2369             apdu_res->u.presentResponse->numberOfRecordsReturned =
2370                 odr_intdup(odr, number_of_records_returned);
2371         }
2372         package.response() = apdu_res;
2373     }
2374 }
2375
2376 void yf::Zoom::Frontend::handle_package(mp::Package &package)
2377 {
2378     Z_GDU *gdu = package.request().get();
2379     if (!gdu)
2380         ;
2381     else if (gdu->which == Z_GDU_Z3950)
2382     {
2383         Z_APDU *apdu_req = gdu->u.z3950;
2384
2385         if (m_backend)
2386             wrbuf_rewind(m_backend->m_apdu_wrbuf);
2387         if (apdu_req->which == Z_APDU_initRequest)
2388         {
2389             mp::odr odr;
2390             package.response() = odr.create_close(
2391                 apdu_req,
2392                 Z_Close_protocolError,
2393                 "double init");
2394         }
2395         else if (apdu_req->which == Z_APDU_searchRequest)
2396         {
2397             handle_search(package);
2398         }
2399         else if (apdu_req->which == Z_APDU_presentRequest)
2400         {
2401             handle_present(package);
2402         }
2403         else
2404         {
2405             mp::odr odr;
2406             package.response() = odr.create_close(
2407                 apdu_req,
2408                 Z_Close_protocolError,
2409                 "zoom filter cannot handle this APDU");
2410             package.session().close();
2411         }
2412         if (m_backend)
2413         {
2414             WRBUF w = m_backend->m_apdu_wrbuf;
2415             package.log_write(wrbuf_buf(w), wrbuf_len(w));
2416         }
2417     }
2418     else
2419     {
2420         package.session().close();
2421     }
2422 }
2423
2424 void yf::Zoom::Impl::process(mp::Package &package)
2425 {
2426     FrontendPtr f = get_frontend(package);
2427     Z_GDU *gdu = package.request().get();
2428
2429     if (f->m_is_virtual)
2430     {
2431         f->handle_package(package);
2432     }
2433     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
2434              Z_APDU_initRequest)
2435     {
2436         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
2437         f->m_init_gdu = gdu;
2438         
2439         mp::odr odr;
2440         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
2441         Z_InitResponse *resp = apdu->u.initResponse;
2442         
2443         int i;
2444         static const int masks[] = {
2445             Z_Options_search,
2446             Z_Options_present,
2447             -1 
2448         };
2449         for (i = 0; masks[i] != -1; i++)
2450             if (ODR_MASK_GET(req->options, masks[i]))
2451                 ODR_MASK_SET(resp->options, masks[i]);
2452         
2453         static const int versions[] = {
2454             Z_ProtocolVersion_1,
2455             Z_ProtocolVersion_2,
2456             Z_ProtocolVersion_3,
2457             -1
2458         };
2459         for (i = 0; versions[i] != -1; i++)
2460             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
2461                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
2462             else
2463                 break;
2464         
2465         *resp->preferredMessageSize = *req->preferredMessageSize;
2466         *resp->maximumRecordSize = *req->maximumRecordSize;
2467         
2468         package.response() = apdu;
2469         f->m_is_virtual = true;
2470     }
2471     else
2472         package.move();
2473
2474     release_frontend(package);
2475 }
2476
2477
2478 static mp::filter::Base* filter_creator()
2479 {
2480     return new mp::filter::Zoom;
2481 }
2482
2483 extern "C" {
2484     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
2485         0,
2486         "zoom",
2487         filter_creator
2488     };
2489 }
2490
2491
2492 /*
2493  * Local variables:
2494  * c-basic-offset: 4
2495  * c-file-style: "Stroustrup"
2496  * indent-tabs-mode: nil
2497  * End:
2498  * vim: shiftwidth=4 tabstop=8 expandtab
2499  */
2500