zoom: honor database argument nocproxy
[metaproxy-moved-to-github.git] / src / filter_zoom.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2011 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             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 content_session_id;
95         public:
96             Backend(SearchablePtr sptr);
97             ~Backend();
98             void connect(std::string zurl, int *error, char **addinfo,
99                          ODR odr);
100             void search(ZOOM_query q, Odr_int *hits,
101                         int *error, char **addinfo, ODR odr);
102             void present(Odr_int start, Odr_int number, ZOOM_record *recs,
103                          int *error, char **addinfo, ODR odr);
104             void set_option(const char *name, const char *value);
105             void set_option(const char *name, std::string value);
106             const char *get_option(const char *name);
107             void get_zoom_error(int *error, char **addinfo, ODR odr);
108         };
109         class Zoom::Frontend : boost::noncopyable {
110             friend class Impl;
111             Impl *m_p;
112             bool m_is_virtual;
113             bool m_in_use;
114             yazpp_1::GDU m_init_gdu;
115             BackendPtr m_backend;
116             void handle_package(mp::Package &package);
117             void handle_search(mp::Package &package);
118             void handle_present(mp::Package &package);
119             BackendPtr get_backend_from_databases(mp::Package &package,
120                                                   std::string &database,
121                                                   int *error,
122                                                   char **addinfo,
123                                                   ODR odr,
124                                                   int *proxy_step);
125
126             bool create_content_session(mp::Package &package,
127                                         BackendPtr b,
128                                         int *error,
129                                         char **addinfo,
130                                         ODR odr,
131                                         std::string authentication,
132                                         std::string proxy);
133             
134             void prepare_elements(BackendPtr b,
135                                   Odr_oid *preferredRecordSyntax,
136                                   const char *element_set_name,
137                                   bool &enable_pz2_retrieval,
138                                   bool &enable_pz2_transform,
139                                   bool &assume_marc8_charset);
140
141             Z_Records *get_records(Package &package,
142                                    Odr_int start,
143                                    Odr_int number_to_present,
144                                    int *error,
145                                    char **addinfo,
146                                    Odr_int *number_of_records_returned,
147                                    ODR odr, BackendPtr b,
148                                    Odr_oid *preferredRecordSyntax,
149                                    const char *element_set_name);
150
151             void log_diagnostic(mp::Package &package,
152                                 int error, const char *addinfo);
153         public:
154             Frontend(Impl *impl);
155             ~Frontend();
156         };
157         class Zoom::Impl {
158             friend class Frontend;
159         public:
160             Impl();
161             ~Impl();
162             void process(metaproxy_1::Package & package);
163             void configure(const xmlNode * ptr, bool test_only,
164                            const char *path);
165         private:
166             void configure_local_records(const xmlNode * ptr, bool test_only);
167             FrontendPtr get_frontend(mp::Package &package);
168             void release_frontend(mp::Package &package);
169             SearchablePtr parse_torus_record(const xmlNode *ptr);
170             struct cql_node *convert_cql_fields(struct cql_node *cn, ODR odr);
171             std::map<mp::Session, FrontendPtr> m_clients;            
172             boost::mutex m_mutex;
173             boost::condition m_cond_session_ready;
174             std::string torus_searchable_url;
175             std::string torus_content_url;
176             std::string default_realm;
177             std::map<std::string,std::string> fieldmap;
178             std::string xsldir;
179             std::string file_path;
180             std::string content_proxy_server;
181             std::string content_tmp_file;
182             bool apdu_log;
183             CCL_bibset bibset;
184             std::string element_transform;
185             std::string element_raw;
186             std::string proxy;
187             std::map<std::string,SearchablePtr> s_map;
188         };
189     }
190 }
191
192 // define Pimpl wrapper forwarding to Impl
193  
194 yf::Zoom::Zoom() : m_p(new Impl)
195 {
196 }
197
198 yf::Zoom::~Zoom()
199 {  // must have a destructor because of boost::scoped_ptr
200 }
201
202 void yf::Zoom::configure(const xmlNode *xmlnode, bool test_only,
203                          const char *path)
204 {
205     m_p->configure(xmlnode, test_only, path);
206 }
207
208 void yf::Zoom::process(mp::Package &package) const
209 {
210     m_p->process(package);
211 }
212
213
214 // define Implementation stuff
215
216 yf::Zoom::Backend::Backend(SearchablePtr ptr) : sptr(ptr)
217 {
218     m_apdu_wrbuf = wrbuf_alloc();
219     m_connection = ZOOM_connection_create(0);
220     ZOOM_connection_save_apdu_wrbuf(m_connection, m_apdu_wrbuf);
221     m_resultset = 0;
222     xsp = 0;
223 }
224
225 yf::Zoom::Backend::~Backend()
226 {
227     if (xsp)
228         xsltFreeStylesheet(xsp);
229     ZOOM_connection_destroy(m_connection);
230     ZOOM_resultset_destroy(m_resultset);
231 }
232
233
234 void yf::Zoom::Backend::get_zoom_error(int *error, char **addinfo,
235                                        ODR odr)
236 {
237     const char *msg = 0;
238     const char *zoom_addinfo = 0;
239     const char *dset = 0;
240     int error0 = ZOOM_connection_error_x(m_connection, &msg,
241                                          &zoom_addinfo, &dset);
242     if (error0)
243     {
244         if (!dset)
245             dset = "Unknown";
246         
247         if (!strcmp(dset, "info:srw/diagnostic/1"))
248             *error = yaz_diag_srw_to_bib1(error0);
249         else if (!strcmp(dset, "Bib-1"))
250             *error = error0;
251         else
252             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
253         
254         *addinfo = (char *) odr_malloc(
255             odr, 30 + strlen(dset) + strlen(msg) +
256             (zoom_addinfo ? strlen(zoom_addinfo) : 0));
257         **addinfo = '\0';
258         if (zoom_addinfo && *zoom_addinfo)
259         {
260             strcpy(*addinfo, zoom_addinfo);
261             strcat(*addinfo, " ");
262         }
263         sprintf(*addinfo + strlen(*addinfo), "(%s %d %s)", dset, error0, msg);
264     }
265 }
266
267 void yf::Zoom::Backend::connect(std::string zurl,
268                                 int *error, char **addinfo,
269                                 ODR odr)
270 {
271     ZOOM_connection_connect(m_connection, zurl.c_str(), 0);
272     get_zoom_error(error, addinfo, odr);
273 }
274
275 void yf::Zoom::Backend::search(ZOOM_query q, Odr_int *hits,
276                                int *error, char **addinfo, ODR odr)
277 {
278     m_resultset = ZOOM_connection_search(m_connection, q);
279     get_zoom_error(error, addinfo, odr);
280     if (*error == 0)
281         *hits = ZOOM_resultset_size(m_resultset);
282     else
283         *hits = 0;
284 }
285
286 void yf::Zoom::Backend::present(Odr_int start, Odr_int number,
287                                 ZOOM_record *recs,
288                                 int *error, char **addinfo, ODR odr)
289 {
290     ZOOM_resultset_records(m_resultset, recs, start, number);
291     get_zoom_error(error, addinfo, odr);
292 }
293
294 void yf::Zoom::Backend::set_option(const char *name, const char *value)
295 {
296     ZOOM_connection_option_set(m_connection, name, value);
297     if (m_resultset)
298         ZOOM_resultset_option_set(m_resultset, name, value);
299 }
300
301 void yf::Zoom::Backend::set_option(const char *name, std::string value)
302 {
303     set_option(name, value.c_str());
304 }
305
306 const char *yf::Zoom::Backend::get_option(const char *name)
307 {
308     return ZOOM_connection_option_get(m_connection, name);
309 }
310
311 yf::Zoom::Searchable::Searchable(CCL_bibset base)
312 {
313     piggyback = true;
314     use_turbomarc = true;
315     sortStrategy = "embed";
316     urlRecipe = "${md-electronic-url}";
317     ccl_bibset = ccl_qual_dup(base);
318 }
319
320 yf::Zoom::Searchable::~Searchable()
321 {
322     ccl_qual_rm(&ccl_bibset);
323 }
324
325 yf::Zoom::Frontend::Frontend(Impl *impl) : 
326     m_p(impl), m_is_virtual(false), m_in_use(true)
327 {
328 }
329
330 yf::Zoom::Frontend::~Frontend()
331 {
332 }
333
334 yf::Zoom::FrontendPtr yf::Zoom::Impl::get_frontend(mp::Package &package)
335 {
336     boost::mutex::scoped_lock lock(m_mutex);
337
338     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
339     
340     while(true)
341     {
342         it = m_clients.find(package.session());
343         if (it == m_clients.end())
344             break;
345         
346         if (!it->second->m_in_use)
347         {
348             it->second->m_in_use = true;
349             return it->second;
350         }
351         m_cond_session_ready.wait(lock);
352     }
353     FrontendPtr f(new Frontend(this));
354     m_clients[package.session()] = f;
355     f->m_in_use = true;
356     return f;
357 }
358
359 void yf::Zoom::Impl::release_frontend(mp::Package &package)
360 {
361     boost::mutex::scoped_lock lock(m_mutex);
362     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
363     
364     it = m_clients.find(package.session());
365     if (it != m_clients.end())
366     {
367         if (package.session().is_closed())
368         {
369             m_clients.erase(it);
370         }
371         else
372         {
373             it->second->m_in_use = false;
374         }
375         m_cond_session_ready.notify_all();
376     }
377 }
378
379 yf::Zoom::Impl::Impl() :
380     apdu_log(false), element_transform("pz2") , element_raw("raw")
381 {
382     bibset = ccl_qual_mk();
383
384     srand((unsigned int) time(0));
385 }
386
387 yf::Zoom::Impl::~Impl()
388
389     ccl_qual_rm(&bibset);
390 }
391
392 yf::Zoom::SearchablePtr yf::Zoom::Impl::parse_torus_record(const xmlNode *ptr)
393 {
394     Zoom::SearchablePtr s(new Searchable(bibset));
395     
396     for (ptr = ptr->children; ptr; ptr = ptr->next)
397     {
398         if (ptr->type != XML_ELEMENT_NODE)
399             continue;
400         if (!strcmp((const char *) ptr->name, "layer"))
401             ptr = ptr->children;
402         else if (!strcmp((const char *) ptr->name,
403                          "authentication"))
404         {
405             s->authentication = mp::xml::get_text(ptr);
406         }
407         else if (!strcmp((const char *) ptr->name,
408                          "cfAuth"))
409         {
410             s->cfAuth = mp::xml::get_text(ptr);
411         } 
412         else if (!strcmp((const char *) ptr->name,
413                          "cfProxy"))
414         {
415             s->cfProxy = mp::xml::get_text(ptr);
416         }  
417         else if (!strcmp((const char *) ptr->name,
418                          "cfSubDB"))
419         {
420             s->cfSubDB = mp::xml::get_text(ptr);
421         }  
422         else if (!strcmp((const char *) ptr->name,
423                          "contentConnector"))
424         {
425             s->contentConnector = mp::xml::get_text(ptr);
426         }  
427         else if (!strcmp((const char *) ptr->name, "udb"))
428         {
429             s->udb = mp::xml::get_text(ptr);
430         }
431         else if (!strcmp((const char *) ptr->name, "zurl"))
432         {
433             s->target = mp::xml::get_text(ptr);
434         }
435         else if (!strcmp((const char *) ptr->name, "sru"))
436         {
437             s->sru = mp::xml::get_text(ptr);
438         }
439         else if (!strcmp((const char *) ptr->name, "SRUVersion") ||
440                  !strcmp((const char *) ptr->name, "sruVersion"))
441         {
442             s->sru_version = mp::xml::get_text(ptr);
443         }
444         else if (!strcmp((const char *) ptr->name,
445                          "queryEncoding"))
446         {
447             s->query_encoding = mp::xml::get_text(ptr);
448         }
449         else if (!strcmp((const char *) ptr->name,
450                          "piggyback"))
451         {
452             s->piggyback = mp::xml::get_bool(ptr, true);
453         }
454         else if (!strcmp((const char *) ptr->name,
455                          "requestSyntax"))
456         {
457             s->request_syntax = mp::xml::get_text(ptr);
458         }
459         else if (!strcmp((const char *) ptr->name,
460                          "elementSet"))
461         {
462             s->element_set = mp::xml::get_text(ptr);
463         }
464         else if (!strcmp((const char *) ptr->name,
465                          "recordEncoding"))
466         {
467             s->record_encoding = mp::xml::get_text(ptr);
468         }
469         else if (!strcmp((const char *) ptr->name,
470                          "transform"))
471         {
472             s->transform_xsl_fname = mp::xml::get_text(ptr);
473         }
474         else if (!strcmp((const char *) ptr->name,
475                          "literalTransform"))
476         {
477             s->transform_xsl_content = mp::xml::get_text(ptr);
478         }
479         else if (!strcmp((const char *) ptr->name,
480                          "urlRecipe"))
481         {
482             s->urlRecipe = mp::xml::get_text(ptr);
483         }
484         else if (!strcmp((const char *) ptr->name,
485                          "useTurboMarc"))
486         {
487             ; // useTurboMarc is ignored
488         }
489         else if (!strncmp((const char *) ptr->name,
490                           "cclmap_", 7))
491         {
492             std::string value = mp::xml::get_text(ptr);
493             ccl_qual_fitem(s->ccl_bibset, value.c_str(),
494                            (const char *) ptr->name + 7);
495         }
496         else if (!strncmp((const char *) ptr->name,
497                           "sortmap_", 8))
498         {
499             std::string value = mp::xml::get_text(ptr);
500             s->sortmap[(const char *) ptr->name + 8] = value;
501         }
502         else if (!strcmp((const char *) ptr->name,
503                           "sortStrategy"))
504         {
505             s->sortStrategy = mp::xml::get_text(ptr);
506         }
507     }
508     return s;
509 }
510
511 void yf::Zoom::Impl::configure_local_records(const xmlNode *ptr, bool test_only)
512 {
513     while (ptr && ptr->type != XML_ELEMENT_NODE)
514         ptr = ptr->next;
515     
516     if (ptr)
517     {
518         if (!strcmp((const char *) ptr->name, "records"))
519         {
520             for (ptr = ptr->children; ptr; ptr = ptr->next)
521             {
522                 if (ptr->type != XML_ELEMENT_NODE)
523                     continue;
524                 if (!strcmp((const char *) ptr->name, "record"))
525                 {
526                     SearchablePtr s = parse_torus_record(ptr);
527                     if (s)
528                     {
529                         std::string udb = s->udb;
530                         if (udb.length())
531                             s_map[s->udb] = s;
532                         else
533                         {
534                             throw mp::filter::FilterException
535                                 ("No udb for local torus record");
536                         }
537                     }
538                 }
539                 else
540                 {
541                     throw mp::filter::FilterException
542                         ("Bad element " 
543                          + std::string((const char *) ptr->name)
544                          + " in zoom filter inside element "
545                          "<torus><records>");
546                 }
547             }
548         }
549         else
550         {
551             throw mp::filter::FilterException
552                 ("Bad element " 
553                  + std::string((const char *) ptr->name)
554                  + " in zoom filter inside element <torus>");
555         }
556     }
557 }
558
559 void yf::Zoom::Impl::configure(const xmlNode *ptr, bool test_only,
560                                const char *path)
561 {
562     content_tmp_file = "/tmp/cf.XXXXXX.p";
563     if (path && *path)
564     {
565         file_path = path;
566     }
567     for (ptr = ptr->children; ptr; ptr = ptr->next)
568     {
569         if (ptr->type != XML_ELEMENT_NODE)
570             continue;
571         else if (!strcmp((const char *) ptr->name, "torus"))
572         {
573             const struct _xmlAttr *attr;
574             for (attr = ptr->properties; attr; attr = attr->next)
575             {
576                 if (!strcmp((const char *) attr->name, "url"))
577                     torus_searchable_url = mp::xml::get_text(attr->children);
578                 else if (!strcmp((const char *) attr->name, "content_url"))
579                     torus_content_url = mp::xml::get_text(attr->children);
580                 else if (!strcmp((const char *) attr->name, "realm"))
581                     default_realm = mp::xml::get_text(attr->children);
582                 else if (!strcmp((const char *) attr->name, "xsldir"))
583                     xsldir = mp::xml::get_text(attr->children);
584                 else if (!strcmp((const char *) attr->name, "element_transform"))
585                     element_transform = mp::xml::get_text(attr->children);
586                 else if (!strcmp((const char *) attr->name, "element_raw"))
587                     element_raw = mp::xml::get_text(attr->children);
588                 else if (!strcmp((const char *) attr->name, "proxy"))
589                     proxy = mp::xml::get_text(attr->children);
590                 else
591                     throw mp::filter::FilterException(
592                         "Bad attribute " + std::string((const char *)
593                                                        attr->name));
594             }
595             // If content_url is not given, use value of searchable, to
596             // ensure backwards compatibility
597             if (!torus_content_url.length())
598                 torus_content_url = torus_searchable_url;
599             configure_local_records(ptr->children, test_only);
600         }
601         else if (!strcmp((const char *) ptr->name, "cclmap"))
602         {
603             const char *addinfo = 0;
604             ccl_xml_config(bibset, ptr, &addinfo);
605         }
606         else if (!strcmp((const char *) ptr->name, "fieldmap"))
607         {
608             const struct _xmlAttr *attr;
609             std::string ccl_field;
610             std::string cql_field;
611             for (attr = ptr->properties; attr; attr = attr->next)
612             {
613                 if (!strcmp((const char *) attr->name, "ccl"))
614                     ccl_field = mp::xml::get_text(attr->children);
615                 else if (!strcmp((const char *) attr->name, "cql"))
616                     cql_field = mp::xml::get_text(attr->children);
617                 else
618                     throw mp::filter::FilterException(
619                         "Bad attribute " + std::string((const char *)
620                                                        attr->name));
621             }
622             if (cql_field.length())
623                 fieldmap[cql_field] = ccl_field;
624         }
625         else if (!strcmp((const char *) ptr->name, "contentProxy"))
626         {
627             const struct _xmlAttr *attr;
628             for (attr = ptr->properties; attr; attr = attr->next)
629             {
630                 if (!strcmp((const char *) attr->name, "server"))
631                     content_proxy_server = mp::xml::get_text(attr->children);
632                 else if (!strcmp((const char *) attr->name, "tmp_file"))
633                     content_tmp_file = mp::xml::get_text(attr->children);
634                 else
635                     throw mp::filter::FilterException(
636                         "Bad attribute " + std::string((const char *)
637                                                        attr->name));
638             }
639         }
640         else if (!strcmp((const char *) ptr->name, "log"))
641         { 
642             const struct _xmlAttr *attr;
643             for (attr = ptr->properties; attr; attr = attr->next)
644             {
645                 if (!strcmp((const char *) attr->name, "apdu"))
646                     apdu_log = mp::xml::get_bool(attr->children, false);
647                 else
648                     throw mp::filter::FilterException(
649                         "Bad attribute " + std::string((const char *)
650                                                        attr->name));
651             }
652         }
653         else
654         {
655             throw mp::filter::FilterException
656                 ("Bad element " 
657                  + std::string((const char *) ptr->name)
658                  + " in zoom filter");
659         }
660     }
661 }
662
663 bool yf::Zoom::Frontend::create_content_session(mp::Package &package,
664                                                 BackendPtr b,
665                                                 int *error, char **addinfo,
666                                                 ODR odr,
667                                                 std::string authentication,
668                                                 std::string proxy)
669 {
670     if (b->sptr->contentConnector.length())
671     {
672         char *fname = (char *) xmalloc(m_p->content_tmp_file.length() + 8);
673         strcpy(fname, m_p->content_tmp_file.c_str());
674         char *xx = strstr(fname, "XXXXXX");
675         if (!xx)
676         {
677             xx = fname + strlen(fname);
678             strcat(fname, "XXXXXX");
679         }
680         char tmp_char = xx[6];
681         sprintf(xx, "%06d", ((unsigned) rand()) % 1000000);
682         xx[6] = tmp_char;
683
684         FILE *file = fopen(fname, "w");
685         if (!file)
686         {
687             package.log("zoom", YLOG_WARN|YLOG_ERRNO, "create %s", fname);
688             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
689             *addinfo = (char *)  odr_malloc(odr, 40 + strlen(fname));
690             sprintf(*addinfo, "Could not create %s", fname);
691             xfree(fname);
692             return false;
693         }
694         b->content_session_id.assign(xx, 6);
695         WRBUF w = wrbuf_alloc();
696         wrbuf_puts(w, "#content_proxy\n");
697         wrbuf_printf(w, "connector: %s\n", b->sptr->contentConnector.c_str());
698         if (authentication.length())
699             wrbuf_printf(w, "auth: %s\n", authentication.c_str());
700         if (proxy.length())
701             wrbuf_printf(w, "proxy: %s\n", proxy.c_str());
702
703         fwrite(wrbuf_buf(w), 1, wrbuf_len(w), file);
704         fclose(file);
705         package.log("zoom", YLOG_LOG, "content file: %s", fname);
706         xfree(fname);
707     }
708     return true;
709 }
710
711 yf::Zoom::BackendPtr yf::Zoom::Frontend::get_backend_from_databases(
712     mp::Package &package,
713     std::string &database, int *error, char **addinfo, ODR odr,
714     int *proxy_step)
715 {
716     std::list<BackendPtr>::const_iterator map_it;
717     if (m_backend && m_backend->m_frontend_database == database)
718         return m_backend;
719
720     std::string input_args;
721     std::string torus_db;
722     size_t db_arg_pos = database.find(',');
723     if (db_arg_pos != std::string::npos)
724     {
725         torus_db = database.substr(0, db_arg_pos);
726         input_args = database.substr(db_arg_pos + 1);
727     }
728     else
729         torus_db = database;
730
731     std::string authentication;
732     std::string content_authentication;
733     std::string proxy;
734     std::string content_proxy;
735     std::string realm = m_p->default_realm;
736
737     const char *param_user = 0;
738     const char *param_password = 0;
739     const char *param_content_user = 0;
740     const char *param_content_password = 0;
741     const char *param_nocproxy = 0;
742     int no_parms = 0;
743
744     char **names;
745     char **values;
746     int no_out_args = 0;
747     if (input_args.length())
748         no_parms = yaz_uri_to_array(input_args.c_str(),
749                                     odr, &names, &values);
750     // adding 10 because we'll be adding other URL args
751     const char **out_names = (const char **)
752         odr_malloc(odr, (10 + no_parms) * sizeof(*out_names));
753     const char **out_values = (const char **)
754         odr_malloc(odr, (10 + no_parms) * sizeof(*out_values));
755     
756     // may be changed if it's a content connection
757     std::string torus_url = m_p->torus_searchable_url;
758     int i;
759     for (i = 0; i < no_parms; i++)
760     {
761         const char *name = names[i];
762         const char *value = values[i];
763         assert(name);
764         assert(value);
765         if (!strcmp(name, "user"))
766             param_user = value;
767         else if (!strcmp(name, "password"))
768             param_password = value;
769         else if (!strcmp(name, "content-user"))
770             param_content_user = value;
771         else if (!strcmp(name, "content-password"))
772             param_content_password = value;
773         else if (!strcmp(name, "content-proxy"))
774             content_proxy = value;
775         else if (!strcmp(name, "nocproxy"))
776             param_nocproxy = value;
777         else if (!strcmp(name, "proxy"))
778         {
779             char **dstr;
780             int dnum = 0;
781             nmem_strsplit(odr->mem, ",", value, &dstr, &dnum);
782             if (*proxy_step >= dnum)
783                 *proxy_step = 0;
784             else
785             {
786                 proxy = dstr[*proxy_step];
787                 
788                 (*proxy_step)++;
789                 if (*proxy_step == dnum)
790                     *proxy_step = 0;
791             }
792         }
793         else if (!strcmp(name, "cproxysession"))
794         {
795             out_names[no_out_args] = name;
796             out_values[no_out_args++] = value;
797             torus_url = m_p->torus_content_url;
798         }
799         else if (!strcmp(name, "realm"))
800             realm = value;
801         else if (name[0] == 'x' && name[1] == '-')
802         {
803             out_names[no_out_args] = name;
804             out_values[no_out_args++] = value;
805         }
806         else
807         {
808             BackendPtr notfound;
809             char *msg = (char*) odr_malloc(odr, strlen(name) + 30);
810             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
811             sprintf(msg, "Bad database argument: %s", name);
812             *addinfo = msg;
813             return notfound;
814         }
815     }
816     if (param_user)
817     {
818         authentication = std::string(param_user);
819         if (param_password)
820             authentication += "/" + std::string(param_password);
821     }
822     if (param_content_user)
823     {
824         content_authentication = std::string(param_content_user);
825         if (param_content_password)
826             content_authentication += "/" + std::string(param_content_password);
827     }
828     SearchablePtr sptr;
829
830     std::map<std::string,SearchablePtr>::iterator it;
831     it = m_p->s_map.find(torus_db);
832     if (it != m_p->s_map.end())
833         sptr = it->second;
834     else if (torus_url.length() > 0)
835     {
836         xmlDoc *doc = mp::get_searchable(package,torus_url, torus_db,
837                                          realm, m_p->proxy);
838         if (!doc)
839         {
840             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
841             *addinfo = odr_strdup(odr, database.c_str());
842             BackendPtr b;
843             return b;
844         }
845         const xmlNode *ptr = xmlDocGetRootElement(doc);
846         if (ptr)
847         {   // presumably ptr is a records element node
848             // parse first record in document
849             for (ptr = ptr->children; ptr; ptr = ptr->next)
850             {
851                 if (ptr->type == XML_ELEMENT_NODE
852                     && !strcmp((const char *) ptr->name, "record"))
853                 {
854                     if (sptr)
855                     {
856                         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
857                         *addinfo = (char*) odr_malloc(odr, 40 + database.length()),
858                         sprintf(*addinfo, "multiple records for udb=%s",
859                                  database.c_str());
860                         xmlFreeDoc(doc);
861                         BackendPtr b;
862                         return b;
863                     }
864                     sptr = m_p->parse_torus_record(ptr);
865                 }
866             }
867         }
868         xmlFreeDoc(doc);
869     }
870
871     if (!sptr)
872     {
873         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
874         *addinfo = odr_strdup(odr, database.c_str());
875         BackendPtr b;
876         return b;
877     }
878         
879     xsltStylesheetPtr xsp = 0;
880     if (sptr->transform_xsl_content.length())
881     {
882         xmlDoc *xsp_doc = xmlParseMemory(sptr->transform_xsl_content.c_str(),
883                                          sptr->transform_xsl_content.length());
884         if (!xsp_doc)
885         {
886             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
887             *addinfo = (char *) odr_malloc(odr, 40);
888             sprintf(*addinfo, "xmlParseMemory failed");
889             BackendPtr b;
890             return b;
891         }
892         xsp = xsltParseStylesheetDoc(xsp_doc);
893         if (!xsp)
894         {
895             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
896             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
897             BackendPtr b;
898             xmlFreeDoc(xsp_doc);
899             return b;
900         }
901     }
902     else if (sptr->transform_xsl_fname.length())
903     {
904         const char *path = 0;
905
906         if (m_p->xsldir.length())
907             path = m_p->xsldir.c_str();
908         else
909             path = m_p->file_path.c_str();
910         std::string fname;
911
912         char fullpath[1024];
913         char *cp = yaz_filepath_resolve(sptr->transform_xsl_fname.c_str(),
914                                         path, 0, fullpath);
915         if (cp)
916             fname.assign(cp);
917         else
918         {
919             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
920             *addinfo = (char *)
921                 odr_malloc(odr, 40 + sptr->transform_xsl_fname.length());
922             sprintf(*addinfo, "File could not be read: %s", 
923                     sptr->transform_xsl_fname.c_str());
924             BackendPtr b;
925             return b;
926         }
927         xmlDoc *xsp_doc = xmlParseFile(fname.c_str());
928         if (!xsp_doc)
929         {
930             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
931             *addinfo = (char *) odr_malloc(odr, 40 + fname.length());
932             sprintf(*addinfo, "xmlParseFile failed. File: %s", fname.c_str());
933             BackendPtr b;
934             return b;
935         }
936         xsp = xsltParseStylesheetDoc(xsp_doc);
937         if (!xsp)
938         {
939             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
940             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
941             BackendPtr b;
942             xmlFreeDoc(xsp_doc);
943             return b;
944         }
945     }
946
947     m_backend.reset();
948
949     BackendPtr b(new Backend(sptr));
950
951     b->xsp = xsp;
952     b->m_frontend_database = database;
953
954     if (sptr->query_encoding.length())
955         b->set_option("rpnCharset", sptr->query_encoding);
956
957     b->set_option("timeout", "40");
958     
959     if (m_p->apdu_log) 
960         b->set_option("apdulog", "1");
961
962     if (sptr->piggyback && sptr->sru.length())
963         b->set_option("count", "1"); /* some SRU servers INSIST on getting
964                                         maximumRecords > 0 */
965     b->set_option("piggyback", sptr->piggyback ? "1" : "0");
966
967     if (authentication.length() == 0)
968         authentication = sptr->authentication;
969
970     if (proxy.length() == 0)
971         proxy = sptr->cfProxy;
972     
973     if (sptr->cfAuth.length())
974     {
975         // A CF target
976         b->set_option("user", sptr->cfAuth);
977         if (authentication.length())
978         {
979             size_t found = authentication.find('/');
980             if (found != std::string::npos)
981             {
982                 out_names[no_out_args] = "user";
983                 out_values[no_out_args++] =
984                     odr_strdup(odr, authentication.substr(0, found).c_str());
985
986                 out_names[no_out_args] = "password";
987                 out_values[no_out_args++] =
988                     odr_strdup(odr, authentication.substr(found+1).c_str());
989             }
990             else
991             {
992                 out_names[no_out_args] = "user";
993                 out_values[no_out_args++] =
994                     odr_strdup(odr, authentication.c_str());
995             }                
996         }
997         if (proxy.length())
998         {
999             out_names[no_out_args] = "proxy";
1000             out_values[no_out_args++] = odr_strdup(odr, proxy.c_str());
1001         }
1002         if (sptr->cfSubDB.length())
1003         {
1004             out_names[no_out_args] = "subdatabase";
1005             out_values[no_out_args++] = odr_strdup(odr, sptr->cfSubDB.c_str());
1006         }
1007         if (param_nocproxy)
1008         {
1009             out_names[no_out_args] = "nocproxy";
1010             out_values[no_out_args++] = odr_strdup(odr, param_nocproxy);
1011         }
1012     }
1013     else
1014     {
1015         size_t found = authentication.find('/');
1016         
1017         if (sptr->sru.length() && found != std::string::npos)
1018         {
1019             b->set_option("user", authentication.substr(0, found));
1020             b->set_option("password", authentication.substr(found+1));
1021         }
1022         else
1023             b->set_option("user", authentication);
1024
1025         if (proxy.length())
1026             b->set_option("proxy", proxy);
1027     }
1028     if (proxy.length())
1029         package.log("zoom", YLOG_LOG, "proxy: %s", proxy.c_str());
1030                 
1031     std::string url;
1032     if (sptr->sru.length())
1033     {
1034         url = "http://" + sptr->target;
1035         b->set_option("sru", sptr->sru);
1036
1037         if (sptr->sru_version.length())
1038             b->set_option("sru_version", sptr->sru_version);
1039     }
1040     else
1041     {
1042         url = sptr->target;
1043     }
1044     if (no_out_args)
1045     {
1046         char *x_args = 0;
1047         out_names[no_out_args] = 0; // terminate list
1048         
1049         yaz_array_to_uri(&x_args, odr, (char **) out_names,
1050                          (char **) out_values);
1051         url += "," + std::string(x_args);
1052     }
1053     package.log("zoom", YLOG_LOG, "url: %s", url.c_str());
1054     b->connect(url, error, addinfo, odr);
1055     if (*error == 0 && !param_nocproxy)
1056         create_content_session(package, b, error, addinfo, odr,
1057                                content_authentication.length() ?
1058                                content_authentication : authentication,
1059                                content_proxy.length() ? content_proxy : proxy);
1060     if (*error == 0)
1061         m_backend = b;
1062     return b;
1063 }
1064
1065 void yf::Zoom::Frontend::prepare_elements(BackendPtr b,
1066                                           Odr_oid *preferredRecordSyntax,
1067                                           const char *element_set_name,
1068                                           bool &enable_pz2_retrieval,
1069                                           bool &enable_pz2_transform,
1070                                           bool &assume_marc8_charset)
1071
1072 {
1073     char oid_name_str[OID_STR_MAX];
1074     const char *syntax_name = 0;
1075     
1076     if (preferredRecordSyntax &&
1077         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
1078         && element_set_name)
1079     {
1080         if (!strcmp(element_set_name, m_p->element_transform.c_str()))
1081         {
1082             enable_pz2_retrieval = true;
1083             enable_pz2_transform = true;
1084         }
1085         else if (!strcmp(element_set_name, m_p->element_raw.c_str()))
1086         {
1087             enable_pz2_retrieval = true;
1088         }
1089     }
1090     
1091     if (enable_pz2_retrieval)
1092     {
1093         std::string configured_request_syntax = b->sptr->request_syntax;
1094         if (configured_request_syntax.length())
1095         {
1096             syntax_name = configured_request_syntax.c_str();
1097             const Odr_oid *syntax_oid = 
1098                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
1099             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
1100                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
1101                 assume_marc8_charset = true;
1102         }
1103     }
1104     else if (preferredRecordSyntax)
1105         syntax_name =
1106             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
1107
1108     if (b->sptr->sru.length())
1109         syntax_name = "XML";
1110
1111     b->set_option("preferredRecordSyntax", syntax_name);
1112
1113     if (enable_pz2_retrieval)
1114     {
1115         element_set_name = 0;
1116         if (b->sptr->element_set.length())
1117             element_set_name = b->sptr->element_set.c_str();
1118     }
1119
1120     b->set_option("elementSetName", element_set_name);
1121     if (b->sptr->sru.length() && element_set_name)
1122         b->set_option("schema", element_set_name);
1123 }
1124
1125 Z_Records *yf::Zoom::Frontend::get_records(Package &package,
1126                                            Odr_int start,
1127                                            Odr_int number_to_present,
1128                                            int *error,
1129                                            char **addinfo,
1130                                            Odr_int *number_of_records_returned,
1131                                            ODR odr,
1132                                            BackendPtr b,
1133                                            Odr_oid *preferredRecordSyntax,
1134                                            const char *element_set_name)
1135 {
1136     *number_of_records_returned = 0;
1137     Z_Records *records = 0;
1138     bool enable_pz2_retrieval = false; // whether target profile is used
1139     bool enable_pz2_transform = false; // whether XSLT is used as well
1140     bool assume_marc8_charset = false;
1141
1142     prepare_elements(b, preferredRecordSyntax,
1143                      element_set_name,
1144                      enable_pz2_retrieval,
1145                      enable_pz2_transform,
1146                      assume_marc8_charset);
1147
1148     package.log("zoom", YLOG_LOG, "pz2_retrieval: %s . pz2_transform: %s",
1149                 enable_pz2_retrieval ? "yes" : "no",
1150                 enable_pz2_transform ? "yes" : "no");
1151
1152     if (start < 0 || number_to_present <=0)
1153         return records;
1154     
1155     if (number_to_present > 10000)
1156         number_to_present = 10000;
1157
1158     ZOOM_record *recs = (ZOOM_record *)
1159         odr_malloc(odr, (size_t) number_to_present * sizeof(*recs));
1160
1161     b->present(start, number_to_present, recs, error, addinfo, odr);
1162
1163     int i = 0;
1164     if (!*error)
1165     {
1166         for (i = 0; i < number_to_present; i++)
1167             if (!recs[i])
1168                 break;
1169     }
1170     if (i > 0)
1171     {  // only return records if no error and at least one record
1172         char *odr_database = odr_strdup(odr,
1173                                         b->m_frontend_database.c_str());
1174         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1175             odr_malloc(odr, sizeof(*npl));
1176         *number_of_records_returned = i;
1177         npl->num_records = i;
1178         npl->records = (Z_NamePlusRecord **)
1179             odr_malloc(odr, i * sizeof(*npl->records));
1180         for (i = 0; i < number_to_present; i++)
1181         {
1182             Z_NamePlusRecord *npr = 0;
1183             const char *addinfo;
1184
1185             package.log("zoom", YLOG_LOG, "Inspecting record at position %d",
1186                         start + i);
1187             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1188                                               &addinfo, 0 /* diagset */);
1189                 
1190             if (sur_error)
1191             {
1192                 log_diagnostic(package, sur_error, addinfo);
1193                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1194                                             addinfo);
1195             }
1196             else if (enable_pz2_retrieval)
1197             {
1198                 char rec_type_str[100];
1199                 const char *record_encoding = 0;
1200
1201                 if (b->sptr->record_encoding.length())
1202                     record_encoding = b->sptr->record_encoding.c_str();
1203                 else if (assume_marc8_charset)
1204                     record_encoding = "marc8";
1205
1206                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1207                 if (record_encoding)
1208                 {
1209                     strcat(rec_type_str, "; charset=");
1210                     strcat(rec_type_str, record_encoding);
1211                 }
1212
1213                 package.log("zoom", YLOG_LOG, "Getting record of type %s",
1214                             rec_type_str);
1215                 int rec_len;
1216                 xmlChar *xmlrec_buf = 0;
1217                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1218                                                       &rec_len);
1219                 if (!rec_buf && !npr)
1220                 {
1221                     std::string addinfo("ZOOM_record_get failed for type ");
1222
1223                     int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1224                     addinfo += rec_type_str;
1225                     log_diagnostic(package, error, addinfo.c_str());
1226                     npr = zget_surrogateDiagRec(odr, odr_database,
1227                                                 error, addinfo.c_str());
1228                 }
1229                 else
1230                 {
1231                     package.log_write(rec_buf, rec_len);
1232                     package.log_write("\r\n", 2);
1233                 }
1234
1235                 if (rec_buf && b->xsp && enable_pz2_transform)
1236                 {
1237                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1238                     if (!rec_doc)
1239                     {
1240                         const char *addinfo = "xml parse failed for record";
1241                         int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1242                         log_diagnostic(package, error, addinfo);
1243                         npr = zget_surrogateDiagRec(
1244                             odr, odr_database, error, addinfo);
1245                     }
1246                     else
1247                     { 
1248                         xmlDoc *rec_res = 
1249                             xsltApplyStylesheet(b->xsp, rec_doc, 0);
1250
1251                         if (rec_res)
1252                         {
1253                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1254                                                    rec_res, b->xsp);
1255                             rec_buf = (const char *) xmlrec_buf;
1256                             package.log("zoom", YLOG_LOG, "xslt successful");
1257                             package.log_write(rec_buf, rec_len);
1258
1259                             xmlFreeDoc(rec_res);
1260                         }
1261                         if (!rec_buf)
1262                         {
1263                             std::string addinfo;
1264                             int error =
1265                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1266
1267                             addinfo = "xslt apply failed for "
1268                                 + b->sptr->transform_xsl_fname;
1269                             log_diagnostic(package, error, addinfo.c_str());
1270                             npr = zget_surrogateDiagRec(
1271                                 odr, odr_database, error, addinfo.c_str());
1272                         }
1273                         xmlFreeDoc(rec_doc);
1274                     }
1275                 }
1276
1277                 if (rec_buf)
1278                 {
1279                     xmlDoc *doc = xmlParseMemory(rec_buf, rec_len);
1280                     std::string res = 
1281                         mp::xml::url_recipe_handle(doc, b->sptr->urlRecipe);
1282                     if (res.length() && b->content_session_id.length())
1283                     {
1284                         size_t off = res.find_first_of("://");
1285                         if (off != std::string::npos)
1286                         {
1287                             char tmp[1024];
1288                             sprintf(tmp, "%s.%s/",
1289                                     b->content_session_id.c_str(),
1290                                     m_p->content_proxy_server.c_str());
1291                             res.insert(off + 3, tmp);
1292                         }
1293                     }
1294                     if (res.length())
1295                     {
1296                         xmlNode *ptr = xmlDocGetRootElement(doc);
1297                         while (ptr && ptr->type != XML_ELEMENT_NODE)
1298                             ptr = ptr->next;
1299                         xmlNode *c = 
1300                             xmlNewChild(ptr, 0, BAD_CAST "metadata", 0);
1301                         xmlNewProp(c, BAD_CAST "type", BAD_CAST
1302                                    "generated-url");
1303                         xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1304                         xmlAddChild(c, t);
1305
1306                         if (xmlrec_buf)
1307                             xmlFree(xmlrec_buf);
1308
1309                         xmlDocDumpMemory(doc, &xmlrec_buf, &rec_len);
1310                         rec_buf = (const char *) xmlrec_buf;
1311                     }
1312                     xmlFreeDoc(doc);
1313                 }
1314                 if (!npr)
1315                 {
1316                     if (!rec_buf)
1317                         npr = zget_surrogateDiagRec(
1318                             odr, odr_database, 
1319                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1320                             rec_type_str);
1321                     else
1322                     {
1323                         npr = (Z_NamePlusRecord *)
1324                             odr_malloc(odr, sizeof(*npr));
1325                         npr->databaseName = odr_database;
1326                         npr->which = Z_NamePlusRecord_databaseRecord;
1327                         npr->u.databaseRecord =
1328                             z_ext_record_xml(odr, rec_buf, rec_len);
1329                     }
1330                 }
1331                 if (xmlrec_buf)
1332                     xmlFree(xmlrec_buf);
1333             }
1334             else
1335             {
1336                 Z_External *ext =
1337                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1338                 if (ext)
1339                 {
1340                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1341                     npr->databaseName = odr_database;
1342                     npr->which = Z_NamePlusRecord_databaseRecord;
1343                     npr->u.databaseRecord = ext;
1344                 }
1345                 else
1346                 {
1347                     npr = zget_surrogateDiagRec(
1348                         odr, odr_database, 
1349                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1350                         "ZOOM_record, type ext");
1351                 }
1352             }
1353             npl->records[i] = npr;
1354         }
1355         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1356         records->which = Z_Records_DBOSD;
1357         records->u.databaseOrSurDiagnostics = npl;
1358     }
1359     return records;
1360 }
1361
1362 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1363                                                     ODR odr)
1364 {
1365     struct cql_node *r = 0;
1366     if (!cn)
1367         return 0;
1368     switch (cn->which)
1369     {
1370     case CQL_NODE_ST:
1371         if (cn->u.st.index)
1372         {
1373             std::map<std::string,std::string>::const_iterator it;
1374             it = fieldmap.find(cn->u.st.index);
1375             if (it == fieldmap.end())
1376                 return cn;
1377             if (it->second.length())
1378                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1379             else
1380                 cn->u.st.index = 0;
1381         }
1382         break;
1383     case CQL_NODE_BOOL:
1384         r = convert_cql_fields(cn->u.boolean.left, odr);
1385         if (!r)
1386             r = convert_cql_fields(cn->u.boolean.right, odr);
1387         break;
1388     case CQL_NODE_SORT:
1389         r = convert_cql_fields(cn->u.sort.search, odr);
1390         break;
1391     }
1392     return r;
1393 }
1394
1395 void yf::Zoom::Frontend::log_diagnostic(mp::Package &package,
1396                                         int error, const char *addinfo)
1397 {
1398     const char *err_msg = yaz_diag_bib1_str(error);
1399     if (addinfo)
1400         package.log("zoom", YLOG_WARN, "Diagnostic %d %s: %s",
1401                     error, err_msg, addinfo);
1402     else
1403         package.log("zoom", YLOG_WARN, "Diagnostic %d %s:",
1404                     error, err_msg);
1405 }
1406
1407 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1408 {
1409     Z_GDU *gdu = package.request().get();
1410     Z_APDU *apdu_req = gdu->u.z3950;
1411     Z_APDU *apdu_res = 0;
1412     mp::odr odr;
1413     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1414     if (sr->num_databaseNames != 1)
1415     {
1416         int error = YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED;
1417         log_diagnostic(package, error, 0);
1418         apdu_res = odr.create_searchResponse(apdu_req, error, 0);
1419         package.response() = apdu_res;
1420         return;
1421     }
1422
1423     int proxy_step = 0;
1424
1425 next_proxy:
1426
1427     int error = 0;
1428     char *addinfo = 0;
1429     std::string db(sr->databaseNames[0]);
1430
1431     BackendPtr b = get_backend_from_databases(package, db, &error,
1432                                               &addinfo, odr, &proxy_step);
1433     if (error && proxy_step)
1434     {
1435         package.log("zoom", YLOG_WARN,
1436                     "create backend failed: trying next proxy");
1437         goto next_proxy;
1438     }
1439     if (error)
1440     {
1441         log_diagnostic(package, error, addinfo);
1442         apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1443         package.response() = apdu_res;
1444         return;
1445     }
1446
1447     b->set_option("setname", "default");
1448
1449     bool enable_pz2_retrieval = false;
1450     bool enable_pz2_transform = false;
1451     bool assume_marc8_charset = false;
1452     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
1453                      enable_pz2_retrieval,
1454                      enable_pz2_transform,
1455                      assume_marc8_charset);
1456
1457     Odr_int hits = 0;
1458     Z_Query *query = sr->query;
1459     WRBUF ccl_wrbuf = 0;
1460     WRBUF pqf_wrbuf = 0;
1461     std::string sortkeys;
1462
1463     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1464     {
1465         // RPN
1466         pqf_wrbuf = wrbuf_alloc();
1467         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1468     }
1469     else if (query->which == Z_Query_type_2)
1470     {
1471         // CCL
1472         ccl_wrbuf = wrbuf_alloc();
1473         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1474                     query->u.type_2->len);
1475     }
1476     else if (query->which == Z_Query_type_104 &&
1477              query->u.type_104->which == Z_External_CQL)
1478     {
1479         // CQL
1480         const char *cql = query->u.type_104->u.cql;
1481         CQL_parser cp = cql_parser_create();
1482         int r = cql_parser_string(cp, cql);
1483         package.log("zoom", YLOG_LOG, "CQL: %s", cql);
1484         if (r)
1485         {
1486             cql_parser_destroy(cp);
1487             error = YAZ_BIB1_MALFORMED_QUERY;
1488             const char *addinfo = "CQL syntax error";
1489             log_diagnostic(package, error, addinfo);
1490             apdu_res = 
1491                 odr.create_searchResponse(apdu_req, error, addinfo);
1492             package.response() = apdu_res;
1493             return;
1494         }
1495         struct cql_node *cn = cql_parser_result(cp);
1496         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1497         if (cn_error)
1498         {
1499             // hopefully we are getting a ptr to a index+relation+term node
1500             error = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1501             addinfo = 0;
1502             if (cn_error->which == CQL_NODE_ST)
1503                 addinfo = cn_error->u.st.index;
1504             
1505             log_diagnostic(package, error, addinfo);
1506             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1507             package.response() = apdu_res;
1508             return;
1509         }
1510         char ccl_buf[1024];
1511
1512         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1513         if (r == 0)
1514         {
1515             ccl_wrbuf = wrbuf_alloc();
1516             wrbuf_puts(ccl_wrbuf, ccl_buf);
1517             
1518             WRBUF sru_sortkeys_wrbuf = wrbuf_alloc();
1519
1520             cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf);
1521             WRBUF sort_spec_wrbuf = wrbuf_alloc();
1522             yaz_srw_sortkeys_to_sort_spec(wrbuf_cstr(sru_sortkeys_wrbuf),
1523                                           sort_spec_wrbuf);
1524             wrbuf_destroy(sru_sortkeys_wrbuf);
1525
1526             yaz_tok_cfg_t tc = yaz_tok_cfg_create();
1527             yaz_tok_parse_t tp =
1528                 yaz_tok_parse_buf(tc, wrbuf_cstr(sort_spec_wrbuf));
1529             yaz_tok_cfg_destroy(tc);
1530
1531             /* go through sortspec and map fields */
1532             int token = yaz_tok_move(tp);
1533             while (token != YAZ_TOK_EOF)
1534             {
1535                 if (token == YAZ_TOK_STRING)
1536                 {
1537                     const char *field = yaz_tok_parse_string(tp);
1538                     std::map<std::string,std::string>::iterator it;
1539                     it = b->sptr->sortmap.find(field);
1540                     if (it != b->sptr->sortmap.end())
1541                         sortkeys += it->second;
1542                     else
1543                         sortkeys += field;
1544                 }
1545                 sortkeys += " ";
1546                 token = yaz_tok_move(tp);
1547                 if (token == YAZ_TOK_STRING)
1548                 {
1549                     sortkeys += yaz_tok_parse_string(tp);
1550                 }
1551                 if (token != YAZ_TOK_EOF)
1552                 {
1553                     sortkeys += " ";
1554                     token = yaz_tok_move(tp);
1555                 }
1556             }
1557             yaz_tok_parse_destroy(tp);
1558             wrbuf_destroy(sort_spec_wrbuf);
1559         }
1560         cql_parser_destroy(cp);
1561         if (r)
1562         {
1563             error = YAZ_BIB1_MALFORMED_QUERY;
1564             const char *addinfo = "CQL to CCL conversion error";
1565
1566             log_diagnostic(package, error, addinfo);
1567             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1568             package.response() = apdu_res;
1569             return;
1570         }
1571     }
1572     else
1573     {
1574         error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
1575         const char *addinfo = 0;
1576         log_diagnostic(package, error, addinfo);
1577         apdu_res =  odr.create_searchResponse(apdu_req, error, addinfo);
1578         package.response() = apdu_res;
1579         return;
1580     }
1581
1582     if (ccl_wrbuf)
1583     {
1584         // CCL to PQF
1585         assert(pqf_wrbuf == 0);
1586         int cerror, cpos;
1587         struct ccl_rpn_node *cn;
1588         package.log("zoom", YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1589         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1590                           &cerror, &cpos);
1591         wrbuf_destroy(ccl_wrbuf);
1592         if (!cn)
1593         {
1594             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1595             error = YAZ_BIB1_MALFORMED_QUERY;
1596
1597             switch (cerror)
1598             {
1599             case CCL_ERR_UNKNOWN_QUAL:
1600                 error = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1601                 break;
1602             case CCL_ERR_TRUNC_NOT_LEFT: 
1603             case CCL_ERR_TRUNC_NOT_RIGHT:
1604             case CCL_ERR_TRUNC_NOT_BOTH:
1605                 error = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
1606                 break;
1607             }
1608             log_diagnostic(package, error, addinfo);
1609             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1610             package.response() = apdu_res;
1611             return;
1612         }
1613         pqf_wrbuf = wrbuf_alloc();
1614         ccl_pquery(pqf_wrbuf, cn);
1615         package.log("zoom", YLOG_LOG, "RPN: %s", wrbuf_cstr(pqf_wrbuf));
1616         ccl_rpn_delete(cn);
1617     }
1618     
1619     assert(pqf_wrbuf);
1620
1621     ZOOM_query q = ZOOM_query_create();
1622     ZOOM_query_sortby2(q, b->sptr->sortStrategy.c_str(), sortkeys.c_str());
1623
1624     if (b->get_option("sru"))
1625     {
1626         int status = 0;
1627         Z_RPNQuery *zquery;
1628         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1629         WRBUF wrb = wrbuf_alloc();
1630             
1631         if (!strcmp(b->get_option("sru"), "solr"))
1632         {
1633             solr_transform_t cqlt = solr_transform_create();
1634             
1635             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1636             
1637             solr_transform_close(cqlt);
1638         }
1639         else
1640         {
1641             cql_transform_t cqlt = cql_transform_create();
1642             
1643             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1644             
1645             cql_transform_close(cqlt);
1646         }
1647         if (status == 0)
1648         {
1649             ZOOM_query_cql(q, wrbuf_cstr(wrb));
1650             package.log("zoom", YLOG_LOG, "CQL: %s", wrbuf_cstr(wrb));
1651             b->search(q, &hits, &error, &addinfo, odr);
1652         }
1653         ZOOM_query_destroy(q);
1654         
1655         wrbuf_destroy(wrb);
1656         wrbuf_destroy(pqf_wrbuf);
1657         if (status)
1658         {
1659             error = YAZ_BIB1_MALFORMED_QUERY;
1660             const char *addinfo = "can not convert from RPN to CQL/SOLR";
1661             log_diagnostic(package, error, addinfo);
1662             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1663             package.response() = apdu_res;
1664             return;
1665         }
1666     }
1667     else
1668     {
1669         ZOOM_query_prefix(q, wrbuf_cstr(pqf_wrbuf));
1670         package.log("zoom", YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1671         b->search(q, &hits, &error, &addinfo, odr);
1672         ZOOM_query_destroy(q);
1673         wrbuf_destroy(pqf_wrbuf);
1674     }
1675
1676     if (error && proxy_step)
1677     {
1678         // reset below prevent reuse in get_backend_from_databases
1679         m_backend.reset();
1680         package.log("zoom", YLOG_WARN, "search failed: trying next proxy");
1681         goto next_proxy;
1682     }
1683
1684     const char *element_set_name = 0;
1685     Odr_int number_to_present = 0;
1686     if (!error)
1687         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1688     
1689     Odr_int number_of_records_returned = 0;
1690     Z_Records *records = get_records(
1691         package,
1692         0, number_to_present, &error, &addinfo,
1693         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1694         element_set_name);
1695     if (error)
1696         log_diagnostic(package, error, addinfo);
1697     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1698     if (records)
1699     {
1700         apdu_res->u.searchResponse->records = records;
1701         apdu_res->u.searchResponse->numberOfRecordsReturned =
1702             odr_intdup(odr, number_of_records_returned);
1703     }
1704     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1705     package.response() = apdu_res;
1706 }
1707
1708 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1709 {
1710     Z_GDU *gdu = package.request().get();
1711     Z_APDU *apdu_req = gdu->u.z3950;
1712     Z_APDU *apdu_res = 0;
1713     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1714
1715     mp::odr odr;
1716     if (!m_backend)
1717     {
1718         package.response() = odr.create_presentResponse(
1719             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1720         return;
1721     }
1722     const char *element_set_name = 0;
1723     Z_RecordComposition *comp = pr->recordComposition;
1724     if (comp && comp->which != Z_RecordComp_simple)
1725     {
1726         package.response() = odr.create_presentResponse(
1727             apdu_req, 
1728             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1729         return;
1730     }
1731     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1732         element_set_name = comp->u.simple->u.generic;
1733     Odr_int number_of_records_returned = 0;
1734     int error = 0;
1735     char *addinfo = 0;
1736     Z_Records *records = get_records(package,
1737         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1738         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1739         pr->preferredRecordSyntax, element_set_name);
1740
1741     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1742     if (records)
1743     {
1744         apdu_res->u.presentResponse->records = records;
1745         apdu_res->u.presentResponse->numberOfRecordsReturned =
1746             odr_intdup(odr, number_of_records_returned);
1747     }
1748     package.response() = apdu_res;
1749 }
1750
1751 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1752 {
1753     Z_GDU *gdu = package.request().get();
1754     if (!gdu)
1755         ;
1756     else if (gdu->which == Z_GDU_Z3950)
1757     {
1758         Z_APDU *apdu_req = gdu->u.z3950;
1759
1760         if (m_backend)
1761             wrbuf_rewind(m_backend->m_apdu_wrbuf);
1762         if (apdu_req->which == Z_APDU_initRequest)
1763         {
1764             mp::odr odr;
1765             package.response() = odr.create_close(
1766                 apdu_req,
1767                 Z_Close_protocolError,
1768                 "double init");
1769         }
1770         else if (apdu_req->which == Z_APDU_searchRequest)
1771         {
1772             handle_search(package);
1773         }
1774         else if (apdu_req->which == Z_APDU_presentRequest)
1775         {
1776             handle_present(package);
1777         }
1778         else
1779         {
1780             mp::odr odr;
1781             package.response() = odr.create_close(
1782                 apdu_req,
1783                 Z_Close_protocolError,
1784                 "zoom filter cannot handle this APDU");
1785             package.session().close();
1786         }
1787         if (m_backend)
1788         {
1789             WRBUF w = m_backend->m_apdu_wrbuf;
1790             package.log_write(wrbuf_buf(w), wrbuf_len(w));
1791         }
1792     }
1793     else
1794     {
1795         package.session().close();
1796     }
1797 }
1798
1799 void yf::Zoom::Impl::process(mp::Package &package)
1800 {
1801     FrontendPtr f = get_frontend(package);
1802     Z_GDU *gdu = package.request().get();
1803
1804     if (f->m_is_virtual)
1805     {
1806         f->handle_package(package);
1807     }
1808     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1809              Z_APDU_initRequest)
1810     {
1811         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1812         f->m_init_gdu = gdu;
1813         
1814         mp::odr odr;
1815         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1816         Z_InitResponse *resp = apdu->u.initResponse;
1817         
1818         int i;
1819         static const int masks[] = {
1820             Z_Options_search,
1821             Z_Options_present,
1822             -1 
1823         };
1824         for (i = 0; masks[i] != -1; i++)
1825             if (ODR_MASK_GET(req->options, masks[i]))
1826                 ODR_MASK_SET(resp->options, masks[i]);
1827         
1828         static const int versions[] = {
1829             Z_ProtocolVersion_1,
1830             Z_ProtocolVersion_2,
1831             Z_ProtocolVersion_3,
1832             -1
1833         };
1834         for (i = 0; versions[i] != -1; i++)
1835             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1836                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1837             else
1838                 break;
1839         
1840         *resp->preferredMessageSize = *req->preferredMessageSize;
1841         *resp->maximumRecordSize = *req->maximumRecordSize;
1842         
1843         package.response() = apdu;
1844         f->m_is_virtual = true;
1845     }
1846     else
1847         package.move();
1848
1849     release_frontend(package);
1850 }
1851
1852
1853 static mp::filter::Base* filter_creator()
1854 {
1855     return new mp::filter::Zoom;
1856 }
1857
1858 extern "C" {
1859     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1860         0,
1861         "zoom",
1862         filter_creator
1863     };
1864 }
1865
1866
1867 /*
1868  * Local variables:
1869  * c-basic-offset: 4
1870  * c-file-style: "Stroustrup"
1871  * indent-tabs-mode: nil
1872  * End:
1873  * vim: shiftwidth=4 tabstop=8 expandtab
1874  */
1875