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