zoom: log diagnostics and records as they pass
[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     *error = ZOOM_connection_error_x(m_connection, &msg, &zoom_addinfo, &dset);
239     if (*error)
240     {
241         if (*error >= ZOOM_ERROR_CONNECT)
242         {
243             // turn ZOOM diagnostic into a Bib-1 2: with addinfo=zoom err msg
244             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
245             *addinfo = (char *) odr_malloc(
246                 odr, 20 + strlen(msg) + 
247                 (zoom_addinfo ? strlen(zoom_addinfo) : 0));
248             strcpy(*addinfo, msg);
249             if (zoom_addinfo)
250             {
251                 strcat(*addinfo, ": ");
252                 strcat(*addinfo, zoom_addinfo);
253             }
254         }
255         else
256         {
257             if (dset && !strcmp(dset, "info:srw/diagnostic/1"))
258                 *error = yaz_diag_srw_to_bib1(*error);
259             *addinfo = (char *) odr_malloc(
260                 odr, 20 + (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             strcat(*addinfo, "(backend)");
268         }
269     }
270 }
271
272 void yf::Zoom::Backend::connect(std::string zurl,
273                                 int *error, char **addinfo,
274                                 ODR odr)
275 {
276     ZOOM_connection_connect(m_connection, zurl.c_str(), 0);
277     get_zoom_error(error, addinfo, odr);
278 }
279
280 void yf::Zoom::Backend::search(ZOOM_query q, Odr_int *hits,
281                                int *error, char **addinfo, ODR odr)
282 {
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_url = mp::xml::get_text(attr->children);
583                 else if (!strcmp((const char *) attr->name, "realm"))
584                     default_realm = mp::xml::get_text(attr->children);
585                 else if (!strcmp((const char *) attr->name, "xsldir"))
586                     xsldir = mp::xml::get_text(attr->children);
587                 else if (!strcmp((const char *) attr->name, "element_transform"))
588                     element_transform = mp::xml::get_text(attr->children);
589                 else if (!strcmp((const char *) attr->name, "element_raw"))
590                     element_raw = mp::xml::get_text(attr->children);
591                 else if (!strcmp((const char *) attr->name, "proxy"))
592                     proxy = mp::xml::get_text(attr->children);
593                 else
594                     throw mp::filter::FilterException(
595                         "Bad attribute " + std::string((const char *)
596                                                        attr->name));
597             }
598             configure_local_records(ptr->children, test_only);
599         }
600         else if (!strcmp((const char *) ptr->name, "cclmap"))
601         {
602             const char *addinfo = 0;
603             ccl_xml_config(bibset, ptr, &addinfo);
604         }
605         else if (!strcmp((const char *) ptr->name, "fieldmap"))
606         {
607             const struct _xmlAttr *attr;
608             std::string ccl_field;
609             std::string cql_field;
610             for (attr = ptr->properties; attr; attr = attr->next)
611             {
612                 if (!strcmp((const char *) attr->name, "ccl"))
613                     ccl_field = mp::xml::get_text(attr->children);
614                 else if (!strcmp((const char *) attr->name, "cql"))
615                     cql_field = mp::xml::get_text(attr->children);
616                 else
617                     throw mp::filter::FilterException(
618                         "Bad attribute " + std::string((const char *)
619                                                        attr->name));
620             }
621             if (cql_field.length())
622                 fieldmap[cql_field] = ccl_field;
623         }
624         else if (!strcmp((const char *) ptr->name, "contentProxy"))
625         {
626             const struct _xmlAttr *attr;
627             for (attr = ptr->properties; attr; attr = attr->next)
628             {
629                 if (!strcmp((const char *) attr->name, "server"))
630                     content_proxy_server = mp::xml::get_text(attr->children);
631                 else if (!strcmp((const char *) attr->name, "tmp_file"))
632                     content_tmp_file = mp::xml::get_text(attr->children);
633                 else
634                     throw mp::filter::FilterException(
635                         "Bad attribute " + std::string((const char *)
636                                                        attr->name));
637             }
638         }
639         else if (!strcmp((const char *) ptr->name, "log"))
640         { 
641             const struct _xmlAttr *attr;
642             for (attr = ptr->properties; attr; attr = attr->next)
643             {
644                 if (!strcmp((const char *) attr->name, "apdu"))
645                     apdu_log = mp::xml::get_bool(attr->children, false);
646                 else
647                     throw mp::filter::FilterException(
648                         "Bad attribute " + std::string((const char *)
649                                                        attr->name));
650             }
651         }
652         else
653         {
654             throw mp::filter::FilterException
655                 ("Bad element " 
656                  + std::string((const char *) ptr->name)
657                  + " in zoom filter");
658         }
659     }
660 }
661
662 bool yf::Zoom::Frontend::create_content_session(mp::Package &package,
663                                                 BackendPtr b,
664                                                 int *error, char **addinfo,
665                                                 ODR odr,
666                                                 std::string authentication,
667                                                 std::string proxy)
668 {
669     if (b->sptr->contentConnector.length())
670     {
671         char *fname = (char *) xmalloc(m_p->content_tmp_file.length() + 8);
672         strcpy(fname, m_p->content_tmp_file.c_str());
673         char *xx = strstr(fname, "XXXXXX");
674         if (!xx)
675         {
676             xx = fname + strlen(fname);
677             strcat(fname, "XXXXXX");
678         }
679         char tmp_char = xx[6];
680         sprintf(xx, "%06d", ((unsigned) rand()) % 1000000);
681         xx[6] = tmp_char;
682
683         FILE *file = fopen(fname, "w");
684         if (!file)
685         {
686             package.log("zoom", YLOG_WARN|YLOG_ERRNO, "create %s", fname);
687             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
688             *addinfo = (char *)  odr_malloc(odr, 40 + strlen(fname));
689             sprintf(*addinfo, "Could not create %s", fname);
690             xfree(fname);
691             return false;
692         }
693         b->content_session_id.assign(xx, 6);
694         WRBUF w = wrbuf_alloc();
695         wrbuf_puts(w, "#content_proxy\n");
696         wrbuf_printf(w, "connector: %s\n", b->sptr->contentConnector.c_str());
697         if (authentication.length())
698             wrbuf_printf(w, "auth: %s\n", authentication.c_str());
699         if (proxy.length())
700             wrbuf_printf(w, "proxy: %s\n", proxy.c_str());
701
702         fwrite(wrbuf_buf(w), 1, wrbuf_len(w), file);
703         fclose(file);
704         package.log("zoom", YLOG_LOG, "content file: %s", fname);
705         xfree(fname);
706     }
707     return true;
708 }
709
710 yf::Zoom::BackendPtr yf::Zoom::Frontend::get_backend_from_databases(
711     mp::Package &package,
712     std::string &database, int *error, char **addinfo, ODR odr)
713 {
714     std::list<BackendPtr>::const_iterator map_it;
715     if (m_backend && m_backend->m_frontend_database == database)
716         return m_backend;
717
718     std::string input_args;
719     std::string torus_db;
720     size_t db_arg_pos = database.find(',');
721     if (db_arg_pos != std::string::npos)
722     {
723         torus_db = database.substr(0, db_arg_pos);
724         input_args = database.substr(db_arg_pos + 1);
725     }
726     else
727         torus_db = database;
728
729     std::string authentication;
730     std::string content_authentication;
731     std::string proxy;
732     std::string realm = m_p->default_realm;
733
734     const char *param_user = 0;
735     const char *param_password = 0;
736     const char *param_content_user = 0;
737     const char *param_content_password = 0;
738     int no_parms = 0;
739
740     char **names;
741     char **values;
742     int no_out_args = 0;
743     if (input_args.length())
744         no_parms = yaz_uri_to_array(input_args.c_str(),
745                                     odr, &names, &values);
746     // adding 10 because we'll be adding other URL args
747     const char **out_names = (const char **)
748         odr_malloc(odr, (10 + no_parms) * sizeof(*out_names));
749     const char **out_values = (const char **)
750         odr_malloc(odr, (10 + no_parms) * sizeof(*out_values));
751     
752     int i;
753     for (i = 0; i < no_parms; i++)
754     {
755         const char *name = names[i];
756         const char *value = values[i];
757         assert(name);
758         assert(value);
759         if (!strcmp(name, "user"))
760             param_user = value;
761         else if (!strcmp(name, "password"))
762             param_password = value;
763         else if (!strcmp(name, "content-user"))
764             param_content_user = value;
765         else if (!strcmp(name, "content-password"))
766             param_content_password = value;
767         else if (!strcmp(name, "proxy"))
768             proxy = value;
769         else if (!strcmp(name, "cproxysession"))
770         {
771             out_names[no_out_args] = name;
772             out_values[no_out_args++] = value;
773         }
774         else if (!strcmp(name, "realm"))
775             realm = value;
776         else if (name[0] == 'x' && name[1] == '-')
777         {
778             out_names[no_out_args] = name;
779             out_values[no_out_args++] = value;
780         }
781         else
782         {
783             BackendPtr notfound;
784             char *msg = (char*) odr_malloc(odr, strlen(name) + 30);
785             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
786             sprintf(msg, "Bad database argument: %s", name);
787             *addinfo = msg;
788             return notfound;
789         }
790     }
791     if (param_user)
792     {
793         authentication = std::string(param_user);
794         if (param_password)
795             authentication += "/" + std::string(param_password);
796     }
797     if (param_content_user)
798     {
799         content_authentication = std::string(param_content_user);
800         if (param_content_password)
801             content_authentication += "/" + std::string(param_content_password);
802     }
803     SearchablePtr sptr;
804
805     std::map<std::string,SearchablePtr>::iterator it;
806     it = m_p->s_map.find(torus_db);
807     if (it != m_p->s_map.end())
808         sptr = it->second;
809     else if (m_p->torus_url.length() > 0)
810     {
811         xmlDoc *doc = mp::get_searchable(package,
812                                          m_p->torus_url, torus_db, realm,
813                                          m_p->proxy);
814         if (!doc)
815         {
816             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
817             *addinfo = odr_strdup(odr, database.c_str());
818             BackendPtr b;
819             return b;
820         }
821         const xmlNode *ptr = xmlDocGetRootElement(doc);
822         if (ptr)
823         {   // presumably ptr is a records element node
824             // parse first record in document
825             for (ptr = ptr->children; ptr; ptr = ptr->next)
826             {
827                 if (ptr->type == XML_ELEMENT_NODE
828                     && !strcmp((const char *) ptr->name, "record"))
829                 {
830                     if (sptr)
831                     {
832                         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
833                         *addinfo = (char*) odr_malloc(odr, 40 + database.length()),
834                         sprintf(*addinfo, "multiple records for udb=%s",
835                                  database.c_str());
836                         xmlFreeDoc(doc);
837                         BackendPtr b;
838                         return b;
839                     }
840                     sptr = m_p->parse_torus_record(ptr);
841                 }
842             }
843         }
844         xmlFreeDoc(doc);
845     }
846
847     if (!sptr)
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         
855     xsltStylesheetPtr xsp = 0;
856     if (sptr->transform_xsl_content.length())
857     {
858         xmlDoc *xsp_doc = xmlParseMemory(sptr->transform_xsl_content.c_str(),
859                                          sptr->transform_xsl_content.length());
860         if (!xsp_doc)
861         {
862             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
863             *addinfo = (char *) odr_malloc(odr, 40);
864             sprintf(*addinfo, "xmlParseMemory failed");
865             BackendPtr b;
866             return b;
867         }
868         xsp = xsltParseStylesheetDoc(xsp_doc);
869         if (!xsp)
870         {
871             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
872             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
873             BackendPtr b;
874             xmlFreeDoc(xsp_doc);
875             return b;
876         }
877     }
878     else if (sptr->transform_xsl_fname.length())
879     {
880         const char *path = 0;
881
882         if (m_p->xsldir.length())
883             path = m_p->xsldir.c_str();
884         else
885             path = m_p->file_path.c_str();
886         std::string fname;
887
888         char fullpath[1024];
889         char *cp = yaz_filepath_resolve(sptr->transform_xsl_fname.c_str(),
890                                         path, 0, fullpath);
891         if (cp)
892             fname.assign(cp);
893         else
894         {
895             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
896             *addinfo = (char *)
897                 odr_malloc(odr, 40 + sptr->transform_xsl_fname.length());
898             sprintf(*addinfo, "File could not be read: %s", 
899                     sptr->transform_xsl_fname.c_str());
900             BackendPtr b;
901             return b;
902         }
903         xmlDoc *xsp_doc = xmlParseFile(fname.c_str());
904         if (!xsp_doc)
905         {
906             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
907             *addinfo = (char *) odr_malloc(odr, 40 + fname.length());
908             sprintf(*addinfo, "xmlParseFile failed. File: %s", fname.c_str());
909             BackendPtr b;
910             return b;
911         }
912         xsp = xsltParseStylesheetDoc(xsp_doc);
913         if (!xsp)
914         {
915             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
916             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
917             BackendPtr b;
918             xmlFreeDoc(xsp_doc);
919             return b;
920         }
921     }
922
923     m_backend.reset();
924
925     BackendPtr b(new Backend(sptr));
926
927     b->xsp = xsp;
928     b->m_frontend_database = database;
929
930     if (sptr->query_encoding.length())
931         b->set_option("rpnCharset", sptr->query_encoding);
932
933     b->set_option("timeout", "40");
934     
935     if (m_p->apdu_log) 
936         b->set_option("apdulog", "1");
937
938     if (sptr->piggyback && sptr->sru.length())
939         b->set_option("count", "1"); /* some SRU servers INSIST on getting
940                                         maximumRecords > 0 */
941     b->set_option("piggyback", sptr->piggyback ? "1" : "0");
942
943     if (authentication.length() == 0)
944         authentication = sptr->authentication;
945
946     if (proxy.length() == 0)
947         proxy = sptr->cfProxy;
948     
949     if (sptr->cfAuth.length())
950     {
951         // A CF target
952         b->set_option("user", sptr->cfAuth);
953         if (authentication.length())
954         {
955             size_t found = authentication.find('/');
956             if (found != std::string::npos)
957             {
958                 out_names[no_out_args] = "user";
959                 out_values[no_out_args++] =
960                     odr_strdup(odr, authentication.substr(0, found).c_str());
961
962                 out_names[no_out_args] = "password";
963                 out_values[no_out_args++] =
964                     odr_strdup(odr, authentication.substr(found+1).c_str());
965             }
966             else
967             {
968                 out_names[no_out_args] = "user";
969                 out_values[no_out_args++] =
970                     odr_strdup(odr, authentication.c_str());
971             }                
972         }
973         if (proxy.length())
974         {
975             out_names[no_out_args] = "proxy";
976             out_values[no_out_args++] = odr_strdup(odr, proxy.c_str());
977         }
978         if (sptr->cfSubDB.length())
979         {
980             out_names[no_out_args] = "subdatabase";
981             out_values[no_out_args++] = odr_strdup(odr, sptr->cfSubDB.c_str());
982         }
983     }
984     else
985     {
986         size_t found = authentication.find('/');
987         
988         if (sptr->sru.length() && found != std::string::npos)
989         {
990             b->set_option("user", authentication.substr(0, found));
991             b->set_option("password", authentication.substr(found+1));
992         }
993         else
994             b->set_option("user", authentication);
995
996         if (proxy.length())
997             b->set_option("proxy", proxy);
998     }
999     std::string url;
1000     if (sptr->sru.length())
1001     {
1002         url = "http://" + sptr->target;
1003         b->set_option("sru", sptr->sru);
1004
1005         if (sptr->sru_version.length())
1006             b->set_option("sru_version", sptr->sru_version);
1007     }
1008     else
1009     {
1010         url = sptr->target;
1011     }
1012     if (no_out_args)
1013     {
1014         char *x_args = 0;
1015         out_names[no_out_args] = 0; // terminate list
1016         
1017         yaz_array_to_uri(&x_args, odr, (char **) out_names,
1018                          (char **) out_values);
1019         url += "," + std::string(x_args);
1020     }
1021     package.log("zoom", YLOG_LOG, "url: %s", url.c_str());
1022     b->connect(url, error, addinfo, odr);
1023     if (*error == 0)
1024         create_content_session(package, b, error, addinfo, odr,
1025                                content_authentication.length() ?
1026                                content_authentication : authentication, proxy);
1027     if (*error == 0)
1028         m_backend = b;
1029     return b;
1030 }
1031
1032 void yf::Zoom::Frontend::prepare_elements(BackendPtr b,
1033                                           Odr_oid *preferredRecordSyntax,
1034                                           const char *element_set_name,
1035                                           bool &enable_pz2_retrieval,
1036                                           bool &enable_pz2_transform,
1037                                           bool &assume_marc8_charset)
1038
1039 {
1040     char oid_name_str[OID_STR_MAX];
1041     const char *syntax_name = 0;
1042     
1043     if (preferredRecordSyntax &&
1044         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
1045         && element_set_name)
1046     {
1047         if (!strcmp(element_set_name, m_p->element_transform.c_str()))
1048         {
1049             enable_pz2_retrieval = true;
1050             enable_pz2_transform = true;
1051         }
1052         else if (!strcmp(element_set_name, m_p->element_raw.c_str()))
1053         {
1054             enable_pz2_retrieval = true;
1055         }
1056     }
1057     
1058     if (enable_pz2_retrieval)
1059     {
1060         std::string configured_request_syntax = b->sptr->request_syntax;
1061         if (configured_request_syntax.length())
1062         {
1063             syntax_name = configured_request_syntax.c_str();
1064             const Odr_oid *syntax_oid = 
1065                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
1066             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
1067                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
1068                 assume_marc8_charset = true;
1069         }
1070     }
1071     else if (preferredRecordSyntax)
1072         syntax_name =
1073             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
1074
1075     if (b->sptr->sru.length())
1076         syntax_name = "XML";
1077
1078     b->set_option("preferredRecordSyntax", syntax_name);
1079
1080     if (enable_pz2_retrieval)
1081     {
1082         element_set_name = 0;
1083         if (b->sptr->element_set.length())
1084             element_set_name = b->sptr->element_set.c_str();
1085     }
1086
1087     b->set_option("elementSetName", element_set_name);
1088     if (b->sptr->sru.length() && element_set_name)
1089         b->set_option("schema", element_set_name);
1090 }
1091
1092 Z_Records *yf::Zoom::Frontend::get_records(Package &package,
1093                                            Odr_int start,
1094                                            Odr_int number_to_present,
1095                                            int *error,
1096                                            char **addinfo,
1097                                            Odr_int *number_of_records_returned,
1098                                            ODR odr,
1099                                            BackendPtr b,
1100                                            Odr_oid *preferredRecordSyntax,
1101                                            const char *element_set_name)
1102 {
1103     *number_of_records_returned = 0;
1104     Z_Records *records = 0;
1105     bool enable_pz2_retrieval = false; // whether target profile is used
1106     bool enable_pz2_transform = false; // whether XSLT is used as well
1107     bool assume_marc8_charset = false;
1108
1109     prepare_elements(b, preferredRecordSyntax,
1110                      element_set_name,
1111                      enable_pz2_retrieval,
1112                      enable_pz2_transform,
1113                      assume_marc8_charset);
1114
1115     package.log("zoom", YLOG_LOG, "pz2_retrieval: %s . pz2_transform: %s",
1116                 enable_pz2_retrieval ? "yes" : "no",
1117                 enable_pz2_transform ? "yes" : "no");
1118
1119     if (start < 0 || number_to_present <=0)
1120         return records;
1121     
1122     if (number_to_present > 10000)
1123         number_to_present = 10000;
1124
1125     ZOOM_record *recs = (ZOOM_record *)
1126         odr_malloc(odr, (size_t) number_to_present * sizeof(*recs));
1127
1128     b->present(start, number_to_present, recs, error, addinfo, odr);
1129
1130     int i = 0;
1131     if (!*error)
1132     {
1133         for (i = 0; i < number_to_present; i++)
1134             if (!recs[i])
1135                 break;
1136     }
1137     if (i > 0)
1138     {  // only return records if no error and at least one record
1139         char *odr_database = odr_strdup(odr,
1140                                         b->m_frontend_database.c_str());
1141         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1142             odr_malloc(odr, sizeof(*npl));
1143         *number_of_records_returned = i;
1144         npl->num_records = i;
1145         npl->records = (Z_NamePlusRecord **)
1146             odr_malloc(odr, i * sizeof(*npl->records));
1147         for (i = 0; i < number_to_present; i++)
1148         {
1149             Z_NamePlusRecord *npr = 0;
1150             const char *addinfo;
1151
1152             package.log("zoom", YLOG_LOG, "Inspecting record at position %d",
1153                         start + i);
1154             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1155                                               &addinfo, 0 /* diagset */);
1156                 
1157             if (sur_error)
1158             {
1159                 log_diagnostic(package, sur_error, addinfo);
1160                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1161                                             addinfo);
1162             }
1163             else if (enable_pz2_retrieval)
1164             {
1165                 char rec_type_str[100];
1166                 const char *record_encoding = 0;
1167
1168                 if (b->sptr->record_encoding.length())
1169                     record_encoding = b->sptr->record_encoding.c_str();
1170                 else if (assume_marc8_charset)
1171                     record_encoding = "marc8";
1172
1173                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1174                 if (record_encoding)
1175                 {
1176                     strcat(rec_type_str, "; charset=");
1177                     strcat(rec_type_str, record_encoding);
1178                 }
1179
1180                 package.log("zoom", YLOG_LOG, "Getting record of type %s",
1181                             rec_type_str);
1182                 int rec_len;
1183                 xmlChar *xmlrec_buf = 0;
1184                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1185                                                       &rec_len);
1186                 if (!rec_buf && !npr)
1187                 {
1188                     std::string addinfo("ZOOM_record_get failed for type ");
1189
1190                     int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1191                     addinfo += rec_type_str;
1192                     log_diagnostic(package, error, addinfo.c_str());
1193                     npr = zget_surrogateDiagRec(odr, odr_database,
1194                                                 error, addinfo.c_str());
1195                 }
1196                 else
1197                 {
1198                     package.log_write(rec_buf, rec_len);
1199                     package.log_write("\r\n", 2);
1200                 }
1201
1202                 if (rec_buf && b->xsp && enable_pz2_transform)
1203                 {
1204                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1205                     if (!rec_doc)
1206                     {
1207                         const char *addinfo = "xml parse failed for record";
1208                         int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1209                         log_diagnostic(package, error, addinfo);
1210                         npr = zget_surrogateDiagRec(
1211                             odr, odr_database, error, addinfo);
1212                     }
1213                     else
1214                     { 
1215                         xmlDoc *rec_res = 
1216                             xsltApplyStylesheet(b->xsp, rec_doc, 0);
1217
1218                         if (rec_res)
1219                         {
1220                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1221                                                    rec_res, b->xsp);
1222                             rec_buf = (const char *) xmlrec_buf;
1223                             package.log("zoom", YLOG_LOG, "xslt successful");
1224                             package.log_write(rec_buf, rec_len);
1225
1226                             xmlFreeDoc(rec_res);
1227                         }
1228                         if (!rec_buf)
1229                         {
1230                             std::string addinfo;
1231                             int error =
1232                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1233
1234                             addinfo = "xslt apply failed for "
1235                                 + b->sptr->transform_xsl_fname;
1236                             log_diagnostic(package, error, addinfo.c_str());
1237                             npr = zget_surrogateDiagRec(
1238                                 odr, odr_database, error, addinfo.c_str());
1239                         }
1240                         xmlFreeDoc(rec_doc);
1241                     }
1242                 }
1243
1244                 if (rec_buf)
1245                 {
1246                     xmlDoc *doc = xmlParseMemory(rec_buf, rec_len);
1247                     std::string res = 
1248                         mp::xml::url_recipe_handle(doc, b->sptr->urlRecipe);
1249                     if (res.length() && b->content_session_id.length())
1250                     {
1251                         size_t off = res.find_first_of("://");
1252                         if (off != std::string::npos)
1253                         {
1254                             char tmp[1024];
1255                             sprintf(tmp, "%s.%s/",
1256                                     b->content_session_id.c_str(),
1257                                     m_p->content_proxy_server.c_str());
1258                             res.insert(off + 3, tmp);
1259                         }
1260                     }
1261                     if (res.length())
1262                     {
1263                         xmlNode *ptr = xmlDocGetRootElement(doc);
1264                         while (ptr && ptr->type != XML_ELEMENT_NODE)
1265                             ptr = ptr->next;
1266                         xmlNode *c = 
1267                             xmlNewChild(ptr, 0, BAD_CAST "metadata", 0);
1268                         xmlNewProp(c, BAD_CAST "type", BAD_CAST
1269                                    "generated-url");
1270                         xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1271                         xmlAddChild(c, t);
1272
1273                         if (xmlrec_buf)
1274                             xmlFree(xmlrec_buf);
1275
1276                         xmlDocDumpMemory(doc, &xmlrec_buf, &rec_len);
1277                         rec_buf = (const char *) xmlrec_buf;
1278                     }
1279                     xmlFreeDoc(doc);
1280                 }
1281                 if (!npr)
1282                 {
1283                     if (!rec_buf)
1284                         npr = zget_surrogateDiagRec(
1285                             odr, odr_database, 
1286                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1287                             rec_type_str);
1288                     else
1289                     {
1290                         npr = (Z_NamePlusRecord *)
1291                             odr_malloc(odr, sizeof(*npr));
1292                         npr->databaseName = odr_database;
1293                         npr->which = Z_NamePlusRecord_databaseRecord;
1294                         npr->u.databaseRecord =
1295                             z_ext_record_xml(odr, rec_buf, rec_len);
1296                     }
1297                 }
1298                 if (xmlrec_buf)
1299                     xmlFree(xmlrec_buf);
1300             }
1301             else
1302             {
1303                 Z_External *ext =
1304                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1305                 if (ext)
1306                 {
1307                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1308                     npr->databaseName = odr_database;
1309                     npr->which = Z_NamePlusRecord_databaseRecord;
1310                     npr->u.databaseRecord = ext;
1311                 }
1312                 else
1313                 {
1314                     npr = zget_surrogateDiagRec(
1315                         odr, odr_database, 
1316                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1317                         "ZOOM_record, type ext");
1318                 }
1319             }
1320             npl->records[i] = npr;
1321         }
1322         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1323         records->which = Z_Records_DBOSD;
1324         records->u.databaseOrSurDiagnostics = npl;
1325     }
1326     return records;
1327 }
1328
1329 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1330                                                     ODR odr)
1331 {
1332     struct cql_node *r = 0;
1333     if (!cn)
1334         return 0;
1335     switch (cn->which)
1336     {
1337     case CQL_NODE_ST:
1338         if (cn->u.st.index)
1339         {
1340             std::map<std::string,std::string>::const_iterator it;
1341             it = fieldmap.find(cn->u.st.index);
1342             if (it == fieldmap.end())
1343                 return cn;
1344             if (it->second.length())
1345                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1346             else
1347                 cn->u.st.index = 0;
1348         }
1349         break;
1350     case CQL_NODE_BOOL:
1351         r = convert_cql_fields(cn->u.boolean.left, odr);
1352         if (!r)
1353             r = convert_cql_fields(cn->u.boolean.right, odr);
1354         break;
1355     case CQL_NODE_SORT:
1356         r = convert_cql_fields(cn->u.sort.search, odr);
1357         break;
1358     }
1359     return r;
1360 }
1361
1362 void yf::Zoom::Frontend::log_diagnostic(mp::Package &package,
1363                                         int error, const char *addinfo)
1364 {
1365     const char *err_msg = yaz_diag_bib1_str(error);
1366     if (addinfo)
1367         package.log("zoom", YLOG_WARN, "Diagnostic %d %s: %s",
1368                     error, err_msg, addinfo);
1369     else
1370         package.log("zoom", YLOG_WARN, "Diagnostic %d %s:",
1371                     error, err_msg);
1372 }
1373
1374 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1375 {
1376     Z_GDU *gdu = package.request().get();
1377     Z_APDU *apdu_req = gdu->u.z3950;
1378     Z_APDU *apdu_res = 0;
1379     mp::odr odr;
1380     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1381     if (sr->num_databaseNames != 1)
1382     {
1383         int error = YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED;
1384         log_diagnostic(package, error, 0);
1385         apdu_res = odr.create_searchResponse(apdu_req, error, 0);
1386         package.response() = apdu_res;
1387         return;
1388     }
1389
1390     int error = 0;
1391     char *addinfo = 0;
1392     std::string db(sr->databaseNames[0]);
1393     BackendPtr b = get_backend_from_databases(package, db, &error,
1394                                               &addinfo, odr);
1395     if (error)
1396     {
1397         log_diagnostic(package, error, addinfo);
1398         apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1399         package.response() = apdu_res;
1400         return;
1401     }
1402
1403     b->set_option("setname", "default");
1404
1405     bool enable_pz2_retrieval = false;
1406     bool enable_pz2_transform = false;
1407     bool assume_marc8_charset = false;
1408     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
1409                      enable_pz2_retrieval,
1410                      enable_pz2_transform,
1411                      assume_marc8_charset);
1412
1413     Odr_int hits = 0;
1414     Z_Query *query = sr->query;
1415     WRBUF ccl_wrbuf = 0;
1416     WRBUF pqf_wrbuf = 0;
1417     std::string sortkeys;
1418
1419     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1420     {
1421         // RPN
1422         pqf_wrbuf = wrbuf_alloc();
1423         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1424     }
1425     else if (query->which == Z_Query_type_2)
1426     {
1427         // CCL
1428         ccl_wrbuf = wrbuf_alloc();
1429         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1430                     query->u.type_2->len);
1431     }
1432     else if (query->which == Z_Query_type_104 &&
1433              query->u.type_104->which == Z_External_CQL)
1434     {
1435         // CQL
1436         const char *cql = query->u.type_104->u.cql;
1437         CQL_parser cp = cql_parser_create();
1438         int r = cql_parser_string(cp, cql);
1439         package.log("zoom", YLOG_LOG, "CQL: %s", cql);
1440         if (r)
1441         {
1442             cql_parser_destroy(cp);
1443             error = YAZ_BIB1_MALFORMED_QUERY;
1444             const char *addinfo = "CQL syntax error";
1445             log_diagnostic(package, error, addinfo);
1446             apdu_res = 
1447                 odr.create_searchResponse(apdu_req, error, addinfo);
1448             package.response() = apdu_res;
1449             return;
1450         }
1451         struct cql_node *cn = cql_parser_result(cp);
1452         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1453         if (cn_error)
1454         {
1455             // hopefully we are getting a ptr to a index+relation+term node
1456             error = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1457             addinfo = 0;
1458             if (cn_error->which == CQL_NODE_ST)
1459                 addinfo = cn_error->u.st.index;
1460             
1461             log_diagnostic(package, error, addinfo);
1462             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1463             package.response() = apdu_res;
1464             return;
1465         }
1466         char ccl_buf[1024];
1467
1468         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1469         if (r == 0)
1470         {
1471             ccl_wrbuf = wrbuf_alloc();
1472             wrbuf_puts(ccl_wrbuf, ccl_buf);
1473             
1474             WRBUF sru_sortkeys_wrbuf = wrbuf_alloc();
1475
1476             cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf);
1477             WRBUF sort_spec_wrbuf = wrbuf_alloc();
1478             yaz_srw_sortkeys_to_sort_spec(wrbuf_cstr(sru_sortkeys_wrbuf),
1479                                           sort_spec_wrbuf);
1480             wrbuf_destroy(sru_sortkeys_wrbuf);
1481
1482             yaz_tok_cfg_t tc = yaz_tok_cfg_create();
1483             yaz_tok_parse_t tp =
1484                 yaz_tok_parse_buf(tc, wrbuf_cstr(sort_spec_wrbuf));
1485             yaz_tok_cfg_destroy(tc);
1486
1487             /* go through sortspec and map fields */
1488             int token = yaz_tok_move(tp);
1489             while (token != YAZ_TOK_EOF)
1490             {
1491                 if (token == YAZ_TOK_STRING)
1492                 {
1493                     const char *field = yaz_tok_parse_string(tp);
1494                     std::map<std::string,std::string>::iterator it;
1495                     it = b->sptr->sortmap.find(field);
1496                     if (it != b->sptr->sortmap.end())
1497                         sortkeys += it->second;
1498                     else
1499                         sortkeys += field;
1500                 }
1501                 sortkeys += " ";
1502                 token = yaz_tok_move(tp);
1503                 if (token == YAZ_TOK_STRING)
1504                 {
1505                     sortkeys += yaz_tok_parse_string(tp);
1506                 }
1507                 if (token != YAZ_TOK_EOF)
1508                 {
1509                     sortkeys += " ";
1510                     token = yaz_tok_move(tp);
1511                 }
1512             }
1513             yaz_tok_parse_destroy(tp);
1514             wrbuf_destroy(sort_spec_wrbuf);
1515         }
1516         cql_parser_destroy(cp);
1517         if (r)
1518         {
1519             error = YAZ_BIB1_MALFORMED_QUERY;
1520             const char *addinfo = "CQL to CCL conversion error";
1521
1522             log_diagnostic(package, error, addinfo);
1523             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1524             package.response() = apdu_res;
1525             return;
1526         }
1527     }
1528     else
1529     {
1530         error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
1531         const char *addinfo = 0;
1532         log_diagnostic(package, error, addinfo);
1533         apdu_res =  odr.create_searchResponse(apdu_req, error, addinfo);
1534         package.response() = apdu_res;
1535         return;
1536     }
1537
1538     if (ccl_wrbuf)
1539     {
1540         // CCL to PQF
1541         assert(pqf_wrbuf == 0);
1542         int cerror, cpos;
1543         struct ccl_rpn_node *cn;
1544         package.log("zoom", YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1545         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1546                           &cerror, &cpos);
1547         wrbuf_destroy(ccl_wrbuf);
1548         if (!cn)
1549         {
1550             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1551             error = YAZ_BIB1_MALFORMED_QUERY;
1552
1553             switch (cerror)
1554             {
1555             case CCL_ERR_UNKNOWN_QUAL:
1556                 error = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1557                 break;
1558             case CCL_ERR_TRUNC_NOT_LEFT: 
1559             case CCL_ERR_TRUNC_NOT_RIGHT:
1560             case CCL_ERR_TRUNC_NOT_BOTH:
1561                 error = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
1562                 break;
1563             }
1564             log_diagnostic(package, error, addinfo);
1565             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1566             package.response() = apdu_res;
1567             return;
1568         }
1569         pqf_wrbuf = wrbuf_alloc();
1570         ccl_pquery(pqf_wrbuf, cn);
1571         package.log("zoom", YLOG_LOG, "RPN: %s", wrbuf_cstr(pqf_wrbuf));
1572         ccl_rpn_delete(cn);
1573     }
1574     
1575     assert(pqf_wrbuf);
1576
1577     ZOOM_query q = ZOOM_query_create();
1578     ZOOM_query_sortby2(q, b->sptr->sortStrategy.c_str(), sortkeys.c_str());
1579
1580     if (b->get_option("sru"))
1581     {
1582         int status = 0;
1583         Z_RPNQuery *zquery;
1584         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1585         WRBUF wrb = wrbuf_alloc();
1586             
1587         if (!strcmp(b->get_option("sru"), "solr"))
1588         {
1589             solr_transform_t cqlt = solr_transform_create();
1590             
1591             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1592             
1593             solr_transform_close(cqlt);
1594         }
1595         else
1596         {
1597             cql_transform_t cqlt = cql_transform_create();
1598             
1599             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1600             
1601             cql_transform_close(cqlt);
1602         }
1603         if (status == 0)
1604         {
1605             ZOOM_query_cql(q, wrbuf_cstr(wrb));
1606             package.log("zoom", YLOG_LOG, "CQL: %s", wrbuf_cstr(wrb));
1607             b->search(q, &hits, &error, &addinfo, odr);
1608         }
1609         ZOOM_query_destroy(q);
1610         
1611         wrbuf_destroy(wrb);
1612         wrbuf_destroy(pqf_wrbuf);
1613         if (status)
1614         {
1615             error = YAZ_BIB1_MALFORMED_QUERY;
1616             const char *addinfo = "can not convert from RPN to CQL/SOLR";
1617             log_diagnostic(package, error, addinfo);
1618             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1619             package.response() = apdu_res;
1620             return;
1621         }
1622     }
1623     else
1624     {
1625         ZOOM_query_prefix(q, wrbuf_cstr(pqf_wrbuf));
1626         package.log("zoom", YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1627         b->search(q, &hits, &error, &addinfo, odr);
1628         ZOOM_query_destroy(q);
1629         wrbuf_destroy(pqf_wrbuf);
1630     }
1631
1632     const char *element_set_name = 0;
1633     Odr_int number_to_present = 0;
1634     if (!error)
1635         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1636     
1637     Odr_int number_of_records_returned = 0;
1638     Z_Records *records = get_records(
1639         package,
1640         0, number_to_present, &error, &addinfo,
1641         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1642         element_set_name);
1643     if (error)
1644         log_diagnostic(package, error, addinfo);
1645     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1646     if (records)
1647     {
1648         apdu_res->u.searchResponse->records = records;
1649         apdu_res->u.searchResponse->numberOfRecordsReturned =
1650             odr_intdup(odr, number_of_records_returned);
1651     }
1652     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1653     package.response() = apdu_res;
1654 }
1655
1656 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1657 {
1658     Z_GDU *gdu = package.request().get();
1659     Z_APDU *apdu_req = gdu->u.z3950;
1660     Z_APDU *apdu_res = 0;
1661     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1662
1663     mp::odr odr;
1664     if (!m_backend)
1665     {
1666         package.response() = odr.create_presentResponse(
1667             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1668         return;
1669     }
1670     const char *element_set_name = 0;
1671     Z_RecordComposition *comp = pr->recordComposition;
1672     if (comp && comp->which != Z_RecordComp_simple)
1673     {
1674         package.response() = odr.create_presentResponse(
1675             apdu_req, 
1676             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1677         return;
1678     }
1679     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1680         element_set_name = comp->u.simple->u.generic;
1681     Odr_int number_of_records_returned = 0;
1682     int error = 0;
1683     char *addinfo = 0;
1684     Z_Records *records = get_records(package,
1685         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1686         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1687         pr->preferredRecordSyntax, element_set_name);
1688
1689     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1690     if (records)
1691     {
1692         apdu_res->u.presentResponse->records = records;
1693         apdu_res->u.presentResponse->numberOfRecordsReturned =
1694             odr_intdup(odr, number_of_records_returned);
1695     }
1696     package.response() = apdu_res;
1697 }
1698
1699 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1700 {
1701     Z_GDU *gdu = package.request().get();
1702     if (!gdu)
1703         ;
1704     else if (gdu->which == Z_GDU_Z3950)
1705     {
1706         Z_APDU *apdu_req = gdu->u.z3950;
1707
1708         if (m_backend)
1709             wrbuf_rewind(m_backend->m_apdu_wrbuf);
1710         if (apdu_req->which == Z_APDU_initRequest)
1711         {
1712             mp::odr odr;
1713             package.response() = odr.create_close(
1714                 apdu_req,
1715                 Z_Close_protocolError,
1716                 "double init");
1717         }
1718         else if (apdu_req->which == Z_APDU_searchRequest)
1719         {
1720             handle_search(package);
1721         }
1722         else if (apdu_req->which == Z_APDU_presentRequest)
1723         {
1724             handle_present(package);
1725         }
1726         else
1727         {
1728             mp::odr odr;
1729             package.response() = odr.create_close(
1730                 apdu_req,
1731                 Z_Close_protocolError,
1732                 "zoom filter cannot handle this APDU");
1733             package.session().close();
1734         }
1735         if (m_backend)
1736         {
1737             WRBUF w = m_backend->m_apdu_wrbuf;
1738             package.log_write(wrbuf_buf(w), wrbuf_len(w));
1739         }
1740     }
1741     else
1742     {
1743         package.session().close();
1744     }
1745 }
1746
1747 void yf::Zoom::Impl::process(mp::Package &package)
1748 {
1749     FrontendPtr f = get_frontend(package);
1750     Z_GDU *gdu = package.request().get();
1751
1752     if (f->m_is_virtual)
1753     {
1754         f->handle_package(package);
1755     }
1756     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1757              Z_APDU_initRequest)
1758     {
1759         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1760         f->m_init_gdu = gdu;
1761         
1762         mp::odr odr;
1763         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1764         Z_InitResponse *resp = apdu->u.initResponse;
1765         
1766         int i;
1767         static const int masks[] = {
1768             Z_Options_search,
1769             Z_Options_present,
1770             -1 
1771         };
1772         for (i = 0; masks[i] != -1; i++)
1773             if (ODR_MASK_GET(req->options, masks[i]))
1774                 ODR_MASK_SET(resp->options, masks[i]);
1775         
1776         static const int versions[] = {
1777             Z_ProtocolVersion_1,
1778             Z_ProtocolVersion_2,
1779             Z_ProtocolVersion_3,
1780             -1
1781         };
1782         for (i = 0; versions[i] != -1; i++)
1783             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1784                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1785             else
1786                 break;
1787         
1788         *resp->preferredMessageSize = *req->preferredMessageSize;
1789         *resp->maximumRecordSize = *req->maximumRecordSize;
1790         
1791         package.response() = apdu;
1792         f->m_is_virtual = true;
1793     }
1794     else
1795         package.move();
1796
1797     release_frontend(package);
1798 }
1799
1800
1801 static mp::filter::Base* filter_creator()
1802 {
1803     return new mp::filter::Zoom;
1804 }
1805
1806 extern "C" {
1807     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1808         0,
1809         "zoom",
1810         filter_creator
1811     };
1812 }
1813
1814
1815 /*
1816  * Local variables:
1817  * c-basic-offset: 4
1818  * c-file-style: "Stroustrup"
1819  * indent-tabs-mode: nil
1820  * End:
1821  * vim: shiftwidth=4 tabstop=8 expandtab
1822  */
1823