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