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