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