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