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