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