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