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