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