zoom: support cf_-params MP-595
[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             std::map<std::string, std::string> cf_param;
87             bool use_turbomarc;
88             bool piggyback;
89             CCL_bibset ccl_bibset;
90             std::map<std::string, std::string> sortmap;
91             Searchable(CCL_bibset base);
92             ~Searchable();
93         };
94         class Zoom::Backend : boost::noncopyable {
95             friend class Impl;
96             friend class Frontend;
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         else if (strlen((const char *) ptr->name) > 3 &&
720                  !memcmp((const char *) ptr->name, "cf_", 3))
721         {
722             s->cf_param[(const char *) ptr->name + 3] = mp::xml::get_text(ptr);
723         }
724     }
725     return s;
726 }
727
728 void yf::Zoom::Impl::configure_local_records(const xmlNode *ptr, bool test_only)
729 {
730     while (ptr && ptr->type != XML_ELEMENT_NODE)
731         ptr = ptr->next;
732
733     if (ptr)
734     {
735         if (!strcmp((const char *) ptr->name, "records"))
736         {
737             for (ptr = ptr->children; ptr; ptr = ptr->next)
738             {
739                 if (ptr->type != XML_ELEMENT_NODE)
740                     continue;
741                 if (!strcmp((const char *) ptr->name, "record"))
742                 {
743                     SearchablePtr s = parse_torus_record(ptr);
744                     if (s)
745                     {
746                         std::string udb = s->udb;
747                         if (udb.length())
748                             s_map[s->udb] = s;
749                         else
750                         {
751                             throw mp::filter::FilterException
752                                 ("No udb for local torus record");
753                         }
754                     }
755                 }
756                 else
757                 {
758                     throw mp::filter::FilterException
759                         ("Bad element "
760                          + std::string((const char *) ptr->name)
761                          + " in zoom filter inside element "
762                          "<torus><records>");
763                 }
764             }
765         }
766         else
767         {
768             throw mp::filter::FilterException
769                 ("Bad element "
770                  + std::string((const char *) ptr->name)
771                  + " in zoom filter inside element <torus>");
772         }
773     }
774 }
775
776 void yf::Zoom::Impl::configure(const xmlNode *ptr, bool test_only,
777                                const char *path)
778 {
779     std::string explain_xslt_fname;
780     std::string record_xslt_fname;
781
782     if (path && *path)
783     {
784         file_path = path;
785     }
786     for (ptr = ptr->children; ptr; ptr = ptr->next)
787     {
788         if (ptr->type != XML_ELEMENT_NODE)
789             continue;
790         else if (!strcmp((const char *) ptr->name, "torus"))
791         {
792             const struct _xmlAttr *attr;
793             for (attr = ptr->properties; attr; attr = attr->next)
794             {
795                 if (!strcmp((const char *) attr->name, "url"))
796                     torus_searchable_url = mp::xml::get_text(attr->children);
797                 else if (!strcmp((const char *) attr->name, "content_url"))
798                     torus_content_url = mp::xml::get_text(attr->children);
799                 else if (!strcmp((const char *) attr->name, "auth_url"))
800                     torus_auth_url = mp::xml::get_text(attr->children);
801                 else if (!strcmp((const char *) attr->name, "allow_ip"))
802                     torus_allow_ip = mp::xml::get_text(attr->children);
803                 else if (!strcmp((const char *) attr->name, "realm"))
804                     default_realm = mp::xml::get_text(attr->children);
805                 else if (!strcmp((const char *) attr->name, "auth_hostname"))
806                     torus_auth_hostname = mp::xml::get_text(attr->children);
807                 else if (!strcmp((const char *) attr->name, "xsldir"))
808                     xsldir = mp::xml::get_text(attr->children);
809                 else if (!strcmp((const char *) attr->name, "element_transform"))
810                     element_transform = mp::xml::get_text(attr->children);
811                 else if (!strcmp((const char *) attr->name, "element_raw"))
812                     element_raw = mp::xml::get_text(attr->children);
813                 else if (!strcmp((const char *) attr->name, "element_passthru"))
814                     element_passthru = mp::xml::get_text(attr->children);
815                 else if (!strcmp((const char *) attr->name, "proxy"))
816                     proxy = mp::xml::get_text(attr->children);
817                 else if (!strcmp((const char *) attr->name, "explain_xsl"))
818                     explain_xslt_fname = mp::xml::get_text(attr->children);
819                 else if (!strcmp((const char *) attr->name, "record_xsl"))
820                     record_xslt_fname = mp::xml::get_text(attr->children);
821                 else
822                     throw mp::filter::FilterException(
823                         "Bad attribute " + std::string((const char *)
824                                                        attr->name));
825             }
826             // If content_url is not given, use value of searchable, to
827             // ensure backwards compatibility
828             if (!torus_content_url.length())
829                 torus_content_url = torus_searchable_url;
830             configure_local_records(ptr->children, test_only);
831         }
832         else if (!strcmp((const char *) ptr->name, "cclmap"))
833         {
834             const char *addinfo = 0;
835             ccl_xml_config(bibset, ptr, &addinfo);
836         }
837         else if (!strcmp((const char *) ptr->name, "fieldmap"))
838         {
839             const struct _xmlAttr *attr;
840             std::string ccl_field;
841             std::string cql_field;
842             for (attr = ptr->properties; attr; attr = attr->next)
843             {
844                 if (!strcmp((const char *) attr->name, "ccl"))
845                     ccl_field = mp::xml::get_text(attr->children);
846                 else if (!strcmp((const char *) attr->name, "cql"))
847                     cql_field = mp::xml::get_text(attr->children);
848                 else
849                     throw mp::filter::FilterException(
850                         "Bad attribute " + std::string((const char *)
851                                                        attr->name));
852             }
853             if (cql_field.length())
854                 fieldmap[cql_field] = ccl_field;
855         }
856         else if (!strcmp((const char *) ptr->name, "contentProxy"))
857         {
858             const struct _xmlAttr *attr;
859             for (attr = ptr->properties; attr; attr = attr->next)
860             {
861                 if (!strcmp((const char *) attr->name, "server"))
862                 {
863                     yaz_log(YLOG_WARN,
864                             "contentProxy's server attribute is deprecated");
865                     yaz_log(YLOG_LOG,
866                             "Specify config_file instead. For example:");
867                     yaz_log(YLOG_LOG,
868                             " content_file=\"/etc/cf-proxy/cproxy.cfg\"");
869                     content_proxy_server = mp::xml::get_text(attr->children);
870                 }
871                 else if (!strcmp((const char *) attr->name, "tmp_file"))
872                     content_tmp_file = mp::xml::get_text(attr->children);
873                 else if (!strcmp((const char *) attr->name, "config_file"))
874                     content_config_file = mp::xml::get_text(attr->children);
875                 else
876                     throw mp::filter::FilterException(
877                         "Bad attribute " + std::string((const char *)
878                                                        attr->name));
879             }
880         }
881         else if (!strcmp((const char *) ptr->name, "log"))
882         {
883             const struct _xmlAttr *attr;
884             for (attr = ptr->properties; attr; attr = attr->next)
885             {
886                 if (!strcmp((const char *) attr->name, "apdu"))
887                     apdu_log = mp::xml::get_bool(attr->children, false);
888                 else
889                     throw mp::filter::FilterException(
890                         "Bad attribute " + std::string((const char *)
891                                                        attr->name));
892             }
893         }
894         else if (!strcmp((const char *) ptr->name, "zoom"))
895         {
896             const struct _xmlAttr *attr;
897             for (attr = ptr->properties; attr; attr = attr->next)
898             {
899                 if (!strcmp((const char *) attr->name, "timeout"))
900                     zoom_timeout = mp::xml::get_text(attr->children);
901                 else if (!strcmp((const char *) attr->name, "proxy_timeout"))
902                     proxy_timeout = mp::xml::get_int(attr->children, 1);
903                 else
904                     throw mp::filter::FilterException(
905                         "Bad attribute " + std::string((const char *)
906                                                        attr->name));
907             }
908         }
909         else
910         {
911             throw mp::filter::FilterException
912                 ("Bad element "
913                  + std::string((const char *) ptr->name)
914                  + " in zoom filter");
915         }
916     }
917
918     if (explain_xslt_fname.length())
919     {
920         const char *path = 0;
921
922         if (xsldir.length())
923             path = xsldir.c_str();
924         else
925             path = file_path.c_str();
926
927         char fullpath[1024];
928         char *cp = yaz_filepath_resolve(explain_xslt_fname.c_str(),
929                                         path, 0, fullpath);
930         if (!cp)
931         {
932             throw mp::filter::FilterException
933                 ("Cannot read XSLT " + explain_xslt_fname);
934         }
935
936         xmlDoc *xsp_doc = xmlParseFile(cp);
937         if (!xsp_doc)
938         {
939             throw mp::filter::FilterException
940                 ("Cannot parse XSLT " + explain_xslt_fname);
941         }
942
943         explain_xsp = xsltParseStylesheetDoc(xsp_doc);
944         if (!explain_xsp)
945         {
946             xmlFreeDoc(xsp_doc);
947             throw mp::filter::FilterException
948                 ("Cannot parse XSLT " + explain_xslt_fname);
949
950         }
951     }
952
953     if (record_xslt_fname.length())
954     {
955         const char *path = 0;
956
957         if (xsldir.length())
958             path = xsldir.c_str();
959         else
960             path = file_path.c_str();
961
962         char fullpath[1024];
963         char *cp = yaz_filepath_resolve(record_xslt_fname.c_str(),
964                                         path, 0, fullpath);
965         if (!cp)
966         {
967             throw mp::filter::FilterException
968                 ("Cannot read XSLT " + record_xslt_fname);
969         }
970
971         xmlDoc *xsp_doc = xmlParseFile(cp);
972         if (!xsp_doc)
973         {
974             throw mp::filter::FilterException
975                 ("Cannot parse XSLT " + record_xslt_fname);
976         }
977
978         record_xsp = xsltParseStylesheetDoc(xsp_doc);
979         if (!record_xsp)
980         {
981             xmlFreeDoc(xsp_doc);
982             throw mp::filter::FilterException
983                 ("Cannot parse XSLT " + record_xslt_fname);
984
985         }
986     }
987 }
988
989 bool yf::Zoom::Frontend::create_content_session(mp::Package &package,
990                                                 BackendPtr b,
991                                                 int *error, char **addinfo,
992                                                 ODR odr,
993                                                 std::string authentication,
994                                                 std::string proxy,
995                                                 std::string realm)
996 {
997     if (b->sptr->contentConnector.length())
998     {
999         std::string proxyhostname;
1000         std::string tmp_file;
1001         bool legacy_format = false;
1002
1003         if (m_p->content_proxy_server.length())
1004         {
1005             proxyhostname = m_p->content_proxy_server;
1006             legacy_format = true;
1007         }
1008
1009         if (m_p->content_tmp_file.length())
1010             tmp_file = m_p->content_tmp_file;
1011
1012         if (m_p->content_config_file.length())
1013         {
1014             FILE *inf = fopen(m_p->content_config_file.c_str(), "r");
1015             if (inf)
1016             {
1017                 char buf[1024];
1018                 while (fgets(buf, sizeof(buf)-1, inf))
1019                 {
1020                     char *cp;
1021                     cp = strchr(buf, '#');
1022                     if (cp)
1023                         *cp = '\0';
1024                     cp = strchr(buf, '\n');
1025                     if (cp)
1026                         *cp = '\0';
1027                     cp = strchr(buf, ':');
1028                     if (cp)
1029                     {
1030                         char *cp1 = cp;
1031                         while (cp1 != buf && cp1[-1] == ' ')
1032                             cp1--;
1033                         *cp1 = '\0';
1034                         cp++;
1035                         while (*cp == ' ')
1036                             cp++;
1037                         if (!strcmp(buf, "proxyhostname"))
1038                             proxyhostname = cp;
1039                         if (!strcmp(buf, "sessiondir") && *cp)
1040                         {
1041                             if (cp[strlen(cp)-1] == '/')
1042                                 cp[strlen(cp)-1] = '\0';
1043                             tmp_file = std::string(cp) + std::string("/cf.XXXXXX.p");
1044                         }
1045                     }
1046                 }
1047                 fclose(inf);
1048             }
1049             else
1050             {
1051                 package.log("zoom", YLOG_WARN|YLOG_ERRNO,
1052                             "unable to open content config %s",
1053                             m_p->content_config_file.c_str());
1054                 *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1055                 *addinfo = (char *)  odr_malloc(odr, 70 + tmp_file.length());
1056                 sprintf(*addinfo, "zoom: unable to open content config %s",
1057                         m_p->content_config_file.c_str());
1058                 return false;
1059             }
1060         }
1061
1062         if (proxyhostname.length() == 0)
1063         {
1064             package.log("zoom", YLOG_WARN, "no proxyhostname");
1065             return true;
1066         }
1067         if (tmp_file.length() == 0)
1068         {
1069             package.log("zoom", YLOG_WARN, "no tmp_file");
1070             return true;
1071         }
1072
1073         char *fname = xstrdup(tmp_file.c_str());
1074         char *xx = strstr(fname, "XXXXXX");
1075         if (!xx)
1076         {
1077             package.log("zoom", YLOG_WARN, "bad tmp_file %s", tmp_file.c_str());
1078             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1079             *addinfo = (char *)  odr_malloc(odr, 60 + tmp_file.length());
1080             sprintf(*addinfo, "zoom: bad format of content tmp_file: %s",
1081                     tmp_file.c_str());
1082             xfree(fname);
1083             return false;
1084         }
1085         char tmp_char = xx[6];
1086         sprintf(xx, "%06d", ((unsigned) rand()) % 1000000);
1087         if (legacy_format)
1088             b->cproxy_host = std::string(xx) + "." + proxyhostname;
1089         else
1090             b->cproxy_host = proxyhostname + "/" + xx;
1091         xx[6] = tmp_char;
1092
1093         FILE *file = fopen(fname, "w");
1094         if (!file)
1095         {
1096             package.log("zoom", YLOG_WARN|YLOG_ERRNO, "create %s", fname);
1097             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1098             *addinfo = (char *) odr_malloc(odr, 50 + strlen(fname));
1099             sprintf(*addinfo, "zoom: could not create %s", fname);
1100             xfree(fname);
1101             return false;
1102         }
1103         mp::wrbuf w;
1104         wrbuf_puts(w, "#content_proxy\n");
1105         wrbuf_printf(w, "connector: %s\n", b->sptr->contentConnector.c_str());
1106         if (authentication.length())
1107             wrbuf_printf(w, "auth: %s\n", authentication.c_str());
1108         if (proxy.length())
1109             wrbuf_printf(w, "proxy: %s\n", proxy.c_str());
1110         if (realm.length())
1111             wrbuf_printf(w, "realm: %s\n", realm.c_str());
1112
1113         fwrite(w.buf(), 1, w.len(), file);
1114         fclose(file);
1115         package.log("zoom", YLOG_LOG, "content file: %s", fname);
1116         xfree(fname);
1117     }
1118     return true;
1119 }
1120
1121 yf::Zoom::BackendPtr yf::Zoom::Frontend::get_backend_from_databases(
1122     mp::Package &package,
1123     std::string &database, int *error, char **addinfo, mp::odr &odr,
1124     int *proxy_step)
1125 {
1126     bool connection_reuse = false;
1127     std::string proxy;
1128
1129     std::list<BackendPtr>::const_iterator map_it;
1130     if (m_backend && !m_backend->enable_explain &&
1131         m_backend->m_frontend_database == database)
1132     {
1133         connection_reuse = true;
1134         proxy = m_backend->m_proxy;
1135     }
1136
1137     std::string input_args;
1138     std::string torus_db;
1139     size_t db_arg_pos = database.find(',');
1140     if (db_arg_pos != std::string::npos)
1141     {
1142         torus_db = database.substr(0, db_arg_pos);
1143         input_args = database.substr(db_arg_pos + 1);
1144     }
1145     else
1146         torus_db = database;
1147
1148     std::string content_proxy;
1149     std::string realm = session_realm;
1150     if (realm.length() == 0)
1151         realm = m_p->default_realm;
1152
1153     const char *param_user = 0;
1154     const char *param_password = 0;
1155     const char *param_content_user = 0;
1156     const char *param_content_password = 0;
1157     const char *param_nocproxy = 0;
1158     const char *param_retry = 0;
1159     int no_parms = 0;
1160
1161     char **names;
1162     char **values;
1163     int no_out_args = 0;
1164     if (input_args.length())
1165         no_parms = yaz_uri_to_array(input_args.c_str(),
1166                                     odr, &names, &values);
1167     // adding 20 because we'll be adding other URL args
1168     const char **out_names = (const char **)
1169         odr_malloc(odr, (20 + no_parms) * sizeof(*out_names));
1170     const char **out_values = (const char **)
1171         odr_malloc(odr, (20 + no_parms) * sizeof(*out_values));
1172
1173     // may be changed if it's a content connection
1174     std::string torus_url = m_p->torus_searchable_url;
1175     int i;
1176     for (i = 0; i < no_parms; i++)
1177     {
1178         const char *name = names[i];
1179         const char *value = values[i];
1180         assert(name);
1181         assert(value);
1182         if (!strcmp(name, "user"))
1183             param_user = value;
1184         else if (!strcmp(name, "password"))
1185             param_password = value;
1186         else if (!strcmp(name, "content-user"))
1187             param_content_user = value;
1188         else if (!strcmp(name, "content-password"))
1189             param_content_password = value;
1190         else if (!strcmp(name, "content-proxy"))
1191             content_proxy = value;
1192         else if (!strcmp(name, "nocproxy"))
1193             param_nocproxy = value;
1194         else if (!strcmp(name, "retry"))
1195             param_retry = value;
1196         else if (!strcmp(name, "proxy"))
1197         {
1198             char **dstr;
1199             int dnum = 0;
1200             nmem_strsplit(((ODR) odr)->mem, ",", value, &dstr, &dnum);
1201             if (connection_reuse)
1202             {
1203                 // find the step after our current proxy
1204                 int i;
1205                 for (i = 0; i < dnum; i++)
1206                     if (!strcmp(proxy.c_str(), dstr[i]))
1207                         break;
1208                 if (i >= dnum - 1)
1209                     *proxy_step = 0;
1210                 else
1211                     *proxy_step = i + 1;
1212             }
1213             else
1214             {
1215                 // step is known.. Guess our proxy from it
1216                 if (*proxy_step >= dnum)
1217                     *proxy_step = 0;
1218                 else
1219                 {
1220                     proxy = dstr[*proxy_step];
1221
1222                     (*proxy_step)++;
1223                     if (*proxy_step == dnum)
1224                         *proxy_step = 0;
1225                 }
1226             }
1227         }
1228         else if (!strcmp(name, "cproxysession"))
1229         {
1230             out_names[no_out_args] = name;
1231             out_values[no_out_args++] = value;
1232             torus_url = m_p->torus_content_url;
1233         }
1234         else if (!strcmp(name, "realm") && session_realm.length() == 0)
1235             realm = value;
1236         else if (!strcmp(name, "torus_url") && session_realm.length() == 0)
1237             torus_url = value;
1238         else if (name[0] == 'x' && name[1] == '-')
1239         {
1240             out_names[no_out_args] = name;
1241             out_values[no_out_args++] = value;
1242         }
1243         else
1244         {
1245             BackendPtr notfound;
1246             char *msg = (char*) odr_malloc(odr, strlen(name) + 30);
1247             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1248             sprintf(msg, "zoom: bad database argument: %s", name);
1249             *addinfo = msg;
1250             return notfound;
1251         }
1252     }
1253     if (proxy.length())
1254         package.log("zoom", YLOG_LOG, "proxy: %s", proxy.c_str());
1255
1256     if (connection_reuse)
1257     {
1258         m_backend->connect("", error, addinfo, odr);
1259         return m_backend;
1260     }
1261
1262     if (torus_db.compare("IR-Explain---1") == 0)
1263         return explain_search(package, database, error, addinfo, odr, torus_url,
1264                               torus_db, realm);
1265
1266     SearchablePtr sptr;
1267
1268     std::map<std::string,SearchablePtr>::iterator it;
1269     it = m_p->s_map.find(torus_db);
1270     if (it != m_p->s_map.end())
1271         sptr = it->second;
1272     else if (torus_url.length() > 0)
1273     {
1274         std::string torus_addinfo;
1275         std::string torus_query = "udb==" + torus_db;
1276         xmlDoc *doc = mp::get_searchable(package,torus_url, torus_db,
1277                                          torus_query,
1278                                          realm, m_p->proxy,
1279                                          torus_addinfo);
1280         if (!doc)
1281         {
1282             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1283             if (torus_addinfo.length())
1284                 *addinfo = odr_strdup(odr, torus_addinfo.c_str());
1285             BackendPtr b;
1286             return b;
1287         }
1288         const xmlNode *ptr = xmlDocGetRootElement(doc);
1289         if (ptr && ptr->type == XML_ELEMENT_NODE)
1290         {
1291             if (!strcmp((const char *) ptr->name, "record"))
1292             {
1293                 sptr = m_p->parse_torus_record(ptr);
1294             }
1295             else if (!strcmp((const char *) ptr->name, "records"))
1296             {
1297                 for (ptr = ptr->children; ptr; ptr = ptr->next)
1298                 {
1299                     if (ptr->type == XML_ELEMENT_NODE
1300                         && !strcmp((const char *) ptr->name, "record"))
1301                     {
1302                         if (sptr)
1303                         {
1304                             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1305                             *addinfo = (char*)
1306                                 odr_malloc(odr, 40 + torus_db.length());
1307                             sprintf(*addinfo, "multiple records for udb=%s",
1308                                     database.c_str());
1309                             xmlFreeDoc(doc);
1310                             BackendPtr b;
1311                             return b;
1312                         }
1313                         sptr = m_p->parse_torus_record(ptr);
1314                     }
1315                 }
1316             }
1317             else
1318             {
1319                 *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1320                 *addinfo = (char*) odr_malloc(
1321                     odr, 40 + strlen((const char *) ptr->name));
1322                 sprintf(*addinfo, "bad root element for torus: %s", ptr->name);
1323                 xmlFreeDoc(doc);
1324                 BackendPtr b;
1325                 return b;
1326             }
1327         }
1328         xmlFreeDoc(doc);
1329     }
1330
1331     if (!sptr)
1332     {
1333         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1334         *addinfo = odr_strdup(odr, torus_db.c_str());
1335         BackendPtr b;
1336         return b;
1337     }
1338
1339     xsltStylesheetPtr xsp = 0;
1340     if (sptr->transform_xsl_content.length())
1341     {
1342         xmlDoc *xsp_doc = xmlParseMemory(sptr->transform_xsl_content.c_str(),
1343                                          sptr->transform_xsl_content.length());
1344         if (!xsp_doc)
1345         {
1346             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1347             *addinfo = odr_strdup(odr, "zoom: xmlParseMemory failed "
1348                                   "for literalTransform XSL");
1349             BackendPtr b;
1350             return b;
1351         }
1352         xsp = xsltParseStylesheetDoc(xsp_doc);
1353         if (!xsp)
1354         {
1355             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1356             *addinfo =
1357                 odr_strdup(odr,"zoom: xsltParseStylesheetDoc failed "
1358                            "for literalTransform XSL");
1359             BackendPtr b;
1360             xmlFreeDoc(xsp_doc);
1361             return b;
1362         }
1363     }
1364     else if (sptr->transform_xsl_fname.length())
1365     {
1366         const char *path = 0;
1367
1368         if (m_p->xsldir.length())
1369             path = m_p->xsldir.c_str();
1370         else
1371             path = m_p->file_path.c_str();
1372         std::string fname;
1373
1374         char fullpath[1024];
1375         char *cp = yaz_filepath_resolve(sptr->transform_xsl_fname.c_str(),
1376                                         path, 0, fullpath);
1377         if (cp)
1378             fname.assign(cp);
1379         else
1380         {
1381             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1382             *addinfo = (char *)
1383                 odr_malloc(odr, 40 + sptr->transform_xsl_fname.length());
1384             sprintf(*addinfo, "zoom: could not open file %s",
1385                     sptr->transform_xsl_fname.c_str());
1386             BackendPtr b;
1387             return b;
1388         }
1389         xmlDoc *xsp_doc = xmlParseFile(fname.c_str());
1390         if (!xsp_doc)
1391         {
1392             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1393             *addinfo = (char *) odr_malloc(odr, 50 + fname.length());
1394             sprintf(*addinfo, "zoom: xmlParseFile failed for file %s",
1395                     fname.c_str());
1396             BackendPtr b;
1397             return b;
1398         }
1399         xsp = xsltParseStylesheetDoc(xsp_doc);
1400         if (!xsp)
1401         {
1402             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1403             *addinfo = (char *) odr_malloc(odr, 50 + fname.length());
1404             sprintf(*addinfo, "zoom: xsltParseStylesheetDoc failed "
1405                     "for file %s", fname.c_str());
1406             BackendPtr b;
1407             xmlFreeDoc(xsp_doc);
1408             return b;
1409         }
1410     }
1411
1412     cql_transform_t cqlt = 0;
1413     if (sptr->rpn2cql_fname.length())
1414     {
1415         char fullpath[1024];
1416         char *cp = yaz_filepath_resolve(sptr->rpn2cql_fname.c_str(),
1417                                         m_p->file_path.c_str(), 0, fullpath);
1418         if (cp)
1419             cqlt = cql_transform_open_fname(fullpath);
1420     }
1421     else
1422         cqlt = cql_transform_create();
1423
1424     if (!cqlt)
1425     {
1426         *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1427         *addinfo = odr_strdup(odr, "zoom: missing/invalid cql2rpn file");
1428         BackendPtr b;
1429         xsltFreeStylesheet(xsp);
1430         return b;
1431     }
1432
1433     m_backend.reset();
1434
1435     BackendPtr b(new Backend);
1436
1437     b->cqlt = cqlt;
1438     b->sptr = sptr;
1439     b->xsp = xsp;
1440     b->m_frontend_database = database;
1441     b->enable_cproxy = param_nocproxy ? false : true;
1442
1443     if (param_retry)
1444         b->retry_on_failure = param_retry;
1445     else
1446         b->retry_on_failure = b->sptr->retry_on_failure;
1447
1448     if (sptr->query_encoding.length())
1449         b->set_option("rpnCharset", sptr->query_encoding);
1450
1451     std::string extraArgs = sptr->extraArgs;
1452
1453     b->set_option("timeout", m_p->zoom_timeout.c_str());
1454
1455     if (m_p->apdu_log)
1456         b->set_option("apdulog", "1");
1457
1458     if (sptr->piggyback && sptr->sru.length())
1459         b->set_option("count", "1"); /* some SRU servers INSIST on getting
1460                                         maximumRecords > 0 */
1461     b->set_option("piggyback", sptr->piggyback ? "1" : "0");
1462
1463     std::string authentication = sptr->authentication;
1464     if (param_user)
1465     {
1466         authentication = std::string(param_user);
1467         if (param_password)
1468             authentication += "/" + std::string(param_password);
1469     }
1470     std::string content_authentication = sptr->contentAuthentication;
1471     if (param_content_user)
1472     {
1473         content_authentication = std::string(param_content_user);
1474         if (param_content_password)
1475             content_authentication += "/" + std::string(param_content_password);
1476     }
1477
1478     if (proxy.length() == 0)
1479         proxy = sptr->cfProxy;
1480     b->m_proxy = proxy;
1481
1482     if (sptr->cfAuth.length())
1483     {
1484         // A CF target
1485         b->set_option("user", sptr->cfAuth);
1486         if (param_user)
1487         {
1488             out_names[no_out_args] = "user";
1489             out_values[no_out_args++] = odr_strdup(odr, param_user);
1490             if (param_password)
1491             {
1492                 out_names[no_out_args] = "password";
1493                 out_values[no_out_args++] = odr_strdup(odr, param_password);
1494             }
1495         }
1496         else if (authentication.length())
1497         {
1498             size_t found = authentication.find('/');
1499             if (found != std::string::npos)
1500             {
1501                 out_names[no_out_args] = "user";
1502                 out_values[no_out_args++] =
1503                     odr_strdup(odr, authentication.substr(0, found).c_str());
1504
1505                 out_names[no_out_args] = "password";
1506                 out_values[no_out_args++] =
1507                     odr_strdup(odr, authentication.substr(found+1).c_str());
1508             }
1509             else
1510             {
1511                 out_names[no_out_args] = "user";
1512                 out_values[no_out_args++] =
1513                     odr_strdup(odr, authentication.c_str());
1514             }
1515         }
1516         if (proxy.length())
1517         {
1518             out_names[no_out_args] = "proxy";
1519             out_values[no_out_args++] = odr_strdup(odr, proxy.c_str());
1520         }
1521         if (sptr->cfSubDB.length())
1522         {
1523             out_names[no_out_args] = "subdatabase";
1524             out_values[no_out_args++] = odr_strdup(odr, sptr->cfSubDB.c_str());
1525         }
1526         if (!param_nocproxy && b->sptr->contentConnector.length())
1527             param_nocproxy = "1";
1528
1529         if (param_nocproxy)
1530         {
1531             out_names[no_out_args] = "nocproxy";
1532             out_values[no_out_args++] = odr_strdup(odr, param_nocproxy);
1533         }
1534         std::map<std::string,std::string>::const_iterator it;
1535         for (it = sptr->cf_param.begin(); it != sptr->cf_param.end(); it++)
1536         {
1537             int i;
1538             const char *n = it->first.c_str();
1539             for (i = 0; i < no_out_args; i++)
1540                 if (!strcmp(n, out_names[i]))
1541                     break;
1542             if (i == no_out_args)
1543             {
1544                 out_names[no_out_args] = odr_strdup(odr, n);
1545                 out_values[no_out_args++] = odr_strdup(odr, it->second.c_str());
1546             }
1547         }
1548     }
1549     else
1550     {
1551         const char *auth = authentication.c_str();
1552         const char *cp1 = strchr(auth, ' ');
1553         if (!cp1 && sptr->sru.length())
1554             cp1 =  strchr(auth, '/');
1555         if (!cp1)
1556         {
1557             /* Z39.50 user/password style, or no password for SRU */
1558             b->set_option("user", auth);
1559         }
1560         else
1561         {
1562             /* now consider group as well */
1563             const char *cp2 = strchr(cp1 + 1, ' ');
1564
1565             b->set_option("user", auth, cp1 - auth);
1566             if (!cp2)
1567                 b->set_option("password", cp1 + 1);
1568             else
1569             {
1570                 b->set_option("group", cp1 + 1, cp2 - cp1 - 1);
1571                 b->set_option("password", cp2 + 1);
1572             }
1573         }
1574         if (sptr->authenticationMode.length())
1575             b->set_option("authenticationMode", sptr->authenticationMode);
1576         if (proxy.length())
1577             b->set_option("proxy", proxy);
1578     }
1579     if (extraArgs.length())
1580         b->set_option("extraArgs", extraArgs);
1581
1582     std::string url(sptr->target);
1583     if (sptr->sru.length())
1584     {
1585         b->set_option("sru", sptr->sru);
1586         if (url.find("://") == std::string::npos)
1587             url = "http://" + url;
1588         if (sptr->sru_version.length())
1589             b->set_option("sru_version", sptr->sru_version);
1590     }
1591     if (no_out_args)
1592     {
1593         char *x_args = 0;
1594         out_names[no_out_args] = 0; // terminate list
1595
1596         yaz_array_to_uri(&x_args, odr, (char **) out_names,
1597                          (char **) out_values);
1598         url += "," + std::string(x_args);
1599     }
1600     package.log("zoom", YLOG_LOG, "url: %s", url.c_str());
1601     b->connect(url, error, addinfo, odr);
1602     if (*error == 0 && b->enable_cproxy)
1603         create_content_session(package, b, error, addinfo, odr,
1604                                content_authentication.length() ?
1605                                content_authentication : authentication,
1606                                content_proxy.length() ? content_proxy : proxy,
1607                                realm);
1608     if (*error == 0)
1609         m_backend = b;
1610     return b;
1611 }
1612
1613 void yf::Zoom::Frontend::prepare_elements(BackendPtr b,
1614                                           Odr_oid *preferredRecordSyntax,
1615                                           const char *element_set_name,
1616                                           bool &enable_pz2_retrieval,
1617                                           bool &enable_pz2_transform,
1618                                           bool &enable_record_transform,
1619                                           bool &assume_marc8_charset)
1620 {
1621     char oid_name_str[OID_STR_MAX];
1622     const char *syntax_name = 0;
1623
1624     if (preferredRecordSyntax &&
1625         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml))
1626     {
1627         if (element_set_name &&
1628             !strcmp(element_set_name, m_p->element_transform.c_str()))
1629         {
1630             enable_pz2_retrieval = true;
1631             enable_pz2_transform = true;
1632         }
1633         else if (element_set_name &&
1634                  !strcmp(element_set_name, m_p->element_raw.c_str()))
1635         {
1636             enable_pz2_retrieval = true;
1637         }
1638         else if (m_p->record_xsp)
1639         {
1640             enable_pz2_retrieval = true;
1641             enable_pz2_transform = true;
1642             enable_record_transform = true;
1643         }
1644     }
1645
1646     if (enable_pz2_retrieval)
1647     {
1648         std::string configured_request_syntax = b->sptr->request_syntax;
1649         if (configured_request_syntax.length())
1650         {
1651             syntax_name = configured_request_syntax.c_str();
1652             const Odr_oid *syntax_oid =
1653                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
1654             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
1655                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
1656                 assume_marc8_charset = true;
1657         }
1658     }
1659     else if (preferredRecordSyntax)
1660         syntax_name =
1661             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
1662
1663     if (b->sptr->sru.length())
1664         syntax_name = "XML";
1665
1666     b->set_option("preferredRecordSyntax", syntax_name);
1667
1668     if (enable_pz2_retrieval)
1669     {
1670         if (element_set_name && !strcmp(element_set_name,
1671                                         m_p->element_passthru.c_str()))
1672             ;
1673         else
1674         {
1675             element_set_name = 0;
1676             if (b->sptr->element_set.length())
1677                 element_set_name = b->sptr->element_set.c_str();
1678         }
1679     }
1680
1681     b->set_option("elementSetName", element_set_name);
1682     if (b->sptr->sru.length() && element_set_name)
1683         b->set_option("schema", element_set_name);
1684 }
1685
1686 Z_Records *yf::Zoom::Frontend::get_explain_records(
1687     mp::Package &package,
1688     Odr_int start,
1689     Odr_int number_to_present,
1690     int *error,
1691     char **addinfo,
1692     Odr_int *number_of_records_returned,
1693     ODR odr,
1694     BackendPtr b,
1695     Odr_oid *preferredRecordSyntax,
1696     const char *element_set_name)
1697 {
1698     Odr_int i;
1699     Z_Records *records = 0;
1700
1701     if (!b->explain_doc)
1702     {
1703         return records;
1704     }
1705     if (number_to_present > 10000)
1706         number_to_present = 10000;
1707
1708     xmlNode *ptr = xmlDocGetRootElement(b->explain_doc);
1709
1710     Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1711         odr_malloc(odr, sizeof(*npl));
1712     npl->records = (Z_NamePlusRecord **)
1713         odr_malloc(odr, number_to_present * sizeof(*npl->records));
1714
1715     for (i = 0; i < number_to_present; i++)
1716     {
1717         int num = 0;
1718         xmlNode *res = xml_node_search(ptr, &num, start + i + 1);
1719         if (!res)
1720             break;
1721         xmlBufferPtr xml_buf = xmlBufferCreate();
1722         xmlNode *tmp_node = xmlCopyNode(res->children, 1);
1723         xmlNodeDump(xml_buf, tmp_node->doc, tmp_node, 0, 0);
1724
1725         Z_NamePlusRecord *npr =
1726             (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1727         npr->databaseName = odr_strdup(odr, b->m_frontend_database.c_str());
1728         npr->which = Z_NamePlusRecord_databaseRecord;
1729         npr->u.databaseRecord =
1730             z_ext_record_xml(odr,
1731                              (const char *) xml_buf->content, xml_buf->use);
1732         npl->records[i] = npr;
1733         xmlFreeNode(tmp_node);
1734         xmlBufferFree(xml_buf);
1735     }
1736     records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1737     records->which = Z_Records_DBOSD;
1738     records->u.databaseOrSurDiagnostics = npl;
1739
1740     npl->num_records = i;
1741     *number_of_records_returned = i;
1742     return records;
1743 }
1744
1745
1746 Z_Records *yf::Zoom::Frontend::get_records(mp::Package &package,
1747                                            Odr_int start,
1748                                            Odr_int number_to_present,
1749                                            int *error,
1750                                            char **addinfo,
1751                                            Odr_int *number_of_records_returned,
1752                                            ODR odr,
1753                                            BackendPtr b,
1754                                            Odr_oid *preferredRecordSyntax,
1755                                            const char *element_set_name)
1756 {
1757     *number_of_records_returned = 0;
1758     Z_Records *records = 0;
1759     bool enable_pz2_retrieval = false; // whether target profile is used
1760     bool enable_pz2_transform = false; // whether XSLT is used as well
1761     bool assume_marc8_charset = false;
1762     bool enable_record_transform = false;
1763
1764     prepare_elements(b, preferredRecordSyntax,
1765                      element_set_name,
1766                      enable_pz2_retrieval,
1767                      enable_pz2_transform,
1768                      enable_record_transform,
1769                      assume_marc8_charset);
1770
1771     package.log("zoom", YLOG_LOG, "pz2_retrieval: %s . pz2_transform: %s",
1772                 enable_pz2_retrieval ? "yes" : "no",
1773                 enable_pz2_transform ? "yes" : "no");
1774
1775     if (start < 0 || number_to_present <=0)
1776         return records;
1777
1778     if (number_to_present > 10000)
1779         number_to_present = 10000;
1780
1781     ZOOM_record *recs = (ZOOM_record *)
1782         odr_malloc(odr, (size_t) number_to_present * sizeof(*recs));
1783
1784     b->present(start, number_to_present, recs, error, addinfo, odr);
1785
1786     int i = 0;
1787     if (!*error)
1788     {
1789         for (i = 0; i < number_to_present; i++)
1790         {
1791             if (!recs[i])
1792                 break;
1793
1794             const char *addinfo;
1795             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1796                                               &addinfo, 0 /* diagset */);
1797             if (sur_error ==
1798                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS && addinfo &&
1799                 !strcmp(addinfo,
1800                         "ZOOM C generated. Present phase and no records"))
1801                 break;
1802         }
1803     }
1804     if (i > 0)
1805     {  // only return records if no error and at least one record
1806
1807         const char *xsl_parms[3];
1808         mp::wrbuf cproxy_host;
1809
1810         if (b->enable_cproxy && b->cproxy_host.length())
1811         {
1812             wrbuf_puts(cproxy_host, "\"");
1813             wrbuf_puts(cproxy_host, b->cproxy_host.c_str());
1814             wrbuf_puts(cproxy_host, "/\"");
1815
1816             xsl_parms[0] = "cproxyhost";
1817             xsl_parms[1] = wrbuf_cstr(cproxy_host);
1818             xsl_parms[2] = 0;
1819         }
1820         else
1821         {
1822             xsl_parms[0] = 0;
1823         }
1824
1825         char *odr_database = odr_strdup(odr,
1826                                         b->m_frontend_database.c_str());
1827         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1828             odr_malloc(odr, sizeof(*npl));
1829         *number_of_records_returned = i;
1830         npl->num_records = i;
1831         npl->records = (Z_NamePlusRecord **)
1832             odr_malloc(odr, i * sizeof(*npl->records));
1833         for (i = 0; i < npl->num_records; i++)
1834         {
1835             Z_NamePlusRecord *npr = 0;
1836             const char *addinfo;
1837
1838             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1839                                               &addinfo, 0 /* diagset */);
1840
1841             if (sur_error)
1842             {
1843                 log_diagnostic(package, sur_error, addinfo);
1844                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1845                                             addinfo);
1846             }
1847             else if (enable_pz2_retrieval)
1848             {
1849                 char rec_type_str[100];
1850                 const char *record_encoding = 0;
1851
1852                 if (b->sptr->record_encoding.length())
1853                     record_encoding = b->sptr->record_encoding.c_str();
1854                 else if (assume_marc8_charset)
1855                     record_encoding = "marc8";
1856
1857                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1858                 if (record_encoding)
1859                 {
1860                     strcat(rec_type_str, "; charset=");
1861                     strcat(rec_type_str, record_encoding);
1862                 }
1863
1864                 package.log("zoom", YLOG_LOG, "Getting record of type %s",
1865                             rec_type_str);
1866                 int rec_len;
1867                 xmlChar *xmlrec_buf = 0;
1868                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1869                                                       &rec_len);
1870                 if (!rec_buf && !npr)
1871                 {
1872                     std::string addinfo("ZOOM_record_get failed for type ");
1873
1874                     int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1875                     addinfo += rec_type_str;
1876                     log_diagnostic(package, error, addinfo.c_str());
1877                     npr = zget_surrogateDiagRec(odr, odr_database,
1878                                                 error, addinfo.c_str());
1879                 }
1880                 else
1881                 {
1882                     package.log_write(rec_buf, rec_len);
1883                     package.log_write("\r\n", 2);
1884                 }
1885
1886                 if (rec_buf && b->xsp && enable_pz2_transform)
1887                 {
1888                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1889                     if (!rec_doc)
1890                     {
1891                         const char *addinfo = "xml parse failed for record";
1892                         int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1893                         log_diagnostic(package, error, addinfo);
1894                         npr = zget_surrogateDiagRec(
1895                             odr, odr_database, error, addinfo);
1896                     }
1897                     else
1898                     {
1899                         // first stage XSLT - per target
1900                         xsltStylesheetPtr xsp = b->xsp;
1901                         xmlDoc *rec_res = xsltApplyStylesheet(xsp, rec_doc,
1902                                                               xsl_parms);
1903                         // insert generated-url
1904                         if (rec_res)
1905                         {
1906                             std::string res =
1907                                 mp::xml::url_recipe_handle(rec_res,
1908                                                            b->sptr->urlRecipe);
1909                             if (res.length())
1910                             {
1911                                 xmlNode *ptr = xmlDocGetRootElement(rec_res);
1912                                 while (ptr && ptr->type != XML_ELEMENT_NODE)
1913                                     ptr = ptr->next;
1914                                 xmlNode *c =
1915                                     xmlNewChild(ptr, 0, BAD_CAST "metadata", 0);
1916                                 xmlNewProp(c, BAD_CAST "type", BAD_CAST
1917                                            "generated-url");
1918                                 xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1919                                 xmlAddChild(c, t);
1920                             }
1921                         }
1922                         // second stage XSLT - common
1923                         if (rec_res && m_p->record_xsp &&
1924                             enable_record_transform)
1925                         {
1926                             xmlDoc *tmp_doc = rec_res;
1927
1928                             xsp = m_p->record_xsp;
1929                             rec_res = xsltApplyStylesheet(xsp, tmp_doc,
1930                                                           xsl_parms);
1931                             xmlFreeDoc(tmp_doc);
1932                         }
1933                         // get result out of it
1934                         if (rec_res)
1935                         {
1936                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1937                                                    rec_res, xsp);
1938                             rec_buf = (const char *) xmlrec_buf;
1939                             package.log_write(rec_buf, rec_len);
1940
1941                             xmlFreeDoc(rec_res);
1942                         }
1943                         if (!rec_buf)
1944                         {
1945                             std::string addinfo;
1946                             int error =
1947                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1948
1949                             addinfo = "xslt apply failed for "
1950                                 + b->sptr->transform_xsl_fname;
1951                             log_diagnostic(package, error, addinfo.c_str());
1952                             npr = zget_surrogateDiagRec(
1953                                 odr, odr_database, error, addinfo.c_str());
1954                         }
1955                         xmlFreeDoc(rec_doc);
1956                     }
1957                 }
1958
1959                 if (!npr)
1960                 {
1961                     if (!rec_buf)
1962                         npr = zget_surrogateDiagRec(
1963                             odr, odr_database,
1964                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1965                             rec_type_str);
1966                     else
1967                     {
1968                         npr = (Z_NamePlusRecord *)
1969                             odr_malloc(odr, sizeof(*npr));
1970                         npr->databaseName = odr_database;
1971                         npr->which = Z_NamePlusRecord_databaseRecord;
1972                         npr->u.databaseRecord =
1973                             z_ext_record_xml(odr, rec_buf, rec_len);
1974                     }
1975                 }
1976                 if (xmlrec_buf)
1977                     xmlFree(xmlrec_buf);
1978             }
1979             else
1980             {
1981                 Z_External *ext =
1982                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1983                 if (ext)
1984                 {
1985                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1986                     npr->databaseName = odr_database;
1987                     npr->which = Z_NamePlusRecord_databaseRecord;
1988                     npr->u.databaseRecord = ext;
1989                 }
1990                 else
1991                 {
1992                     npr = zget_surrogateDiagRec(
1993                         odr, odr_database,
1994                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1995                         "ZOOM_record, type ext");
1996                 }
1997             }
1998             npl->records[i] = npr;
1999         }
2000         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
2001         records->which = Z_Records_DBOSD;
2002         records->u.databaseOrSurDiagnostics = npl;
2003     }
2004     return records;
2005 }
2006
2007 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
2008                                                     ODR odr)
2009 {
2010     struct cql_node *r = 0;
2011     if (!cn)
2012         return 0;
2013     switch (cn->which)
2014     {
2015     case CQL_NODE_ST:
2016         if (cn->u.st.index)
2017         {
2018             std::map<std::string,std::string>::const_iterator it;
2019             it = fieldmap.find(cn->u.st.index);
2020             if (it == fieldmap.end())
2021                 return cn;
2022             if (it->second.length())
2023                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
2024             else
2025                 cn->u.st.index = 0;
2026         }
2027         break;
2028     case CQL_NODE_BOOL:
2029         r = convert_cql_fields(cn->u.boolean.left, odr);
2030         if (!r)
2031             r = convert_cql_fields(cn->u.boolean.right, odr);
2032         break;
2033     case CQL_NODE_SORT:
2034         r = convert_cql_fields(cn->u.sort.search, odr);
2035         break;
2036     }
2037     return r;
2038 }
2039
2040 void yf::Zoom::Frontend::log_diagnostic(mp::Package &package,
2041                                         int error, const char *addinfo)
2042 {
2043     const char *err_msg = yaz_diag_bib1_str(error);
2044     if (addinfo)
2045         package.log("zoom", YLOG_WARN, "Diagnostic %d %s: %s",
2046                     error, err_msg, addinfo);
2047     else
2048         package.log("zoom", YLOG_WARN, "Diagnostic %d %s:",
2049                     error, err_msg);
2050 }
2051
2052 yf::Zoom::BackendPtr yf::Zoom::Frontend::explain_search(mp::Package &package,
2053                                                         std::string &database,
2054                                                         int *error,
2055                                                         char **addinfo,
2056                                                         mp::odr &odr,
2057                                                         std::string torus_url,
2058                                                         std::string &torus_db,
2059                                                         std::string &realm)
2060 {
2061     m_backend.reset();
2062
2063     BackendPtr b(new Backend);
2064
2065     b->m_frontend_database = database;
2066     b->enable_explain = true;
2067
2068     Z_GDU *gdu = package.request().get();
2069     Z_APDU *apdu_req = gdu->u.z3950;
2070     Z_SearchRequest *sr = apdu_req->u.searchRequest;
2071     Z_Query *query = sr->query;
2072
2073     if (!m_p->explain_xsp)
2074     {
2075         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
2076         *addinfo =
2077             odr_strdup(odr, "IR-Explain---1 unsupported. "
2078                        "Torus explain_xsl not defined");
2079         return m_backend;
2080     }
2081     else if (query->which == Z_Query_type_104 &&
2082         query->u.type_104->which == Z_External_CQL)
2083     {
2084         std::string torus_addinfo;
2085         std::string torus_query(query->u.type_104->u.cql);
2086         xmlDoc *doc = mp::get_searchable(package, torus_url, "",
2087                                          torus_query,
2088                                          realm, m_p->proxy,
2089                                          torus_addinfo);
2090         if (m_p->explain_xsp)
2091         {
2092             xmlDoc *rec_res =  xsltApplyStylesheet(m_p->explain_xsp, doc, 0);
2093
2094             xmlFreeDoc(doc);
2095             doc = rec_res;
2096         }
2097         if (!doc)
2098         {
2099             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
2100             if (torus_addinfo.length())
2101                 *addinfo = odr_strdup(odr, torus_addinfo.c_str());
2102         }
2103         else
2104         {
2105             xmlNode *ptr = xmlDocGetRootElement(doc);
2106             int hits = 0;
2107
2108             xml_node_search(ptr, &hits, 0);
2109
2110             Z_APDU *apdu_res = odr.create_searchResponse(apdu_req, 0, 0);
2111             apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
2112             package.response() = apdu_res;
2113             m_backend = b;
2114         }
2115         if (b->explain_doc)
2116             xmlFreeDoc(b->explain_doc);
2117         b->explain_doc = doc;
2118         return m_backend;
2119     }
2120     else
2121     {
2122         *error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
2123         *addinfo = odr_strdup(odr, "IR-Explain---1 only supports CQL");
2124         return m_backend;
2125     }
2126 }
2127
2128 static bool wait_conn(COMSTACK cs, int secs)
2129 {
2130     struct yaz_poll_fd pfd;
2131
2132     yaz_poll_add(pfd.input_mask, yaz_poll_except);
2133     if (cs->io_pending & CS_WANT_WRITE)
2134         yaz_poll_add(pfd.input_mask, yaz_poll_write);
2135     if (cs->io_pending & CS_WANT_READ)
2136         yaz_poll_add(pfd.input_mask, yaz_poll_read);
2137
2138     pfd.fd = cs_fileno(cs);
2139     pfd.client_data = 0;
2140
2141     int ret = yaz_poll(&pfd, 1, secs, 0);
2142     return ret > 0;
2143 }
2144
2145 bool yf::Zoom::Impl::check_proxy(const char *proxy)
2146 {
2147     COMSTACK conn = 0;
2148     const char *uri = "http://localhost/";
2149     void *add;
2150     mp::odr odr;
2151     bool outcome = false;
2152     conn = cs_create_host_proxy(uri, 0, &add, proxy);
2153
2154     if (!conn)
2155         return false;
2156
2157     Z_GDU *gdu = z_get_HTTP_Request_uri(odr, uri, 0, 1);
2158     gdu->u.HTTP_Request->method = odr_strdup(odr, "GET");
2159
2160     if (z_GDU(odr, &gdu, 0, 0))
2161     {
2162         int len;
2163         char *buf = odr_getbuf(odr, &len, 0);
2164
2165         int ret = cs_connect(conn, add);
2166         if (ret > 0 || (ret == 0 && wait_conn(conn, 1)))
2167         {
2168             while (1)
2169             {
2170                 ret = cs_put(conn, buf, len);
2171                 if (ret != 1)
2172                     break;
2173                 if (!wait_conn(conn, proxy_timeout))
2174                     break;
2175             }
2176             if (ret == 0)
2177                 outcome = true;
2178         }
2179     }
2180     cs_close(conn);
2181     return outcome;
2182 }
2183
2184 bool yf::Zoom::Frontend::retry(mp::Package &package,
2185                                mp::odr &odr,
2186                                BackendPtr b,
2187                                int &error, char **addinfo,
2188                                int &proxy_step, int &same_retries,
2189                                int &proxy_retries)
2190 {
2191     if (b && b->m_proxy.length() && !m_p->check_proxy(b->m_proxy.c_str()))
2192     {
2193         log_diagnostic(package, error, *addinfo);
2194         package.log("zoom", YLOG_LOG, "proxy %s fails", b->m_proxy.c_str());
2195         m_backend.reset();
2196         if (proxy_step) // there is a failover
2197         {
2198             proxy_retries++;
2199             package.log("zoom", YLOG_WARN, "search failed: trying next proxy");
2200             return true;
2201         }
2202         error = YAZ_BIB1_PROXY_FAILURE;
2203         *addinfo = odr_strdup(odr, b->m_proxy.c_str());
2204     }
2205     else if (b && b->retry_on_failure.compare("0")
2206              && same_retries == 0 && proxy_retries == 0)
2207     {
2208         log_diagnostic(package, error, *addinfo);
2209         same_retries++;
2210         package.log("zoom", YLOG_WARN, "search failed: retry");
2211         m_backend.reset();
2212         proxy_step = 0;
2213         return true;
2214     }
2215     return false;
2216 }
2217
2218 void yf::Zoom::Frontend::handle_search(mp::Package &package)
2219 {
2220     Z_GDU *gdu = package.request().get();
2221     Z_APDU *apdu_req = gdu->u.z3950;
2222     Z_APDU *apdu_res = 0;
2223     mp::odr odr;
2224     Z_SearchRequest *sr = apdu_req->u.searchRequest;
2225     if (sr->num_databaseNames != 1)
2226     {
2227         int error = YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED;
2228         log_diagnostic(package, error, 0);
2229         apdu_res = odr.create_searchResponse(apdu_req, error, 0);
2230         package.response() = apdu_res;
2231         return;
2232     }
2233     int proxy_step = 0;
2234     int same_retries = 0;
2235     int proxy_retries = 0;
2236
2237 next_proxy:
2238
2239     int error = 0;
2240     char *addinfo = 0;
2241     std::string db(sr->databaseNames[0]);
2242
2243     BackendPtr b = get_backend_from_databases(package, db, &error,
2244                                               &addinfo, odr, &proxy_step);
2245     if (error)
2246     {
2247         if (retry(package, odr, b, error, &addinfo, proxy_step,
2248                   same_retries, proxy_retries))
2249             goto next_proxy;
2250     }
2251     if (error)
2252     {
2253         log_diagnostic(package, error, addinfo);
2254         apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2255         package.response() = apdu_res;
2256         return;
2257     }
2258     if (!b || b->enable_explain)
2259         return;
2260
2261     b->set_option("setname", "default");
2262
2263     bool enable_pz2_retrieval = false;
2264     bool enable_pz2_transform = false;
2265     bool enable_record_transform = false;
2266     bool assume_marc8_charset = false;
2267     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
2268                      enable_pz2_retrieval,
2269                      enable_pz2_transform,
2270                      enable_record_transform,
2271                      assume_marc8_charset);
2272
2273     Odr_int hits = 0;
2274     Z_Query *query = sr->query;
2275     mp::wrbuf ccl_wrbuf;
2276     mp::wrbuf pqf_wrbuf;
2277     std::string sortkeys;
2278
2279     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
2280     {
2281         // RPN
2282         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
2283     }
2284     else if (query->which == Z_Query_type_2)
2285     {
2286         // CCL
2287         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
2288                     query->u.type_2->len);
2289     }
2290     else if (query->which == Z_Query_type_104 &&
2291              query->u.type_104->which == Z_External_CQL)
2292     {
2293         // CQL
2294         const char *cql = query->u.type_104->u.cql;
2295         CQL_parser cp = cql_parser_create();
2296         int r = cql_parser_string(cp, cql);
2297         package.log("zoom", YLOG_LOG, "CQL: %s", cql);
2298         if (r)
2299         {
2300             cql_parser_destroy(cp);
2301             error = YAZ_BIB1_MALFORMED_QUERY;
2302             const char *addinfo = "CQL syntax error";
2303             log_diagnostic(package, error, addinfo);
2304             apdu_res =
2305                 odr.create_searchResponse(apdu_req, error, addinfo);
2306             package.response() = apdu_res;
2307             return;
2308         }
2309         struct cql_node *cn = cql_parser_result(cp);
2310         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
2311         if (cn_error)
2312         {
2313             // hopefully we are getting a ptr to a index+relation+term node
2314             error = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
2315             addinfo = 0;
2316             if (cn_error->which == CQL_NODE_ST)
2317                 addinfo = cn_error->u.st.index;
2318
2319             log_diagnostic(package, error, addinfo);
2320             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2321             package.response() = apdu_res;
2322             cql_parser_destroy(cp);
2323             return;
2324         }
2325         r = cql_to_ccl(cn, wrbuf_vp_puts,  ccl_wrbuf);
2326         if (r)
2327         {
2328             error = YAZ_BIB1_MALFORMED_QUERY;
2329             const char *addinfo = "CQL to CCL conversion error";
2330
2331             log_diagnostic(package, error, addinfo);
2332             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2333             package.response() = apdu_res;
2334             cql_parser_destroy(cp);
2335             return;
2336         }
2337
2338         mp::wrbuf sru_sortkeys_wrbuf;
2339         if (cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf))
2340         {
2341             error = YAZ_BIB1_ILLEGAL_SORT_RELATION;
2342             const char *addinfo = "CQL to CCL sortby conversion";
2343
2344             log_diagnostic(package, error, addinfo);
2345             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2346             package.response() = apdu_res;
2347             cql_parser_destroy(cp);
2348             return;
2349         }
2350         mp::wrbuf sort_spec_wrbuf;
2351         yaz_srw_sortkeys_to_sort_spec(wrbuf_cstr(sru_sortkeys_wrbuf),
2352                                       sort_spec_wrbuf);
2353         yaz_tok_cfg_t tc = yaz_tok_cfg_create();
2354         yaz_tok_parse_t tp =
2355             yaz_tok_parse_buf(tc, wrbuf_cstr(sort_spec_wrbuf));
2356         yaz_tok_cfg_destroy(tc);
2357
2358         /* go through sortspec and map fields */
2359         int token = yaz_tok_move(tp);
2360         while (token != YAZ_TOK_EOF)
2361         {
2362             if (token == YAZ_TOK_STRING)
2363             {
2364                 const char *field = yaz_tok_parse_string(tp);
2365                 std::map<std::string,std::string>::iterator it;
2366                 it = b->sptr->sortmap.find(field);
2367                 if (it != b->sptr->sortmap.end())
2368                     sortkeys += it->second;
2369                 else
2370                     sortkeys += field;
2371             }
2372             sortkeys += " ";
2373             token = yaz_tok_move(tp);
2374             if (token == YAZ_TOK_STRING)
2375             {
2376                 sortkeys += yaz_tok_parse_string(tp);
2377             }
2378             if (token != YAZ_TOK_EOF)
2379             {
2380                 sortkeys += " ";
2381                 token = yaz_tok_move(tp);
2382             }
2383         }
2384         yaz_tok_parse_destroy(tp);
2385         cql_parser_destroy(cp);
2386     }
2387     else
2388     {
2389         error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
2390         const char *addinfo = 0;
2391         log_diagnostic(package, error, addinfo);
2392         apdu_res =  odr.create_searchResponse(apdu_req, error, addinfo);
2393         package.response() = apdu_res;
2394         return;
2395     }
2396
2397     if (ccl_wrbuf.len())
2398     {
2399         // CCL to PQF
2400         assert(pqf_wrbuf.len() == 0);
2401         int cerror, cpos;
2402         struct ccl_rpn_node *cn;
2403         package.log("zoom", YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
2404         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
2405                           &cerror, &cpos);
2406         if (!cn)
2407         {
2408             char *addinfo = odr_strdup_null(odr, ccl_err_msg(cerror));
2409             error = YAZ_BIB1_MALFORMED_QUERY;
2410
2411             switch (cerror)
2412             {
2413             case CCL_ERR_UNKNOWN_QUAL:
2414             case CCL_ERR_TRUNC_NOT_LEFT:
2415             case CCL_ERR_TRUNC_NOT_RIGHT:
2416             case CCL_ERR_TRUNC_NOT_BOTH:
2417 #ifdef CCL_ERR_TRUNC_NOT_EMBED
2418             case CCL_ERR_TRUNC_NOT_EMBED:
2419 #endif
2420 #ifdef CCL_ERR_TRUNC_NOT_SINGLE
2421             case CCL_ERR_TRUNC_NOT_SINGLE:
2422 #endif
2423                 error = YAZ_BIB1_UNSUPP_SEARCH;
2424                 break;
2425             }
2426             log_diagnostic(package, error, addinfo);
2427             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2428             package.response() = apdu_res;
2429             return;
2430         }
2431         ccl_pquery(pqf_wrbuf, cn);
2432         package.log("zoom", YLOG_LOG, "RPN: %s", wrbuf_cstr(pqf_wrbuf));
2433         ccl_rpn_delete(cn);
2434     }
2435
2436     assert(pqf_wrbuf.len());
2437
2438     ZOOM_query q = ZOOM_query_create();
2439     ZOOM_query_sortby2(q, b->sptr->sortStrategy.c_str(), sortkeys.c_str());
2440
2441     Z_FacetList *fl = 0;
2442
2443     // Facets for request.. And later for reponse
2444     if (!fl)
2445         fl = yaz_oi_get_facetlist(&sr->otherInfo);
2446     if (!fl)
2447         fl = yaz_oi_get_facetlist(&sr->additionalSearchInfo);
2448
2449     if (b->get_option("sru"))
2450     {
2451         Z_RPNQuery *zquery;
2452         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
2453         mp::wrbuf wrb_cql;
2454         mp::wrbuf wrb_addinfo;
2455
2456         if (!strcmp(b->get_option("sru"), "solr"))
2457             error = solr_transform_rpn2solr_stream_r(b->cqlt, wrb_addinfo,
2458                                                      wrbuf_vp_puts, wrb_cql,
2459                                                      zquery);
2460         else
2461             error = cql_transform_rpn2cql_stream_r(b->cqlt, wrb_addinfo,
2462                                                    wrbuf_vp_puts, wrb_cql,
2463                                                    zquery);
2464         if (error)
2465         {
2466             log_diagnostic(package, error, wrb_addinfo.c_str_null());
2467             apdu_res = odr.create_searchResponse(apdu_req, error,
2468                                                  wrb_addinfo.c_str_null());
2469             package.response() = apdu_res;
2470             return;
2471         }
2472         ZOOM_query_cql(q, wrb_cql.c_str());
2473         package.log("zoom", YLOG_LOG, "search CQL: %s", wrb_cql.c_str());
2474         b->search(q, &hits, &error, &addinfo, &fl, odr);
2475         ZOOM_query_destroy(q);
2476     }
2477     else
2478     {
2479         ZOOM_query_prefix(q, pqf_wrbuf.c_str());
2480         package.log("zoom", YLOG_LOG, "search PQF: %s", pqf_wrbuf.c_str());
2481         b->search(q, &hits, &error, &addinfo, &fl, odr);
2482         ZOOM_query_destroy(q);
2483     }
2484
2485     if (error)
2486     {
2487         if (retry(package, odr, b, error, &addinfo, proxy_step,
2488                   same_retries, proxy_retries))
2489             goto next_proxy;
2490     }
2491
2492     const char *element_set_name = 0;
2493     Odr_int number_to_present = 0;
2494     if (!error)
2495         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
2496
2497     Odr_int number_of_records_returned = 0;
2498     Z_Records *records = get_records(
2499         package,
2500         0, number_to_present, &error, &addinfo,
2501         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
2502         element_set_name);
2503     if (error)
2504         log_diagnostic(package, error, addinfo);
2505     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2506     if (records)
2507     {
2508         apdu_res->u.searchResponse->records = records;
2509         apdu_res->u.searchResponse->numberOfRecordsReturned =
2510             odr_intdup(odr, number_of_records_returned);
2511     }
2512     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
2513     if (fl)
2514         yaz_oi_set_facetlist(&apdu_res->u.searchResponse->additionalSearchInfo,
2515                              odr, fl);
2516     package.response() = apdu_res;
2517 }
2518
2519 void yf::Zoom::Frontend::handle_present(mp::Package &package)
2520 {
2521     Z_GDU *gdu = package.request().get();
2522     Z_APDU *apdu_req = gdu->u.z3950;
2523     Z_APDU *apdu_res = 0;
2524     Z_PresentRequest *pr = apdu_req->u.presentRequest;
2525
2526     mp::odr odr;
2527     if (!m_backend)
2528     {
2529         package.response() = odr.create_presentResponse(
2530             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
2531         return;
2532     }
2533     const char *element_set_name = 0;
2534     Z_RecordComposition *comp = pr->recordComposition;
2535     if (comp && comp->which != Z_RecordComp_simple)
2536     {
2537         package.response() = odr.create_presentResponse(
2538             apdu_req,
2539             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
2540         return;
2541     }
2542     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
2543         element_set_name = comp->u.simple->u.generic;
2544     Odr_int number_of_records_returned = 0;
2545     int error = 0;
2546     char *addinfo = 0;
2547
2548     if (m_backend->enable_explain)
2549     {
2550         Z_Records *records =
2551             get_explain_records(
2552                 package,
2553                 *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2554                 &error, &addinfo, &number_of_records_returned, odr, m_backend,
2555                 pr->preferredRecordSyntax, element_set_name);
2556
2557         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2558         if (records)
2559         {
2560             apdu_res->u.presentResponse->records = records;
2561             apdu_res->u.presentResponse->numberOfRecordsReturned =
2562                 odr_intdup(odr, number_of_records_returned);
2563         }
2564         package.response() = apdu_res;
2565     }
2566     else
2567     {
2568         Z_Records *records =
2569             get_records(package,
2570                         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2571                         &error, &addinfo, &number_of_records_returned, odr, m_backend,
2572                         pr->preferredRecordSyntax, element_set_name);
2573
2574         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2575         if (records)
2576         {
2577             apdu_res->u.presentResponse->records = records;
2578             apdu_res->u.presentResponse->numberOfRecordsReturned =
2579                 odr_intdup(odr, number_of_records_returned);
2580         }
2581         package.response() = apdu_res;
2582     }
2583 }
2584
2585 void yf::Zoom::Frontend::handle_package(mp::Package &package)
2586 {
2587     Z_GDU *gdu = package.request().get();
2588     if (!gdu)
2589         ;
2590     else if (gdu->which == Z_GDU_Z3950)
2591     {
2592         Z_APDU *apdu_req = gdu->u.z3950;
2593
2594         if (m_backend)
2595             wrbuf_rewind(m_backend->m_apdu_wrbuf);
2596         if (apdu_req->which == Z_APDU_initRequest)
2597         {
2598             mp::odr odr;
2599             package.response() = odr.create_close(
2600                 apdu_req,
2601                 Z_Close_protocolError,
2602                 "double init");
2603         }
2604         else if (apdu_req->which == Z_APDU_searchRequest)
2605         {
2606             handle_search(package);
2607         }
2608         else if (apdu_req->which == Z_APDU_presentRequest)
2609         {
2610             handle_present(package);
2611         }
2612         else
2613         {
2614             mp::odr odr;
2615             package.response() = odr.create_close(
2616                 apdu_req,
2617                 Z_Close_protocolError,
2618                 "zoom filter cannot handle this APDU");
2619             package.session().close();
2620         }
2621         if (m_backend)
2622         {
2623             WRBUF w = m_backend->m_apdu_wrbuf;
2624             package.log_write(wrbuf_buf(w), wrbuf_len(w));
2625         }
2626     }
2627     else
2628     {
2629         package.session().close();
2630     }
2631 }
2632
2633 std::string escape_cql_term(std::string inp)
2634 {
2635     std::string res;
2636     size_t l = inp.length();
2637     size_t i;
2638     for (i = 0; i < l; i++)
2639     {
2640         if (strchr("*?^\"", inp[i]))
2641             res += "\\";
2642         res += inp[i];
2643     }
2644     return res;
2645 }
2646
2647 void yf::Zoom::Frontend::auth(mp::Package &package, Z_InitRequest *req,
2648                               int *error, char **addinfo, ODR odr)
2649 {
2650     if (m_p->torus_auth_url.length() == 0)
2651         return;
2652
2653     std::string user;
2654     std::string password;
2655     if (req->idAuthentication)
2656     {
2657         Z_IdAuthentication *auth = req->idAuthentication;
2658         switch (auth->which)
2659         {
2660         case Z_IdAuthentication_open:
2661             if (auth->u.open)
2662             {
2663                 const char *cp = strchr(auth->u.open, '/');
2664                 if (cp)
2665                 {
2666                     user.assign(auth->u.open, cp - auth->u.open);
2667                     password.assign(cp + 1);
2668                 }
2669             }
2670             break;
2671         case Z_IdAuthentication_idPass:
2672             if (auth->u.idPass->userId)
2673                 user.assign(auth->u.idPass->userId);
2674             if (auth->u.idPass->password)
2675                 password.assign(auth->u.idPass->password);
2676             break;
2677         }
2678     }
2679
2680     Z_OtherInformation **oi = &req->otherInfo;
2681     const char *ip_cstr =
2682         yaz_oi_get_string_oid(oi, yaz_oid_userinfo_client_ip, 1, 0);
2683     std::string ip;
2684     if (ip_cstr)
2685         ip = ip_cstr;
2686     else
2687         ip = package.origin().get_address();
2688
2689     yaz_log(YLOG_LOG, "IP=%s", ip.c_str());
2690
2691     {
2692         NMEM nmem = nmem_create();
2693         char **darray;
2694         int i, num;
2695         nmem_strsplit_blank(nmem, m_p->torus_allow_ip.c_str(), &darray, &num);
2696         for (i = 0; i < num; i++)
2697         {
2698             yaz_log(YLOG_LOG, "check against %s+%s", darray[i], ip.c_str());
2699             if (yaz_match_glob(darray[i], ip.c_str()))
2700                 break;
2701         }
2702         nmem_destroy(nmem);
2703         if (i < num)
2704             return;  /* allow this IP */
2705     }
2706     std::string torus_query;
2707     int failure_code;
2708
2709     if (user.length() && password.length())
2710     {
2711         torus_query = "userName==\"" + escape_cql_term(user) +
2712             "\" and password==\"" + escape_cql_term(password) + "\"";
2713         failure_code = YAZ_BIB1_INIT_AC_BAD_USERID_AND_OR_PASSWORD;
2714     }
2715     else
2716     {
2717         torus_query = "ipRanges encloses/net.ipaddress \"";
2718         torus_query += escape_cql_term(std::string(ip));
2719         torus_query += "\"";
2720
2721         if (m_p->torus_auth_hostname.length())
2722         {
2723             torus_query += " AND hostName == \"";
2724             torus_query += escape_cql_term(m_p->torus_auth_hostname);
2725             torus_query += "\"";
2726         }
2727         failure_code = YAZ_BIB1_INIT_AC_BLOCKED_NETWORK_ADDRESS;
2728     }
2729
2730     std::string dummy_db;
2731     std::string dummy_realm;
2732     std::string torus_addinfo;
2733     xmlDoc *doc = mp::get_searchable(package, m_p->torus_auth_url, dummy_db,
2734                                      torus_query, dummy_realm, m_p->proxy,
2735                                      torus_addinfo);
2736     if (!doc)
2737     {
2738         // something fundamental broken in lookup.
2739         *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
2740         if (torus_addinfo.length())
2741             *addinfo = odr_strdup(odr, torus_addinfo.c_str());
2742         return;
2743     }
2744     const xmlNode *ptr = xmlDocGetRootElement(doc);
2745     if (ptr && ptr->type == XML_ELEMENT_NODE)
2746     {
2747         if (strcmp((const char *) ptr->name, "records") == 0)
2748         {
2749             ptr = ptr->children;
2750             while (ptr && ptr->type != XML_ELEMENT_NODE)
2751                 ptr = ptr->next;
2752         }
2753         if (ptr && strcmp((const char *) ptr->name, "record") == 0)
2754         {
2755             ptr = ptr->children;
2756             while (ptr && ptr->type != XML_ELEMENT_NODE)
2757                 ptr = ptr->next;
2758         }
2759         if (ptr && strcmp((const char *) ptr->name, "layer") == 0)
2760         {
2761             ptr = ptr->children;
2762             while (ptr && ptr->type != XML_ELEMENT_NODE)
2763                 ptr = ptr->next;
2764         }
2765         while (ptr)
2766         {
2767             if (ptr && ptr->type == XML_ELEMENT_NODE &&
2768                 !strcmp((const char *) ptr->name, "identityId"))
2769                 break;
2770             ptr = ptr->next;
2771         }
2772     }
2773     if (!ptr)
2774     {
2775         *error = failure_code;
2776         return;
2777     }
2778     session_realm = mp::xml::get_text(ptr);
2779 }
2780
2781 void yf::Zoom::Impl::process(mp::Package &package)
2782 {
2783     FrontendPtr f = get_frontend(package);
2784     Z_GDU *gdu = package.request().get();
2785
2786     if (f->m_is_virtual)
2787     {
2788         f->handle_package(package);
2789     }
2790     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
2791              Z_APDU_initRequest)
2792     {
2793         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
2794         f->m_init_gdu = gdu;
2795
2796         mp::odr odr;
2797         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
2798         Z_InitResponse *resp = apdu->u.initResponse;
2799
2800         int i;
2801         static const int masks[] = {
2802             Z_Options_search,
2803             Z_Options_present,
2804             -1
2805         };
2806         for (i = 0; masks[i] != -1; i++)
2807             if (ODR_MASK_GET(req->options, masks[i]))
2808                 ODR_MASK_SET(resp->options, masks[i]);
2809
2810         static const int versions[] = {
2811             Z_ProtocolVersion_1,
2812             Z_ProtocolVersion_2,
2813             Z_ProtocolVersion_3,
2814             -1
2815         };
2816         for (i = 0; versions[i] != -1; i++)
2817             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
2818                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
2819             else
2820                 break;
2821
2822         *resp->preferredMessageSize = *req->preferredMessageSize;
2823         *resp->maximumRecordSize = *req->maximumRecordSize;
2824
2825         int error = 0;
2826         char *addinfo = 0;
2827         f->auth(package, req, &error, &addinfo, odr);
2828         if (error)
2829         {
2830             resp->userInformationField =
2831                 zget_init_diagnostics(odr, error, addinfo);
2832             *resp->result = 0;
2833             package.session().close();
2834         }
2835         else
2836             f->m_is_virtual = true;
2837         package.response() = apdu;
2838     }
2839     else
2840         package.move();
2841
2842     release_frontend(package);
2843 }
2844
2845
2846 static mp::filter::Base* filter_creator()
2847 {
2848     return new mp::filter::Zoom;
2849 }
2850
2851 extern "C" {
2852     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
2853         0,
2854         "zoom",
2855         filter_creator
2856     };
2857 }
2858
2859
2860 /*
2861  * Local variables:
2862  * c-basic-offset: 4
2863  * c-file-style: "Stroustrup"
2864  * indent-tabs-mode: nil
2865  * End:
2866  * vim: shiftwidth=4 tabstop=8 expandtab
2867  */
2868