a17617bcecf3f12d255e0330520de18c830de186
[metaproxy-moved-to-github.git] / src / filter_zoom.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) Index Data
3
4 Metaproxy is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17 */
18
19 #include "config.hpp"
20
21 #include <stdlib.h>
22 #include <sys/types.h>
23 #include "filter_zoom.hpp"
24 #include <metaproxy/package.hpp>
25 #include <metaproxy/util.hpp>
26 #include <metaproxy/xmlutil.hpp>
27 #include <yaz/comstack.h>
28 #include <yaz/poll.h>
29 #include "torus.hpp"
30
31 #include <libxslt/xsltutils.h>
32 #include <libxslt/transform.h>
33
34 #include <boost/thread/mutex.hpp>
35 #include <boost/thread/condition.hpp>
36
37 #include <yaz/yaz-version.h>
38 #include <yaz/tpath.h>
39 #include <yaz/srw.h>
40 #include <yaz/ccl_xml.h>
41 #include <yaz/ccl.h>
42 #include <yaz/rpn2cql.h>
43 #include <yaz/rpn2solr.h>
44 #include <yaz/pquery.h>
45 #include <yaz/cql.h>
46 #include <yaz/oid_db.h>
47 #include <yaz/diagbib1.h>
48 #include <yaz/log.h>
49 #include <yaz/zgdu.h>
50 #include <yaz/querytowrbuf.h>
51 #include <yaz/sortspec.h>
52 #include <yaz/tokenizer.h>
53 #include <yaz/zoom.h>
54 #include <yaz/otherinfo.h>
55 #include <yaz/match_glob.h>
56
57 namespace mp = metaproxy_1;
58 namespace yf = mp::filter;
59
60 namespace metaproxy_1 {
61     namespace filter {
62         class Zoom::Searchable : boost::noncopyable {
63           public:
64             std::string authentication;
65             std::string authenticationMode;
66             std::string contentAuthentication;
67             std::string cfAuth;
68             std::string cfProxy;
69             std::string cfSubDB;
70             std::string udb;
71             std::string target;
72             std::string query_encoding;
73             std::string sru;
74             std::string sru_version;
75             std::string request_syntax;
76             std::string element_set;
77             std::string record_encoding;
78             std::string transform_xsl_fname;
79             std::string transform_xsl_content;
80             std::string urlRecipe;
81             std::string contentConnector;
82             std::string sortStrategy;
83             std::string extraArgs;
84             std::string rpn2cql_fname;
85             std::string retry_on_failure;
86             bool use_turbomarc;
87             bool piggyback;
88             CCL_bibset ccl_bibset;
89             std::map<std::string, std::string> sortmap;
90             Searchable(CCL_bibset base);
91             ~Searchable();
92         };
93         class Zoom::Backend : boost::noncopyable {
94             friend class Impl;
95             friend class Frontend;
96             mp::wrbuf m_apdu_wrbuf;
97             ZOOM_connection m_connection;
98             ZOOM_resultset m_resultset;
99             std::string m_frontend_database;
100             SearchablePtr sptr;
101             xsltStylesheetPtr xsp;
102             std::string cproxy_host;
103             bool enable_cproxy;
104             bool enable_explain;
105             xmlDoc *explain_doc;
106             std::string m_proxy;
107             cql_transform_t cqlt;
108             std::string retry_on_failure;
109         public:
110             Backend();
111             ~Backend();
112             void connect(std::string zurl, int *error, char **addinfo,
113                          ODR odr);
114             void search(ZOOM_query q, Odr_int *hits,
115                         int *error, char **addinfo, Z_FacetList **fl, ODR odr);
116             void present(Odr_int start, Odr_int number, ZOOM_record *recs,
117                          int *error, char **addinfo, ODR odr);
118             void set_option(const char *name, const char *value);
119             void set_option(const char *name, const char *value, size_t l);
120             void set_option(const char *name, std::string value);
121             const char *get_option(const char *name);
122             void get_zoom_error(int *error, char **addinfo, ODR odr);
123         };
124         class Zoom::Frontend : boost::noncopyable {
125             friend class Impl;
126             Impl *m_p;
127             bool m_is_virtual;
128             bool m_in_use;
129             std::string session_realm;
130             yazpp_1::GDU m_init_gdu;
131             BackendPtr m_backend;
132             void handle_package(mp::Package &package);
133             void handle_search(mp::Package &package);
134             void auth(mp::Package &package, Z_InitRequest *req,
135                       int *error, char **addinfo, ODR odr);
136
137             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_backend->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     b->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, b->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,
1794                                         b->m_frontend_database.c_str());
1795         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1796             odr_malloc(odr, sizeof(*npl));
1797         *number_of_records_returned = i;
1798         npl->num_records = i;
1799         npl->records = (Z_NamePlusRecord **)
1800             odr_malloc(odr, i * sizeof(*npl->records));
1801         for (i = 0; i < npl->num_records; i++)
1802         {
1803             Z_NamePlusRecord *npr = 0;
1804             const char *addinfo;
1805
1806             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1807                                               &addinfo, 0 /* diagset */);
1808
1809             if (sur_error)
1810             {
1811                 log_diagnostic(package, sur_error, addinfo);
1812                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1813                                             addinfo);
1814             }
1815             else if (enable_pz2_retrieval)
1816             {
1817                 char rec_type_str[100];
1818                 const char *record_encoding = 0;
1819
1820                 if (b->sptr->record_encoding.length())
1821                     record_encoding = b->sptr->record_encoding.c_str();
1822                 else if (assume_marc8_charset)
1823                     record_encoding = "marc8";
1824
1825                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1826                 if (record_encoding)
1827                 {
1828                     strcat(rec_type_str, "; charset=");
1829                     strcat(rec_type_str, record_encoding);
1830                 }
1831
1832                 package.log("zoom", YLOG_LOG, "Getting record of type %s",
1833                             rec_type_str);
1834                 int rec_len;
1835                 xmlChar *xmlrec_buf = 0;
1836                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1837                                                       &rec_len);
1838                 if (!rec_buf && !npr)
1839                 {
1840                     std::string addinfo("ZOOM_record_get failed for type ");
1841
1842                     int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1843                     addinfo += rec_type_str;
1844                     log_diagnostic(package, error, addinfo.c_str());
1845                     npr = zget_surrogateDiagRec(odr, odr_database,
1846                                                 error, addinfo.c_str());
1847                 }
1848                 else
1849                 {
1850                     package.log_write(rec_buf, rec_len);
1851                     package.log_write("\r\n", 2);
1852                 }
1853
1854                 if (rec_buf && b->xsp && enable_pz2_transform)
1855                 {
1856                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1857                     if (!rec_doc)
1858                     {
1859                         const char *addinfo = "xml parse failed for record";
1860                         int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1861                         log_diagnostic(package, error, addinfo);
1862                         npr = zget_surrogateDiagRec(
1863                             odr, odr_database, error, addinfo);
1864                     }
1865                     else
1866                     {
1867                         // first stage XSLT - per target
1868                         xsltStylesheetPtr xsp = b->xsp;
1869                         xmlDoc *rec_res = xsltApplyStylesheet(xsp, rec_doc,
1870                                                               xsl_parms);
1871                         // insert generated-url
1872                         if (rec_res)
1873                         {
1874                             std::string res =
1875                                 mp::xml::url_recipe_handle(rec_res,
1876                                                            b->sptr->urlRecipe);
1877                             if (res.length())
1878                             {
1879                                 xmlNode *ptr = xmlDocGetRootElement(rec_res);
1880                                 while (ptr && ptr->type != XML_ELEMENT_NODE)
1881                                     ptr = ptr->next;
1882                                 xmlNode *c =
1883                                     xmlNewChild(ptr, 0, BAD_CAST "metadata", 0);
1884                                 xmlNewProp(c, BAD_CAST "type", BAD_CAST
1885                                            "generated-url");
1886                                 xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1887                                 xmlAddChild(c, t);
1888                             }
1889                         }
1890                         // second stage XSLT - common
1891                         if (rec_res && m_p->record_xsp &&
1892                             enable_record_transform)
1893                         {
1894                             xmlDoc *tmp_doc = rec_res;
1895
1896                             xsp = m_p->record_xsp;
1897                             rec_res = xsltApplyStylesheet(xsp, tmp_doc,
1898                                                           xsl_parms);
1899                             xmlFreeDoc(tmp_doc);
1900                         }
1901                         // get result out of it
1902                         if (rec_res)
1903                         {
1904                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1905                                                    rec_res, xsp);
1906                             rec_buf = (const char *) xmlrec_buf;
1907                             package.log_write(rec_buf, rec_len);
1908
1909                             xmlFreeDoc(rec_res);
1910                         }
1911                         if (!rec_buf)
1912                         {
1913                             std::string addinfo;
1914                             int error =
1915                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1916
1917                             addinfo = "xslt apply failed for "
1918                                 + b->sptr->transform_xsl_fname;
1919                             log_diagnostic(package, error, addinfo.c_str());
1920                             npr = zget_surrogateDiagRec(
1921                                 odr, odr_database, error, addinfo.c_str());
1922                         }
1923                         xmlFreeDoc(rec_doc);
1924                     }
1925                 }
1926
1927                 if (!npr)
1928                 {
1929                     if (!rec_buf)
1930                         npr = zget_surrogateDiagRec(
1931                             odr, odr_database,
1932                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1933                             rec_type_str);
1934                     else
1935                     {
1936                         npr = (Z_NamePlusRecord *)
1937                             odr_malloc(odr, sizeof(*npr));
1938                         npr->databaseName = odr_database;
1939                         npr->which = Z_NamePlusRecord_databaseRecord;
1940                         npr->u.databaseRecord =
1941                             z_ext_record_xml(odr, rec_buf, rec_len);
1942                     }
1943                 }
1944                 if (xmlrec_buf)
1945                     xmlFree(xmlrec_buf);
1946             }
1947             else
1948             {
1949                 Z_External *ext =
1950                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1951                 if (ext)
1952                 {
1953                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1954                     npr->databaseName = odr_database;
1955                     npr->which = Z_NamePlusRecord_databaseRecord;
1956                     npr->u.databaseRecord = ext;
1957                 }
1958                 else
1959                 {
1960                     npr = zget_surrogateDiagRec(
1961                         odr, odr_database,
1962                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1963                         "ZOOM_record, type ext");
1964                 }
1965             }
1966             npl->records[i] = npr;
1967         }
1968         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1969         records->which = Z_Records_DBOSD;
1970         records->u.databaseOrSurDiagnostics = npl;
1971     }
1972     return records;
1973 }
1974
1975 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1976                                                     ODR odr)
1977 {
1978     struct cql_node *r = 0;
1979     if (!cn)
1980         return 0;
1981     switch (cn->which)
1982     {
1983     case CQL_NODE_ST:
1984         if (cn->u.st.index)
1985         {
1986             std::map<std::string,std::string>::const_iterator it;
1987             it = fieldmap.find(cn->u.st.index);
1988             if (it == fieldmap.end())
1989                 return cn;
1990             if (it->second.length())
1991                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1992             else
1993                 cn->u.st.index = 0;
1994         }
1995         break;
1996     case CQL_NODE_BOOL:
1997         r = convert_cql_fields(cn->u.boolean.left, odr);
1998         if (!r)
1999             r = convert_cql_fields(cn->u.boolean.right, odr);
2000         break;
2001     case CQL_NODE_SORT:
2002         r = convert_cql_fields(cn->u.sort.search, odr);
2003         break;
2004     }
2005     return r;
2006 }
2007
2008 void yf::Zoom::Frontend::log_diagnostic(mp::Package &package,
2009                                         int error, const char *addinfo)
2010 {
2011     const char *err_msg = yaz_diag_bib1_str(error);
2012     if (addinfo)
2013         package.log("zoom", YLOG_WARN, "Diagnostic %d %s: %s",
2014                     error, err_msg, addinfo);
2015     else
2016         package.log("zoom", YLOG_WARN, "Diagnostic %d %s:",
2017                     error, err_msg);
2018 }
2019
2020 void yf::Zoom::Frontend::explain_search(mp::Package &package,
2021                                         std::string &database,
2022                                         int *error,
2023                                         char **addinfo,
2024                                         mp::odr &odr,
2025                                         std::string torus_url,
2026                                         std::string &torus_db,
2027                                         std::string &realm)
2028 {
2029     m_backend.reset();
2030
2031     BackendPtr b(new Backend);
2032
2033     b->m_frontend_database = database;
2034     b->enable_explain = true;
2035
2036     Z_GDU *gdu = package.request().get();
2037     Z_APDU *apdu_req = gdu->u.z3950;
2038     Z_SearchRequest *sr = apdu_req->u.searchRequest;
2039     Z_Query *query = sr->query;
2040
2041     if (!m_p->explain_xsp)
2042     {
2043         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
2044         *addinfo =
2045             odr_strdup(odr, "IR-Explain---1 unsupported. "
2046                        "Torus explain_xsl not defined");
2047         return;
2048     }
2049     else if (query->which == Z_Query_type_104 &&
2050         query->u.type_104->which == Z_External_CQL)
2051     {
2052         std::string torus_addinfo;
2053         std::string torus_query(query->u.type_104->u.cql);
2054         xmlDoc *doc = mp::get_searchable(package, torus_url, "",
2055                                          torus_query,
2056                                          realm, m_p->proxy,
2057                                          torus_addinfo);
2058         if (m_p->explain_xsp)
2059         {
2060             xmlDoc *rec_res =  xsltApplyStylesheet(m_p->explain_xsp, doc, 0);
2061
2062             xmlFreeDoc(doc);
2063             doc = rec_res;
2064         }
2065         if (!doc)
2066         {
2067             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
2068             if (torus_addinfo.length())
2069                 *addinfo = odr_strdup(odr, torus_addinfo.c_str());
2070         }
2071         else
2072         {
2073             xmlNode *ptr = xmlDocGetRootElement(doc);
2074             int hits = 0;
2075
2076             xml_node_search(ptr, &hits, 0);
2077
2078             Z_APDU *apdu_res = odr.create_searchResponse(apdu_req, 0, 0);
2079             apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
2080             package.response() = apdu_res;
2081             m_backend = b;
2082         }
2083         if (b->explain_doc)
2084             xmlFreeDoc(b->explain_doc);
2085         b->explain_doc = doc;
2086     }
2087     else
2088     {
2089         *error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
2090         *addinfo = odr_strdup(odr, "IR-Explain---1 only supports CQL");
2091     }
2092 }
2093
2094 static bool wait_conn(COMSTACK cs, int secs)
2095 {
2096     struct yaz_poll_fd pfd;
2097
2098     yaz_poll_add(pfd.input_mask, yaz_poll_except);
2099     if (cs->io_pending & CS_WANT_WRITE)
2100         yaz_poll_add(pfd.input_mask, yaz_poll_write);
2101     if (cs->io_pending & CS_WANT_READ)
2102         yaz_poll_add(pfd.input_mask, yaz_poll_read);
2103
2104     pfd.fd = cs_fileno(cs);
2105     pfd.client_data = 0;
2106
2107     int ret = yaz_poll(&pfd, 1, secs, 0);
2108     return ret > 0;
2109 }
2110
2111 bool yf::Zoom::Impl::check_proxy(const char *proxy)
2112 {
2113     COMSTACK conn = 0;
2114     const char *uri = "http://localhost/";
2115     void *add;
2116     mp::odr odr;
2117     bool outcome = false;
2118     conn = cs_create_host_proxy(uri, 0, &add, proxy);
2119
2120     if (!conn)
2121         return false;
2122
2123     Z_GDU *gdu = z_get_HTTP_Request_uri(odr, uri, 0, 1);
2124     gdu->u.HTTP_Request->method = odr_strdup(odr, "GET");
2125
2126     if (z_GDU(odr, &gdu, 0, 0))
2127     {
2128         int len;
2129         char *buf = odr_getbuf(odr, &len, 0);
2130
2131         int ret = cs_connect(conn, add);
2132         if (ret > 0 || (ret == 0 && wait_conn(conn, 1)))
2133         {
2134             while (1)
2135             {
2136                 ret = cs_put(conn, buf, len);
2137                 if (ret != 1)
2138                     break;
2139                 if (!wait_conn(conn, proxy_timeout))
2140                     break;
2141             }
2142             if (ret == 0)
2143                 outcome = true;
2144         }
2145     }
2146     cs_close(conn);
2147     return outcome;
2148 }
2149
2150 bool yf::Zoom::Frontend::retry(mp::Package &package,
2151                                mp::odr &odr,
2152                                BackendPtr b,
2153                                int &error, char **addinfo,
2154                                int &proxy_step, int &same_retries,
2155                                int &proxy_retries)
2156 {
2157     if (b && b->m_proxy.length() && !m_p->check_proxy(b->m_proxy.c_str()))
2158     {
2159         log_diagnostic(package, error, *addinfo);
2160         package.log("zoom", YLOG_LOG, "proxy %s fails", b->m_proxy.c_str());
2161         m_backend.reset();
2162         if (proxy_step) // there is a failover
2163         {
2164             proxy_retries++;
2165             package.log("zoom", YLOG_WARN, "search failed: trying next proxy");
2166             return true;
2167         }
2168         error = YAZ_BIB1_PROXY_FAILURE;
2169         *addinfo = odr_strdup(odr, b->m_proxy.c_str());
2170     }
2171     else if (b && b->retry_on_failure.compare("0")
2172              && same_retries == 0 && proxy_retries == 0)
2173     {
2174         log_diagnostic(package, error, *addinfo);
2175         same_retries++;
2176         package.log("zoom", YLOG_WARN, "search failed: retry");
2177         m_backend.reset();
2178         proxy_step = 0;
2179         return true;
2180     }
2181     return false;
2182 }
2183
2184 void yf::Zoom::Frontend::handle_search(mp::Package &package)
2185 {
2186     Z_GDU *gdu = package.request().get();
2187     Z_APDU *apdu_req = gdu->u.z3950;
2188     Z_APDU *apdu_res = 0;
2189     mp::odr odr;
2190     Z_SearchRequest *sr = apdu_req->u.searchRequest;
2191     if (sr->num_databaseNames != 1)
2192     {
2193         int error = YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED;
2194         log_diagnostic(package, error, 0);
2195         apdu_res = odr.create_searchResponse(apdu_req, error, 0);
2196         package.response() = apdu_res;
2197         return;
2198     }
2199     int proxy_step = 0;
2200     int same_retries = 0;
2201     int proxy_retries = 0;
2202
2203 next_proxy:
2204
2205     int error = 0;
2206     char *addinfo = 0;
2207     std::string db(sr->databaseNames[0]);
2208
2209     get_backend_from_databases(package, db, &error,
2210                                &addinfo, odr, &proxy_step);
2211     BackendPtr b = m_backend;
2212     if (error)
2213     {
2214         if (retry(package, odr, b, error, &addinfo, proxy_step,
2215                   same_retries, proxy_retries))
2216             goto next_proxy;
2217     }
2218     if (error)
2219     {
2220         log_diagnostic(package, error, addinfo);
2221         apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2222         package.response() = apdu_res;
2223         return;
2224     }
2225     if (!b || b->enable_explain)
2226         return;
2227
2228     b->set_option("setname", "default");
2229
2230     bool enable_pz2_retrieval = false;
2231     bool enable_pz2_transform = false;
2232     bool enable_record_transform = false;
2233     bool assume_marc8_charset = false;
2234     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
2235                      enable_pz2_retrieval,
2236                      enable_pz2_transform,
2237                      enable_record_transform,
2238                      assume_marc8_charset);
2239
2240     Odr_int hits = 0;
2241     Z_Query *query = sr->query;
2242     mp::wrbuf ccl_wrbuf;
2243     mp::wrbuf pqf_wrbuf;
2244     std::string sortkeys;
2245
2246     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
2247     {
2248         // RPN
2249         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
2250     }
2251     else if (query->which == Z_Query_type_2)
2252     {
2253         // CCL
2254         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
2255                     query->u.type_2->len);
2256     }
2257     else if (query->which == Z_Query_type_104 &&
2258              query->u.type_104->which == Z_External_CQL)
2259     {
2260         // CQL
2261         const char *cql = query->u.type_104->u.cql;
2262         CQL_parser cp = cql_parser_create();
2263         int r = cql_parser_string(cp, cql);
2264         package.log("zoom", YLOG_LOG, "CQL: %s", cql);
2265         if (r)
2266         {
2267             cql_parser_destroy(cp);
2268             error = YAZ_BIB1_MALFORMED_QUERY;
2269             const char *addinfo = "CQL syntax error";
2270             log_diagnostic(package, error, addinfo);
2271             apdu_res =
2272                 odr.create_searchResponse(apdu_req, error, addinfo);
2273             package.response() = apdu_res;
2274             return;
2275         }
2276         struct cql_node *cn = cql_parser_result(cp);
2277         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
2278         if (cn_error)
2279         {
2280             // hopefully we are getting a ptr to a index+relation+term node
2281             error = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
2282             addinfo = 0;
2283             if (cn_error->which == CQL_NODE_ST)
2284                 addinfo = cn_error->u.st.index;
2285
2286             log_diagnostic(package, error, addinfo);
2287             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2288             package.response() = apdu_res;
2289             cql_parser_destroy(cp);
2290             return;
2291         }
2292         r = cql_to_ccl(cn, wrbuf_vp_puts,  ccl_wrbuf);
2293         if (r)
2294         {
2295             error = YAZ_BIB1_MALFORMED_QUERY;
2296             const char *addinfo = "CQL to CCL conversion error";
2297
2298             log_diagnostic(package, error, addinfo);
2299             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2300             package.response() = apdu_res;
2301             cql_parser_destroy(cp);
2302             return;
2303         }
2304
2305         mp::wrbuf sru_sortkeys_wrbuf;
2306         if (cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf))
2307         {
2308             error = YAZ_BIB1_ILLEGAL_SORT_RELATION;
2309             const char *addinfo = "CQL to CCL sortby conversion";
2310
2311             log_diagnostic(package, error, addinfo);
2312             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2313             package.response() = apdu_res;
2314             cql_parser_destroy(cp);
2315             return;
2316         }
2317         mp::wrbuf sort_spec_wrbuf;
2318         yaz_srw_sortkeys_to_sort_spec(wrbuf_cstr(sru_sortkeys_wrbuf),
2319                                       sort_spec_wrbuf);
2320         yaz_tok_cfg_t tc = yaz_tok_cfg_create();
2321         yaz_tok_parse_t tp =
2322             yaz_tok_parse_buf(tc, wrbuf_cstr(sort_spec_wrbuf));
2323         yaz_tok_cfg_destroy(tc);
2324
2325         /* go through sortspec and map fields */
2326         int token = yaz_tok_move(tp);
2327         while (token != YAZ_TOK_EOF)
2328         {
2329             if (token == YAZ_TOK_STRING)
2330             {
2331                 const char *field = yaz_tok_parse_string(tp);
2332                 std::map<std::string,std::string>::iterator it;
2333                 it = b->sptr->sortmap.find(field);
2334                 if (it != b->sptr->sortmap.end())
2335                     sortkeys += it->second;
2336                 else
2337                     sortkeys += field;
2338             }
2339             sortkeys += " ";
2340             token = yaz_tok_move(tp);
2341             if (token == YAZ_TOK_STRING)
2342             {
2343                 sortkeys += yaz_tok_parse_string(tp);
2344             }
2345             if (token != YAZ_TOK_EOF)
2346             {
2347                 sortkeys += " ";
2348                 token = yaz_tok_move(tp);
2349             }
2350         }
2351         yaz_tok_parse_destroy(tp);
2352         cql_parser_destroy(cp);
2353     }
2354     else
2355     {
2356         error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
2357         const char *addinfo = 0;
2358         log_diagnostic(package, error, addinfo);
2359         apdu_res =  odr.create_searchResponse(apdu_req, error, addinfo);
2360         package.response() = apdu_res;
2361         return;
2362     }
2363
2364     if (ccl_wrbuf.len())
2365     {
2366         // CCL to PQF
2367         assert(pqf_wrbuf.len() == 0);
2368         int cerror, cpos;
2369         struct ccl_rpn_node *cn;
2370         package.log("zoom", YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
2371         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
2372                           &cerror, &cpos);
2373         if (!cn)
2374         {
2375             char *addinfo = odr_strdup_null(odr, ccl_err_msg(cerror));
2376             error = YAZ_BIB1_MALFORMED_QUERY;
2377
2378             switch (cerror)
2379             {
2380             case CCL_ERR_UNKNOWN_QUAL:
2381             case CCL_ERR_TRUNC_NOT_LEFT:
2382             case CCL_ERR_TRUNC_NOT_RIGHT:
2383             case CCL_ERR_TRUNC_NOT_BOTH:
2384 #ifdef CCL_ERR_TRUNC_NOT_EMBED
2385             case CCL_ERR_TRUNC_NOT_EMBED:
2386 #endif
2387 #ifdef CCL_ERR_TRUNC_NOT_SINGLE
2388             case CCL_ERR_TRUNC_NOT_SINGLE:
2389 #endif
2390                 error = YAZ_BIB1_UNSUPP_SEARCH;
2391                 break;
2392             }
2393             log_diagnostic(package, error, addinfo);
2394             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2395             package.response() = apdu_res;
2396             return;
2397         }
2398         ccl_pquery(pqf_wrbuf, cn);
2399         package.log("zoom", YLOG_LOG, "RPN: %s", wrbuf_cstr(pqf_wrbuf));
2400         ccl_rpn_delete(cn);
2401     }
2402
2403     assert(pqf_wrbuf.len());
2404
2405     ZOOM_query q = ZOOM_query_create();
2406     ZOOM_query_sortby2(q, b->sptr->sortStrategy.c_str(), sortkeys.c_str());
2407
2408     Z_FacetList *fl = 0;
2409
2410     // Facets for request.. And later for reponse
2411     if (!fl)
2412         fl = yaz_oi_get_facetlist(&sr->otherInfo);
2413     if (!fl)
2414         fl = yaz_oi_get_facetlist(&sr->additionalSearchInfo);
2415
2416     if (b->get_option("sru"))
2417     {
2418         Z_RPNQuery *zquery;
2419         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
2420         mp::wrbuf wrb_cql;
2421         mp::wrbuf wrb_addinfo;
2422
2423         if (!strcmp(b->get_option("sru"), "solr"))
2424             error = solr_transform_rpn2solr_stream_r(b->cqlt, wrb_addinfo,
2425                                                      wrbuf_vp_puts, wrb_cql,
2426                                                      zquery);
2427         else
2428             error = cql_transform_rpn2cql_stream_r(b->cqlt, wrb_addinfo,
2429                                                    wrbuf_vp_puts, wrb_cql,
2430                                                    zquery);
2431         if (error)
2432         {
2433             log_diagnostic(package, error, wrb_addinfo.c_str_null());
2434             apdu_res = odr.create_searchResponse(apdu_req, error,
2435                                                  wrb_addinfo.c_str_null());
2436             package.response() = apdu_res;
2437             return;
2438         }
2439         ZOOM_query_cql(q, wrb_cql.c_str());
2440         package.log("zoom", YLOG_LOG, "search CQL: %s", wrb_cql.c_str());
2441         b->search(q, &hits, &error, &addinfo, &fl, odr);
2442         ZOOM_query_destroy(q);
2443     }
2444     else
2445     {
2446         ZOOM_query_prefix(q, pqf_wrbuf.c_str());
2447         package.log("zoom", YLOG_LOG, "search PQF: %s", pqf_wrbuf.c_str());
2448         b->search(q, &hits, &error, &addinfo, &fl, odr);
2449         ZOOM_query_destroy(q);
2450     }
2451
2452     if (error)
2453     {
2454         if (retry(package, odr, b, error, &addinfo, proxy_step,
2455                   same_retries, proxy_retries))
2456             goto next_proxy;
2457     }
2458
2459     const char *element_set_name = 0;
2460     Odr_int number_to_present = 0;
2461     if (!error)
2462         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
2463
2464     Odr_int number_of_records_returned = 0;
2465     Z_Records *records = get_records(
2466         package,
2467         0, number_to_present, &error, &addinfo,
2468         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
2469         element_set_name);
2470     if (error)
2471         log_diagnostic(package, error, addinfo);
2472     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2473     if (records)
2474     {
2475         apdu_res->u.searchResponse->records = records;
2476         apdu_res->u.searchResponse->numberOfRecordsReturned =
2477             odr_intdup(odr, number_of_records_returned);
2478     }
2479     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
2480     if (fl)
2481         yaz_oi_set_facetlist(&apdu_res->u.searchResponse->additionalSearchInfo,
2482                              odr, fl);
2483     package.response() = apdu_res;
2484 }
2485
2486 void yf::Zoom::Frontend::handle_present(mp::Package &package)
2487 {
2488     Z_GDU *gdu = package.request().get();
2489     Z_APDU *apdu_req = gdu->u.z3950;
2490     Z_APDU *apdu_res = 0;
2491     Z_PresentRequest *pr = apdu_req->u.presentRequest;
2492
2493     mp::odr odr;
2494     if (!m_backend)
2495     {
2496         package.response() = odr.create_presentResponse(
2497             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
2498         return;
2499     }
2500     const char *element_set_name = 0;
2501     Z_RecordComposition *comp = pr->recordComposition;
2502     if (comp && comp->which != Z_RecordComp_simple)
2503     {
2504         package.response() = odr.create_presentResponse(
2505             apdu_req,
2506             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
2507         return;
2508     }
2509     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
2510         element_set_name = comp->u.simple->u.generic;
2511     Odr_int number_of_records_returned = 0;
2512     int error = 0;
2513     char *addinfo = 0;
2514
2515     if (m_backend->enable_explain)
2516     {
2517         Z_Records *records =
2518             get_explain_records(
2519                 package,
2520                 *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2521                 &error, &addinfo, &number_of_records_returned, odr, m_backend,
2522                 pr->preferredRecordSyntax, element_set_name);
2523
2524         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2525         if (records)
2526         {
2527             apdu_res->u.presentResponse->records = records;
2528             apdu_res->u.presentResponse->numberOfRecordsReturned =
2529                 odr_intdup(odr, number_of_records_returned);
2530         }
2531         package.response() = apdu_res;
2532     }
2533     else
2534     {
2535         Z_Records *records =
2536             get_records(package,
2537                         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2538                         &error, &addinfo, &number_of_records_returned, odr, m_backend,
2539                         pr->preferredRecordSyntax, element_set_name);
2540
2541         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2542         if (records)
2543         {
2544             apdu_res->u.presentResponse->records = records;
2545             apdu_res->u.presentResponse->numberOfRecordsReturned =
2546                 odr_intdup(odr, number_of_records_returned);
2547         }
2548         package.response() = apdu_res;
2549     }
2550 }
2551
2552 void yf::Zoom::Frontend::handle_package(mp::Package &package)
2553 {
2554     Z_GDU *gdu = package.request().get();
2555     if (!gdu)
2556         ;
2557     else if (gdu->which == Z_GDU_Z3950)
2558     {
2559         Z_APDU *apdu_req = gdu->u.z3950;
2560
2561         if (m_backend)
2562             wrbuf_rewind(m_backend->m_apdu_wrbuf);
2563         if (apdu_req->which == Z_APDU_initRequest)
2564         {
2565             mp::odr odr;
2566             package.response() = odr.create_close(
2567                 apdu_req,
2568                 Z_Close_protocolError,
2569                 "double init");
2570         }
2571         else if (apdu_req->which == Z_APDU_searchRequest)
2572         {
2573             handle_search(package);
2574         }
2575         else if (apdu_req->which == Z_APDU_presentRequest)
2576         {
2577             handle_present(package);
2578         }
2579         else
2580         {
2581             mp::odr odr;
2582             package.response() = odr.create_close(
2583                 apdu_req,
2584                 Z_Close_protocolError,
2585                 "zoom filter cannot handle this APDU");
2586             package.session().close();
2587         }
2588         if (m_backend)
2589         {
2590             WRBUF w = m_backend->m_apdu_wrbuf;
2591             package.log_write(wrbuf_buf(w), wrbuf_len(w));
2592         }
2593     }
2594     else
2595     {
2596         package.session().close();
2597     }
2598 }
2599
2600 std::string escape_cql_term(std::string inp)
2601 {
2602     std::string res;
2603     size_t l = inp.length();
2604     size_t i;
2605     for (i = 0; i < l; i++)
2606     {
2607         if (strchr("*?^\"", inp[i]))
2608             res += "\\";
2609         res += inp[i];
2610     }
2611     return res;
2612 }
2613
2614 void yf::Zoom::Frontend::auth(mp::Package &package, Z_InitRequest *req,
2615                               int *error, char **addinfo, ODR odr)
2616 {
2617     if (m_p->torus_auth_url.length() == 0)
2618         return;
2619
2620     std::string user;
2621     std::string password;
2622     if (req->idAuthentication)
2623     {
2624         Z_IdAuthentication *auth = req->idAuthentication;
2625         switch (auth->which)
2626         {
2627         case Z_IdAuthentication_open:
2628             if (auth->u.open)
2629             {
2630                 const char *cp = strchr(auth->u.open, '/');
2631                 if (cp)
2632                 {
2633                     user.assign(auth->u.open, cp - auth->u.open);
2634                     password.assign(cp + 1);
2635                 }
2636             }
2637             break;
2638         case Z_IdAuthentication_idPass:
2639             if (auth->u.idPass->userId)
2640                 user.assign(auth->u.idPass->userId);
2641             if (auth->u.idPass->password)
2642                 password.assign(auth->u.idPass->password);
2643             break;
2644         }
2645     }
2646
2647     Z_OtherInformation **oi = &req->otherInfo;
2648     const char *ip_cstr =
2649         yaz_oi_get_string_oid(oi, yaz_oid_userinfo_client_ip, 1, 0);
2650     std::string ip;
2651     if (ip_cstr)
2652         ip = ip_cstr;
2653     else
2654         ip = package.origin().get_address();
2655
2656     yaz_log(YLOG_LOG, "IP=%s", ip.c_str());
2657
2658     {
2659         NMEM nmem = nmem_create();
2660         char **darray;
2661         int i, num;
2662         nmem_strsplit_blank(nmem, m_p->torus_allow_ip.c_str(), &darray, &num);
2663         for (i = 0; i < num; i++)
2664         {
2665             yaz_log(YLOG_LOG, "check against %s+%s", darray[i], ip.c_str());
2666             if (yaz_match_glob(darray[i], ip.c_str()))
2667                 break;
2668         }
2669         nmem_destroy(nmem);
2670         if (i < num)
2671             return;  /* allow this IP */
2672     }
2673     std::string torus_query;
2674     int failure_code;
2675
2676     if (user.length() && password.length())
2677     {
2678         torus_query = "userName==\"" + escape_cql_term(user) +
2679             "\" and password==\"" + escape_cql_term(password) + "\"";
2680         failure_code = YAZ_BIB1_INIT_AC_BAD_USERID_AND_OR_PASSWORD;
2681     }
2682     else
2683     {
2684         torus_query = "ipRanges encloses/net.ipaddress \"";
2685         torus_query += escape_cql_term(std::string(ip));
2686         torus_query += "\"";
2687
2688         if (m_p->torus_auth_hostname.length())
2689         {
2690             torus_query += " AND hostName == \"";
2691             torus_query += escape_cql_term(m_p->torus_auth_hostname);
2692             torus_query += "\"";
2693         }
2694         failure_code = YAZ_BIB1_INIT_AC_BLOCKED_NETWORK_ADDRESS;
2695     }
2696
2697     std::string dummy_db;
2698     std::string dummy_realm;
2699     std::string torus_addinfo;
2700     xmlDoc *doc = mp::get_searchable(package, m_p->torus_auth_url, dummy_db,
2701                                      torus_query, dummy_realm, m_p->proxy,
2702                                      torus_addinfo);
2703     if (!doc)
2704     {
2705         // something fundamental broken in lookup.
2706         *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
2707         if (torus_addinfo.length())
2708             *addinfo = odr_strdup(odr, torus_addinfo.c_str());
2709         return;
2710     }
2711     const xmlNode *ptr = xmlDocGetRootElement(doc);
2712     if (ptr && ptr->type == XML_ELEMENT_NODE)
2713     {
2714         if (strcmp((const char *) ptr->name, "records") == 0)
2715         {
2716             ptr = ptr->children;
2717             while (ptr && ptr->type != XML_ELEMENT_NODE)
2718                 ptr = ptr->next;
2719         }
2720         if (ptr && strcmp((const char *) ptr->name, "record") == 0)
2721         {
2722             ptr = ptr->children;
2723             while (ptr && ptr->type != XML_ELEMENT_NODE)
2724                 ptr = ptr->next;
2725         }
2726         if (ptr && strcmp((const char *) ptr->name, "layer") == 0)
2727         {
2728             ptr = ptr->children;
2729             while (ptr && ptr->type != XML_ELEMENT_NODE)
2730                 ptr = ptr->next;
2731         }
2732         while (ptr)
2733         {
2734             if (ptr && ptr->type == XML_ELEMENT_NODE &&
2735                 !strcmp((const char *) ptr->name, "identityId"))
2736                 break;
2737             ptr = ptr->next;
2738         }
2739     }
2740     if (!ptr)
2741     {
2742         *error = failure_code;
2743         return;
2744     }
2745     session_realm = mp::xml::get_text(ptr);
2746 }
2747
2748 void yf::Zoom::Impl::process(mp::Package &package)
2749 {
2750     FrontendPtr f = get_frontend(package);
2751     Z_GDU *gdu = package.request().get();
2752
2753     if (f->m_is_virtual)
2754     {
2755         f->handle_package(package);
2756     }
2757     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
2758              Z_APDU_initRequest)
2759     {
2760         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
2761         f->m_init_gdu = gdu;
2762
2763         mp::odr odr;
2764         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
2765         Z_InitResponse *resp = apdu->u.initResponse;
2766
2767         int i;
2768         static const int masks[] = {
2769             Z_Options_search,
2770             Z_Options_present,
2771             -1
2772         };
2773         for (i = 0; masks[i] != -1; i++)
2774             if (ODR_MASK_GET(req->options, masks[i]))
2775                 ODR_MASK_SET(resp->options, masks[i]);
2776
2777         static const int versions[] = {
2778             Z_ProtocolVersion_1,
2779             Z_ProtocolVersion_2,
2780             Z_ProtocolVersion_3,
2781             -1
2782         };
2783         for (i = 0; versions[i] != -1; i++)
2784             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
2785                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
2786             else
2787                 break;
2788
2789         *resp->preferredMessageSize = *req->preferredMessageSize;
2790         *resp->maximumRecordSize = *req->maximumRecordSize;
2791
2792         int error = 0;
2793         char *addinfo = 0;
2794         f->auth(package, req, &error, &addinfo, odr);
2795         if (error)
2796         {
2797             resp->userInformationField =
2798                 zget_init_diagnostics(odr, error, addinfo);
2799             *resp->result = 0;
2800             package.session().close();
2801         }
2802         else
2803             f->m_is_virtual = true;
2804         package.response() = apdu;
2805     }
2806     else
2807         package.move();
2808
2809     release_frontend(package);
2810 }
2811
2812
2813 static mp::filter::Base* filter_creator()
2814 {
2815     return new mp::filter::Zoom;
2816 }
2817
2818 extern "C" {
2819     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
2820         0,
2821         "zoom",
2822         filter_creator
2823     };
2824 }
2825
2826
2827 /*
2828  * Local variables:
2829  * c-basic-offset: 4
2830  * c-file-style: "Stroustrup"
2831  * indent-tabs-mode: nil
2832  * End:
2833  * vim: shiftwidth=4 tabstop=8 expandtab
2834  */
2835