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