zoom: remove 'xslt successful' message
[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             mp::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_connection = ZOOM_connection_create(0);
267     ZOOM_connection_save_apdu_wrbuf(m_connection, m_apdu_wrbuf);
268     m_resultset = 0;
269     xsp = 0;
270     enable_cproxy = true;
271     enable_explain = false;
272     explain_doc = 0;
273 }
274
275 yf::Zoom::Backend::~Backend()
276 {
277     if (xsp)
278         xsltFreeStylesheet(xsp);
279     if (explain_doc)
280         xmlFreeDoc(explain_doc);
281     ZOOM_connection_destroy(m_connection);
282     ZOOM_resultset_destroy(m_resultset);
283 }
284
285
286 void yf::Zoom::Backend::get_zoom_error(int *error, char **addinfo,
287                                        ODR odr)
288 {
289     const char *msg = 0;
290     const char *zoom_addinfo = 0;
291     const char *dset = 0;
292     int error0 = ZOOM_connection_error_x(m_connection, &msg,
293                                          &zoom_addinfo, &dset);
294     if (error0)
295     {
296         if (!dset)
297             dset = "Unknown";
298         
299         if (!strcmp(dset, "info:srw/diagnostic/1"))
300             *error = yaz_diag_srw_to_bib1(error0);
301         else if (!strcmp(dset, "Bib-1"))
302             *error = error0;
303         else
304             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
305         
306         *addinfo = (char *) odr_malloc(
307             odr, 30 + strlen(dset) + strlen(msg) +
308             (zoom_addinfo ? strlen(zoom_addinfo) : 0));
309         **addinfo = '\0';
310         if (zoom_addinfo && *zoom_addinfo)
311         {
312             strcpy(*addinfo, zoom_addinfo);
313             strcat(*addinfo, " ");
314         }
315         sprintf(*addinfo + strlen(*addinfo), "(%s %d %s)", dset, error0, msg);
316     }
317 }
318
319 void yf::Zoom::Backend::connect(std::string zurl,
320                                 int *error, char **addinfo,
321                                 ODR odr)
322 {
323     ZOOM_connection_connect(m_connection, zurl.length() ? zurl.c_str() : 0, 0);
324     get_zoom_error(error, addinfo, odr);
325 }
326
327 void yf::Zoom::Backend::search(ZOOM_query q, Odr_int *hits,
328                                int *error, char **addinfo, ODR odr)
329 {
330     ZOOM_resultset_destroy(m_resultset);
331     m_resultset = ZOOM_connection_search(m_connection, q);
332     get_zoom_error(error, addinfo, odr);
333     if (*error == 0)
334         *hits = ZOOM_resultset_size(m_resultset);
335     else
336         *hits = 0;
337 }
338
339 void yf::Zoom::Backend::present(Odr_int start, Odr_int number,
340                                 ZOOM_record *recs,
341                                 int *error, char **addinfo, ODR odr)
342 {
343     ZOOM_resultset_records(m_resultset, recs, start, number);
344     get_zoom_error(error, addinfo, odr);
345 }
346
347 void yf::Zoom::Backend::set_option(const char *name, const char *value)
348 {
349     ZOOM_connection_option_set(m_connection, name, value);
350     if (m_resultset)
351         ZOOM_resultset_option_set(m_resultset, name, value);
352 }
353
354 void yf::Zoom::Backend::set_option(const char *name, std::string value)
355 {
356     set_option(name, value.c_str());
357 }
358
359 const char *yf::Zoom::Backend::get_option(const char *name)
360 {
361     return ZOOM_connection_option_get(m_connection, name);
362 }
363
364 yf::Zoom::Searchable::Searchable(CCL_bibset base)
365 {
366     piggyback = true;
367     use_turbomarc = true;
368     sortStrategy = "embed";
369     ccl_bibset = ccl_qual_dup(base);
370 }
371
372 yf::Zoom::Searchable::~Searchable()
373 {
374     ccl_qual_rm(&ccl_bibset);
375 }
376
377 yf::Zoom::Frontend::Frontend(Impl *impl) : 
378     m_p(impl), m_is_virtual(false), m_in_use(true)
379 {
380 }
381
382 yf::Zoom::Frontend::~Frontend()
383 {
384 }
385
386 yf::Zoom::FrontendPtr yf::Zoom::Impl::get_frontend(mp::Package &package)
387 {
388     boost::mutex::scoped_lock lock(m_mutex);
389
390     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
391     
392     while(true)
393     {
394         it = m_clients.find(package.session());
395         if (it == m_clients.end())
396             break;
397         
398         if (!it->second->m_in_use)
399         {
400             it->second->m_in_use = true;
401             return it->second;
402         }
403         m_cond_session_ready.wait(lock);
404     }
405     FrontendPtr f(new Frontend(this));
406     m_clients[package.session()] = f;
407     f->m_in_use = true;
408     return f;
409 }
410
411 void yf::Zoom::Impl::release_frontend(mp::Package &package)
412 {
413     boost::mutex::scoped_lock lock(m_mutex);
414     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
415     
416     it = m_clients.find(package.session());
417     if (it != m_clients.end())
418     {
419         if (package.session().is_closed())
420         {
421             m_clients.erase(it);
422         }
423         else
424         {
425             it->second->m_in_use = false;
426         }
427         m_cond_session_ready.notify_all();
428     }
429 }
430
431 yf::Zoom::Impl::Impl() :
432     apdu_log(false), element_transform("pz2") , element_raw("raw"),
433     zoom_timeout("40")
434 {
435     bibset = ccl_qual_mk();
436
437     explain_xsp = 0;
438     record_xsp = 0;
439     srand((unsigned int) time(0));
440 }
441
442 yf::Zoom::Impl::~Impl()
443 {
444     if (explain_xsp)
445         xsltFreeStylesheet(explain_xsp);
446     ccl_qual_rm(&bibset);
447 }
448
449 yf::Zoom::SearchablePtr yf::Zoom::Impl::parse_torus_record(const xmlNode *ptr)
450 {
451     Zoom::SearchablePtr s(new Searchable(bibset));
452     
453     for (ptr = ptr->children; ptr; ptr = ptr->next)
454     {
455         if (ptr->type != XML_ELEMENT_NODE)
456             continue;
457         if (!strcmp((const char *) ptr->name, "layer"))
458             ptr = ptr->children;
459         else if (!strcmp((const char *) ptr->name,
460                          "authentication"))
461         {
462             s->authentication = mp::xml::get_text(ptr);
463         }
464         else if (!strcmp((const char *) ptr->name,
465                          "cfAuth"))
466         {
467             s->cfAuth = mp::xml::get_text(ptr);
468         } 
469         else if (!strcmp((const char *) ptr->name,
470                          "cfProxy"))
471         {
472             s->cfProxy = mp::xml::get_text(ptr);
473         }  
474         else if (!strcmp((const char *) ptr->name,
475                          "cfSubDB"))
476         {
477             s->cfSubDB = mp::xml::get_text(ptr);
478         }  
479         else if (!strcmp((const char *) ptr->name,
480                          "contentConnector"))
481         {
482             s->contentConnector = mp::xml::get_text(ptr);
483         }  
484         else if (!strcmp((const char *) ptr->name, "udb"))
485         {
486             s->udb = mp::xml::get_text(ptr);
487         }
488         else if (!strcmp((const char *) ptr->name, "zurl"))
489         {
490             s->target = mp::xml::get_text(ptr);
491         }
492         else if (!strcmp((const char *) ptr->name, "sru"))
493         {
494             s->sru = mp::xml::get_text(ptr);
495         }
496         else if (!strcmp((const char *) ptr->name, "SRUVersion") ||
497                  !strcmp((const char *) ptr->name, "sruVersion"))
498         {
499             s->sru_version = mp::xml::get_text(ptr);
500         }
501         else if (!strcmp((const char *) ptr->name,
502                          "queryEncoding"))
503         {
504             s->query_encoding = mp::xml::get_text(ptr);
505         }
506         else if (!strcmp((const char *) ptr->name,
507                          "piggyback"))
508         {
509             s->piggyback = mp::xml::get_bool(ptr, true);
510         }
511         else if (!strcmp((const char *) ptr->name,
512                          "requestSyntax"))
513         {
514             s->request_syntax = mp::xml::get_text(ptr);
515         }
516         else if (!strcmp((const char *) ptr->name,
517                          "elementSet"))
518         {
519             s->element_set = mp::xml::get_text(ptr);
520         }
521         else if (!strcmp((const char *) ptr->name,
522                          "recordEncoding"))
523         {
524             s->record_encoding = mp::xml::get_text(ptr);
525         }
526         else if (!strcmp((const char *) ptr->name,
527                          "transform"))
528         {
529             s->transform_xsl_fname = mp::xml::get_text(ptr);
530         }
531         else if (!strcmp((const char *) ptr->name,
532                          "literalTransform"))
533         {
534             s->transform_xsl_content = mp::xml::get_text(ptr);
535         }
536         else if (!strcmp((const char *) ptr->name,
537                          "urlRecipe"))
538         {
539             s->urlRecipe = mp::xml::get_text(ptr);
540         }
541         else if (!strcmp((const char *) ptr->name,
542                          "useTurboMarc"))
543         {
544             ; // useTurboMarc is ignored
545         }
546         else if (!strncmp((const char *) ptr->name,
547                           "cclmap_", 7))
548         {
549             std::string value = mp::xml::get_text(ptr);
550             if (value.length() > 0)
551             {
552                 ccl_qual_fitem(s->ccl_bibset, value.c_str(),
553                                (const char *) ptr->name + 7);
554             }
555         }
556         else if (!strncmp((const char *) ptr->name,
557                           "sortmap_", 8))
558         {
559             std::string value = mp::xml::get_text(ptr);
560             s->sortmap[(const char *) ptr->name + 8] = value;
561         }
562         else if (!strcmp((const char *) ptr->name,
563                           "sortStrategy"))
564         {
565             s->sortStrategy = mp::xml::get_text(ptr);
566         }
567     }
568     return s;
569 }
570
571 void yf::Zoom::Impl::configure_local_records(const xmlNode *ptr, bool test_only)
572 {
573     while (ptr && ptr->type != XML_ELEMENT_NODE)
574         ptr = ptr->next;
575     
576     if (ptr)
577     {
578         if (!strcmp((const char *) ptr->name, "records"))
579         {
580             for (ptr = ptr->children; ptr; ptr = ptr->next)
581             {
582                 if (ptr->type != XML_ELEMENT_NODE)
583                     continue;
584                 if (!strcmp((const char *) ptr->name, "record"))
585                 {
586                     SearchablePtr s = parse_torus_record(ptr);
587                     if (s)
588                     {
589                         std::string udb = s->udb;
590                         if (udb.length())
591                             s_map[s->udb] = s;
592                         else
593                         {
594                             throw mp::filter::FilterException
595                                 ("No udb for local torus record");
596                         }
597                     }
598                 }
599                 else
600                 {
601                     throw mp::filter::FilterException
602                         ("Bad element " 
603                          + std::string((const char *) ptr->name)
604                          + " in zoom filter inside element "
605                          "<torus><records>");
606                 }
607             }
608         }
609         else
610         {
611             throw mp::filter::FilterException
612                 ("Bad element " 
613                  + std::string((const char *) ptr->name)
614                  + " in zoom filter inside element <torus>");
615         }
616     }
617 }
618
619 void yf::Zoom::Impl::configure(const xmlNode *ptr, bool test_only,
620                                const char *path)
621 {
622     std::string explain_xslt_fname;
623     std::string record_xslt_fname;
624
625     content_tmp_file = "/tmp/cf.XXXXXX.p";
626     if (path && *path)
627     {
628         file_path = path;
629     }
630     for (ptr = ptr->children; ptr; ptr = ptr->next)
631     {
632         if (ptr->type != XML_ELEMENT_NODE)
633             continue;
634         else if (!strcmp((const char *) ptr->name, "torus"))
635         {
636             const struct _xmlAttr *attr;
637             for (attr = ptr->properties; attr; attr = attr->next)
638             {
639                 if (!strcmp((const char *) attr->name, "url"))
640                     torus_searchable_url = mp::xml::get_text(attr->children);
641                 else if (!strcmp((const char *) attr->name, "content_url"))
642                     torus_content_url = mp::xml::get_text(attr->children);
643                 else if (!strcmp((const char *) attr->name, "realm"))
644                     default_realm = mp::xml::get_text(attr->children);
645                 else if (!strcmp((const char *) attr->name, "xsldir"))
646                     xsldir = mp::xml::get_text(attr->children);
647                 else if (!strcmp((const char *) attr->name, "element_transform"))
648                     element_transform = mp::xml::get_text(attr->children);
649                 else if (!strcmp((const char *) attr->name, "element_raw"))
650                     element_raw = mp::xml::get_text(attr->children);
651                 else if (!strcmp((const char *) attr->name, "proxy"))
652                     proxy = mp::xml::get_text(attr->children);
653                 else if (!strcmp((const char *) attr->name, "explain_xsl"))
654                     explain_xslt_fname = mp::xml::get_text(attr->children);
655                 else if (!strcmp((const char *) attr->name, "record_xsl"))
656                     record_xslt_fname = mp::xml::get_text(attr->children);
657                 else
658                     throw mp::filter::FilterException(
659                         "Bad attribute " + std::string((const char *)
660                                                        attr->name));
661             }
662             // If content_url is not given, use value of searchable, to
663             // ensure backwards compatibility
664             if (!torus_content_url.length())
665                 torus_content_url = torus_searchable_url;
666             configure_local_records(ptr->children, test_only);
667         }
668         else if (!strcmp((const char *) ptr->name, "cclmap"))
669         {
670             const char *addinfo = 0;
671             ccl_xml_config(bibset, ptr, &addinfo);
672         }
673         else if (!strcmp((const char *) ptr->name, "fieldmap"))
674         {
675             const struct _xmlAttr *attr;
676             std::string ccl_field;
677             std::string cql_field;
678             for (attr = ptr->properties; attr; attr = attr->next)
679             {
680                 if (!strcmp((const char *) attr->name, "ccl"))
681                     ccl_field = mp::xml::get_text(attr->children);
682                 else if (!strcmp((const char *) attr->name, "cql"))
683                     cql_field = mp::xml::get_text(attr->children);
684                 else
685                     throw mp::filter::FilterException(
686                         "Bad attribute " + std::string((const char *)
687                                                        attr->name));
688             }
689             if (cql_field.length())
690                 fieldmap[cql_field] = ccl_field;
691         }
692         else if (!strcmp((const char *) ptr->name, "contentProxy"))
693         {
694             const struct _xmlAttr *attr;
695             for (attr = ptr->properties; attr; attr = attr->next)
696             {
697                 if (!strcmp((const char *) attr->name, "server"))
698                     content_proxy_server = mp::xml::get_text(attr->children);
699                 else if (!strcmp((const char *) attr->name, "tmp_file"))
700                     content_tmp_file = mp::xml::get_text(attr->children);
701                 else
702                     throw mp::filter::FilterException(
703                         "Bad attribute " + std::string((const char *)
704                                                        attr->name));
705             }
706         }
707         else if (!strcmp((const char *) ptr->name, "log"))
708         { 
709             const struct _xmlAttr *attr;
710             for (attr = ptr->properties; attr; attr = attr->next)
711             {
712                 if (!strcmp((const char *) attr->name, "apdu"))
713                     apdu_log = mp::xml::get_bool(attr->children, false);
714                 else
715                     throw mp::filter::FilterException(
716                         "Bad attribute " + std::string((const char *)
717                                                        attr->name));
718             }
719         }
720         else if (!strcmp((const char *) ptr->name, "zoom"))
721         {
722             const struct _xmlAttr *attr;
723             for (attr = ptr->properties; attr; attr = attr->next)
724             {
725                 if (!strcmp((const char *) attr->name, "timeout"))
726                     zoom_timeout = mp::xml::get_text(attr->children);
727                 else
728                     throw mp::filter::FilterException(
729                         "Bad attribute " + std::string((const char *)
730                                                        attr->name));
731             }
732         }
733         else
734         {
735             throw mp::filter::FilterException
736                 ("Bad element " 
737                  + std::string((const char *) ptr->name)
738                  + " in zoom filter");
739         }
740     }
741
742     if (explain_xslt_fname.length())
743     {
744         const char *path = 0;
745         
746         if (xsldir.length())
747             path = xsldir.c_str();
748         else
749             path = file_path.c_str();
750         
751         char fullpath[1024];
752         char *cp = yaz_filepath_resolve(explain_xslt_fname.c_str(),
753                                         path, 0, fullpath);
754         if (!cp)
755         {
756             throw mp::filter::FilterException
757                 ("Cannot read XSLT " + explain_xslt_fname);
758         }
759
760         xmlDoc *xsp_doc = xmlParseFile(cp);
761         if (!xsp_doc)
762         {
763             throw mp::filter::FilterException
764                 ("Cannot parse XSLT " + explain_xslt_fname);
765         }
766
767         explain_xsp = xsltParseStylesheetDoc(xsp_doc);
768         if (!explain_xsp)
769         {
770             xmlFreeDoc(xsp_doc);
771             throw mp::filter::FilterException
772                 ("Cannot parse XSLT " + explain_xslt_fname);
773             
774         }
775     }
776
777     if (record_xslt_fname.length())
778     {
779         const char *path = 0;
780         
781         if (xsldir.length())
782             path = xsldir.c_str();
783         else
784             path = file_path.c_str();
785         
786         char fullpath[1024];
787         char *cp = yaz_filepath_resolve(record_xslt_fname.c_str(),
788                                         path, 0, fullpath);
789         if (!cp)
790         {
791             throw mp::filter::FilterException
792                 ("Cannot read XSLT " + record_xslt_fname);
793         }
794
795         xmlDoc *xsp_doc = xmlParseFile(cp);
796         if (!xsp_doc)
797         {
798             throw mp::filter::FilterException
799                 ("Cannot parse XSLT " + record_xslt_fname);
800         }
801
802         record_xsp = xsltParseStylesheetDoc(xsp_doc);
803         if (!record_xsp)
804         {
805             xmlFreeDoc(xsp_doc);
806             throw mp::filter::FilterException
807                 ("Cannot parse XSLT " + record_xslt_fname);
808             
809         }
810     }
811 }
812
813 bool yf::Zoom::Frontend::create_content_session(mp::Package &package,
814                                                 BackendPtr b,
815                                                 int *error, char **addinfo,
816                                                 ODR odr,
817                                                 std::string authentication,
818                                                 std::string proxy,
819                                                 std::string realm)
820 {
821     if (b->sptr->contentConnector.length())
822     {
823         char *fname = (char *) xmalloc(m_p->content_tmp_file.length() + 8);
824         strcpy(fname, m_p->content_tmp_file.c_str());
825         char *xx = strstr(fname, "XXXXXX");
826         if (!xx)
827         {
828             xx = fname + strlen(fname);
829             strcat(fname, "XXXXXX");
830         }
831         char tmp_char = xx[6];
832         sprintf(xx, "%06d", ((unsigned) rand()) % 1000000);
833         xx[6] = tmp_char;
834
835         FILE *file = fopen(fname, "w");
836         if (!file)
837         {
838             package.log("zoom", YLOG_WARN|YLOG_ERRNO, "create %s", fname);
839             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
840             *addinfo = (char *)  odr_malloc(odr, 40 + strlen(fname));
841             sprintf(*addinfo, "Could not create %s", fname);
842             xfree(fname);
843             return false;
844         }
845         b->content_session_id.assign(xx, 6);
846         mp::wrbuf w;
847         wrbuf_puts(w, "#content_proxy\n");
848         wrbuf_printf(w, "connector: %s\n", b->sptr->contentConnector.c_str());
849         if (authentication.length())
850             wrbuf_printf(w, "auth: %s\n", authentication.c_str());
851         if (proxy.length())
852             wrbuf_printf(w, "proxy: %s\n", proxy.c_str());
853         if (realm.length())
854             wrbuf_printf(w, "realm: %s\n", realm.c_str());
855
856         fwrite(w.buf(), 1, w.len(), file);
857         fclose(file);
858         package.log("zoom", YLOG_LOG, "content file: %s", fname);
859         xfree(fname);
860     }
861     return true;
862 }
863
864 yf::Zoom::BackendPtr yf::Zoom::Frontend::get_backend_from_databases(
865     mp::Package &package,
866     std::string &database, int *error, char **addinfo, mp::odr &odr,
867     int *proxy_step)
868 {
869     std::list<BackendPtr>::const_iterator map_it;
870     if (m_backend && !m_backend->enable_explain && 
871         m_backend->m_frontend_database == database)
872     {
873         m_backend->connect("", error, addinfo, odr);
874         return m_backend;
875     }
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_write(rec_buf, rec_len);
1549
1550                             xmlFreeDoc(rec_res);
1551                         }
1552                         if (!rec_buf)
1553                         {
1554                             std::string addinfo;
1555                             int error =
1556                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS;
1557
1558                             addinfo = "xslt apply failed for "
1559                                 + b->sptr->transform_xsl_fname;
1560                             log_diagnostic(package, error, addinfo.c_str());
1561                             npr = zget_surrogateDiagRec(
1562                                 odr, odr_database, error, addinfo.c_str());
1563                         }
1564                         xmlFreeDoc(rec_doc);
1565                     }
1566                 }
1567
1568                 if (!npr)
1569                 {
1570                     if (!rec_buf)
1571                         npr = zget_surrogateDiagRec(
1572                             odr, odr_database, 
1573                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1574                             rec_type_str);
1575                     else
1576                     {
1577                         npr = (Z_NamePlusRecord *)
1578                             odr_malloc(odr, sizeof(*npr));
1579                         npr->databaseName = odr_database;
1580                         npr->which = Z_NamePlusRecord_databaseRecord;
1581                         npr->u.databaseRecord =
1582                             z_ext_record_xml(odr, rec_buf, rec_len);
1583                     }
1584                 }
1585                 if (xmlrec_buf)
1586                     xmlFree(xmlrec_buf);
1587             }
1588             else
1589             {
1590                 Z_External *ext =
1591                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1592                 if (ext)
1593                 {
1594                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1595                     npr->databaseName = odr_database;
1596                     npr->which = Z_NamePlusRecord_databaseRecord;
1597                     npr->u.databaseRecord = ext;
1598                 }
1599                 else
1600                 {
1601                     npr = zget_surrogateDiagRec(
1602                         odr, odr_database, 
1603                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1604                         "ZOOM_record, type ext");
1605                 }
1606             }
1607             npl->records[i] = npr;
1608         }
1609         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1610         records->which = Z_Records_DBOSD;
1611         records->u.databaseOrSurDiagnostics = npl;
1612     }
1613     return records;
1614 }
1615
1616 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1617                                                     ODR odr)
1618 {
1619     struct cql_node *r = 0;
1620     if (!cn)
1621         return 0;
1622     switch (cn->which)
1623     {
1624     case CQL_NODE_ST:
1625         if (cn->u.st.index)
1626         {
1627             std::map<std::string,std::string>::const_iterator it;
1628             it = fieldmap.find(cn->u.st.index);
1629             if (it == fieldmap.end())
1630                 return cn;
1631             if (it->second.length())
1632                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1633             else
1634                 cn->u.st.index = 0;
1635         }
1636         break;
1637     case CQL_NODE_BOOL:
1638         r = convert_cql_fields(cn->u.boolean.left, odr);
1639         if (!r)
1640             r = convert_cql_fields(cn->u.boolean.right, odr);
1641         break;
1642     case CQL_NODE_SORT:
1643         r = convert_cql_fields(cn->u.sort.search, odr);
1644         break;
1645     }
1646     return r;
1647 }
1648
1649 void yf::Zoom::Frontend::log_diagnostic(mp::Package &package,
1650                                         int error, const char *addinfo)
1651 {
1652     const char *err_msg = yaz_diag_bib1_str(error);
1653     if (addinfo)
1654         package.log("zoom", YLOG_WARN, "Diagnostic %d %s: %s",
1655                     error, err_msg, addinfo);
1656     else
1657         package.log("zoom", YLOG_WARN, "Diagnostic %d %s:",
1658                     error, err_msg);
1659 }
1660
1661 yf::Zoom::BackendPtr yf::Zoom::Frontend::explain_search(mp::Package &package,
1662                                                         std::string &database,
1663                                                         int *error,
1664                                                         char **addinfo,
1665                                                         mp::odr &odr,
1666                                                         std::string &torus_db,
1667                                                         std::string &realm)
1668 {
1669     m_backend.reset();
1670
1671     BackendPtr b(new Backend);
1672
1673     b->m_frontend_database = database;
1674     b->enable_explain = true;
1675    
1676     Z_GDU *gdu = package.request().get();
1677     Z_APDU *apdu_req = gdu->u.z3950;
1678     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1679     Z_Query *query = sr->query;
1680
1681     if (!m_p->explain_xsp)
1682     {
1683         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1684         *addinfo =
1685             odr_strdup(odr, "IR-Explain---1 unsupported. "
1686                        "Torus explain_xsl not defined");
1687         return m_backend;
1688     }
1689     else if (query->which == Z_Query_type_104 &&
1690         query->u.type_104->which == Z_External_CQL)
1691     {
1692         std::string torus_url = m_p->torus_searchable_url;
1693         std::string torus_query(query->u.type_104->u.cql);
1694         xmlDoc *doc = mp::get_searchable(package, torus_url, "",
1695                                          torus_query,
1696                                          realm, m_p->proxy);
1697         if (m_p->explain_xsp)
1698         {
1699             xmlDoc *rec_res =  xsltApplyStylesheet(m_p->explain_xsp, doc, 0);
1700
1701             xmlFreeDoc(doc);
1702             doc = rec_res;
1703         }
1704         if (!doc)
1705         {
1706             *error = YAZ_BIB1_UNSPECIFIED_ERROR;
1707             *addinfo = odr_strdup(odr, "IR-Explain---1 problem. " 
1708                                   "Could not obtain Torus records for Explain");
1709         }
1710         else
1711         {
1712             xmlNode *ptr = xmlDocGetRootElement(doc);
1713             int hits = 0;
1714             
1715             xml_node_search(ptr, &hits, 0);
1716
1717             Z_APDU *apdu_res = odr.create_searchResponse(apdu_req, 0, 0);
1718             apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1719             package.response() = apdu_res;
1720             m_backend = b;
1721         }
1722         if (b->explain_doc)
1723             xmlFreeDoc(b->explain_doc);
1724         b->explain_doc = doc;
1725         return m_backend;
1726     }
1727     else
1728     {
1729         *error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
1730         *addinfo = odr_strdup(odr, "IR-Explain---1 only supports CQL");
1731         return m_backend;
1732     }
1733 }
1734
1735 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1736 {
1737     Z_GDU *gdu = package.request().get();
1738     Z_APDU *apdu_req = gdu->u.z3950;
1739     Z_APDU *apdu_res = 0;
1740     mp::odr odr;
1741     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1742     if (sr->num_databaseNames != 1)
1743     {
1744         int error = YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED;
1745         log_diagnostic(package, error, 0);
1746         apdu_res = odr.create_searchResponse(apdu_req, error, 0);
1747         package.response() = apdu_res;
1748         return;
1749     }
1750     int proxy_step = 0;
1751
1752 next_proxy:
1753
1754     int error = 0;
1755     char *addinfo = 0;
1756     std::string db(sr->databaseNames[0]);
1757
1758     BackendPtr b = get_backend_from_databases(package, db, &error,
1759                                               &addinfo, odr, &proxy_step);
1760     if (error && proxy_step)
1761     {
1762         package.log("zoom", YLOG_WARN,
1763                     "create backend failed: trying next proxy");
1764         goto next_proxy;
1765     }
1766     if (error)
1767     {
1768         log_diagnostic(package, error, addinfo);
1769         apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1770         package.response() = apdu_res;
1771         return;
1772     }
1773     if (!b || b->enable_explain)
1774         return;
1775
1776     b->set_option("setname", "default");
1777
1778     bool enable_pz2_retrieval = false;
1779     bool enable_pz2_transform = false;
1780     bool enable_record_transform = false;
1781     bool assume_marc8_charset = false;
1782     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
1783                      enable_pz2_retrieval,
1784                      enable_pz2_transform,
1785                      enable_record_transform,
1786                      assume_marc8_charset);
1787
1788     Odr_int hits = 0;
1789     Z_Query *query = sr->query;
1790     mp::wrbuf ccl_wrbuf;
1791     mp::wrbuf pqf_wrbuf;
1792     std::string sortkeys;
1793
1794     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1795     {
1796         // RPN
1797         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1798     }
1799     else if (query->which == Z_Query_type_2)
1800     {
1801         // CCL
1802         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1803                     query->u.type_2->len);
1804     }
1805     else if (query->which == Z_Query_type_104 &&
1806              query->u.type_104->which == Z_External_CQL)
1807     {
1808         // CQL
1809         const char *cql = query->u.type_104->u.cql;
1810         CQL_parser cp = cql_parser_create();
1811         int r = cql_parser_string(cp, cql);
1812         package.log("zoom", YLOG_LOG, "CQL: %s", cql);
1813         if (r)
1814         {
1815             cql_parser_destroy(cp);
1816             error = YAZ_BIB1_MALFORMED_QUERY;
1817             const char *addinfo = "CQL syntax error";
1818             log_diagnostic(package, error, addinfo);
1819             apdu_res = 
1820                 odr.create_searchResponse(apdu_req, error, addinfo);
1821             package.response() = apdu_res;
1822             return;
1823         }
1824         struct cql_node *cn = cql_parser_result(cp);
1825         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1826         if (cn_error)
1827         {
1828             // hopefully we are getting a ptr to a index+relation+term node
1829             error = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1830             addinfo = 0;
1831             if (cn_error->which == CQL_NODE_ST)
1832                 addinfo = cn_error->u.st.index;
1833             
1834             log_diagnostic(package, error, addinfo);
1835             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1836             package.response() = apdu_res;
1837             cql_parser_destroy(cp);
1838             return;
1839         }
1840         char ccl_buf[1024];
1841         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1842         if (r)
1843         {
1844             error = YAZ_BIB1_MALFORMED_QUERY;
1845             const char *addinfo = "CQL to CCL conversion error";
1846
1847             log_diagnostic(package, error, addinfo);
1848             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1849             package.response() = apdu_res;
1850             cql_parser_destroy(cp);
1851             return;
1852         }
1853
1854         mp::wrbuf sru_sortkeys_wrbuf;
1855         if (cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf))
1856         {
1857             error = YAZ_BIB1_ILLEGAL_SORT_RELATION;
1858             const char *addinfo = "CQL to CCL sortby conversion";
1859
1860             log_diagnostic(package, error, addinfo);
1861             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1862             package.response() = apdu_res;
1863             cql_parser_destroy(cp);
1864             return;
1865         }
1866         mp::wrbuf sort_spec_wrbuf;
1867         yaz_srw_sortkeys_to_sort_spec(wrbuf_cstr(sru_sortkeys_wrbuf),
1868                                       sort_spec_wrbuf);
1869         wrbuf_puts(ccl_wrbuf, ccl_buf);
1870         
1871         yaz_tok_cfg_t tc = yaz_tok_cfg_create();
1872         yaz_tok_parse_t tp =
1873             yaz_tok_parse_buf(tc, wrbuf_cstr(sort_spec_wrbuf));
1874         yaz_tok_cfg_destroy(tc);
1875         
1876         /* go through sortspec and map fields */
1877         int token = yaz_tok_move(tp);
1878         while (token != YAZ_TOK_EOF)
1879         {
1880             if (token == YAZ_TOK_STRING)
1881             {
1882                 const char *field = yaz_tok_parse_string(tp);
1883                 std::map<std::string,std::string>::iterator it;
1884                 it = b->sptr->sortmap.find(field);
1885                 if (it != b->sptr->sortmap.end())
1886                     sortkeys += it->second;
1887                 else
1888                     sortkeys += field;
1889             }
1890             sortkeys += " ";
1891             token = yaz_tok_move(tp);
1892             if (token == YAZ_TOK_STRING)
1893             {
1894                 sortkeys += yaz_tok_parse_string(tp);
1895             }
1896             if (token != YAZ_TOK_EOF)
1897             {
1898                 sortkeys += " ";
1899                 token = yaz_tok_move(tp);
1900             }
1901         }
1902         yaz_tok_parse_destroy(tp);
1903         cql_parser_destroy(cp);
1904     }
1905     else
1906     {
1907         error = YAZ_BIB1_QUERY_TYPE_UNSUPP;
1908         const char *addinfo = 0;
1909         log_diagnostic(package, error, addinfo);
1910         apdu_res =  odr.create_searchResponse(apdu_req, error, addinfo);
1911         package.response() = apdu_res;
1912         return;
1913     }
1914
1915     if (ccl_wrbuf.len())
1916     {
1917         // CCL to PQF
1918         assert(pqf_wrbuf.len() == 0);
1919         int cerror, cpos;
1920         struct ccl_rpn_node *cn;
1921         package.log("zoom", YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1922         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1923                           &cerror, &cpos);
1924         if (!cn)
1925         {
1926             char *addinfo = odr_strdup_null(odr, ccl_err_msg(cerror));
1927             error = YAZ_BIB1_MALFORMED_QUERY;
1928
1929             switch (cerror)
1930             {
1931             case CCL_ERR_UNKNOWN_QUAL:
1932             case CCL_ERR_TRUNC_NOT_LEFT: 
1933             case CCL_ERR_TRUNC_NOT_RIGHT:
1934             case CCL_ERR_TRUNC_NOT_BOTH:
1935 #ifdef CCL_ERR_TRUNC_NOT_EMBED
1936             case CCL_ERR_TRUNC_NOT_EMBED:
1937 #endif
1938 #ifdef CCL_ERR_TRUNC_NOT_SINGLE
1939             case CCL_ERR_TRUNC_NOT_SINGLE:
1940 #endif
1941                 error = YAZ_BIB1_UNSUPP_SEARCH;
1942                 break;
1943             }
1944             log_diagnostic(package, error, addinfo);
1945             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1946             package.response() = apdu_res;
1947             return;
1948         }
1949         ccl_pquery(pqf_wrbuf, cn);
1950         package.log("zoom", YLOG_LOG, "RPN: %s", wrbuf_cstr(pqf_wrbuf));
1951         ccl_rpn_delete(cn);
1952     }
1953     
1954     assert(pqf_wrbuf.len());
1955
1956     ZOOM_query q = ZOOM_query_create();
1957     ZOOM_query_sortby2(q, b->sptr->sortStrategy.c_str(), sortkeys.c_str());
1958
1959     if (b->get_option("sru"))
1960     {
1961         int status = 0;
1962         Z_RPNQuery *zquery;
1963         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1964         mp::wrbuf wrb;
1965             
1966         if (!strcmp(b->get_option("sru"), "solr"))
1967         {
1968             solr_transform_t cqlt = solr_transform_create();
1969             
1970             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1971             
1972             solr_transform_close(cqlt);
1973         }
1974         else
1975         {
1976             cql_transform_t cqlt = cql_transform_create();
1977             
1978             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1979             
1980             cql_transform_close(cqlt);
1981         }
1982         if (status == 0)
1983         {
1984             ZOOM_query_cql(q, wrbuf_cstr(wrb));
1985             package.log("zoom", YLOG_LOG, "CQL: %s", wrbuf_cstr(wrb));
1986             b->search(q, &hits, &error, &addinfo, odr);
1987         }
1988         ZOOM_query_destroy(q);
1989         
1990         if (status)
1991         {
1992             error = YAZ_BIB1_MALFORMED_QUERY;
1993             const char *addinfo = "can not convert from RPN to CQL/SOLR";
1994             log_diagnostic(package, error, addinfo);
1995             apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1996             package.response() = apdu_res;
1997             return;
1998         }
1999     }
2000     else
2001     {
2002         ZOOM_query_prefix(q, wrbuf_cstr(pqf_wrbuf));
2003         package.log("zoom", YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
2004         b->search(q, &hits, &error, &addinfo, odr);
2005         ZOOM_query_destroy(q);
2006     }
2007
2008     if (error && proxy_step)
2009     {
2010         // reset below prevent reuse in get_backend_from_databases
2011         m_backend.reset();
2012         package.log("zoom", YLOG_WARN, "search failed: trying next proxy");
2013         goto next_proxy;
2014     }
2015
2016     const char *element_set_name = 0;
2017     Odr_int number_to_present = 0;
2018     if (!error)
2019         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
2020     
2021     Odr_int number_of_records_returned = 0;
2022     Z_Records *records = get_records(
2023         package,
2024         0, number_to_present, &error, &addinfo,
2025         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
2026         element_set_name);
2027     if (error)
2028         log_diagnostic(package, error, addinfo);
2029     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
2030     if (records)
2031     {
2032         apdu_res->u.searchResponse->records = records;
2033         apdu_res->u.searchResponse->numberOfRecordsReturned =
2034             odr_intdup(odr, number_of_records_returned);
2035     }
2036     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
2037     package.response() = apdu_res;
2038 }
2039
2040 void yf::Zoom::Frontend::handle_present(mp::Package &package)
2041 {
2042     Z_GDU *gdu = package.request().get();
2043     Z_APDU *apdu_req = gdu->u.z3950;
2044     Z_APDU *apdu_res = 0;
2045     Z_PresentRequest *pr = apdu_req->u.presentRequest;
2046
2047     mp::odr odr;
2048     if (!m_backend)
2049     {
2050         package.response() = odr.create_presentResponse(
2051             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
2052         return;
2053     }
2054     const char *element_set_name = 0;
2055     Z_RecordComposition *comp = pr->recordComposition;
2056     if (comp && comp->which != Z_RecordComp_simple)
2057     {
2058         package.response() = odr.create_presentResponse(
2059             apdu_req, 
2060             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
2061         return;
2062     }
2063     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
2064         element_set_name = comp->u.simple->u.generic;
2065     Odr_int number_of_records_returned = 0;
2066     int error = 0;
2067     char *addinfo = 0;
2068
2069     if (m_backend->enable_explain)
2070     {
2071         Z_Records *records =
2072             get_explain_records(
2073                 package,
2074                 *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2075                 &error, &addinfo, &number_of_records_returned, odr, m_backend,
2076                 pr->preferredRecordSyntax, element_set_name);
2077         
2078         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2079         if (records)
2080         {
2081             apdu_res->u.presentResponse->records = records;
2082             apdu_res->u.presentResponse->numberOfRecordsReturned =
2083                 odr_intdup(odr, number_of_records_returned);
2084         }
2085         package.response() = apdu_res;
2086     }
2087     else
2088     {
2089         Z_Records *records =
2090             get_records(package,
2091                         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
2092                         &error, &addinfo, &number_of_records_returned, odr, m_backend,
2093                         pr->preferredRecordSyntax, element_set_name);
2094         
2095         apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
2096         if (records)
2097         {
2098             apdu_res->u.presentResponse->records = records;
2099             apdu_res->u.presentResponse->numberOfRecordsReturned =
2100                 odr_intdup(odr, number_of_records_returned);
2101         }
2102         package.response() = apdu_res;
2103     }
2104 }
2105
2106 void yf::Zoom::Frontend::handle_package(mp::Package &package)
2107 {
2108     Z_GDU *gdu = package.request().get();
2109     if (!gdu)
2110         ;
2111     else if (gdu->which == Z_GDU_Z3950)
2112     {
2113         Z_APDU *apdu_req = gdu->u.z3950;
2114
2115         if (m_backend)
2116             wrbuf_rewind(m_backend->m_apdu_wrbuf);
2117         if (apdu_req->which == Z_APDU_initRequest)
2118         {
2119             mp::odr odr;
2120             package.response() = odr.create_close(
2121                 apdu_req,
2122                 Z_Close_protocolError,
2123                 "double init");
2124         }
2125         else if (apdu_req->which == Z_APDU_searchRequest)
2126         {
2127             handle_search(package);
2128         }
2129         else if (apdu_req->which == Z_APDU_presentRequest)
2130         {
2131             handle_present(package);
2132         }
2133         else
2134         {
2135             mp::odr odr;
2136             package.response() = odr.create_close(
2137                 apdu_req,
2138                 Z_Close_protocolError,
2139                 "zoom filter cannot handle this APDU");
2140             package.session().close();
2141         }
2142         if (m_backend)
2143         {
2144             WRBUF w = m_backend->m_apdu_wrbuf;
2145             package.log_write(wrbuf_buf(w), wrbuf_len(w));
2146         }
2147     }
2148     else
2149     {
2150         package.session().close();
2151     }
2152 }
2153
2154 void yf::Zoom::Impl::process(mp::Package &package)
2155 {
2156     FrontendPtr f = get_frontend(package);
2157     Z_GDU *gdu = package.request().get();
2158
2159     if (f->m_is_virtual)
2160     {
2161         f->handle_package(package);
2162     }
2163     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
2164              Z_APDU_initRequest)
2165     {
2166         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
2167         f->m_init_gdu = gdu;
2168         
2169         mp::odr odr;
2170         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
2171         Z_InitResponse *resp = apdu->u.initResponse;
2172         
2173         int i;
2174         static const int masks[] = {
2175             Z_Options_search,
2176             Z_Options_present,
2177             -1 
2178         };
2179         for (i = 0; masks[i] != -1; i++)
2180             if (ODR_MASK_GET(req->options, masks[i]))
2181                 ODR_MASK_SET(resp->options, masks[i]);
2182         
2183         static const int versions[] = {
2184             Z_ProtocolVersion_1,
2185             Z_ProtocolVersion_2,
2186             Z_ProtocolVersion_3,
2187             -1
2188         };
2189         for (i = 0; versions[i] != -1; i++)
2190             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
2191                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
2192             else
2193                 break;
2194         
2195         *resp->preferredMessageSize = *req->preferredMessageSize;
2196         *resp->maximumRecordSize = *req->maximumRecordSize;
2197         
2198         package.response() = apdu;
2199         f->m_is_virtual = true;
2200     }
2201     else
2202         package.move();
2203
2204     release_frontend(package);
2205 }
2206
2207
2208 static mp::filter::Base* filter_creator()
2209 {
2210     return new mp::filter::Zoom;
2211 }
2212
2213 extern "C" {
2214     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
2215         0,
2216         "zoom",
2217         filter_creator
2218     };
2219 }
2220
2221
2222 /*
2223  * Local variables:
2224  * c-basic-offset: 4
2225  * c-file-style: "Stroustrup"
2226  * indent-tabs-mode: nil
2227  * End:
2228  * vim: shiftwidth=4 tabstop=8 expandtab
2229  */
2230