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