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