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