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