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