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