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