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