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