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