zoom: use WRBUF for CCL buffer
[metaproxy-moved-to-github.git] / src / filter_zoom.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2012 Index Data
3
4 Metaproxy is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17 */
18
19 #include "config.hpp"
20
21 #include <stdlib.h>
22 #include <sys/types.h>
23 #include "filter_zoom.hpp"
24 #include <metaproxy/package.hpp>
25 #include <metaproxy/util.hpp>
26 #include <metaproxy/xmlutil.hpp>
27 #include <yaz/comstack.h>
28 #include <yaz/poll.h>
29 #include "torus.hpp"
30
31 #include <libxslt/xsltutils.h>
32 #include <libxslt/transform.h>
33
34 #include <boost/thread/mutex.hpp>
35 #include <boost/thread/condition.hpp>
36
37 #include <yaz/yaz-version.h>
38 #include <yaz/tpath.h>
39 #include <yaz/srw.h>
40 #include <yaz/ccl_xml.h>
41 #include <yaz/ccl.h>
42 #include <yaz/rpn2cql.h>
43 #include <yaz/rpn2solr.h>
44 #include <yaz/pquery.h>
45 #include <yaz/cql.h>
46 #include <yaz/oid_db.h>
47 #include <yaz/diagbib1.h>
48 #include <yaz/log.h>
49 #include <yaz/zgdu.h>
50 #include <yaz/querytowrbuf.h>
51 #include <yaz/sortspec.h>
52 #include <yaz/tokenizer.h>
53 #include <yaz/zoom.h>
54
55 namespace mp = metaproxy_1;
56 namespace yf = mp::filter;
57
58 namespace metaproxy_1 {
59     namespace filter {
60         class Zoom::Searchable : boost::noncopyable {
61           public:
62             std::string authentication;
63             std::string cfAuth;
64             std::string cfProxy;
65             std::string cfSubDB;
66             std::string udb;
67             std::string target;
68             std::string query_encoding;
69             std::string sru;
70             std::string sru_version;
71             std::string request_syntax;
72             std::string element_set;
73             std::string record_encoding;
74             std::string transform_xsl_fname;
75             std::string transform_xsl_content;
76             std::string urlRecipe;
77             std::string contentConnector;
78             std::string sortStrategy;
79             bool use_turbomarc;
80             bool piggyback;
81             CCL_bibset ccl_bibset;
82             std::map<std::string, std::string> sortmap;
83             Searchable(CCL_bibset base);
84             ~Searchable();
85         };
86         class Zoom::Backend : boost::noncopyable {
87             friend class Impl;
88             friend class Frontend;
89             std::string zurl;
90             mp::wrbuf m_apdu_wrbuf;
91             ZOOM_connection m_connection;
92             ZOOM_resultset m_resultset;
93             std::string m_frontend_database;
94             SearchablePtr sptr;
95             xsltStylesheetPtr xsp;
96             std::string cproxy_host;
97             bool enable_cproxy;
98             bool enable_explain;
99             xmlDoc *explain_doc;
100             std::string m_proxy;
101         public:
102             Backend();
103             ~Backend();
104             void connect(std::string zurl, int *error, char **addinfo,
105                          ODR odr);
106             void search(ZOOM_query q, Odr_int *hits,
107                         int *error, char **addinfo, ODR odr);
108             void present(Odr_int start, Odr_int number, ZOOM_record *recs,
109                          int *error, char **addinfo, ODR odr);
110             void set_option(const char *name, const char *value);
111             void set_option(const char *name, std::string value);
112             const char *get_option(const char *name);
113             void get_zoom_error(int *error, char **addinfo, ODR odr);
114         };
115         class Zoom::Frontend : boost::noncopyable {
116             friend class Impl;
117             Impl *m_p;
118             bool m_is_virtual;
119             bool m_in_use;
120             yazpp_1::GDU m_init_gdu;
121             BackendPtr m_backend;
122             void handle_package(mp::Package &package);
123             void handle_search(mp::Package &package);
124
125             BackendPtr explain_search(mp::Package &package,
126                                       std::string &database,
127                                       int *error,
128                                       char **addinfo,
129                                       mp::odr &odr,
130                                       std::string &torus_db,
131                                       std::string &realm);
132             void handle_present(mp::Package &package);
133             BackendPtr get_backend_from_databases(mp::Package &package,
134                                                   std::string &database,
135                                                   int *error,
136                                                   char **addinfo,
137                                                   mp::odr &odr,
138                                                   int *proxy_step);
139
140             bool create_content_session(mp::Package &package,
141                                         BackendPtr b,
142                                         int *error,
143                                         char **addinfo,
144                                         ODR odr,
145                                         std::string authentication,
146                                         std::string proxy,
147                                         std::string realm);
148             
149             void prepare_elements(BackendPtr b,
150                                   Odr_oid *preferredRecordSyntax,
151                                   const char *element_set_name,
152                                   bool &enable_pz2_retrieval,
153                                   bool &enable_pz2_transform,
154                                   bool &enable_record_transform,
155                                   bool &assume_marc8_charset);
156
157             Z_Records *get_records(Package &package,
158                                    Odr_int start,
159                                    Odr_int number_to_present,
160                                    int *error,
161                                    char **addinfo,
162                                    Odr_int *number_of_records_returned,
163                                    ODR odr, BackendPtr b,
164                                    Odr_oid *preferredRecordSyntax,
165                                    const char *element_set_name);
166             Z_Records *get_explain_records(Package &package,
167                                            Odr_int start,
168                                            Odr_int number_to_present,
169                                            int *error,
170                                            char **addinfo,
171                                            Odr_int *number_of_records_returned,
172                                            ODR odr, BackendPtr b,
173                                            Odr_oid *preferredRecordSyntax,
174                                            const char *element_set_name);
175             bool retry(mp::Package &package,
176                        mp::odr &odr,
177                        BackendPtr b, 
178                        int &error, char **addinfo,
179                        int &proxy_step, int &same_retries,
180                        int &proxy_retries);
181             void log_diagnostic(mp::Package &package,
182                                 int error, const char *addinfo);
183         public:
184             Frontend(Impl *impl);
185             ~Frontend();
186         };
187         class Zoom::Impl {
188             friend class Frontend;
189         public:
190             Impl();
191             ~Impl();
192             void process(metaproxy_1::Package & package);
193             void configure(const xmlNode * ptr, bool test_only,
194                            const char *path);
195         private:
196             void configure_local_records(const xmlNode * ptr, bool test_only);
197             bool check_proxy(const char *proxy);
198
199
200
201             FrontendPtr get_frontend(mp::Package &package);
202             void release_frontend(mp::Package &package);
203             SearchablePtr parse_torus_record(const xmlNode *ptr);
204             struct cql_node *convert_cql_fields(struct cql_node *cn, ODR odr);
205             std::map<mp::Session, FrontendPtr> m_clients;            
206             boost::mutex m_mutex;
207             boost::condition m_cond_session_ready;
208             std::string torus_searchable_url;
209             std::string torus_content_url;
210             std::string default_realm;
211             std::map<std::string,std::string> fieldmap;
212             std::string xsldir;
213             std::string file_path;
214             std::string content_proxy_server;
215             std::string content_tmp_file;
216             std::string content_config_file;
217             bool apdu_log;
218             CCL_bibset bibset;
219             std::string element_transform;
220             std::string element_raw;
221             std::string proxy;
222             xsltStylesheetPtr explain_xsp;
223             xsltStylesheetPtr record_xsp;
224             std::map<std::string,SearchablePtr> s_map;
225             std::string zoom_timeout;
226             int proxy_timeout;
227         };
228     }
229 }
230
231
232 static xmlNode *xml_node_search(xmlNode *ptr, int *num, int m)
233 {
234     while (ptr)
235     {
236         if (ptr->type == XML_ELEMENT_NODE &&
237             !strcmp((const char *) ptr->name, "recordData"))
238         {
239             (*num)++;
240             if (m == *num)
241                 return ptr;
242         }
243         else  // else: we don't want to find nested nodes
244         {   
245             xmlNode *ret_node = xml_node_search(ptr->children, num, m);
246             if (ret_node)
247                 return ret_node;
248         }
249         ptr = ptr->next;
250     }
251     return 0;
252 }
253
254 // define Pimpl wrapper forwarding to Impl
255  
256 yf::Zoom::Zoom() : m_p(new Impl)
257 {
258 }
259
260 yf::Zoom::~Zoom()
261 {  // must have a destructor because of boost::scoped_ptr
262 }
263
264 void yf::Zoom::configure(const xmlNode *xmlnode, bool test_only,
265                          const char *path)
266 {
267     m_p->configure(xmlnode, test_only, path);
268 }
269
270 void yf::Zoom::process(mp::Package &package) const
271 {
272     m_p->process(package);
273 }
274
275
276 // define Implementation stuff
277
278 yf::Zoom::Backend::Backend()
279 {
280     m_connection = ZOOM_connection_create(0);
281     ZOOM_connection_save_apdu_wrbuf(m_connection, m_apdu_wrbuf);
282     m_resultset = 0;
283     xsp = 0;
284     enable_cproxy = true;
285     enable_explain = false;
286     explain_doc = 0;
287 }
288
289 yf::Zoom::Backend::~Backend()
290 {
291     if (xsp)
292         xsltFreeStylesheet(xsp);
293     if (explain_doc)
294         xmlFreeDoc(explain_doc);
295     ZOOM_connection_destroy(m_connection);
296     ZOOM_resultset_destroy(m_resultset);
297 }
298
299
300 void yf::Zoom::Backend::get_zoom_error(int *error, char **addinfo,
301                                        ODR odr)
302 {
303     const char *msg = 0;
304     const char *zoom_addinfo = 0;
305     const char *dset = 0;
306     int error0 = ZOOM_connection_error_x(m_connection, &msg,
307                                          &zoom_addinfo, &dset);
308     if (error0)
309     {
310         if (!dset)
311             dset = "Unknown";
312         
313         if (!strcmp(dset, "info:srw/diagnostic/1"))
314             *error = yaz_diag_srw_to_bib1(error0);
315         else if (!strcmp(dset, "Bib-1"))
316             *error = error0;
317         else if (!strcmp(dset, "ZOOM"))
318         {
319             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;                
320             if (error0 == ZOOM_ERROR_INIT)
321                 *error = YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR;
322             else if (error0 == ZOOM_ERROR_DECODE)
323             {
324                 if (zoom_addinfo)
325                 {
326                     if (strstr(zoom_addinfo, "Authentication") ||
327                         strstr(zoom_addinfo, "authentication"))
328                         *error = YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR;
329                 }
330             }
331         }
332         else
333             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
334         
335         *addinfo = (char *) odr_malloc(
336             odr, 30 + strlen(dset) + strlen(msg) +
337             (zoom_addinfo ? strlen(zoom_addinfo) : 0));
338         **addinfo = '\0';
339         if (zoom_addinfo && *zoom_addinfo)
340         {
341             strcpy(*addinfo, zoom_addinfo);
342             strcat(*addinfo, " ");
343         }
344         sprintf(*addinfo + strlen(*addinfo), "(%s %d %s)", dset, error0, msg);
345     }
346 }
347
348 void yf::Zoom::Backend::connect(std::string zurl,
349                                 int *error, char **addinfo,
350                                 ODR odr)
351 {
352     ZOOM_connection_connect(m_connection, zurl.length() ? zurl.c_str() : 0, 0);
353     get_zoom_error(error, addinfo, odr);
354 }
355
356 void yf::Zoom::Backend::search(ZOOM_query q, Odr_int *hits,
357                                int *error, char **addinfo, ODR odr)
358 {
359     ZOOM_resultset_destroy(m_resultset);
360     m_resultset = ZOOM_connection_search(m_connection, q);
361     get_zoom_error(error, addinfo, odr);
362     if (*error == 0)
363         *hits = ZOOM_resultset_size(m_resultset);
364     else
365         *hits = 0;
366 }
367
368 void yf::Zoom::Backend::present(Odr_int start, Odr_int number,
369                                 ZOOM_record *recs,
370                                 int *error, char **addinfo, ODR odr)
371 {
372     ZOOM_resultset_records(m_resultset, recs, start, number);
373     get_zoom_error(error, addinfo, odr);
374 }
375
376 void yf::Zoom::Backend::set_option(const char *name, const char *value)
377 {
378     ZOOM_connection_option_set(m_connection, name, value);
379     if (m_resultset)
380         ZOOM_resultset_option_set(m_resultset, name, value);
381 }
382
383 void yf::Zoom::Backend::set_option(const char *name, std::string value)
384 {
385     set_option(name, value.c_str());
386 }
387
388 const char *yf::Zoom::Backend::get_option(const char *name)
389 {
390     return ZOOM_connection_option_get(m_connection, name);
391 }
392
393 yf::Zoom::Searchable::Searchable(CCL_bibset base)
394 {
395     piggyback = true;
396     use_turbomarc = true;
397     sortStrategy = "embed";
398     ccl_bibset = ccl_qual_dup(base);
399 }
400
401 yf::Zoom::Searchable::~Searchable()
402 {
403     ccl_qual_rm(&ccl_bibset);
404 }
405
406 yf::Zoom::Frontend::Frontend(Impl *impl) : 
407     m_p(impl), m_is_virtual(false), m_in_use(true)
408 {
409 }
410
411 yf::Zoom::Frontend::~Frontend()
412 {
413 }
414
415 yf::Zoom::FrontendPtr yf::Zoom::Impl::get_frontend(mp::Package &package)
416 {
417     boost::mutex::scoped_lock lock(m_mutex);
418
419     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
420     
421     while(true)
422     {
423         it = m_clients.find(package.session());
424         if (it == m_clients.end())
425             break;
426         
427         if (!it->second->m_in_use)
428         {
429             it->second->m_in_use = true;
430             return it->second;
431         }
432         m_cond_session_ready.wait(lock);
433     }
434     FrontendPtr f(new Frontend(this));
435     m_clients[package.session()] = f;
436     f->m_in_use = true;
437     return f;
438 }
439
440 void yf::Zoom::Impl::release_frontend(mp::Package &package)
441 {
442     boost::mutex::scoped_lock lock(m_mutex);
443     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
444     
445     it = m_clients.find(package.session());
446     if (it != m_clients.end())
447     {
448         if (package.session().is_closed())
449         {
450             m_clients.erase(it);
451         }
452         else
453         {
454             it->second->m_in_use = false;
455         }
456         m_cond_session_ready.notify_all();
457     }
458 }
459
460 yf::Zoom::Impl::Impl() :
461     apdu_log(false), element_transform("pz2") , element_raw("raw"),
462     zoom_timeout("40"), proxy_timeout(1)
463 {
464     bibset = ccl_qual_mk();
465
466     explain_xsp = 0;
467     record_xsp = 0;
468     srand((unsigned int) time(0));
469 }
470
471 yf::Zoom::Impl::~Impl()
472 {
473     if (explain_xsp)
474         xsltFreeStylesheet(explain_xsp);
475     ccl_qual_rm(&bibset);
476 }
477
478 yf::Zoom::SearchablePtr yf::Zoom::Impl::parse_torus_record(const xmlNode *ptr)
479 {
480     Zoom::SearchablePtr s(new Searchable(bibset));
481     
482     for (ptr = ptr->children; ptr; ptr = ptr->next)
483     {
484         if (ptr->type != XML_ELEMENT_NODE)
485             continue;
486         if (!strcmp((const char *) ptr->name, "layer"))
487             ptr = ptr->children;
488         else if (!strcmp((const char *) ptr->name,
489                          "authentication"))
490         {
491             s->authentication = mp::xml::get_text(ptr);
492         }
493         else if (!strcmp((const char *) ptr->name,
494                          "cfAuth"))
495         {
496             s->cfAuth = mp::xml::get_text(ptr);
497         } 
498         else if (!strcmp((const char *) ptr->name,
499                          "cfProxy"))
500         {
501             s->cfProxy = mp::xml::get_text(ptr);
502         }  
503         else if (!strcmp((const char *) ptr->name,
504                          "cfSubDB"))
505         {
506             s->cfSubDB = mp::xml::get_text(ptr);
507         }  
508         else if (!strcmp((const char *) ptr->name,
509                          "contentConnector"))
510         {
511             s->contentConnector = mp::xml::get_text(ptr);
512         }  
513         else if (!strcmp((const char *) ptr->name, "udb"))
514         {
515             s->udb = mp::xml::get_text(ptr);
516         }
517         else if (!strcmp((const char *) ptr->name, "zurl"))
518         {
519             s->target = mp::xml::get_text(ptr);
520         }
521         else if (!strcmp((const char *) ptr->name, "sru"))
522         {
523             s->sru = mp::xml::get_text(ptr);
524         }
525         else if (!strcmp((const char *) ptr->name, "SRUVersion") ||
526                  !strcmp((const char *) ptr->name, "sruVersion"))
527         {
528             s->sru_version = mp::xml::get_text(ptr);
529         }
530         else if (!strcmp((const char *) ptr->name,
531                          "queryEncoding"))
532         {
533             s->query_encoding = mp::xml::get_text(ptr);
534         }
535         else if (!strcmp((const char *) ptr->name,
536                          "piggyback"))
537         {
538             s->piggyback = mp::xml::get_bool(ptr, true);
539         }
540         else if (!strcmp((const char *) ptr->name,
541                          "requestSyntax"))
542         {
543             s->request_syntax = mp::xml::get_text(ptr);
544         }
545         else if (!strcmp((const char *) ptr->name,
546                          "elementSet"))
547         {
548             s->element_set = mp::xml::get_text(ptr);
549         }
550         else if (!strcmp((const char *) ptr->name,
551                          "recordEncoding"))
552         {
553             s->record_encoding = mp::xml::get_text(ptr);
554         }
555         else if (!strcmp((const char *) ptr->name,
556                          "transform"))
557         {
558             s->transform_xsl_fname = mp::xml::get_text(ptr);
559         }
560         else if (!strcmp((const char *) ptr->name,
561                          "literalTransform"))
562         {
563             s->transform_xsl_content = mp::xml::get_text(ptr);
564         }
565         else if (!strcmp((const char *) ptr->name,
566                          "urlRecipe"))
567         {
568             s->urlRecipe = mp::xml::get_text(ptr);
569         }
570         else if (!strcmp((const char *) ptr->name,
571                          "useTurboMarc"))
572         {
573             ; // useTurboMarc is ignored
574         }
575         else if (!strncmp((const char *) ptr->name,
576                           "cclmap_", 7))
577         {
578             std::string value = mp::xml::get_text(ptr);
579             if (value.length() > 0)
580             {
581                 ccl_qual_fitem(s->ccl_bibset, value.c_str(),
582                                (const char *) ptr->name + 7);
583             }
584         }
585         else if (!strncmp((const char *) ptr->name,
586                           "sortmap_", 8))
587         {
588             std::string value = mp::xml::get_text(ptr);
589             s->sortmap[(const char *) ptr->name + 8] = value;
590         }
591         else if (!strcmp((const char *) ptr->name,
592                           "sortStrategy"))
593         {
594             s->sortStrategy = mp::xml::get_text(ptr);
595         }
596     }
597     return s;
598 }
599
600 void yf::Zoom::Impl::configure_local_records(const xmlNode *ptr, bool test_only)
601 {
602     while (ptr && ptr->type != XML_ELEMENT_NODE)
603         ptr = ptr->next;
604     
605     if (ptr)
606     {
607         if (!strcmp((const char *) ptr->name, "records"))
608         {
609             for (ptr = ptr->children; ptr; ptr = ptr->next)
610             {
611                 if (ptr->type != XML_ELEMENT_NODE)
612                     continue;
613                 if (!strcmp((const char *) ptr->name, "record"))
614                 {
615                     SearchablePtr s = parse_torus_record(ptr);
616                     if (s)
617                     {
618                         std::string udb = s->udb;
619                         if (udb.length())
620                             s_map[s->udb] = s;
621                         else
622                         {
623                             throw mp::filter::FilterException
624                                 ("No udb for local torus record");
625                         }
626                     }
627                 }
628                 else
629                 {
630                     throw mp::filter::FilterException
631                         ("Bad element " 
632                          + std::string((const char *) ptr->name)
633                          + " in zoom filter inside element "
634                          "<torus><records>");
635                 }
636             }
637         }
638         else
639         {
640             throw mp::filter::FilterException
641                 ("Bad element " 
642                  + std::string((const char *) ptr->name)
643                  + " in zoom filter inside element <torus>");
644         }
645     }
646 }
647
648 void yf::Zoom::Impl::configure(const xmlNode *ptr, bool test_only,
649                                const char *path)
650 {
651     std::string explain_xslt_fname;
652     std::string record_xslt_fname;
653
654     if (path && *path)
655     {
656         file_path = path;
657     }
658     for (ptr = ptr->children; ptr; ptr = ptr->next)
659     {
660         if (ptr->type != XML_ELEMENT_NODE)
661             continue;
662         else if (!strcmp((const char *) ptr->name, "torus"))
663         {
664             const struct _xmlAttr *attr;
665             for (attr = ptr->properties; attr; attr = attr->next)
666             {
667                 if (!strcmp((const char *) attr->name, "url"))
668                     torus_searchable_url = mp::xml::get_text(attr->children);
669                 else if (!strcmp((const char *) attr->name, "content_url"))
670                     torus_content_url = mp::xml::get_text(attr->children);
671                 else if (!strcmp((const char *) attr->name, "realm"))
672                     default_realm = mp::xml::get_text(attr->children);
673                 else if (!strcmp((const char *) attr->name, "xsldir"))
674                     xsldir = mp::xml::get_text(attr->children);
675                 else if (!strcmp((const char *) attr->name, "element_transform"))
676                     element_transform = mp::xml::get_text(attr->children);
677                 else if (!strcmp((const char *) attr->name, "element_raw"))
678                     element_raw = mp::xml::get_text(attr->children);
679                 else if (!strcmp((const char *) attr->name, "proxy"))
680                     proxy = mp::xml::get_text(attr->children);
681                 else if (!strcmp((const char *) attr->name, "explain_xsl"))
682                     explain_xslt_fname = mp::xml::get_text(attr->children);
683                 else if (!strcmp((const char *) attr->name, "record_xsl"))
684                     record_xslt_fname = mp::xml::get_text(attr->children);
685                 else
686                     throw mp::filter::FilterException(
687                         "Bad attribute " + std::string((const char *)
688                                                        attr->name));
689             }
690             // If content_url is not given, use value of searchable, to
691             // ensure backwards compatibility
692             if (!torus_content_url.length())
693                 torus_content_url = torus_searchable_url;
694             configure_local_records(ptr->children, test_only);
695         }
696         else if (!strcmp((const char *) ptr->name, "cclmap"))
697         {
698             const char *addinfo = 0;
699             ccl_xml_config(bibset, ptr, &addinfo);
700         }
701         else if (!strcmp((const char *) ptr->name, "fieldmap"))
702         {
703             const struct _xmlAttr *attr;
704             std::string ccl_field;
705             std::string cql_field;
706             for (attr = ptr->properties; attr; attr = attr->next)
707             {
708                 if (!strcmp((const char *) attr->name, "ccl"))
709                     ccl_field = mp::xml::get_text(attr->children);
710                 else if (!strcmp((const char *) attr->name, "cql"))
711                     cql_field = mp::xml::get_text(attr->children);
712                 else
713                     throw mp::filter::FilterException(
714                         "Bad attribute " + std::string((const char *)
715                                                        attr->name));
716             }
717             if (cql_field.length())
718                 fieldmap[cql_field] = ccl_field;
719         }
720         else if (!strcmp((const char *) ptr->name, "contentProxy"))
721         {
722             const struct _xmlAttr *attr;
723             for (attr = ptr->properties; attr; attr = attr->next)
724             {
725                 if (!strcmp((const char *) attr->name, "server"))
726                 {
727                     yaz_log(YLOG_WARN,
728                             "contentProxy's server attribute is deprecated");
729                     yaz_log(YLOG_LOG, 
730                             "Specify config_file instead. For example:");
731                     yaz_log(YLOG_LOG, 
732                             " content_file=\"/etc/cf-proxy/cproxy.cfg\"");
733                     content_proxy_server = mp::xml::get_text(attr->children);
734                 }
735                 else if (!strcmp((const char *) attr->name, "tmp_file"))
736                     content_tmp_file = mp::xml::get_text(attr->children);
737                 else if (!strcmp((const char *) attr->name, "config_file"))
738                     content_config_file = mp::xml::get_text(attr->children);
739                 else
740                     throw mp::filter::FilterException(
741                         "Bad attribute " + std::string((const char *)
742                                                        attr->name));
743             }
744         }
745         else if (!strcmp((const char *) ptr->name, "log"))
746         { 
747             const struct _xmlAttr *attr;
748             for (attr = ptr->properties; attr; attr = attr->next)
749             {
750                 if (!strcmp((const char *) attr->name, "apdu"))
751                     apdu_log = mp::xml::get_bool(attr->children, false);
752                 else
753                     throw mp::filter::FilterException(
754                         "Bad attribute " + std::string((const char *)
755                                                        attr->name));
756             }
757         }
758         else if (!strcmp((const char *) ptr->name, "zoom"))
759         {
760             const struct _xmlAttr *attr;
761             for (attr = ptr->properties; attr; attr = attr->next)
762             {
763                 if (!strcmp((const char *) attr->name, "timeout"))
764                     zoom_timeout = mp::xml::get_text(attr->children);
765                 else if (!strcmp((const char *) attr->name, "proxy_timeout"))
766                     proxy_timeout = mp::xml::get_int(attr->children, 1);
767                 else
768                     throw mp::filter::FilterException(
769                         "Bad attribute " + std::string((const char *)
770                                                        attr->name));
771             }
772         }
773         else
774         {
775             throw mp::filter::FilterException
776                 ("Bad element " 
777                  + std::string((const char *) ptr->name)
778                  + " in zoom filter");
779         }
780     }
781
782     if (explain_xslt_fname.length())
783     {
784         const char *path = 0;
785         
786         if (xsldir.length())
787             path = xsldir.c_str();
788         else
789             path = file_path.c_str();
790         
791         char fullpath[1024];
792         char *cp = yaz_filepath_resolve(explain_xslt_fname.c_str(),
793                                         path, 0, fullpath);
794         if (!cp)
795         {
796             throw mp::filter::FilterException
797                 ("Cannot read XSLT " + explain_xslt_fname);
798         }
799
800         xmlDoc *xsp_doc = xmlParseFile(cp);
801         if (!xsp_doc)
802         {
803             throw mp::filter::FilterException
804                 ("Cannot parse XSLT " + explain_xslt_fname);
805         }
806
807         explain_xsp = xsltParseStylesheetDoc(xsp_doc);
808         if (!explain_xsp)
809         {
810             xmlFreeDoc(xsp_doc);
811             throw mp::filter::FilterException
812                 ("Cannot parse XSLT " + explain_xslt_fname);
813             
814         }
815     }
816
817     if (record_xslt_fname.length())
818     {
819         const char *path = 0;
820         
821         if (xsldir.length())
822             path = xsldir.c_str();
823         else
824             path = file_path.c_str();
825         
826         char fullpath[1024];
827         char *cp = yaz_filepath_resolve(record_xslt_fname.c_str(),
828                                         path, 0, fullpath);
829         if (!cp)
830         {
831             throw mp::filter::FilterException
832                 ("Cannot read XSLT " + record_xslt_fname);
833         }
834
835         xmlDoc *xsp_doc = xmlParseFile(cp);
836         if (!xsp_doc)
837         {
838             throw mp::filter::FilterException
839                 ("Cannot parse XSLT " + record_xslt_fname);
840         }
841
842         record_xsp = xsltParseStylesheetDoc(xsp_doc);
843         if (!record_xsp)
844         {
845             xmlFreeDoc(xsp_doc);
846             throw mp::filter::FilterException
847                 ("Cannot parse XSLT " + record_xslt_fname);
848             
849         }
850     }
851 }
852
853 bool yf::Zoom::Frontend::create_content_session(mp::Package &package,
854                                                 BackendPtr b,
855                                                 int *error, char **addinfo,
856                                                 ODR odr,
857                                                 std::string authentication,
858                                                 std::string proxy,
859                                                 std::string realm)
860 {
861     if (b->sptr->contentConnector.length())
862     {
863         std::string proxyhostname;
864         std::string tmp_file;
865         bool legacy_format = false;
866
867         if (m_p->content_proxy_server.length())
868         {
869             proxyhostname = m_p->content_proxy_server;
870             legacy_format = true;
871         }
872             
873         if (m_p->content_tmp_file.length())
874             tmp_file = m_p->content_tmp_file;
875
876         if (m_p->content_config_file.length())
877         {
878             FILE *inf = fopen(m_p->content_config_file.c_str(), "r");
879             if (inf)
880             {
881                 char buf[1024];
882                 while (fgets(buf, sizeof(buf)-1, inf))
883                 {
884                     char *cp;
885                     cp = strchr(buf, '#');
886                     if (cp)
887                         *cp = '\0';
888                     cp = strchr(buf, '\n');
889                     if (cp)
890                         *cp = '\0';
891                     cp = strchr(buf, ':');
892                     if (cp)
893                     {
894                         char *cp1 = cp;
895                         while (cp1 != buf && cp1[-1] == ' ')
896                             cp1--;
897                         *cp1 = '\0';
898                         cp++;
899                         while (*cp == ' ')
900                             cp++;
901                         if (!strcmp(buf, "proxyhostname"))
902                             proxyhostname = cp; 
903                         if (!strcmp(buf, "sessiondir") && *cp)
904                         {
905                             if (cp[strlen(cp)-1] == '/')
906                                 cp[strlen(cp)-1] = '\0';
907                             tmp_file = std::string(cp) + std::string("/cf.XXXXXX.p");
908                         }
909                     }
910                 }
911                 fclose(inf);
912             }
913             else
914             {
915                 package.log("zoom", YLOG_WARN|YLOG_ERRNO,
916                             "unable to open content config %s",
917                             m_p->content_config_file.c_str());
918                 *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
919                 *addinfo = (char *)  odr_malloc(odr, 60 + tmp_file.length());
920                 sprintf(*addinfo, "unable to open content config %s",
921                         m_p->content_config_file.c_str());
922                 return false;
923             }
924         }
925
926         if (proxyhostname.length() == 0)
927         {
928             package.log("zoom", YLOG_WARN, "no proxyhostname");
929             return true;
930         }
931         if (tmp_file.length() == 0)
932         {
933             package.log("zoom", YLOG_WARN, "no tmp_file");
934             return true;
935         }
936
937         char *fname = xstrdup(tmp_file.c_str());
938         char *xx = strstr(fname, "XXXXXX");
939         if (!xx)
940         {
941             package.log("zoom", YLOG_WARN, "bad tmp_file %s", tmp_file.c_str());
942             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
943             *addinfo = (char *)  odr_malloc(odr, 60 + tmp_file.length());
944             sprintf(*addinfo, "bad format of content tmp_file: %s",
945                     tmp_file.c_str());
946             xfree(fname);
947             return false;
948         }
949         char tmp_char = xx[6];
950         sprintf(xx, "%06d", ((unsigned) rand()) % 1000000);
951         if (legacy_format)
952             b->cproxy_host = std::string(xx) + "." + proxyhostname;
953         else
954             b->cproxy_host = proxyhostname + "/" + xx;
955         xx[6] = tmp_char;
956
957         FILE *file = fopen(fname, "w");
958         if (!file)
959         {
960             package.log("zoom", YLOG_WARN|YLOG_ERRNO, "create %s", fname);
961             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
962             *addinfo = (char *)  odr_malloc(odr, 40 + strlen(fname));
963             sprintf(*addinfo, "Could not create %s", fname);
964             xfree(fname);
965             return false;
966         }
967         mp::wrbuf w;
968         wrbuf_puts(w, "#content_proxy\n");
969         wrbuf_printf(w, "connector: %s\n", b->sptr->contentConnector.c_str());
970         if (authentication.length())
971             wrbuf_printf(w, "auth: %s\n", authentication.c_str());
972         if (proxy.length())
973             wrbuf_printf(w, "proxy: %s\n", proxy.c_str());
974         if (realm.length())
975             wrbuf_printf(w, "realm: %s\n", realm.c_str());
976
977         fwrite(w.buf(), 1, w.len(), file);
978         fclose(file);
979         package.log("zoom", YLOG_LOG, "content file: %s", fname);
980         xfree(fname);
981     }
982     return true;
983 }
984
985 yf::Zoom::BackendPtr yf::Zoom::Frontend::get_backend_from_databases(
986     mp::Package &package,
987     std::string &database, int *error, char **addinfo, mp::odr &odr,
988     int *proxy_step)
989 {
990     bool connection_reuse = false;
991     std::string proxy;
992
993     std::list<BackendPtr>::const_iterator map_it;
994     if (m_backend && !m_backend->enable_explain && 
995         m_backend->m_frontend_database == database)
996     {
997         connection_reuse = true;
998         proxy = m_backend->m_proxy;
999     }
1000
1001     std::string input_args;
1002     std::string torus_db;
1003     size_t db_arg_pos = database.find(',');
1004     if (db_arg_pos != std::string::npos)
1005     {
1006         torus_db = database.substr(0, db_arg_pos);
1007         input_args = database.substr(db_arg_pos + 1);
1008     }
1009     else
1010         torus_db = database;
1011
1012     std::string authentication;
1013     std::string content_authentication;
1014     std::string content_proxy;
1015     std::string realm = m_p->default_realm;
1016
1017     const char *param_user = 0;
1018     const char *param_password = 0;
1019     const char *param_content_user = 0;
1020     const char *param_content_password = 0;
1021     const char *param_nocproxy = 0;
1022     int no_parms = 0;
1023
1024     char **names;
1025     char **values;
1026     int no_out_args = 0;
1027     if (input_args.length())
1028         no_parms = yaz_uri_to_array(input_args.c_str(),
1029                                     odr, &names, &values);
1030     // adding 10 because we'll be adding other URL args
1031     const char **out_names = (const char **)
1032         odr_malloc(odr, (10 + no_parms) * sizeof(*out_names));
1033     const char **out_values = (const char **)
1034         odr_malloc(odr, (10 + no_parms) * sizeof(*out_values));
1035     
1036     // may be changed if it's a content connection
1037     std::string torus_url = m_p->torus_searchable_url;
1038     int i;
1039     for (i = 0; i < no_parms; i++)
1040     {
1041         const char *name = names[i];
1042         const char *value = values[i];
1043         assert(name);
1044         assert(value);
1045         if (!strcmp(name, "user"))
1046             param_user = value;
1047         else if (!strcmp(name, "password"))
1048             param_password = value;
1049         else if (!strcmp(name, "content-user"))
1050             param_content_user = value;
1051         else if (!strcmp(name, "content-password"))
1052             param_content_password = value;
1053         else if (!strcmp(name, "content-proxy"))
1054             content_proxy = value;
1055         else if (!strcmp(name, "nocproxy"))
1056             param_nocproxy = value;
1057         else if (!strcmp(name, "proxy"))
1058         {
1059             char **dstr;
1060             int dnum = 0;
1061             nmem_strsplit(((ODR) odr)->mem, ",", value, &dstr, &dnum);
1062             if (connection_reuse)
1063             {
1064                 // find the step after our current proxy
1065                 int i;
1066                 for (i = 0; i < dnum; i++)
1067                     if (!strcmp(proxy.c_str(), dstr[i]))
1068                         break;
1069                 if (i >= dnum - 1)
1070                     *proxy_step = 0;
1071                 else
1072                     *proxy_step = i + 1;
1073             }
1074             else
1075             {
1076                 // step is known.. Guess our proxy from it
1077                 if (*proxy_step >= dnum)
1078                     *proxy_step = 0;
1079                 else
1080                 {
1081                     proxy = dstr[*proxy_step];
1082                     
1083                     (*proxy_step)++;
1084                     if (*proxy_step == dnum)
1085                         *proxy_step = 0;
1086                 }
1087             }
1088         }
1089         else if (!strcmp(name, "cproxysession"))
1090         {
1091             out_names[no_out_args] = name;
1092             out_values[no_out_args++] = value;
1093             torus_url = m_p->torus_content_url;
1094         }
1095         else if (!strcmp(name, "realm"))
1096             realm = value;
1097         else if (name[0] == 'x' && name[1] == '-')
1098         {
1099             out_names[no_out_args] = name;
1100             out_values[no_out_args++] = value;
1101         }
1102         else
1103         {
1104             BackendPtr notfound;
1105             char *msg = (char*) odr_malloc(odr, strlen(name) + 30);
1106             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1107             sprintf(msg, "Bad database argument: %s", name);
1108             *addinfo = msg;
1109             return notfound;
1110         }
1111     }    
1112     if (proxy.length())
1113         package.log("zoom", YLOG_LOG, "proxy: %s", proxy.c_str());
1114
1115     if (connection_reuse)
1116     {
1117         m_backend->connect("", error, addinfo, odr);
1118         return m_backend;
1119     }
1120
1121     if (param_user)
1122     {
1123         authentication = std::string(param_user);
1124         if (param_password)
1125             authentication += "/" + std::string(param_password);
1126     }
1127     if (param_content_user)
1128     {
1129         content_authentication = std::string(param_content_user);
1130         if (param_content_password)
1131             content_authentication += "/" + std::string(param_content_password);
1132     }
1133
1134     if (torus_db.compare("IR-Explain---1") == 0)
1135         return explain_search(package, database, error, addinfo, odr, torus_db,
1136             realm);
1137     
1138     SearchablePtr sptr;
1139
1140     std::map<std::string,SearchablePtr>::iterator it;
1141     it = m_p->s_map.find(torus_db);
1142     if (it != m_p->s_map.end())
1143         sptr = it->second;
1144     else if (torus_url.length() > 0)
1145     {
1146         std::string torus_query = "udb==" + torus_db;
1147         xmlDoc *doc = mp::get_searchable(package,torus_url, torus_db,
1148                                          torus_query,
1149                                          realm, m_p->proxy);
1150         if (!doc)
1151         {
1152             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1153             *addinfo = odr_strdup(odr, "Torus server unavailable or "
1154                                   "incorrectly configured");
1155             BackendPtr b;
1156             return b;
1157         }
1158         const xmlNode *ptr = xmlDocGetRootElement(doc);
1159         if (ptr)
1160         {   // presumably ptr is a records element node
1161             // parse first record in document
1162             for (ptr = ptr->children; ptr; ptr = ptr->next)
1163             {
1164                 if (ptr->type == XML_ELEMENT_NODE
1165                     && !strcmp((const char *) ptr->name, "record"))
1166                 {
1167                     if (sptr)
1168                     {
1169                         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1170                         *addinfo = (char*) odr_malloc(odr, 40 + database.length()),
1171                         sprintf(*addinfo, "multiple records for udb=%s",
1172                                  database.c_str());
1173                         xmlFreeDoc(doc);
1174                         BackendPtr b;
1175                         return b;
1176                     }
1177                     sptr = m_p->parse_torus_record(ptr);
1178                 }
1179             }
1180         }
1181         xmlFreeDoc(doc);
1182     }
1183
1184     if (!sptr)
1185     {
1186         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1187         *addinfo = odr_strdup(odr, torus_db.c_str());
1188         BackendPtr b;
1189         return b;
1190     }
1191         
1192     xsltStylesheetPtr xsp = 0;
1193     if (sptr->transform_xsl_content.length())
1194     {
1195         xmlDoc *xsp_doc = xmlParseMemory(sptr->transform_xsl_content.c_str(),
1196                                          sptr->transform_xsl_content.length());
1197         if (!xsp_doc)
1198         {
1199             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1200             *addinfo = (char *) odr_malloc(odr, 40);
1201             sprintf(*addinfo, "xmlParseMemory failed");
1202             BackendPtr b;
1203             return b;
1204         }
1205         xsp = xsltParseStylesheetDoc(xsp_doc);
1206         if (!xsp)
1207         {
1208             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1209             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
1210             BackendPtr b;
1211             xmlFreeDoc(xsp_doc);
1212             return b;
1213         }
1214     }
1215     else if (sptr->transform_xsl_fname.length())
1216     {
1217         const char *path = 0;
1218
1219         if (m_p->xsldir.length())
1220             path = m_p->xsldir.c_str();
1221         else
1222             path = m_p->file_path.c_str();
1223         std::string fname;
1224
1225         char fullpath[1024];
1226         char *cp = yaz_filepath_resolve(sptr->transform_xsl_fname.c_str(),
1227                                         path, 0, fullpath);
1228         if (cp)
1229             fname.assign(cp);
1230         else
1231         {
1232             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1233             *addinfo = (char *)
1234                 odr_malloc(odr, 40 + sptr->transform_xsl_fname.length());
1235             sprintf(*addinfo, "File could not be read: %s", 
1236                     sptr->transform_xsl_fname.c_str());
1237             BackendPtr b;
1238             return b;
1239         }
1240         xmlDoc *xsp_doc = xmlParseFile(fname.c_str());
1241         if (!xsp_doc)
1242         {
1243             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1244             *addinfo = (char *) odr_malloc(odr, 40 + fname.length());
1245             sprintf(*addinfo, "xmlParseFile failed. File: %s", fname.c_str());
1246             BackendPtr b;
1247             return b;
1248         }
1249         xsp = xsltParseStylesheetDoc(xsp_doc);
1250         if (!xsp)
1251         {
1252             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1253             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
1254             BackendPtr b;
1255             xmlFreeDoc(xsp_doc);
1256             return b;
1257         }
1258     }
1259
1260     m_backend.reset();
1261
1262     BackendPtr b(new Backend);
1263
1264     b->sptr = sptr;
1265     b->xsp = xsp;
1266     b->m_frontend_database = database;
1267     b->enable_cproxy = param_nocproxy ? false : true;
1268
1269     if (sptr->query_encoding.length())
1270         b->set_option("rpnCharset", sptr->query_encoding);
1271
1272     b->set_option("timeout", m_p->zoom_timeout.c_str());
1273     
1274     if (m_p->apdu_log) 
1275         b->set_option("apdulog", "1");
1276
1277     if (sptr->piggyback && sptr->sru.length())
1278         b->set_option("count", "1"); /* some SRU servers INSIST on getting
1279                                         maximumRecords > 0 */
1280     b->set_option("piggyback", sptr->piggyback ? "1" : "0");
1281
1282     if (authentication.length() == 0)
1283         authentication = sptr->authentication;
1284
1285     if (proxy.length() == 0)
1286         proxy = sptr->cfProxy;
1287     b->m_proxy = proxy;
1288     
1289     if (sptr->cfAuth.length())
1290     {
1291         // A CF target
1292         b->set_option("user", sptr->cfAuth);
1293         if (authentication.length())
1294         {
1295             size_t found = authentication.find('/');
1296             if (found != std::string::npos)
1297             {
1298                 out_names[no_out_args] = "user";
1299                 out_values[no_out_args++] =
1300                     odr_strdup(odr, authentication.substr(0, found).c_str());
1301
1302                 out_names[no_out_args] = "password";
1303                 out_values[no_out_args++] =
1304                     odr_strdup(odr, authentication.substr(found+1).c_str());
1305             }
1306             else
1307             {
1308                 out_names[no_out_args] = "user";
1309                 out_values[no_out_args++] =
1310                     odr_strdup(odr, authentication.c_str());
1311             }                
1312         }
1313         if (proxy.length())
1314         {
1315             out_names[no_out_args] = "proxy";
1316             out_values[no_out_args++] = odr_strdup(odr, proxy.c_str());
1317         }
1318         if (sptr->cfSubDB.length())
1319         {
1320             out_names[no_out_args] = "subdatabase";
1321             out_values[no_out_args++] = odr_strdup(odr, sptr->cfSubDB.c_str());
1322         }
1323         if (param_nocproxy)
1324         {
1325             out_names[no_out_args] = "nocproxy";
1326             out_values[no_out_args++] = odr_strdup(odr, param_nocproxy);
1327         }
1328     }
1329     else
1330     {
1331         size_t found = authentication.find('/');
1332         
1333         if (sptr->sru.length() && found != std::string::npos)
1334         {
1335             b->set_option("user", authentication.substr(0, found));
1336             b->set_option("password", authentication.substr(found+1));
1337         }
1338         else
1339             b->set_option("user", authentication);
1340
1341         if (proxy.length())
1342             b->set_option("proxy", proxy);
1343     }
1344     std::string url;
1345     if (sptr->sru.length())
1346     {
1347         url = "http://" + sptr->target;
1348         b->set_option("sru", sptr->sru);
1349
1350         if (sptr->sru_version.length())
1351             b->set_option("sru_version", sptr->sru_version);
1352     }
1353     else
1354     {
1355         url = sptr->target;
1356     }
1357     if (no_out_args)
1358     {
1359         char *x_args = 0;
1360         out_names[no_out_args] = 0; // terminate list
1361         
1362         yaz_array_to_uri(&x_args, odr, (char **) out_names,
1363                          (char **) out_values);
1364         url += "," + std::string(x_args);
1365     }
1366     package.log("zoom", YLOG_LOG, "url: %s", url.c_str());
1367     b->connect(url, error, addinfo, odr);
1368     if (*error == 0 && b->enable_cproxy)
1369         create_content_session(package, b, error, addinfo, odr,
1370                                content_authentication.length() ?
1371                                content_authentication : authentication,
1372                                content_proxy.length() ? content_proxy : proxy,
1373                                realm);
1374     if (*error == 0)
1375         m_backend = b;
1376     return b;
1377 }
1378
1379 void yf::Zoom::Frontend::prepare_elements(BackendPtr b,
1380                                           Odr_oid *preferredRecordSyntax,
1381                                           const char *element_set_name,
1382                                           bool &enable_pz2_retrieval,
1383                                           bool &enable_pz2_transform,
1384                                           bool &enable_record_transform,
1385                                           bool &assume_marc8_charset)
1386 {
1387     char oid_name_str[OID_STR_MAX];
1388     const char *syntax_name = 0;
1389     
1390     if (preferredRecordSyntax &&
1391         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml))
1392     {
1393         if (element_set_name &&
1394             !strcmp(element_set_name, m_p->element_transform.c_str()))
1395         {
1396             enable_pz2_retrieval = true;
1397             enable_pz2_transform = true;
1398         }
1399         else if (element_set_name && 
1400                  !strcmp(element_set_name, m_p->element_raw.c_str()))
1401         {
1402             enable_pz2_retrieval = true;
1403         }
1404         else if (m_p->record_xsp)
1405         {
1406             enable_pz2_retrieval = true;
1407             enable_pz2_transform = true;
1408             enable_record_transform = true;
1409         }
1410     }
1411     
1412     if (enable_pz2_retrieval)
1413     {
1414         std::string configured_request_syntax = b->sptr->request_syntax;
1415         if (configured_request_syntax.length())
1416         {
1417             syntax_name = configured_request_syntax.c_str();
1418             const Odr_oid *syntax_oid = 
1419                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
1420             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
1421                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
1422                 assume_marc8_charset = true;
1423         }
1424     }
1425     else if (preferredRecordSyntax)
1426         syntax_name =
1427             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
1428
1429     if (b->sptr->sru.length())
1430         syntax_name = "XML";
1431
1432     b->set_option("preferredRecordSyntax", syntax_name);
1433
1434     if (enable_pz2_retrieval)
1435     {
1436         element_set_name = 0;
1437         if (b->sptr->element_set.length())
1438             element_set_name = b->sptr->element_set.c_str();
1439     }
1440
1441     b->set_option("elementSetName", element_set_name);
1442     if (b->sptr->sru.length() && element_set_name)
1443         b->set_option("schema", element_set_name);
1444 }
1445
1446 Z_Records *yf::Zoom::Frontend::get_explain_records(
1447     mp::Package &package,
1448     Odr_int start,
1449     Odr_int number_to_present,
1450     int *error,
1451     char **addinfo,
1452     Odr_int *number_of_records_returned,
1453     ODR odr,
1454     BackendPtr b,
1455     Odr_oid *preferredRecordSyntax,
1456     const char *element_set_name)
1457 {
1458     Odr_int i;
1459     Z_Records *records = 0;
1460
1461     if (!b->explain_doc)
1462     {
1463         return records;
1464     }
1465     if (number_to_present > 10000)
1466         number_to_present = 10000;
1467
1468     xmlNode *ptr = xmlDocGetRootElement(b->explain_doc);
1469     
1470     Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1471         odr_malloc(odr, sizeof(*npl));
1472     npl->records = (Z_NamePlusRecord **)
1473         odr_malloc(odr, number_to_present * sizeof(*npl->records));
1474     
1475     for (i = 0; i < number_to_present; i++)
1476     {
1477         int num = 0;
1478         xmlNode *res = xml_node_search(ptr, &num, start + i + 1);
1479         if (!res)
1480             break;
1481         xmlBufferPtr xml_buf = xmlBufferCreate();
1482         xmlNode *tmp_node = xmlCopyNode(res->children, 1);
1483         xmlNodeDump(xml_buf, tmp_node->doc, tmp_node, 0, 0);
1484
1485         Z_NamePlusRecord *npr =
1486             (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1487         npr->databaseName = odr_strdup(odr, b->m_frontend_database.c_str());
1488         npr->which = Z_NamePlusRecord_databaseRecord;
1489         npr->u.databaseRecord =
1490             z_ext_record_xml(odr,
1491                              (const char *) xml_buf->content, xml_buf->use);
1492         npl->records[i] = npr;
1493         xmlFreeNode(tmp_node);
1494         xmlBufferFree(xml_buf);
1495     }
1496     records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1497     records->which = Z_Records_DBOSD;
1498     records->u.databaseOrSurDiagnostics = npl;
1499
1500     npl->num_records = i;
1501     *number_of_records_returned = i;
1502     return records;
1503 }
1504
1505
1506 Z_Records *yf::Zoom::Frontend::get_records(mp::Package &package,
1507                                            Odr_int start,
1508                                            Odr_int number_to_present,
1509                                            int *error,
1510                                            char **addinfo,
1511                                            Odr_int *number_of_records_returned,
1512                                            ODR odr,
1513                                            BackendPtr b,
1514                                            Odr_oid *preferredRecordSyntax,
1515                                            const char *element_set_name)
1516 {
1517     *number_of_records_returned = 0;
1518     Z_Records *records = 0;
1519     bool enable_pz2_retrieval = false; // whether target profile is used
1520     bool enable_pz2_transform = false; // whether XSLT is used as well
1521     bool assume_marc8_charset = false;
1522     bool enable_record_transform = false;
1523
1524     prepare_elements(b, preferredRecordSyntax,
1525                      element_set_name,
1526                      enable_pz2_retrieval,
1527                      enable_pz2_transform,
1528                      enable_record_transform,
1529                      assume_marc8_charset);
1530
1531     package.log("zoom", YLOG_LOG, "pz2_retrieval: %s . pz2_transform: %s",
1532                 enable_pz2_retrieval ? "yes" : "no",
1533                 enable_pz2_transform ? "yes" : "no");
1534
1535     if (start < 0 || number_to_present <=0)
1536         return records;
1537     
1538     if (number_to_present > 10000)
1539         number_to_present = 10000;
1540
1541     ZOOM_record *recs = (ZOOM_record *)
1542         odr_malloc(odr, (size_t) number_to_present * sizeof(*recs));
1543
1544     b->present(start, number_to_present, recs, error, addinfo, odr);
1545
1546     int i = 0;
1547     if (!*error)
1548     {
1549         for (i = 0; i < number_to_present; i++)
1550             if (!recs[i])
1551                 break;
1552     }
1553     if (i > 0)
1554     {  // only return records if no error and at least one record
1555
1556         const char *xsl_parms[3];
1557         mp::wrbuf cproxy_host;
1558         
1559         if (b->enable_cproxy && b->cproxy_host.length())
1560         {
1561             wrbuf_puts(cproxy_host, "\"");
1562             wrbuf_puts(cproxy_host, b->cproxy_host.c_str());
1563             wrbuf_puts(cproxy_host, "/\"");
1564
1565             xsl_parms[0] = "cproxyhost";
1566             xsl_parms[1] = wrbuf_cstr(cproxy_host);
1567             xsl_parms[2] = 0;
1568         }
1569         else
1570         {
1571             xsl_parms[0] = 0;
1572         }
1573
1574         char *odr_database = odr_strdup(odr,
1575                                         b->m_frontend_database.c_str());
1576         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1577             odr_malloc(odr, sizeof(*npl));
1578         *number_of_records_returned = i;
1579         npl->num_records = i;
1580         npl->records = (Z_NamePlusRecord **)
1581             odr_malloc(odr, i * sizeof(*npl->records));
1582         for (i = 0; i < number_to_present; i++)
1583         {
1584             Z_NamePlusRecord *npr = 0;
1585             const char *addinfo;
1586
1587             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1588                                               &addinfo, 0 /* diagset */);
1589                 
1590             if (sur_error)
1591             {
1592                 log_diagnostic(package, sur_error, addinfo);
1593                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1594                                             addinfo);
1595             }
1596             else if (enable_pz2_retrieval)
1597             {
1598                 char rec_type_str[100];
1599                 const char *record_encoding = 0;
1600
1601                 if (b->sptr->record_encoding.length())
1602                     record_encoding = b->sptr->record_encoding.c_str();
1603                 else if (assume_marc8_charset)
1604                     record_encoding = "marc8";
1605
1606                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1607                 if (record_encoding)
1608                 {
1609                     strcat(rec_type_str, "; charset=");
1610                     strcat(rec_type_str, record_encoding);
1611                 }
1612
1613                 package.log("zoom", YLOG_LOG, "Getting record of type %s",
1614                             rec_type_str);
1615                 int rec_len;
1616                 xmlChar *xmlrec_buf = 0;
1617                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1618                                                       &rec_len);
1619                 if (!rec_buf && !npr)
1620                 {
1621                     std::string addinfo("ZOOM_record_get failed for type ");
1622
1623                     int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1624                     addinfo += rec_type_str;
1625                     log_diagnostic(package, error, addinfo.c_str());
1626                     npr = zget_surrogateDiagRec(odr, odr_database,
1627                                                 error, addinfo.c_str());
1628                 }
1629                 else
1630                 {
1631                     package.log_write(rec_buf, rec_len);
1632                     package.log_write("\r\n", 2);
1633                 }
1634
1635                 if (rec_buf && b->xsp && enable_pz2_transform)
1636                 {
1637                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1638                     if (!rec_doc)
1639                     {
1640                         const char *addinfo = "xml parse failed for record";
1641                         int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1642                         log_diagnostic(package, error, addinfo);
1643                         npr = zget_surrogateDiagRec(
1644                             odr, odr_database, error, addinfo);
1645                     }
1646                     else
1647                     { 
1648                         // first stage XSLT - per target
1649                         xsltStylesheetPtr xsp = b->xsp;
1650                         xmlDoc *rec_res = xsltApplyStylesheet(xsp, rec_doc,
1651                                                               xsl_parms);
1652                         // insert generated-url
1653                         if (rec_res)
1654                         {
1655                             std::string res = 
1656                                 mp::xml::url_recipe_handle(rec_res,
1657                                                            b->sptr->urlRecipe);
1658                             if (res.length())
1659                             {
1660                                 xmlNode *ptr = xmlDocGetRootElement(rec_res);
1661                                 while (ptr && ptr->type != XML_ELEMENT_NODE)
1662                                     ptr = ptr->next;
1663                                 xmlNode *c = 
1664                                     xmlNewChild(ptr, 0, BAD_CAST "metadata", 0);
1665                                 xmlNewProp(c, BAD_CAST "type", BAD_CAST
1666                                            "generated-url");
1667                                 xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1668                                 xmlAddChild(c, t);
1669                             }
1670                         }
1671                         // second stage XSLT - common
1672                         if (rec_res && m_p->record_xsp &&
1673                             enable_record_transform)
1674                         {
1675                             xmlDoc *tmp_doc = rec_res;
1676
1677                             xsp = m_p->record_xsp;
1678                             rec_res = xsltApplyStylesheet(xsp, tmp_doc,
1679                                                           xsl_parms);
1680                             xmlFreeDoc(tmp_doc);
1681                         }
1682                         // get result out of it
1683                         if (rec_res)
1684                         {
1685                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1686                                                    rec_res, xsp);
1687                             rec_buf = (const char *) xmlrec_buf;
1688                             package.log_write(rec_buf, rec_len);
1689
1690                             xmlFreeDoc(rec_res);
1691                         }
1692                         if (!rec_buf)
1693                         {
1694                             std::string addinfo;
1695                             int error =
1696                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1697
1698                             addinfo = "xslt apply failed for "
1699                                 + b->sptr->transform_xsl_fname;
1700                             log_diagnostic(package, error, addinfo.c_str());
1701                             npr = zget_surrogateDiagRec(
1702                                 odr, odr_database, error, addinfo.c_str());
1703                         }
1704                         xmlFreeDoc(rec_doc);
1705                     }
1706                 }
1707
1708                 if (!npr)
1709                 {
1710                     if (!rec_buf)
1711                         npr = zget_surrogateDiagRec(
1712                             odr, odr_database, 
1713                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1714                             rec_type_str);
1715                     else
1716                     {
1717                         npr = (Z_NamePlusRecord *)
1718                             odr_malloc(odr, sizeof(*npr));
1719                         npr->databaseName = odr_database;
1720                         npr->which = Z_NamePlusRecord_databaseRecord;
1721                         npr->u.databaseRecord =
1722                             z_ext_record_xml(odr, rec_buf, rec_len);
1723                     }
1724                 }
1725                 if (xmlrec_buf)
1726                     xmlFree(xmlrec_buf);
1727             }
1728             else
1729             {
1730                 Z_External *ext =
1731                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1732                 if (ext)
1733                 {
1734                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1735                     npr->databaseName = odr_database;
1736                     npr->which = Z_NamePlusRecord_databaseRecord;
1737                     npr->u.databaseRecord = ext;
1738                 }
1739                 else
1740                 {
1741                     npr = zget_surrogateDiagRec(
1742                         odr, odr_database, 
1743                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1744                         "ZOOM_record, type ext");
1745                 }
1746             }
1747             npl->records[i] = npr;
1748         }
1749         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1750         records->which = Z_Records_DBOSD;
1751         records->u.databaseOrSurDiagnostics = npl;
1752     }
1753     return records;
1754 }
1755
1756 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1757                                                     ODR odr)
1758 {
1759     struct cql_node *r = 0;
1760     if (!cn)
1761         return 0;
1762     switch (cn->which)
1763     {
1764     case CQL_NODE_ST:
1765         if (cn->u.st.index)
1766         {
1767             std::map<std::string,std::string>::const_iterator it;
1768             it = fieldmap.find(cn->u.st.index);
1769             if (it == fieldmap.end())
1770                 return cn;
1771             if (it->second.length())
1772                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1773             else
1774                 cn->u.st.index = 0;
1775         }
1776         break;
1777     case CQL_NODE_BOOL:
1778         r = convert_cql_fields(cn->u.boolean.left, odr);
1779         if (!r)
1780             r = convert_cql_fields(cn->u.boolean.right, odr);
1781         break;
1782     case CQL_NODE_SORT:
1783         r = convert_cql_fields(cn->u.sort.search, odr);
1784         break;
1785     }
1786     return r;
1787 }
1788
1789 void yf::Zoom::Frontend::log_diagnostic(mp::Package &package,
1790                                         int error, const char *addinfo)
1791 {
1792     const char *err_msg = yaz_diag_bib1_str(error);
1793     if (addinfo)
1794         package.log("zoom", YLOG_WARN, "Diagnostic %d %s: %s",
1795                     error, err_msg, addinfo);
1796     else
1797         package.log("zoom", YLOG_WARN, "Diagnostic %d %s:",
1798                     error, err_msg);
1799 }
1800
1801 yf::Zoom::BackendPtr yf::Zoom::Frontend::explain_search(mp::Package &package,
1802                                                         std::string &database,
1803                                                         int *error,
1804                                                         char **addinfo,
1805                                                         mp::odr &odr,
1806                                                         std::string &torus_db,
1807                                                         std::string &realm)
1808 {
1809     m_backend.reset();
1810
1811     BackendPtr b(new Backend);
1812
1813     b->m_frontend_database = database;
1814     b->enable_explain = true;
1815    
1816     Z_GDU *gdu = package.request().get();
1817     Z_APDU *apdu_req = gdu->u.z3950;
1818     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1819     Z_Query *query = sr->query;
1820
1821     if (!m_p->explain_xsp)
1822     {
1823         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1824         *addinfo =
1825             odr_strdup(odr, "IR-Explain---1 unsupported. "
1826                        "Torus explain_xsl not defined");
1827         return m_backend;
1828     }
1829     else if (query->which == Z_Query_type_104 &&
1830         query->u.type_104->which == Z_External_CQL)
1831     {
1832         std::string torus_url = m_p->torus_searchable_url;
1833         std::string torus_query(query->u.type_104->u.cql);
1834         xmlDoc *doc = mp::get_searchable(package, torus_url, "",
1835                                          torus_query,
1836                                          realm, m_p->proxy);
1837         if (m_p->explain_xsp)
1838         {
1839             xmlDoc *rec_res =  xsltApplyStylesheet(m_p->explain_xsp, doc, 0);
1840
1841             xmlFreeDoc(doc);
1842             doc = rec_res;
1843         }
1844         if (!doc)
1845         {
1846             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1847             *addinfo = odr_strdup(odr, "Torus server unavailable or "
1848                                   "incorrectly configured");
1849         }
1850         else
1851         {
1852             xmlNode *ptr = xmlDocGetRootElement(doc);
1853             int hits = 0;
1854             
1855             xml_node_search(ptr, &hits, 0);
1856
1857             Z_APDU *apdu_res = odr.create_searchResponse(apdu_req, 0, 0);
1858             apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1859             package.response() = apdu_res;
1860             m_backend = b;
1861         }
1862         if (b->explain_doc)
1863             xmlFreeDoc(b->explain_doc);
1864         b->explain_doc = doc;
1865         return m_backend;
1866     }
1867     else
1868     {
1869         *error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
1870         *addinfo = odr_strdup(odr, "IR-Explain---1 only supports CQL");
1871         return m_backend;
1872     }
1873 }
1874
1875 static bool wait_conn(COMSTACK cs, int secs)
1876 {
1877     struct yaz_poll_fd pfd;
1878
1879     yaz_poll_add(pfd.input_mask, yaz_poll_except);
1880     if (cs->io_pending && CS_WANT_WRITE)
1881         yaz_poll_add(pfd.input_mask, yaz_poll_write);
1882     if (cs->io_pending & CS_WANT_READ)
1883         yaz_poll_add(pfd.input_mask, yaz_poll_read);
1884
1885     pfd.fd = cs_fileno(cs);
1886     pfd.client_data = 0;
1887     
1888     int ret = yaz_poll(&pfd, 1, secs, 0);
1889     return ret > 0;
1890 }
1891
1892 bool yf::Zoom::Impl::check_proxy(const char *proxy)
1893 {
1894     COMSTACK conn = 0;
1895     const char *uri = "http://localhost/";
1896     void *add;
1897     mp::odr odr;
1898     bool outcome = false;
1899     conn = cs_create_host_proxy(uri, 0, &add, proxy);
1900
1901     if (!conn)
1902         return false;
1903
1904     Z_GDU *gdu = z_get_HTTP_Request_uri(odr, uri, 0, 1);
1905     gdu->u.HTTP_Request->method = odr_strdup(odr, "GET");
1906     
1907     if (z_GDU(odr, &gdu, 0, 0))
1908     {
1909         int len;
1910         char *buf = odr_getbuf(odr, &len, 0);
1911         
1912         int ret = cs_connect(conn, add);
1913         if (ret > 0 || (ret == 0 && wait_conn(conn, 1)))
1914         {
1915             while (1)
1916             {
1917                 ret = cs_put(conn, buf, len);
1918                 if (ret != 1)
1919                     break;
1920                 if (!wait_conn(conn, proxy_timeout))
1921                     break;
1922             }
1923             if (ret == 0)
1924                 outcome = true;
1925         }
1926     }
1927     cs_close(conn);
1928     return outcome;
1929 }
1930
1931 bool yf::Zoom::Frontend::retry(mp::Package &package,
1932                                mp::odr &odr,
1933                                BackendPtr b, 
1934                                int &error, char **addinfo,
1935                                int &proxy_step, int &same_retries,
1936                                int &proxy_retries)
1937 {
1938     if (b && b->m_proxy.length() && !m_p->check_proxy(b->m_proxy.c_str()))
1939     {
1940         log_diagnostic(package, error, *addinfo);
1941         package.log("zoom", YLOG_LOG, "proxy %s fails", b->m_proxy.c_str());
1942         m_backend.reset();
1943         if (proxy_step) // there is a failover
1944         {
1945             proxy_retries++;
1946             package.log("zoom", YLOG_WARN, "search failed: trying next proxy");
1947             return true;
1948         }
1949         error = YAZ_BIB1_PROXY_FAILURE;
1950         *addinfo = odr_strdup(odr, b->m_proxy.c_str());
1951     }
1952     else if (same_retries == 0 && proxy_retries == 0)
1953     {
1954         log_diagnostic(package, error, *addinfo);
1955         same_retries++;
1956         package.log("zoom", YLOG_WARN, "search failed: retry");
1957         m_backend.reset();
1958         proxy_step = 0;
1959         return true;
1960     }
1961     return false;
1962 }
1963
1964 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1965 {
1966     Z_GDU *gdu = package.request().get();
1967     Z_APDU *apdu_req = gdu->u.z3950;
1968     Z_APDU *apdu_res = 0;
1969     mp::odr odr;
1970     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1971     if (sr->num_databaseNames != 1)
1972     {
1973         int error = YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED;
1974         log_diagnostic(package, error, 0);
1975         apdu_res = odr.create_searchResponse(apdu_req, error, 0);
1976         package.response() = apdu_res;
1977         return;
1978     }
1979     int proxy_step = 0;
1980     int same_retries = 0;
1981     int proxy_retries = 0;
1982
1983 next_proxy:
1984
1985     int error = 0;
1986     char *addinfo = 0;
1987     std::string db(sr->databaseNames[0]);
1988
1989     BackendPtr b = get_backend_from_databases(package, db, &error,
1990                                               &addinfo, odr, &proxy_step);
1991     if (error)
1992     {
1993         if (retry(package, odr, b, error, &addinfo, proxy_step,
1994                   same_retries, proxy_retries))
1995             goto next_proxy;
1996     }
1997     if (error)
1998     {
1999         log_diagnostic(package, error, addinfo);
2000         apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2001         package.response() = apdu_res;
2002         return;
2003     }
2004     if (!b || b->enable_explain)
2005         return;
2006
2007     b->set_option("setname", "default");
2008
2009     bool enable_pz2_retrieval = false;
2010     bool enable_pz2_transform = false;
2011     bool enable_record_transform = false;
2012     bool assume_marc8_charset = false;
2013     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
2014                      enable_pz2_retrieval,
2015                      enable_pz2_transform,
2016                      enable_record_transform,
2017                      assume_marc8_charset);
2018
2019     Odr_int hits = 0;
2020     Z_Query *query = sr->query;
2021     mp::wrbuf ccl_wrbuf;
2022     mp::wrbuf pqf_wrbuf;
2023     std::string sortkeys;
2024
2025     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
2026     {
2027         // RPN
2028         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
2029     }
2030     else if (query->which == Z_Query_type_2)
2031     {
2032         // CCL
2033         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
2034                     query->u.type_2->len);
2035     }
2036     else if (query->which == Z_Query_type_104 &&
2037              query->u.type_104->which == Z_External_CQL)
2038     {
2039         // CQL
2040         const char *cql = query->u.type_104->u.cql;
2041         CQL_parser cp = cql_parser_create();
2042         int r = cql_parser_string(cp, cql);
2043         package.log("zoom", YLOG_LOG, "CQL: %s", cql);
2044         if (r)
2045         {
2046             cql_parser_destroy(cp);
2047             error = YAZ_BIB1_MALFORMED_QUERY;
2048             const char *addinfo = "CQL syntax error";
2049             log_diagnostic(package, error, addinfo);
2050             apdu_res = 
2051                 odr.create_searchResponse(apdu_req, error, addinfo);
2052             package.response() = apdu_res;
2053             return;
2054         }
2055         struct cql_node *cn = cql_parser_result(cp);
2056         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
2057         if (cn_error)
2058         {
2059             // hopefully we are getting a ptr to a index+relation+term node
2060             error = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
2061             addinfo = 0;
2062             if (cn_error->which == CQL_NODE_ST)
2063                 addinfo = cn_error->u.st.index;
2064             
2065             log_diagnostic(package, error, addinfo);
2066             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2067             package.response() = apdu_res;
2068             cql_parser_destroy(cp);
2069             return;
2070         }
2071         r = cql_to_ccl(cn, wrbuf_vp_puts,  ccl_wrbuf);
2072         if (r)
2073         {
2074             error = YAZ_BIB1_MALFORMED_QUERY;
2075             const char *addinfo = "CQL to CCL conversion error";
2076
2077             log_diagnostic(package, error, addinfo);
2078             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2079             package.response() = apdu_res;
2080             cql_parser_destroy(cp);
2081             return;
2082         }
2083
2084         mp::wrbuf sru_sortkeys_wrbuf;
2085         if (cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf))
2086         {
2087             error = YAZ_BIB1_ILLEGAL_SORT_RELATION;
2088             const char *addinfo = "CQL to CCL sortby conversion";
2089
2090             log_diagnostic(package, error, addinfo);
2091             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2092             package.response() = apdu_res;
2093             cql_parser_destroy(cp);
2094             return;
2095         }
2096         mp::wrbuf sort_spec_wrbuf;
2097         yaz_srw_sortkeys_to_sort_spec(wrbuf_cstr(sru_sortkeys_wrbuf),
2098                                       sort_spec_wrbuf);
2099         yaz_tok_cfg_t tc = yaz_tok_cfg_create();
2100         yaz_tok_parse_t tp =
2101             yaz_tok_parse_buf(tc, wrbuf_cstr(sort_spec_wrbuf));
2102         yaz_tok_cfg_destroy(tc);
2103         
2104         /* go through sortspec and map fields */
2105         int token = yaz_tok_move(tp);
2106         while (token != YAZ_TOK_EOF)
2107         {
2108             if (token == YAZ_TOK_STRING)
2109             {
2110                 const char *field = yaz_tok_parse_string(tp);
2111                 std::map<std::string,std::string>::iterator it;
2112                 it = b->sptr->sortmap.find(field);
2113                 if (it != b->sptr->sortmap.end())
2114                     sortkeys += it->second;
2115                 else
2116                     sortkeys += field;
2117             }
2118             sortkeys += " ";
2119             token = yaz_tok_move(tp);
2120             if (token == YAZ_TOK_STRING)
2121             {
2122                 sortkeys += yaz_tok_parse_string(tp);
2123             }
2124             if (token != YAZ_TOK_EOF)
2125             {
2126                 sortkeys += " ";
2127                 token = yaz_tok_move(tp);
2128             }
2129         }
2130         yaz_tok_parse_destroy(tp);
2131         cql_parser_destroy(cp);
2132     }
2133     else
2134     {
2135         error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
2136         const char *addinfo = 0;
2137         log_diagnostic(package, error, addinfo);
2138         apdu_res =  odr.create_searchResponse(apdu_req, error, addinfo);
2139         package.response() = apdu_res;
2140         return;
2141     }
2142
2143     if (ccl_wrbuf.len())
2144     {
2145         // CCL to PQF
2146         assert(pqf_wrbuf.len() == 0);
2147         int cerror, cpos;
2148         struct ccl_rpn_node *cn;
2149         package.log("zoom", YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
2150         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
2151                           &cerror, &cpos);
2152         if (!cn)
2153         {
2154             char *addinfo = odr_strdup_null(odr, ccl_err_msg(cerror));
2155             error = YAZ_BIB1_MALFORMED_QUERY;
2156
2157             switch (cerror)
2158             {
2159             case CCL_ERR_UNKNOWN_QUAL:
2160             case CCL_ERR_TRUNC_NOT_LEFT: 
2161             case CCL_ERR_TRUNC_NOT_RIGHT:
2162             case CCL_ERR_TRUNC_NOT_BOTH:
2163 #ifdef CCL_ERR_TRUNC_NOT_EMBED
2164             case CCL_ERR_TRUNC_NOT_EMBED:
2165 #endif
2166 #ifdef CCL_ERR_TRUNC_NOT_SINGLE
2167             case CCL_ERR_TRUNC_NOT_SINGLE:
2168 #endif
2169                 error = YAZ_BIB1_UNSUPP_SEARCH;
2170                 break;
2171             }
2172             log_diagnostic(package, error, addinfo);
2173             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2174             package.response() = apdu_res;
2175             return;
2176         }
2177         ccl_pquery(pqf_wrbuf, cn);
2178         package.log("zoom", YLOG_LOG, "RPN: %s", wrbuf_cstr(pqf_wrbuf));
2179         ccl_rpn_delete(cn);
2180     }
2181     
2182     assert(pqf_wrbuf.len());
2183
2184     ZOOM_query q = ZOOM_query_create();
2185     ZOOM_query_sortby2(q, b->sptr->sortStrategy.c_str(), sortkeys.c_str());
2186
2187     if (b->get_option("sru"))
2188     {
2189         int status = 0;
2190         Z_RPNQuery *zquery;
2191         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
2192         mp::wrbuf wrb;
2193             
2194         if (!strcmp(b->get_option("sru"), "solr"))
2195         {
2196             solr_transform_t cqlt = solr_transform_create();
2197             
2198             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
2199             
2200             solr_transform_close(cqlt);
2201         }
2202         else
2203         {
2204             cql_transform_t cqlt = cql_transform_create();
2205             
2206             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
2207             
2208             cql_transform_close(cqlt);
2209         }
2210         if (status == 0)
2211         {
2212             ZOOM_query_cql(q, wrbuf_cstr(wrb));
2213             package.log("zoom", YLOG_LOG, "CQL: %s", wrbuf_cstr(wrb));
2214             b->search(q, &hits, &error, &addinfo, odr);
2215         }
2216         ZOOM_query_destroy(q);
2217         
2218         if (status)
2219         {
2220             error = YAZ_BIB1_MALFORMED_QUERY;
2221             const char *addinfo = "can not convert from RPN to CQL/SOLR";
2222             log_diagnostic(package, error, addinfo);
2223             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2224             package.response() = apdu_res;
2225             return;
2226         }
2227     }
2228     else
2229     {
2230         ZOOM_query_prefix(q, wrbuf_cstr(pqf_wrbuf));
2231         package.log("zoom", YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
2232         b->search(q, &hits, &error, &addinfo, odr);
2233         ZOOM_query_destroy(q);
2234     }
2235
2236     if (error)
2237     {
2238         if (retry(package, odr, b, error, &addinfo, proxy_step,
2239                   same_retries, proxy_retries))
2240             goto next_proxy;
2241     }
2242
2243     const char *element_set_name = 0;
2244     Odr_int number_to_present = 0;
2245     if (!error)
2246         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
2247     
2248     Odr_int number_of_records_returned = 0;
2249     Z_Records *records = get_records(
2250         package,
2251         0, number_to_present, &error, &addinfo,
2252         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
2253         element_set_name);
2254     if (error)
2255         log_diagnostic(package, error, addinfo);
2256     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2257     if (records)
2258     {
2259         apdu_res->u.searchResponse->records = records;
2260         apdu_res->u.searchResponse->numberOfRecordsReturned =
2261             odr_intdup(odr, number_of_records_returned);
2262     }
2263     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
2264     package.response() = apdu_res;
2265 }
2266
2267 void yf::Zoom::Frontend::handle_present(mp::Package &package)
2268 {
2269     Z_GDU *gdu = package.request().get();
2270     Z_APDU *apdu_req = gdu->u.z3950;
2271     Z_APDU *apdu_res = 0;
2272     Z_PresentRequest *pr = apdu_req->u.presentRequest;
2273
2274     mp::odr odr;
2275     if (!m_backend)
2276     {
2277         package.response() = odr.create_presentResponse(
2278             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
2279         return;
2280     }
2281     const char *element_set_name = 0;
2282     Z_RecordComposition *comp = pr->recordComposition;
2283     if (comp && comp->which != Z_RecordComp_simple)
2284     {
2285         package.response() = odr.create_presentResponse(
2286             apdu_req, 
2287             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
2288         return;
2289     }
2290     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
2291         element_set_name = comp->u.simple->u.generic;
2292     Odr_int number_of_records_returned = 0;
2293     int error = 0;
2294     char *addinfo = 0;
2295
2296     if (m_backend->enable_explain)
2297     {
2298         Z_Records *records =
2299             get_explain_records(
2300                 package,
2301                 *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2302                 &error, &addinfo, &number_of_records_returned, odr, m_backend,
2303                 pr->preferredRecordSyntax, element_set_name);
2304         
2305         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2306         if (records)
2307         {
2308             apdu_res->u.presentResponse->records = records;
2309             apdu_res->u.presentResponse->numberOfRecordsReturned =
2310                 odr_intdup(odr, number_of_records_returned);
2311         }
2312         package.response() = apdu_res;
2313     }
2314     else
2315     {
2316         Z_Records *records =
2317             get_records(package,
2318                         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2319                         &error, &addinfo, &number_of_records_returned, odr, m_backend,
2320                         pr->preferredRecordSyntax, element_set_name);
2321         
2322         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2323         if (records)
2324         {
2325             apdu_res->u.presentResponse->records = records;
2326             apdu_res->u.presentResponse->numberOfRecordsReturned =
2327                 odr_intdup(odr, number_of_records_returned);
2328         }
2329         package.response() = apdu_res;
2330     }
2331 }
2332
2333 void yf::Zoom::Frontend::handle_package(mp::Package &package)
2334 {
2335     Z_GDU *gdu = package.request().get();
2336     if (!gdu)
2337         ;
2338     else if (gdu->which == Z_GDU_Z3950)
2339     {
2340         Z_APDU *apdu_req = gdu->u.z3950;
2341
2342         if (m_backend)
2343             wrbuf_rewind(m_backend->m_apdu_wrbuf);
2344         if (apdu_req->which == Z_APDU_initRequest)
2345         {
2346             mp::odr odr;
2347             package.response() = odr.create_close(
2348                 apdu_req,
2349                 Z_Close_protocolError,
2350                 "double init");
2351         }
2352         else if (apdu_req->which == Z_APDU_searchRequest)
2353         {
2354             handle_search(package);
2355         }
2356         else if (apdu_req->which == Z_APDU_presentRequest)
2357         {
2358             handle_present(package);
2359         }
2360         else
2361         {
2362             mp::odr odr;
2363             package.response() = odr.create_close(
2364                 apdu_req,
2365                 Z_Close_protocolError,
2366                 "zoom filter cannot handle this APDU");
2367             package.session().close();
2368         }
2369         if (m_backend)
2370         {
2371             WRBUF w = m_backend->m_apdu_wrbuf;
2372             package.log_write(wrbuf_buf(w), wrbuf_len(w));
2373         }
2374     }
2375     else
2376     {
2377         package.session().close();
2378     }
2379 }
2380
2381 void yf::Zoom::Impl::process(mp::Package &package)
2382 {
2383     FrontendPtr f = get_frontend(package);
2384     Z_GDU *gdu = package.request().get();
2385
2386     if (f->m_is_virtual)
2387     {
2388         f->handle_package(package);
2389     }
2390     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
2391              Z_APDU_initRequest)
2392     {
2393         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
2394         f->m_init_gdu = gdu;
2395         
2396         mp::odr odr;
2397         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
2398         Z_InitResponse *resp = apdu->u.initResponse;
2399         
2400         int i;
2401         static const int masks[] = {
2402             Z_Options_search,
2403             Z_Options_present,
2404             -1 
2405         };
2406         for (i = 0; masks[i] != -1; i++)
2407             if (ODR_MASK_GET(req->options, masks[i]))
2408                 ODR_MASK_SET(resp->options, masks[i]);
2409         
2410         static const int versions[] = {
2411             Z_ProtocolVersion_1,
2412             Z_ProtocolVersion_2,
2413             Z_ProtocolVersion_3,
2414             -1
2415         };
2416         for (i = 0; versions[i] != -1; i++)
2417             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
2418                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
2419             else
2420                 break;
2421         
2422         *resp->preferredMessageSize = *req->preferredMessageSize;
2423         *resp->maximumRecordSize = *req->maximumRecordSize;
2424         
2425         package.response() = apdu;
2426         f->m_is_virtual = true;
2427     }
2428     else
2429         package.move();
2430
2431     release_frontend(package);
2432 }
2433
2434
2435 static mp::filter::Base* filter_creator()
2436 {
2437     return new mp::filter::Zoom;
2438 }
2439
2440 extern "C" {
2441     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
2442         0,
2443         "zoom",
2444         filter_creator
2445     };
2446 }
2447
2448
2449 /*
2450  * Local variables:
2451  * c-basic-offset: 4
2452  * c-file-style: "Stroustrup"
2453  * indent-tabs-mode: nil
2454  * End:
2455  * vim: shiftwidth=4 tabstop=8 expandtab
2456  */
2457