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