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