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