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