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