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