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