zoom: use thread-safe RPN to CQL/Solr conversion MP-497
[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_query = "udb==" + torus_db;
1261         xmlDoc *doc = mp::get_searchable(package,torus_url, torus_db,
1262                                          torus_query,
1263                                          realm, m_p->proxy);
1264         if (!doc)
1265         {
1266             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1267             *addinfo = odr_strdup(odr, "Torus server unavailable or "
1268                                   "incorrectly configured");
1269             BackendPtr b;
1270             return b;
1271         }
1272         const xmlNode *ptr = xmlDocGetRootElement(doc);
1273         if (ptr && ptr->type == XML_ELEMENT_NODE)
1274         {
1275             if (!strcmp((const char *) ptr->name, "record"))
1276             {
1277                 sptr = m_p->parse_torus_record(ptr);
1278             }
1279             else if (!strcmp((const char *) ptr->name, "records"))
1280             {
1281                 for (ptr = ptr->children; ptr; ptr = ptr->next)
1282                 {
1283                     if (ptr->type == XML_ELEMENT_NODE
1284                         && !strcmp((const char *) ptr->name, "record"))
1285                     {
1286                         if (sptr)
1287                         {
1288                             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1289                             *addinfo = (char*)
1290                                 odr_malloc(odr, 40 + torus_db.length());
1291                             sprintf(*addinfo, "multiple records for udb=%s",
1292                                     database.c_str());
1293                             xmlFreeDoc(doc);
1294                             BackendPtr b;
1295                             return b;
1296                         }
1297                         sptr = m_p->parse_torus_record(ptr);
1298                     }
1299                 }
1300             }
1301             else
1302             {
1303                 *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1304                 *addinfo = (char*) odr_malloc(
1305                     odr, 40 + strlen((const char *) ptr->name));
1306                 sprintf(*addinfo, "bad root element for torus: %s", ptr->name);
1307                 xmlFreeDoc(doc);
1308                 BackendPtr b;
1309                 return b;
1310             }
1311         }
1312         xmlFreeDoc(doc);
1313     }
1314
1315     if (!sptr)
1316     {
1317         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1318         *addinfo = odr_strdup(odr, torus_db.c_str());
1319         BackendPtr b;
1320         return b;
1321     }
1322
1323     xsltStylesheetPtr xsp = 0;
1324     if (sptr->transform_xsl_content.length())
1325     {
1326         xmlDoc *xsp_doc = xmlParseMemory(sptr->transform_xsl_content.c_str(),
1327                                          sptr->transform_xsl_content.length());
1328         if (!xsp_doc)
1329         {
1330             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1331             *addinfo = odr_strdup(odr, "zoom: xmlParseMemory failed "
1332                                   "for literalTransform XSL");
1333             BackendPtr b;
1334             return b;
1335         }
1336         xsp = xsltParseStylesheetDoc(xsp_doc);
1337         if (!xsp)
1338         {
1339             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
1340             *addinfo =
1341                 odr_strdup(odr,"zoom: xsltParseStylesheetDoc failed "
1342                            "for literalTransform XSL");
1343             BackendPtr b;
1344             xmlFreeDoc(xsp_doc);
1345             return b;
1346         }
1347     }
1348     else if (sptr->transform_xsl_fname.length())
1349     {
1350         const char *path = 0;
1351
1352         if (m_p->xsldir.length())
1353             path = m_p->xsldir.c_str();
1354         else
1355             path = m_p->file_path.c_str();
1356         std::string fname;
1357
1358         char fullpath[1024];
1359         char *cp = yaz_filepath_resolve(sptr->transform_xsl_fname.c_str(),
1360                                         path, 0, fullpath);
1361         if (cp)
1362             fname.assign(cp);
1363         else
1364         {
1365             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1366             *addinfo = (char *)
1367                 odr_malloc(odr, 40 + sptr->transform_xsl_fname.length());
1368             sprintf(*addinfo, "zoom: could not open file %s",
1369                     sptr->transform_xsl_fname.c_str());
1370             BackendPtr b;
1371             return b;
1372         }
1373         xmlDoc *xsp_doc = xmlParseFile(fname.c_str());
1374         if (!xsp_doc)
1375         {
1376             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1377             *addinfo = (char *) odr_malloc(odr, 50 + fname.length());
1378             sprintf(*addinfo, "zoom: xmlParseFile failed for file %s",
1379                     fname.c_str());
1380             BackendPtr b;
1381             return b;
1382         }
1383         xsp = xsltParseStylesheetDoc(xsp_doc);
1384         if (!xsp)
1385         {
1386             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1387             *addinfo = (char *) odr_malloc(odr, 50 + fname.length());
1388             sprintf(*addinfo, "zoom: xsltParseStylesheetDoc failed "
1389                     "for file %s", fname.c_str());
1390             BackendPtr b;
1391             xmlFreeDoc(xsp_doc);
1392             return b;
1393         }
1394     }
1395
1396     cql_transform_t cqlt = 0;
1397     if (sptr->rpn2cql_fname.length())
1398     {
1399         char fullpath[1024];
1400         char *cp = yaz_filepath_resolve(sptr->rpn2cql_fname.c_str(),
1401                                         m_p->file_path.c_str(), 0, fullpath);
1402         if (cp)
1403             cqlt = cql_transform_open_fname(fullpath);
1404     }
1405     else
1406         cqlt = cql_transform_create();
1407
1408     if (!cqlt)
1409     {
1410         *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1411         *addinfo = odr_strdup(odr, "zoom: missing/invalid cql2rpn file");
1412         BackendPtr b;
1413         xsltFreeStylesheet(xsp);
1414         return b;
1415     }
1416
1417     m_backend.reset();
1418
1419     BackendPtr b(new Backend);
1420
1421     b->cqlt = cqlt;
1422     b->sptr = sptr;
1423     b->xsp = xsp;
1424     b->m_frontend_database = database;
1425     b->enable_cproxy = param_nocproxy ? false : true;
1426
1427     if (sptr->query_encoding.length())
1428         b->set_option("rpnCharset", sptr->query_encoding);
1429
1430     std::string extraArgs = sptr->extraArgs;
1431
1432     b->set_option("timeout", m_p->zoom_timeout.c_str());
1433
1434     if (m_p->apdu_log)
1435         b->set_option("apdulog", "1");
1436
1437     if (sptr->piggyback && sptr->sru.length())
1438         b->set_option("count", "1"); /* some SRU servers INSIST on getting
1439                                         maximumRecords > 0 */
1440     b->set_option("piggyback", sptr->piggyback ? "1" : "0");
1441
1442     if (authentication.length() == 0)
1443         authentication = sptr->authentication;
1444
1445     if (proxy.length() == 0)
1446         proxy = sptr->cfProxy;
1447     b->m_proxy = proxy;
1448
1449     if (sptr->cfAuth.length())
1450     {
1451         // A CF target
1452         b->set_option("user", sptr->cfAuth);
1453         if (authentication.length())
1454         {
1455             size_t found = authentication.find('/');
1456             if (found != std::string::npos)
1457             {
1458                 out_names[no_out_args] = "user";
1459                 out_values[no_out_args++] =
1460                     odr_strdup(odr, authentication.substr(0, found).c_str());
1461
1462                 out_names[no_out_args] = "password";
1463                 out_values[no_out_args++] =
1464                     odr_strdup(odr, authentication.substr(found+1).c_str());
1465             }
1466             else
1467             {
1468                 out_names[no_out_args] = "user";
1469                 out_values[no_out_args++] =
1470                     odr_strdup(odr, authentication.c_str());
1471             }
1472         }
1473         if (proxy.length())
1474         {
1475             out_names[no_out_args] = "proxy";
1476             out_values[no_out_args++] = odr_strdup(odr, proxy.c_str());
1477         }
1478         if (sptr->cfSubDB.length())
1479         {
1480             out_names[no_out_args] = "subdatabase";
1481             out_values[no_out_args++] = odr_strdup(odr, sptr->cfSubDB.c_str());
1482         }
1483         if (!param_nocproxy && b->sptr->contentConnector.length())
1484             param_nocproxy = "1";
1485
1486         if (param_nocproxy)
1487         {
1488             out_names[no_out_args] = "nocproxy";
1489             out_values[no_out_args++] = odr_strdup(odr, param_nocproxy);
1490         }
1491     }
1492     else
1493     {
1494         const char *auth = authentication.c_str();
1495         const char *cp1 = strchr(auth, ' ');
1496         if (!cp1 && sptr->sru.length())
1497             cp1 =  strchr(auth, '/');
1498         if (!cp1)
1499         {
1500             /* Z39.50 user/password style, or no password for SRU */
1501             b->set_option("user", auth);
1502         }
1503         else
1504         {
1505             /* now consider group as well */
1506             const char *cp2 = strchr(cp1 + 1, ' ');
1507
1508             b->set_option("user", auth, cp1 - auth);
1509             if (!cp2)
1510                 b->set_option("password", cp1 + 1);
1511             else
1512             {
1513                 b->set_option("group", cp1 + 1, cp2 - cp1 - 1);
1514                 b->set_option("password", cp2 + 1);
1515             }
1516         }
1517         if (sptr->authenticationMode.length())
1518             b->set_option("authenticationMode", sptr->authenticationMode);
1519         if (proxy.length())
1520             b->set_option("proxy", proxy);
1521     }
1522     if (extraArgs.length())
1523         b->set_option("extraArgs", extraArgs);
1524
1525     std::string url(sptr->target);
1526     if (sptr->sru.length())
1527     {
1528         b->set_option("sru", sptr->sru);
1529         if (url.find("://") == std::string::npos)
1530             url = "http://" + url;
1531         if (sptr->sru_version.length())
1532             b->set_option("sru_version", sptr->sru_version);
1533     }
1534     if (no_out_args)
1535     {
1536         char *x_args = 0;
1537         out_names[no_out_args] = 0; // terminate list
1538
1539         yaz_array_to_uri(&x_args, odr, (char **) out_names,
1540                          (char **) out_values);
1541         url += "," + std::string(x_args);
1542     }
1543     package.log("zoom", YLOG_LOG, "url: %s", url.c_str());
1544     b->connect(url, error, addinfo, odr);
1545     if (*error == 0 && b->enable_cproxy)
1546         create_content_session(package, b, error, addinfo, odr,
1547                                content_authentication.length() ?
1548                                content_authentication : authentication,
1549                                content_proxy.length() ? content_proxy : proxy,
1550                                realm);
1551     if (*error == 0)
1552         m_backend = b;
1553     return b;
1554 }
1555
1556 void yf::Zoom::Frontend::prepare_elements(BackendPtr b,
1557                                           Odr_oid *preferredRecordSyntax,
1558                                           const char *element_set_name,
1559                                           bool &enable_pz2_retrieval,
1560                                           bool &enable_pz2_transform,
1561                                           bool &enable_record_transform,
1562                                           bool &assume_marc8_charset)
1563 {
1564     char oid_name_str[OID_STR_MAX];
1565     const char *syntax_name = 0;
1566
1567     if (preferredRecordSyntax &&
1568         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml))
1569     {
1570         if (element_set_name &&
1571             !strcmp(element_set_name, m_p->element_transform.c_str()))
1572         {
1573             enable_pz2_retrieval = true;
1574             enable_pz2_transform = true;
1575         }
1576         else if (element_set_name &&
1577                  !strcmp(element_set_name, m_p->element_raw.c_str()))
1578         {
1579             enable_pz2_retrieval = true;
1580         }
1581         else if (m_p->record_xsp)
1582         {
1583             enable_pz2_retrieval = true;
1584             enable_pz2_transform = true;
1585             enable_record_transform = true;
1586         }
1587     }
1588
1589     if (enable_pz2_retrieval)
1590     {
1591         std::string configured_request_syntax = b->sptr->request_syntax;
1592         if (configured_request_syntax.length())
1593         {
1594             syntax_name = configured_request_syntax.c_str();
1595             const Odr_oid *syntax_oid =
1596                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
1597             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
1598                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
1599                 assume_marc8_charset = true;
1600         }
1601     }
1602     else if (preferredRecordSyntax)
1603         syntax_name =
1604             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
1605
1606     if (b->sptr->sru.length())
1607         syntax_name = "XML";
1608
1609     b->set_option("preferredRecordSyntax", syntax_name);
1610
1611     if (enable_pz2_retrieval)
1612     {
1613         if (element_set_name && !strcmp(element_set_name,
1614                                         m_p->element_passthru.c_str()))
1615             ;
1616         else
1617         {
1618             element_set_name = 0;
1619             if (b->sptr->element_set.length())
1620                 element_set_name = b->sptr->element_set.c_str();
1621         }
1622     }
1623
1624     b->set_option("elementSetName", element_set_name);
1625     if (b->sptr->sru.length() && element_set_name)
1626         b->set_option("schema", element_set_name);
1627 }
1628
1629 Z_Records *yf::Zoom::Frontend::get_explain_records(
1630     mp::Package &package,
1631     Odr_int start,
1632     Odr_int number_to_present,
1633     int *error,
1634     char **addinfo,
1635     Odr_int *number_of_records_returned,
1636     ODR odr,
1637     BackendPtr b,
1638     Odr_oid *preferredRecordSyntax,
1639     const char *element_set_name)
1640 {
1641     Odr_int i;
1642     Z_Records *records = 0;
1643
1644     if (!b->explain_doc)
1645     {
1646         return records;
1647     }
1648     if (number_to_present > 10000)
1649         number_to_present = 10000;
1650
1651     xmlNode *ptr = xmlDocGetRootElement(b->explain_doc);
1652
1653     Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1654         odr_malloc(odr, sizeof(*npl));
1655     npl->records = (Z_NamePlusRecord **)
1656         odr_malloc(odr, number_to_present * sizeof(*npl->records));
1657
1658     for (i = 0; i < number_to_present; i++)
1659     {
1660         int num = 0;
1661         xmlNode *res = xml_node_search(ptr, &num, start + i + 1);
1662         if (!res)
1663             break;
1664         xmlBufferPtr xml_buf = xmlBufferCreate();
1665         xmlNode *tmp_node = xmlCopyNode(res->children, 1);
1666         xmlNodeDump(xml_buf, tmp_node->doc, tmp_node, 0, 0);
1667
1668         Z_NamePlusRecord *npr =
1669             (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1670         npr->databaseName = odr_strdup(odr, b->m_frontend_database.c_str());
1671         npr->which = Z_NamePlusRecord_databaseRecord;
1672         npr->u.databaseRecord =
1673             z_ext_record_xml(odr,
1674                              (const char *) xml_buf->content, xml_buf->use);
1675         npl->records[i] = npr;
1676         xmlFreeNode(tmp_node);
1677         xmlBufferFree(xml_buf);
1678     }
1679     records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1680     records->which = Z_Records_DBOSD;
1681     records->u.databaseOrSurDiagnostics = npl;
1682
1683     npl->num_records = i;
1684     *number_of_records_returned = i;
1685     return records;
1686 }
1687
1688
1689 Z_Records *yf::Zoom::Frontend::get_records(mp::Package &package,
1690                                            Odr_int start,
1691                                            Odr_int number_to_present,
1692                                            int *error,
1693                                            char **addinfo,
1694                                            Odr_int *number_of_records_returned,
1695                                            ODR odr,
1696                                            BackendPtr b,
1697                                            Odr_oid *preferredRecordSyntax,
1698                                            const char *element_set_name)
1699 {
1700     *number_of_records_returned = 0;
1701     Z_Records *records = 0;
1702     bool enable_pz2_retrieval = false; // whether target profile is used
1703     bool enable_pz2_transform = false; // whether XSLT is used as well
1704     bool assume_marc8_charset = false;
1705     bool enable_record_transform = false;
1706
1707     prepare_elements(b, preferredRecordSyntax,
1708                      element_set_name,
1709                      enable_pz2_retrieval,
1710                      enable_pz2_transform,
1711                      enable_record_transform,
1712                      assume_marc8_charset);
1713
1714     package.log("zoom", YLOG_LOG, "pz2_retrieval: %s . pz2_transform: %s",
1715                 enable_pz2_retrieval ? "yes" : "no",
1716                 enable_pz2_transform ? "yes" : "no");
1717
1718     if (start < 0 || number_to_present <=0)
1719         return records;
1720
1721     if (number_to_present > 10000)
1722         number_to_present = 10000;
1723
1724     ZOOM_record *recs = (ZOOM_record *)
1725         odr_malloc(odr, (size_t) number_to_present * sizeof(*recs));
1726
1727     b->present(start, number_to_present, recs, error, addinfo, odr);
1728
1729     int i = 0;
1730     if (!*error)
1731     {
1732         for (i = 0; i < number_to_present; i++)
1733             if (!recs[i])
1734                 break;
1735     }
1736     if (i > 0)
1737     {  // only return records if no error and at least one record
1738
1739         const char *xsl_parms[3];
1740         mp::wrbuf cproxy_host;
1741
1742         if (b->enable_cproxy && b->cproxy_host.length())
1743         {
1744             wrbuf_puts(cproxy_host, "\"");
1745             wrbuf_puts(cproxy_host, b->cproxy_host.c_str());
1746             wrbuf_puts(cproxy_host, "/\"");
1747
1748             xsl_parms[0] = "cproxyhost";
1749             xsl_parms[1] = wrbuf_cstr(cproxy_host);
1750             xsl_parms[2] = 0;
1751         }
1752         else
1753         {
1754             xsl_parms[0] = 0;
1755         }
1756
1757         char *odr_database = odr_strdup(odr,
1758                                         b->m_frontend_database.c_str());
1759         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1760             odr_malloc(odr, sizeof(*npl));
1761         *number_of_records_returned = i;
1762         npl->num_records = i;
1763         npl->records = (Z_NamePlusRecord **)
1764             odr_malloc(odr, i * sizeof(*npl->records));
1765         for (i = 0; i < number_to_present; i++)
1766         {
1767             Z_NamePlusRecord *npr = 0;
1768             const char *addinfo;
1769
1770             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1771                                               &addinfo, 0 /* diagset */);
1772
1773             if (sur_error)
1774             {
1775                 log_diagnostic(package, sur_error, addinfo);
1776                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1777                                             addinfo);
1778             }
1779             else if (enable_pz2_retrieval)
1780             {
1781                 char rec_type_str[100];
1782                 const char *record_encoding = 0;
1783
1784                 if (b->sptr->record_encoding.length())
1785                     record_encoding = b->sptr->record_encoding.c_str();
1786                 else if (assume_marc8_charset)
1787                     record_encoding = "marc8";
1788
1789                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1790                 if (record_encoding)
1791                 {
1792                     strcat(rec_type_str, "; charset=");
1793                     strcat(rec_type_str, record_encoding);
1794                 }
1795
1796                 package.log("zoom", YLOG_LOG, "Getting record of type %s",
1797                             rec_type_str);
1798                 int rec_len;
1799                 xmlChar *xmlrec_buf = 0;
1800                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1801                                                       &rec_len);
1802                 if (!rec_buf && !npr)
1803                 {
1804                     std::string addinfo("ZOOM_record_get failed for type ");
1805
1806                     int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1807                     addinfo += rec_type_str;
1808                     log_diagnostic(package, error, addinfo.c_str());
1809                     npr = zget_surrogateDiagRec(odr, odr_database,
1810                                                 error, addinfo.c_str());
1811                 }
1812                 else
1813                 {
1814                     package.log_write(rec_buf, rec_len);
1815                     package.log_write("\r\n", 2);
1816                 }
1817
1818                 if (rec_buf && b->xsp && enable_pz2_transform)
1819                 {
1820                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1821                     if (!rec_doc)
1822                     {
1823                         const char *addinfo = "xml parse failed for record";
1824                         int error = YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1825                         log_diagnostic(package, error, addinfo);
1826                         npr = zget_surrogateDiagRec(
1827                             odr, odr_database, error, addinfo);
1828                     }
1829                     else
1830                     {
1831                         // first stage XSLT - per target
1832                         xsltStylesheetPtr xsp = b->xsp;
1833                         xmlDoc *rec_res = xsltApplyStylesheet(xsp, rec_doc,
1834                                                               xsl_parms);
1835                         // insert generated-url
1836                         if (rec_res)
1837                         {
1838                             std::string res =
1839                                 mp::xml::url_recipe_handle(rec_res,
1840                                                            b->sptr->urlRecipe);
1841                             if (res.length())
1842                             {
1843                                 xmlNode *ptr = xmlDocGetRootElement(rec_res);
1844                                 while (ptr && ptr->type != XML_ELEMENT_NODE)
1845                                     ptr = ptr->next;
1846                                 xmlNode *c =
1847                                     xmlNewChild(ptr, 0, BAD_CAST "metadata", 0);
1848                                 xmlNewProp(c, BAD_CAST "type", BAD_CAST
1849                                            "generated-url");
1850                                 xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1851                                 xmlAddChild(c, t);
1852                             }
1853                         }
1854                         // second stage XSLT - common
1855                         if (rec_res && m_p->record_xsp &&
1856                             enable_record_transform)
1857                         {
1858                             xmlDoc *tmp_doc = rec_res;
1859
1860                             xsp = m_p->record_xsp;
1861                             rec_res = xsltApplyStylesheet(xsp, tmp_doc,
1862                                                           xsl_parms);
1863                             xmlFreeDoc(tmp_doc);
1864                         }
1865                         // get result out of it
1866                         if (rec_res)
1867                         {
1868                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1869                                                    rec_res, xsp);
1870                             rec_buf = (const char *) xmlrec_buf;
1871                             package.log_write(rec_buf, rec_len);
1872
1873                             xmlFreeDoc(rec_res);
1874                         }
1875                         if (!rec_buf)
1876                         {
1877                             std::string addinfo;
1878                             int error =
1879                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1880
1881                             addinfo = "xslt apply failed for "
1882                                 + b->sptr->transform_xsl_fname;
1883                             log_diagnostic(package, error, addinfo.c_str());
1884                             npr = zget_surrogateDiagRec(
1885                                 odr, odr_database, error, addinfo.c_str());
1886                         }
1887                         xmlFreeDoc(rec_doc);
1888                     }
1889                 }
1890
1891                 if (!npr)
1892                 {
1893                     if (!rec_buf)
1894                         npr = zget_surrogateDiagRec(
1895                             odr, odr_database,
1896                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1897                             rec_type_str);
1898                     else
1899                     {
1900                         npr = (Z_NamePlusRecord *)
1901                             odr_malloc(odr, sizeof(*npr));
1902                         npr->databaseName = odr_database;
1903                         npr->which = Z_NamePlusRecord_databaseRecord;
1904                         npr->u.databaseRecord =
1905                             z_ext_record_xml(odr, rec_buf, rec_len);
1906                     }
1907                 }
1908                 if (xmlrec_buf)
1909                     xmlFree(xmlrec_buf);
1910             }
1911             else
1912             {
1913                 Z_External *ext =
1914                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1915                 if (ext)
1916                 {
1917                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1918                     npr->databaseName = odr_database;
1919                     npr->which = Z_NamePlusRecord_databaseRecord;
1920                     npr->u.databaseRecord = ext;
1921                 }
1922                 else
1923                 {
1924                     npr = zget_surrogateDiagRec(
1925                         odr, odr_database,
1926                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1927                         "ZOOM_record, type ext");
1928                 }
1929             }
1930             npl->records[i] = npr;
1931         }
1932         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1933         records->which = Z_Records_DBOSD;
1934         records->u.databaseOrSurDiagnostics = npl;
1935     }
1936     return records;
1937 }
1938
1939 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1940                                                     ODR odr)
1941 {
1942     struct cql_node *r = 0;
1943     if (!cn)
1944         return 0;
1945     switch (cn->which)
1946     {
1947     case CQL_NODE_ST:
1948         if (cn->u.st.index)
1949         {
1950             std::map<std::string,std::string>::const_iterator it;
1951             it = fieldmap.find(cn->u.st.index);
1952             if (it == fieldmap.end())
1953                 return cn;
1954             if (it->second.length())
1955                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1956             else
1957                 cn->u.st.index = 0;
1958         }
1959         break;
1960     case CQL_NODE_BOOL:
1961         r = convert_cql_fields(cn->u.boolean.left, odr);
1962         if (!r)
1963             r = convert_cql_fields(cn->u.boolean.right, odr);
1964         break;
1965     case CQL_NODE_SORT:
1966         r = convert_cql_fields(cn->u.sort.search, odr);
1967         break;
1968     }
1969     return r;
1970 }
1971
1972 void yf::Zoom::Frontend::log_diagnostic(mp::Package &package,
1973                                         int error, const char *addinfo)
1974 {
1975     const char *err_msg = yaz_diag_bib1_str(error);
1976     if (addinfo)
1977         package.log("zoom", YLOG_WARN, "Diagnostic %d %s: %s",
1978                     error, err_msg, addinfo);
1979     else
1980         package.log("zoom", YLOG_WARN, "Diagnostic %d %s:",
1981                     error, err_msg);
1982 }
1983
1984 yf::Zoom::BackendPtr yf::Zoom::Frontend::explain_search(mp::Package &package,
1985                                                         std::string &database,
1986                                                         int *error,
1987                                                         char **addinfo,
1988                                                         mp::odr &odr,
1989                                                         std::string torus_url,
1990                                                         std::string &torus_db,
1991                                                         std::string &realm)
1992 {
1993     m_backend.reset();
1994
1995     BackendPtr b(new Backend);
1996
1997     b->m_frontend_database = database;
1998     b->enable_explain = true;
1999
2000     Z_GDU *gdu = package.request().get();
2001     Z_APDU *apdu_req = gdu->u.z3950;
2002     Z_SearchRequest *sr = apdu_req->u.searchRequest;
2003     Z_Query *query = sr->query;
2004
2005     if (!m_p->explain_xsp)
2006     {
2007         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
2008         *addinfo =
2009             odr_strdup(odr, "IR-Explain---1 unsupported. "
2010                        "Torus explain_xsl not defined");
2011         return m_backend;
2012     }
2013     else if (query->which == Z_Query_type_104 &&
2014         query->u.type_104->which == Z_External_CQL)
2015     {
2016         std::string torus_query(query->u.type_104->u.cql);
2017         xmlDoc *doc = mp::get_searchable(package, torus_url, "",
2018                                          torus_query,
2019                                          realm, m_p->proxy);
2020         if (m_p->explain_xsp)
2021         {
2022             xmlDoc *rec_res =  xsltApplyStylesheet(m_p->explain_xsp, doc, 0);
2023
2024             xmlFreeDoc(doc);
2025             doc = rec_res;
2026         }
2027         if (!doc)
2028         {
2029             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
2030             *addinfo = odr_strdup(odr, "Torus server unavailable or "
2031                                   "incorrectly configured");
2032         }
2033         else
2034         {
2035             xmlNode *ptr = xmlDocGetRootElement(doc);
2036             int hits = 0;
2037
2038             xml_node_search(ptr, &hits, 0);
2039
2040             Z_APDU *apdu_res = odr.create_searchResponse(apdu_req, 0, 0);
2041             apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
2042             package.response() = apdu_res;
2043             m_backend = b;
2044         }
2045         if (b->explain_doc)
2046             xmlFreeDoc(b->explain_doc);
2047         b->explain_doc = doc;
2048         return m_backend;
2049     }
2050     else
2051     {
2052         *error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
2053         *addinfo = odr_strdup(odr, "IR-Explain---1 only supports CQL");
2054         return m_backend;
2055     }
2056 }
2057
2058 static bool wait_conn(COMSTACK cs, int secs)
2059 {
2060     struct yaz_poll_fd pfd;
2061
2062     yaz_poll_add(pfd.input_mask, yaz_poll_except);
2063     if (cs->io_pending && CS_WANT_WRITE)
2064         yaz_poll_add(pfd.input_mask, yaz_poll_write);
2065     if (cs->io_pending & CS_WANT_READ)
2066         yaz_poll_add(pfd.input_mask, yaz_poll_read);
2067
2068     pfd.fd = cs_fileno(cs);
2069     pfd.client_data = 0;
2070
2071     int ret = yaz_poll(&pfd, 1, secs, 0);
2072     return ret > 0;
2073 }
2074
2075 bool yf::Zoom::Impl::check_proxy(const char *proxy)
2076 {
2077     COMSTACK conn = 0;
2078     const char *uri = "http://localhost/";
2079     void *add;
2080     mp::odr odr;
2081     bool outcome = false;
2082     conn = cs_create_host_proxy(uri, 0, &add, proxy);
2083
2084     if (!conn)
2085         return false;
2086
2087     Z_GDU *gdu = z_get_HTTP_Request_uri(odr, uri, 0, 1);
2088     gdu->u.HTTP_Request->method = odr_strdup(odr, "GET");
2089
2090     if (z_GDU(odr, &gdu, 0, 0))
2091     {
2092         int len;
2093         char *buf = odr_getbuf(odr, &len, 0);
2094
2095         int ret = cs_connect(conn, add);
2096         if (ret > 0 || (ret == 0 && wait_conn(conn, 1)))
2097         {
2098             while (1)
2099             {
2100                 ret = cs_put(conn, buf, len);
2101                 if (ret != 1)
2102                     break;
2103                 if (!wait_conn(conn, proxy_timeout))
2104                     break;
2105             }
2106             if (ret == 0)
2107                 outcome = true;
2108         }
2109     }
2110     cs_close(conn);
2111     return outcome;
2112 }
2113
2114 bool yf::Zoom::Frontend::retry(mp::Package &package,
2115                                mp::odr &odr,
2116                                BackendPtr b,
2117                                int &error, char **addinfo,
2118                                int &proxy_step, int &same_retries,
2119                                int &proxy_retries)
2120 {
2121     if (b && b->m_proxy.length() && !m_p->check_proxy(b->m_proxy.c_str()))
2122     {
2123         log_diagnostic(package, error, *addinfo);
2124         package.log("zoom", YLOG_LOG, "proxy %s fails", b->m_proxy.c_str());
2125         m_backend.reset();
2126         if (proxy_step) // there is a failover
2127         {
2128             proxy_retries++;
2129             package.log("zoom", YLOG_WARN, "search failed: trying next proxy");
2130             return true;
2131         }
2132         error = YAZ_BIB1_PROXY_FAILURE;
2133         *addinfo = odr_strdup(odr, b->m_proxy.c_str());
2134     }
2135     else if (same_retries == 0 && proxy_retries == 0)
2136     {
2137         log_diagnostic(package, error, *addinfo);
2138         same_retries++;
2139         package.log("zoom", YLOG_WARN, "search failed: retry");
2140         m_backend.reset();
2141         proxy_step = 0;
2142         return true;
2143     }
2144     return false;
2145 }
2146
2147 void yf::Zoom::Frontend::handle_search(mp::Package &package)
2148 {
2149     Z_GDU *gdu = package.request().get();
2150     Z_APDU *apdu_req = gdu->u.z3950;
2151     Z_APDU *apdu_res = 0;
2152     mp::odr odr;
2153     Z_SearchRequest *sr = apdu_req->u.searchRequest;
2154     if (sr->num_databaseNames != 1)
2155     {
2156         int error = YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED;
2157         log_diagnostic(package, error, 0);
2158         apdu_res = odr.create_searchResponse(apdu_req, error, 0);
2159         package.response() = apdu_res;
2160         return;
2161     }
2162     int proxy_step = 0;
2163     int same_retries = 0;
2164     int proxy_retries = 0;
2165
2166 next_proxy:
2167
2168     int error = 0;
2169     char *addinfo = 0;
2170     std::string db(sr->databaseNames[0]);
2171
2172     BackendPtr b = get_backend_from_databases(package, db, &error,
2173                                               &addinfo, odr, &proxy_step);
2174     if (error)
2175     {
2176         if (retry(package, odr, b, error, &addinfo, proxy_step,
2177                   same_retries, proxy_retries))
2178             goto next_proxy;
2179     }
2180     if (error)
2181     {
2182         log_diagnostic(package, error, addinfo);
2183         apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2184         package.response() = apdu_res;
2185         return;
2186     }
2187     if (!b || b->enable_explain)
2188         return;
2189
2190     b->set_option("setname", "default");
2191
2192     bool enable_pz2_retrieval = false;
2193     bool enable_pz2_transform = false;
2194     bool enable_record_transform = false;
2195     bool assume_marc8_charset = false;
2196     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
2197                      enable_pz2_retrieval,
2198                      enable_pz2_transform,
2199                      enable_record_transform,
2200                      assume_marc8_charset);
2201
2202     Odr_int hits = 0;
2203     Z_Query *query = sr->query;
2204     mp::wrbuf ccl_wrbuf;
2205     mp::wrbuf pqf_wrbuf;
2206     std::string sortkeys;
2207
2208     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
2209     {
2210         // RPN
2211         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
2212     }
2213     else if (query->which == Z_Query_type_2)
2214     {
2215         // CCL
2216         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
2217                     query->u.type_2->len);
2218     }
2219     else if (query->which == Z_Query_type_104 &&
2220              query->u.type_104->which == Z_External_CQL)
2221     {
2222         // CQL
2223         const char *cql = query->u.type_104->u.cql;
2224         CQL_parser cp = cql_parser_create();
2225         int r = cql_parser_string(cp, cql);
2226         package.log("zoom", YLOG_LOG, "CQL: %s", cql);
2227         if (r)
2228         {
2229             cql_parser_destroy(cp);
2230             error = YAZ_BIB1_MALFORMED_QUERY;
2231             const char *addinfo = "CQL syntax error";
2232             log_diagnostic(package, error, addinfo);
2233             apdu_res =
2234                 odr.create_searchResponse(apdu_req, error, addinfo);
2235             package.response() = apdu_res;
2236             return;
2237         }
2238         struct cql_node *cn = cql_parser_result(cp);
2239         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
2240         if (cn_error)
2241         {
2242             // hopefully we are getting a ptr to a index+relation+term node
2243             error = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
2244             addinfo = 0;
2245             if (cn_error->which == CQL_NODE_ST)
2246                 addinfo = cn_error->u.st.index;
2247
2248             log_diagnostic(package, error, addinfo);
2249             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2250             package.response() = apdu_res;
2251             cql_parser_destroy(cp);
2252             return;
2253         }
2254         r = cql_to_ccl(cn, wrbuf_vp_puts,  ccl_wrbuf);
2255         if (r)
2256         {
2257             error = YAZ_BIB1_MALFORMED_QUERY;
2258             const char *addinfo = "CQL to CCL conversion error";
2259
2260             log_diagnostic(package, error, addinfo);
2261             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2262             package.response() = apdu_res;
2263             cql_parser_destroy(cp);
2264             return;
2265         }
2266
2267         mp::wrbuf sru_sortkeys_wrbuf;
2268         if (cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf))
2269         {
2270             error = YAZ_BIB1_ILLEGAL_SORT_RELATION;
2271             const char *addinfo = "CQL to CCL sortby conversion";
2272
2273             log_diagnostic(package, error, addinfo);
2274             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2275             package.response() = apdu_res;
2276             cql_parser_destroy(cp);
2277             return;
2278         }
2279         mp::wrbuf sort_spec_wrbuf;
2280         yaz_srw_sortkeys_to_sort_spec(wrbuf_cstr(sru_sortkeys_wrbuf),
2281                                       sort_spec_wrbuf);
2282         yaz_tok_cfg_t tc = yaz_tok_cfg_create();
2283         yaz_tok_parse_t tp =
2284             yaz_tok_parse_buf(tc, wrbuf_cstr(sort_spec_wrbuf));
2285         yaz_tok_cfg_destroy(tc);
2286
2287         /* go through sortspec and map fields */
2288         int token = yaz_tok_move(tp);
2289         while (token != YAZ_TOK_EOF)
2290         {
2291             if (token == YAZ_TOK_STRING)
2292             {
2293                 const char *field = yaz_tok_parse_string(tp);
2294                 std::map<std::string,std::string>::iterator it;
2295                 it = b->sptr->sortmap.find(field);
2296                 if (it != b->sptr->sortmap.end())
2297                     sortkeys += it->second;
2298                 else
2299                     sortkeys += field;
2300             }
2301             sortkeys += " ";
2302             token = yaz_tok_move(tp);
2303             if (token == YAZ_TOK_STRING)
2304             {
2305                 sortkeys += yaz_tok_parse_string(tp);
2306             }
2307             if (token != YAZ_TOK_EOF)
2308             {
2309                 sortkeys += " ";
2310                 token = yaz_tok_move(tp);
2311             }
2312         }
2313         yaz_tok_parse_destroy(tp);
2314         cql_parser_destroy(cp);
2315     }
2316     else
2317     {
2318         error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
2319         const char *addinfo = 0;
2320         log_diagnostic(package, error, addinfo);
2321         apdu_res =  odr.create_searchResponse(apdu_req, error, addinfo);
2322         package.response() = apdu_res;
2323         return;
2324     }
2325
2326     if (ccl_wrbuf.len())
2327     {
2328         // CCL to PQF
2329         assert(pqf_wrbuf.len() == 0);
2330         int cerror, cpos;
2331         struct ccl_rpn_node *cn;
2332         package.log("zoom", YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
2333         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
2334                           &cerror, &cpos);
2335         if (!cn)
2336         {
2337             char *addinfo = odr_strdup_null(odr, ccl_err_msg(cerror));
2338             error = YAZ_BIB1_MALFORMED_QUERY;
2339
2340             switch (cerror)
2341             {
2342             case CCL_ERR_UNKNOWN_QUAL:
2343             case CCL_ERR_TRUNC_NOT_LEFT:
2344             case CCL_ERR_TRUNC_NOT_RIGHT:
2345             case CCL_ERR_TRUNC_NOT_BOTH:
2346 #ifdef CCL_ERR_TRUNC_NOT_EMBED
2347             case CCL_ERR_TRUNC_NOT_EMBED:
2348 #endif
2349 #ifdef CCL_ERR_TRUNC_NOT_SINGLE
2350             case CCL_ERR_TRUNC_NOT_SINGLE:
2351 #endif
2352                 error = YAZ_BIB1_UNSUPP_SEARCH;
2353                 break;
2354             }
2355             log_diagnostic(package, error, addinfo);
2356             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2357             package.response() = apdu_res;
2358             return;
2359         }
2360         ccl_pquery(pqf_wrbuf, cn);
2361         package.log("zoom", YLOG_LOG, "RPN: %s", wrbuf_cstr(pqf_wrbuf));
2362         ccl_rpn_delete(cn);
2363     }
2364
2365     assert(pqf_wrbuf.len());
2366
2367     ZOOM_query q = ZOOM_query_create();
2368     ZOOM_query_sortby2(q, b->sptr->sortStrategy.c_str(), sortkeys.c_str());
2369
2370     Z_FacetList *fl = 0;
2371
2372     // Facets for request.. And later for reponse
2373     if (!fl)
2374         fl = yaz_oi_get_facetlist(&sr->otherInfo);
2375     if (!fl)
2376         fl = yaz_oi_get_facetlist(&sr->additionalSearchInfo);
2377
2378     if (b->get_option("sru"))
2379     {
2380         Z_RPNQuery *zquery;
2381         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
2382         mp::wrbuf wrb_cql;
2383         mp::wrbuf wrb_addinfo;
2384
2385         if (!strcmp(b->get_option("sru"), "solr"))
2386             error = solr_transform_rpn2solr_stream_r(b->cqlt, wrb_addinfo,
2387                                                      wrbuf_vp_puts, wrb_cql,
2388                                                      zquery);
2389         else
2390             error = cql_transform_rpn2cql_stream_r(b->cqlt, wrb_addinfo,
2391                                                    wrbuf_vp_puts, wrb_cql,
2392                                                    zquery);
2393         if (error)
2394         {
2395             log_diagnostic(package, error, wrb_addinfo.c_str_null());
2396             apdu_res = odr.create_searchResponse(apdu_req, error,
2397                                                  wrb_addinfo.c_str_null());
2398             package.response() = apdu_res;
2399             return;
2400         }
2401         ZOOM_query_cql(q, wrb_cql.c_str());
2402         package.log("zoom", YLOG_LOG, "search CQL: %s", wrb_cql.c_str());
2403         b->search(q, &hits, &error, &addinfo, &fl, odr);
2404         ZOOM_query_destroy(q);
2405     }
2406     else
2407     {
2408         ZOOM_query_prefix(q, pqf_wrbuf.c_str());
2409         package.log("zoom", YLOG_LOG, "search PQF: %s", pqf_wrbuf.c_str());
2410         b->search(q, &hits, &error, &addinfo, &fl, odr);
2411         ZOOM_query_destroy(q);
2412     }
2413
2414     if (error)
2415     {
2416         if (retry(package, odr, b, error, &addinfo, proxy_step,
2417                   same_retries, proxy_retries))
2418             goto next_proxy;
2419     }
2420
2421     const char *element_set_name = 0;
2422     Odr_int number_to_present = 0;
2423     if (!error)
2424         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
2425
2426     Odr_int number_of_records_returned = 0;
2427     Z_Records *records = get_records(
2428         package,
2429         0, number_to_present, &error, &addinfo,
2430         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
2431         element_set_name);
2432     if (error)
2433         log_diagnostic(package, error, addinfo);
2434     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2435     if (records)
2436     {
2437         apdu_res->u.searchResponse->records = records;
2438         apdu_res->u.searchResponse->numberOfRecordsReturned =
2439             odr_intdup(odr, number_of_records_returned);
2440     }
2441     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
2442     if (fl)
2443         yaz_oi_set_facetlist(&apdu_res->u.searchResponse->additionalSearchInfo,
2444                              odr, fl);
2445     package.response() = apdu_res;
2446 }
2447
2448 void yf::Zoom::Frontend::handle_present(mp::Package &package)
2449 {
2450     Z_GDU *gdu = package.request().get();
2451     Z_APDU *apdu_req = gdu->u.z3950;
2452     Z_APDU *apdu_res = 0;
2453     Z_PresentRequest *pr = apdu_req->u.presentRequest;
2454
2455     mp::odr odr;
2456     if (!m_backend)
2457     {
2458         package.response() = odr.create_presentResponse(
2459             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
2460         return;
2461     }
2462     const char *element_set_name = 0;
2463     Z_RecordComposition *comp = pr->recordComposition;
2464     if (comp && comp->which != Z_RecordComp_simple)
2465     {
2466         package.response() = odr.create_presentResponse(
2467             apdu_req,
2468             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
2469         return;
2470     }
2471     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
2472         element_set_name = comp->u.simple->u.generic;
2473     Odr_int number_of_records_returned = 0;
2474     int error = 0;
2475     char *addinfo = 0;
2476
2477     if (m_backend->enable_explain)
2478     {
2479         Z_Records *records =
2480             get_explain_records(
2481                 package,
2482                 *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2483                 &error, &addinfo, &number_of_records_returned, odr, m_backend,
2484                 pr->preferredRecordSyntax, element_set_name);
2485
2486         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2487         if (records)
2488         {
2489             apdu_res->u.presentResponse->records = records;
2490             apdu_res->u.presentResponse->numberOfRecordsReturned =
2491                 odr_intdup(odr, number_of_records_returned);
2492         }
2493         package.response() = apdu_res;
2494     }
2495     else
2496     {
2497         Z_Records *records =
2498             get_records(package,
2499                         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2500                         &error, &addinfo, &number_of_records_returned, odr, m_backend,
2501                         pr->preferredRecordSyntax, element_set_name);
2502
2503         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2504         if (records)
2505         {
2506             apdu_res->u.presentResponse->records = records;
2507             apdu_res->u.presentResponse->numberOfRecordsReturned =
2508                 odr_intdup(odr, number_of_records_returned);
2509         }
2510         package.response() = apdu_res;
2511     }
2512 }
2513
2514 void yf::Zoom::Frontend::handle_package(mp::Package &package)
2515 {
2516     Z_GDU *gdu = package.request().get();
2517     if (!gdu)
2518         ;
2519     else if (gdu->which == Z_GDU_Z3950)
2520     {
2521         Z_APDU *apdu_req = gdu->u.z3950;
2522
2523         if (m_backend)
2524             wrbuf_rewind(m_backend->m_apdu_wrbuf);
2525         if (apdu_req->which == Z_APDU_initRequest)
2526         {
2527             mp::odr odr;
2528             package.response() = odr.create_close(
2529                 apdu_req,
2530                 Z_Close_protocolError,
2531                 "double init");
2532         }
2533         else if (apdu_req->which == Z_APDU_searchRequest)
2534         {
2535             handle_search(package);
2536         }
2537         else if (apdu_req->which == Z_APDU_presentRequest)
2538         {
2539             handle_present(package);
2540         }
2541         else
2542         {
2543             mp::odr odr;
2544             package.response() = odr.create_close(
2545                 apdu_req,
2546                 Z_Close_protocolError,
2547                 "zoom filter cannot handle this APDU");
2548             package.session().close();
2549         }
2550         if (m_backend)
2551         {
2552             WRBUF w = m_backend->m_apdu_wrbuf;
2553             package.log_write(wrbuf_buf(w), wrbuf_len(w));
2554         }
2555     }
2556     else
2557     {
2558         package.session().close();
2559     }
2560 }
2561
2562 std::string escape_cql_term(std::string inp)
2563 {
2564     std::string res;
2565     size_t l = inp.length();
2566     size_t i;
2567     for (i = 0; i < l; i++)
2568     {
2569         if (strchr("*?^\"", inp[i]))
2570             res += "\\";
2571         res += inp[i];
2572     }
2573     return res;
2574 }
2575
2576 void yf::Zoom::Frontend::auth(mp::Package &package, Z_InitRequest *req,
2577                               int *error, char **addinfo, ODR odr)
2578 {
2579     if (m_p->torus_auth_url.length() == 0)
2580         return;
2581
2582     std::string user;
2583     std::string password;
2584     if (req->idAuthentication)
2585     {
2586         Z_IdAuthentication *auth = req->idAuthentication;
2587         switch (auth->which)
2588         {
2589         case Z_IdAuthentication_open:
2590             if (auth->u.open)
2591             {
2592                 const char *cp = strchr(auth->u.open, '/');
2593                 if (cp)
2594                 {
2595                     user.assign(auth->u.open, cp - auth->u.open);
2596                     password.assign(cp + 1);
2597                 }
2598             }
2599             break;
2600         case Z_IdAuthentication_idPass:
2601             if (auth->u.idPass->userId)
2602                 user.assign(auth->u.idPass->userId);
2603             if (auth->u.idPass->password)
2604                 password.assign(auth->u.idPass->password);
2605             break;
2606         }
2607     }
2608
2609     Z_OtherInformation **oi = &req->otherInfo;
2610     const char *ip =
2611         yaz_oi_get_string_oid(oi, yaz_oid_userinfo_client_ip, 1, 0);
2612     if (!ip)
2613         ip = package.origin().get_address().c_str();
2614
2615     yaz_log(YLOG_LOG, "IP=%s", ip);
2616
2617     std::string torus_query;
2618     int failure_code;
2619
2620     if (user.length() && password.length())
2621     {
2622         torus_query = "userName==\"" + escape_cql_term(user) +
2623             "\" and password==\"" + escape_cql_term(password) + "\"";
2624         failure_code = YAZ_BIB1_INIT_AC_BAD_USERID_AND_OR_PASSWORD;
2625     }
2626     else
2627     {
2628         torus_query = "ip encloses/net.ipaddress \"";
2629         torus_query += escape_cql_term(std::string(ip));
2630         torus_query += "\"";
2631         failure_code = YAZ_BIB1_INIT_AC_BLOCKED_NETWORK_ADDRESS;
2632     }
2633
2634     std::string dummy_db;
2635     std::string dummy_realm;
2636     xmlDoc *doc = mp::get_searchable(package, m_p->torus_auth_url, dummy_db,
2637                                      torus_query, dummy_realm, m_p->proxy);
2638     if (!doc)
2639     {
2640         // something fundamental broken in lookup.
2641         *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
2642         *addinfo = odr_strdup(odr, "zoom: torus server unavailable or "
2643                               "incorrectly configured.");
2644         return;
2645     }
2646     const xmlNode *ptr = xmlDocGetRootElement(doc);
2647     if (ptr && ptr->type == XML_ELEMENT_NODE)
2648     {
2649         if (strcmp((const char *) ptr->name, "records") == 0)
2650         {
2651             ptr = ptr->children;
2652             while (ptr && ptr->type != XML_ELEMENT_NODE)
2653                 ptr = ptr->next;
2654         }
2655         if (ptr && strcmp((const char *) ptr->name, "record") == 0)
2656         {
2657             ptr = ptr->children;
2658             while (ptr && ptr->type != XML_ELEMENT_NODE)
2659                 ptr = ptr->next;
2660         }
2661         if (ptr && strcmp((const char *) ptr->name, "layer") == 0)
2662         {
2663             ptr = ptr->children;
2664             while (ptr && ptr->type != XML_ELEMENT_NODE)
2665                 ptr = ptr->next;
2666         }
2667         while (ptr)
2668         {
2669             if (ptr && ptr->type == XML_ELEMENT_NODE &&
2670                 !strcmp((const char *) ptr->name, "identityId"))
2671                 break;
2672             ptr = ptr->next;
2673         }
2674     }
2675     if (!ptr)
2676     {
2677         *error = failure_code;
2678         return;
2679     }
2680     session_realm = mp::xml::get_text(ptr);
2681 }
2682
2683 void yf::Zoom::Impl::process(mp::Package &package)
2684 {
2685     FrontendPtr f = get_frontend(package);
2686     Z_GDU *gdu = package.request().get();
2687
2688     if (f->m_is_virtual)
2689     {
2690         f->handle_package(package);
2691     }
2692     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
2693              Z_APDU_initRequest)
2694     {
2695         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
2696         f->m_init_gdu = gdu;
2697
2698         mp::odr odr;
2699         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
2700         Z_InitResponse *resp = apdu->u.initResponse;
2701
2702         int i;
2703         static const int masks[] = {
2704             Z_Options_search,
2705             Z_Options_present,
2706             -1
2707         };
2708         for (i = 0; masks[i] != -1; i++)
2709             if (ODR_MASK_GET(req->options, masks[i]))
2710                 ODR_MASK_SET(resp->options, masks[i]);
2711
2712         static const int versions[] = {
2713             Z_ProtocolVersion_1,
2714             Z_ProtocolVersion_2,
2715             Z_ProtocolVersion_3,
2716             -1
2717         };
2718         for (i = 0; versions[i] != -1; i++)
2719             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
2720                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
2721             else
2722                 break;
2723
2724         *resp->preferredMessageSize = *req->preferredMessageSize;
2725         *resp->maximumRecordSize = *req->maximumRecordSize;
2726
2727         int error = 0;
2728         char *addinfo = 0;
2729         f->auth(package, req, &error, &addinfo, odr);
2730         if (error)
2731         {
2732             resp->userInformationField =
2733                 zget_init_diagnostics(odr, error, addinfo);
2734             *resp->result = 0;
2735             package.session().close();
2736         }
2737         else
2738             f->m_is_virtual = true;
2739         package.response() = apdu;
2740     }
2741     else
2742         package.move();
2743
2744     release_frontend(package);
2745 }
2746
2747
2748 static mp::filter::Base* filter_creator()
2749 {
2750     return new mp::filter::Zoom;
2751 }
2752
2753 extern "C" {
2754     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
2755         0,
2756         "zoom",
2757         filter_creator
2758     };
2759 }
2760
2761
2762 /*
2763  * Local variables:
2764  * c-basic-offset: 4
2765  * c-file-style: "Stroustrup"
2766  * indent-tabs-mode: nil
2767  * End:
2768  * vim: shiftwidth=4 tabstop=8 expandtab
2769  */
2770