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