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