35512cac23b84de227440dbdcfcbef5ed14ea695
[metaproxy-moved-to-github.git] / src / filter_zoom.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2011 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 #include "filter_zoom.hpp"
21 #include <yaz/zoom.h>
22 #include <yaz/yaz-version.h>
23 #include <yaz/srw.h>
24 #include <metaproxy/package.hpp>
25 #include <metaproxy/util.hpp>
26 #include "torus.hpp"
27
28 #include <libxslt/xsltutils.h>
29 #include <libxslt/transform.h>
30
31 #include <boost/thread/mutex.hpp>
32 #include <boost/thread/condition.hpp>
33 #include <yaz/ccl_xml.h>
34 #include <yaz/ccl.h>
35 #include <yaz/rpn2cql.h>
36 #include <yaz/rpn2solr.h>
37 #include <yaz/pquery.h>
38 #include <yaz/cql.h>
39 #include <yaz/oid_db.h>
40 #include <yaz/diagbib1.h>
41 #include <yaz/log.h>
42 #include <yaz/zgdu.h>
43 #include <yaz/querytowrbuf.h>
44
45 namespace mp = metaproxy_1;
46 namespace yf = mp::filter;
47
48 namespace metaproxy_1 {
49     namespace filter {
50         struct Zoom::Searchable : boost::noncopyable {
51             std::string authentication;
52             std::string cfAuth;
53             std::string cfProxy;
54             std::string cfSubDb;
55             std::string udb;
56             std::string target;
57             std::string query_encoding;
58             std::string sru;
59             std::string request_syntax;
60             std::string element_set;
61             std::string record_encoding;
62             std::string transform_xsl_fname;
63             bool use_turbomarc;
64             bool piggyback;
65             CCL_bibset ccl_bibset;
66             Searchable(CCL_bibset base);
67             ~Searchable();
68         };
69         class Zoom::Backend : boost::noncopyable {
70             friend class Impl;
71             friend class Frontend;
72             std::string zurl;
73             ZOOM_connection m_connection;
74             ZOOM_resultset m_resultset;
75             std::string m_frontend_database;
76             SearchablePtr sptr;
77             xsltStylesheetPtr xsp;
78         public:
79             Backend(SearchablePtr sptr);
80             ~Backend();
81             void connect(std::string zurl, int *error, const char **addinfo);
82             void search_pqf(const char *pqf, Odr_int *hits,
83                             int *error, const char **addinfo);
84             void search_cql(const char *cql, Odr_int *hits,
85                             int *error, const char **addinfo);
86             void present(Odr_int start, Odr_int number, ZOOM_record *recs,
87                          int *error, const char **addinfo);
88             void set_option(const char *name, const char *value);
89             const char *get_option(const char *name);
90             void get_zoom_error(int *error, const char **addinfo);
91         };
92         class Zoom::Frontend : boost::noncopyable {
93             friend class Impl;
94             Impl *m_p;
95             bool m_is_virtual;
96             bool m_in_use;
97             yazpp_1::GDU m_init_gdu;
98             BackendPtr m_backend;
99             void handle_package(mp::Package &package);
100             void handle_search(mp::Package &package);
101             void handle_present(mp::Package &package);
102             BackendPtr get_backend_from_databases(std::string &database,
103                                                   int *error,
104                                                   char **addinfo,
105                                                   ODR odr);
106             Z_Records *get_records(Odr_int start,
107                                    Odr_int number_to_present,
108                                    int *error,
109                                    const char **addinfo,
110                                    Odr_int *number_of_records_returned,
111                                    ODR odr, BackendPtr b,
112                                    Odr_oid *preferredRecordSyntax,
113                                    const char *element_set_name);
114         public:
115             Frontend(Impl *impl);
116             ~Frontend();
117         };
118         class Zoom::Impl {
119             friend class Frontend;
120         public:
121             Impl();
122             ~Impl();
123             void process(metaproxy_1::Package & package);
124             void configure(const xmlNode * ptr, bool test_only);
125         private:
126             void configure_local_records(const xmlNode * ptr, bool test_only);
127             FrontendPtr get_frontend(mp::Package &package);
128             void release_frontend(mp::Package &package);
129             SearchablePtr parse_torus_record(const xmlNode *ptr);
130             struct cql_node *convert_cql_fields(struct cql_node *cn, ODR odr);
131             std::map<mp::Session, FrontendPtr> m_clients;            
132             boost::mutex m_mutex;
133             boost::condition m_cond_session_ready;
134             std::string torus_url;
135             std::map<std::string,std::string> fieldmap;
136             std::string xsldir;
137             CCL_bibset bibset;
138             std::string element_transform;
139             std::string element_raw;
140             std::map<std::string,SearchablePtr> s_map;
141         };
142     }
143 }
144
145 // define Pimpl wrapper forwarding to Impl
146  
147 yf::Zoom::Zoom() : m_p(new Impl)
148 {
149 }
150
151 yf::Zoom::~Zoom()
152 {  // must have a destructor because of boost::scoped_ptr
153 }
154
155 void yf::Zoom::configure(const xmlNode *xmlnode, bool test_only)
156 {
157     m_p->configure(xmlnode, test_only);
158 }
159
160 void yf::Zoom::process(mp::Package &package) const
161 {
162     m_p->process(package);
163 }
164
165
166 // define Implementation stuff
167
168 yf::Zoom::Backend::Backend(SearchablePtr ptr) : sptr(ptr)
169 {
170     m_connection = ZOOM_connection_create(0);
171     m_resultset = 0;
172     xsp = 0;
173 }
174
175 yf::Zoom::Backend::~Backend()
176 {
177     if (xsp)
178         xsltFreeStylesheet(xsp);
179     ZOOM_connection_destroy(m_connection);
180     ZOOM_resultset_destroy(m_resultset);
181 }
182
183
184 void yf::Zoom::Backend::get_zoom_error(int *error, const char **addinfo)
185 {
186     const char *msg = 0;
187     *error = ZOOM_connection_error(m_connection, &msg, addinfo);
188     if (*error)
189     {
190         if (*error >= ZOOM_ERROR_CONNECT)
191         {
192             // turn ZOOM diagnostic into a Bib-1 2: with addinfo=zoom err msg
193             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
194             if (addinfo)
195                 *addinfo = msg;
196         }
197     }
198 }
199
200 void yf::Zoom::Backend::connect(std::string zurl,
201                                 int *error, const char **addinfo)
202 {
203     ZOOM_connection_connect(m_connection, zurl.c_str(), 0);
204     get_zoom_error(error, addinfo);
205 }
206
207 void yf::Zoom::Backend::search_pqf(const char *pqf, Odr_int *hits,
208                                    int *error, const char **addinfo)
209 {
210     m_resultset = ZOOM_connection_search_pqf(m_connection, pqf);
211     get_zoom_error(error, addinfo);
212     if (*error == 0)
213         *hits = ZOOM_resultset_size(m_resultset);
214     else
215         *hits = 0;
216 }
217
218 void yf::Zoom::Backend::search_cql(const char *cql, Odr_int *hits,
219                                    int *error, const char **addinfo)
220 {
221     ZOOM_query q = ZOOM_query_create();
222
223     ZOOM_query_cql(q, cql);
224
225     m_resultset = ZOOM_connection_search(m_connection, q);
226     ZOOM_query_destroy(q);
227     get_zoom_error(error, addinfo);
228     if (*error == 0)
229         *hits = ZOOM_resultset_size(m_resultset);
230     else
231         *hits = 0;
232 }
233
234 void yf::Zoom::Backend::present(Odr_int start, Odr_int number,
235                                 ZOOM_record *recs,
236                                 int *error, const char **addinfo)
237 {
238     ZOOM_resultset_records(m_resultset, recs, start, number);
239     get_zoom_error(error, addinfo);
240 }
241
242 void yf::Zoom::Backend::set_option(const char *name, const char *value)
243 {
244     ZOOM_connection_option_set(m_connection, name, value);
245     if (m_resultset)
246         ZOOM_resultset_option_set(m_resultset, name, value);
247 }
248
249 const char *yf::Zoom::Backend::get_option(const char *name)
250 {
251     return ZOOM_connection_option_get(m_connection, name);
252 }
253
254 yf::Zoom::Searchable::Searchable(CCL_bibset base)
255 {
256     piggyback = true;
257     use_turbomarc = true;
258     ccl_bibset = ccl_qual_dup(base);
259 }
260
261 yf::Zoom::Searchable::~Searchable()
262 {
263     ccl_qual_rm(&ccl_bibset);
264 }
265
266 yf::Zoom::Frontend::Frontend(Impl *impl) : 
267     m_p(impl), m_is_virtual(false), m_in_use(true)
268 {
269 }
270
271 yf::Zoom::Frontend::~Frontend()
272 {
273 }
274
275 yf::Zoom::FrontendPtr yf::Zoom::Impl::get_frontend(mp::Package &package)
276 {
277     boost::mutex::scoped_lock lock(m_mutex);
278
279     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
280     
281     while(true)
282     {
283         it = m_clients.find(package.session());
284         if (it == m_clients.end())
285             break;
286         
287         if (!it->second->m_in_use)
288         {
289             it->second->m_in_use = true;
290             return it->second;
291         }
292         m_cond_session_ready.wait(lock);
293     }
294     FrontendPtr f(new Frontend(this));
295     m_clients[package.session()] = f;
296     f->m_in_use = true;
297     return f;
298 }
299
300 void yf::Zoom::Impl::release_frontend(mp::Package &package)
301 {
302     boost::mutex::scoped_lock lock(m_mutex);
303     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
304     
305     it = m_clients.find(package.session());
306     if (it != m_clients.end())
307     {
308         if (package.session().is_closed())
309         {
310             m_clients.erase(it);
311         }
312         else
313         {
314             it->second->m_in_use = false;
315         }
316         m_cond_session_ready.notify_all();
317     }
318 }
319
320 yf::Zoom::Impl::Impl() : element_transform("pz2") , element_raw("raw")
321 {
322     bibset = ccl_qual_mk();
323 }
324
325 yf::Zoom::Impl::~Impl()
326
327     ccl_qual_rm(&bibset);
328 }
329
330 yf::Zoom::SearchablePtr yf::Zoom::Impl::parse_torus_record(const xmlNode *ptr)
331 {
332     Zoom::SearchablePtr s(new Searchable(bibset));
333     
334     for (ptr = ptr->children; ptr; ptr = ptr->next)
335     {
336         if (ptr->type != XML_ELEMENT_NODE)
337             continue;
338         if (!strcmp((const char *) ptr->name, "layer"))
339             ptr = ptr->children;
340         else if (!strcmp((const char *) ptr->name,
341                          "authentication"))
342         {
343             s->authentication = mp::xml::get_text(ptr);
344         }
345         else if (!strcmp((const char *) ptr->name,
346                          "cfAuth"))
347         {
348             s->cfAuth = mp::xml::get_text(ptr);
349         } 
350         else if (!strcmp((const char *) ptr->name,
351                          "cfProxy"))
352         {
353             s->cfProxy = mp::xml::get_text(ptr);
354         }  
355         else if (!strcmp((const char *) ptr->name,
356                          "cfSubDb"))
357         {
358             s->cfSubDb = mp::xml::get_text(ptr);
359         }  
360         else if (!strcmp((const char *) ptr->name, "udb"))
361         {
362             s->udb = mp::xml::get_text(ptr);
363         }
364         else if (!strcmp((const char *) ptr->name, "zurl"))
365         {
366             s->target = mp::xml::get_text(ptr);
367         }
368         else if (!strcmp((const char *) ptr->name, "sru"))
369         {
370             s->sru = mp::xml::get_text(ptr);
371         }
372         else if (!strcmp((const char *) ptr->name,
373                          "queryEncoding"))
374         {
375             s->query_encoding = mp::xml::get_text(ptr);
376         }
377         else if (!strcmp((const char *) ptr->name,
378                          "piggyback"))
379         {
380             s->piggyback = mp::xml::get_bool(ptr, true);
381         }
382         else if (!strcmp((const char *) ptr->name,
383                          "requestSyntax"))
384         {
385             s->request_syntax = mp::xml::get_text(ptr);
386         }
387         else if (!strcmp((const char *) ptr->name,
388                          "elementSet"))
389         {
390             s->element_set = mp::xml::get_text(ptr);
391         }
392         else if (!strcmp((const char *) ptr->name,
393                          "recordEncoding"))
394         {
395             s->record_encoding = mp::xml::get_text(ptr);
396         }
397         else if (!strcmp((const char *) ptr->name,
398                          "transform"))
399         {
400             s->transform_xsl_fname = mp::xml::get_text(ptr);
401         }
402         else if (!strcmp((const char *) ptr->name,
403                          "useTurboMarc"))
404         {
405             ; // useTurboMarc is ignored
406         }
407         else if (!strncmp((const char *) ptr->name,
408                           "cclmap_", 7))
409         {
410             std::string value = mp::xml::get_text(ptr);
411             ccl_qual_fitem(s->ccl_bibset, value.c_str(),
412                            (const char *) ptr->name + 7);
413         }
414     }
415     return s;
416 }
417
418 void yf::Zoom::Impl::configure_local_records(const xmlNode *ptr, bool test_only)
419 {
420     while (ptr && ptr->type != XML_ELEMENT_NODE)
421         ptr = ptr->next;
422     
423     if (ptr)
424     {
425         if (!strcmp((const char *) ptr->name, "records"))
426         {
427             for (ptr = ptr->children; ptr; ptr = ptr->next)
428             {
429                 if (ptr->type != XML_ELEMENT_NODE)
430                     continue;
431                 if (!strcmp((const char *) ptr->name, "record"))
432                 {
433                     SearchablePtr s = parse_torus_record(ptr);
434                     if (s)
435                     {
436                         std::string udb = s->udb;
437                         if (udb.length())
438                             s_map[s->udb] = s;
439                         else
440                         {
441                             throw mp::filter::FilterException
442                                 ("No udb for local torus record");
443                         }
444                     }
445                 }
446                 else
447                 {
448                     throw mp::filter::FilterException
449                         ("Bad element " 
450                          + std::string((const char *) ptr->name)
451                          + " in zoom filter inside element "
452                          "<torus><records>");
453                 }
454             }
455         }
456         else
457         {
458             throw mp::filter::FilterException
459                 ("Bad element " 
460                  + std::string((const char *) ptr->name)
461                  + " in zoom filter inside element <torus>");
462         }
463     }
464 }
465
466 void yf::Zoom::Impl::configure(const xmlNode *ptr, bool test_only)
467 {
468     for (ptr = ptr->children; ptr; ptr = ptr->next)
469     {
470         if (ptr->type != XML_ELEMENT_NODE)
471             continue;
472         else if (!strcmp((const char *) ptr->name, "torus"))
473         {
474             const struct _xmlAttr *attr;
475             for (attr = ptr->properties; attr; attr = attr->next)
476             {
477                 if (!strcmp((const char *) attr->name, "url"))
478                     torus_url = mp::xml::get_text(attr->children);
479                 else if (!strcmp((const char *) attr->name, "xsldir"))
480                     xsldir = mp::xml::get_text(attr->children);
481                 else if (!strcmp((const char *) attr->name, "element_transform"))
482                     element_transform = mp::xml::get_text(attr->children);
483                 else if (!strcmp((const char *) attr->name, "element_raw"))
484                     element_raw = mp::xml::get_text(attr->children);
485                 else
486                     throw mp::filter::FilterException(
487                         "Bad attribute " + std::string((const char *)
488                                                        attr->name));
489             }
490             configure_local_records(ptr->children, test_only);
491         }
492         else if (!strcmp((const char *) ptr->name, "cclmap"))
493         {
494             const char *addinfo = 0;
495             ccl_xml_config(bibset, ptr, &addinfo);
496         }
497         else if (!strcmp((const char *) ptr->name, "fieldmap"))
498         {
499             const struct _xmlAttr *attr;
500             std::string ccl_field;
501             std::string cql_field;
502             for (attr = ptr->properties; attr; attr = attr->next)
503             {
504                 if (!strcmp((const char *) attr->name, "ccl"))
505                     ccl_field = mp::xml::get_text(attr->children);
506                 else if (!strcmp((const char *) attr->name, "cql"))
507                     cql_field = mp::xml::get_text(attr->children);
508                 else
509                     throw mp::filter::FilterException(
510                         "Bad attribute " + std::string((const char *)
511                                                        attr->name));
512             }
513             if (cql_field.length())
514                 fieldmap[cql_field] = ccl_field;
515         }
516         else
517         {
518             throw mp::filter::FilterException
519                 ("Bad element " 
520                  + std::string((const char *) ptr->name)
521                  + " in zoom filter");
522         }
523     }
524 }
525
526 yf::Zoom::BackendPtr yf::Zoom::Frontend::get_backend_from_databases(
527     std::string &database, int *error, char **addinfo, ODR odr)
528 {
529     std::list<BackendPtr>::const_iterator map_it;
530     if (m_backend && m_backend->m_frontend_database == database)
531         return m_backend;
532
533     std::string db_args;
534     std::string torus_db;
535     size_t db_arg_pos = database.find(',');
536     if (db_arg_pos != std::string::npos)
537     {
538         torus_db = database.substr(0, db_arg_pos);
539         db_args = database.substr(db_arg_pos + 1);
540     }
541     else
542         torus_db = database;
543  
544     SearchablePtr sptr;
545
546     std::map<std::string,SearchablePtr>::iterator it;
547     it = m_p->s_map.find(torus_db);
548     if (it != m_p->s_map.end())
549         sptr = it->second;
550     else
551     {
552         xmlDoc *doc = mp::get_searchable(m_p->torus_url, torus_db);
553         if (!doc)
554         {
555             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
556             *addinfo = odr_strdup(odr, database.c_str());
557             BackendPtr b;
558             return b;
559         }
560         const xmlNode *ptr = xmlDocGetRootElement(doc);
561         if (ptr)
562         {   // presumably ptr is a records element node
563             // parse first record in document
564             for (ptr = ptr->children; ptr; ptr = ptr->next)
565             {
566                 if (ptr->type == XML_ELEMENT_NODE
567                     && !strcmp((const char *) ptr->name, "record"))
568                 {
569                     sptr = m_p->parse_torus_record(ptr);
570                     break;
571                 }
572             }
573         }
574         xmlFreeDoc(doc);
575     }
576
577     if (!sptr)
578     {
579         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
580         *addinfo = odr_strdup(odr, database.c_str());
581         BackendPtr b;
582         return b;
583     }
584         
585     xsltStylesheetPtr xsp = 0;
586     if (sptr->transform_xsl_fname.length())
587     {
588         std::string fname;
589
590         if (m_p->xsldir.length()) 
591             fname = m_p->xsldir + "/" + sptr->transform_xsl_fname;
592         else
593             fname = sptr->transform_xsl_fname;
594         xmlDoc *xsp_doc = xmlParseFile(fname.c_str());
595         if (!xsp_doc)
596         {
597             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
598             *addinfo = (char *) odr_malloc(odr, 40 + strlen(fname.c_str()));
599             sprintf(*addinfo, "xmlParseFile failed. File %s", fname.c_str());
600             BackendPtr b;
601             return b;
602         }
603         xsp = xsltParseStylesheetDoc(xsp_doc);
604         if (!xsp)
605         {
606             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
607             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
608             BackendPtr b;
609             xmlFreeDoc(xsp_doc);
610             return b;
611         }
612     }
613
614     m_backend.reset();
615
616     BackendPtr b(new Backend(sptr));
617
618     b->xsp = xsp;
619     b->m_frontend_database = database;
620     std::string authentication = sptr->authentication;
621         
622     b->set_option("timeout", "40");
623
624     if (sptr->query_encoding.length())
625         b->set_option("rpnCharset", sptr->query_encoding.c_str());
626
627     if (sptr->cfAuth.length())
628     {
629         // A CF target
630         b->set_option("user", sptr->cfAuth.c_str());
631         if (authentication.length() && db_args.length() == 0)
632         {
633             // no database (auth) args specified already.. and the
634             // Torus authentication has it.. Generate the args that CF
635             // understands..
636             size_t found = authentication.find('/');
637             if (found != std::string::npos)
638             {
639                 db_args += "user=" + mp::util::uri_encode(authentication.substr(0, found))
640                     + "&password=" + mp::util::uri_encode(authentication.substr(found+1));
641             }
642             else
643                 db_args += "user=" + mp::util::uri_encode(authentication);
644         }
645     }
646     else
647     {
648         // A non-CF target
649         if (db_args.length())
650         {
651             // user has specified backend authentication
652             const char *param_user = 0;
653             const char *param_password = 0;
654             char **names;
655             char **values;
656             int i;
657             int no_parms = yaz_uri_to_array(db_args.c_str(),
658                                             odr, &names, &values);
659             for (i = 0; i < no_parms; i++)
660             {
661                 const char *name = names[i];
662                 const char *value = values[i];
663                 if (!strcmp(name, "user"))
664                     param_user = value;
665                 else if (!strcmp(name, "password"))
666                     param_password = value;
667                 else
668                 {
669                     BackendPtr notfound;
670                     char *msg = (char*) odr_malloc(odr, strlen(name) + 30);
671                     *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
672                     sprintf(msg, "Bad database argument: %s", name);
673                     *addinfo = msg;
674                     return notfound;
675                 }
676             }
677             if (param_user && param_password)
678             {
679                 char *auth = (char*) odr_malloc(
680                     odr, strlen(param_user) + strlen(param_password) + 2);
681                 strcpy(auth, param_user);
682                 strcat(auth, "/");
683                 strcat(auth, param_password);
684                 b->set_option("user", auth);
685             }
686             db_args.clear(); // no arguments to be passed (non-CF)
687         }
688         else
689         {
690             // use authentication from Torus, if given
691             if (authentication.length())
692                 b->set_option("user", authentication.c_str());
693         }
694     }
695     if (sptr->cfProxy.length())
696     {
697         if (db_args.length())
698             db_args += "&";
699         db_args += "proxy=" + mp::util::uri_encode(sptr->cfProxy);
700     }
701     if (sptr->cfSubDb.length())
702     {
703         if (db_args.length())
704             db_args += "&";
705         db_args += "subdatabase=" + mp::util::uri_encode(sptr->cfSubDb);
706     }
707
708     std::string url;
709     if (sptr->sru.length())
710     {
711         url = "http://" + sptr->target;
712         b->set_option("sru", sptr->sru.c_str());
713     }
714     else
715     {
716         url = sptr->target;
717     }
718     if (db_args.length())
719         url += "," + db_args;
720     yaz_log(YLOG_LOG, "url=%s", url.c_str());
721     const char *addinfo_c = 0;
722     b->connect(url, error, &addinfo_c);
723     if (addinfo_c)
724         *addinfo = odr_strdup(odr, addinfo_c);
725     if (*error == 0)
726     {
727         m_backend = b;
728     }
729     return b;
730 }
731
732 Z_Records *yf::Zoom::Frontend::get_records(Odr_int start,
733                                            Odr_int number_to_present,
734                                            int *error,
735                                            const char **addinfo,
736                                            Odr_int *number_of_records_returned,
737                                            ODR odr,
738                                            BackendPtr b,
739                                            Odr_oid *preferredRecordSyntax,
740                                            const char *element_set_name)
741 {
742     *number_of_records_returned = 0;
743     Z_Records *records = 0;
744     bool enable_pz2_retrieval = false; // whether target profile is used
745     bool enable_pz2_transform = false; // whether XSLT is used as well
746     bool assume_marc8_charset = false;
747
748     if (start < 0 || number_to_present <= 0)
749         return records;
750     
751     if (number_to_present > 10000)
752         number_to_present = 10000;
753     
754     ZOOM_record *recs = (ZOOM_record *)
755         odr_malloc(odr, number_to_present * sizeof(*recs));
756
757     char oid_name_str[OID_STR_MAX];
758     const char *syntax_name = 0;
759     
760     if (preferredRecordSyntax &&
761         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
762         && element_set_name)
763     {
764         if (!strcmp(element_set_name, m_p->element_transform.c_str()))
765         {
766             enable_pz2_retrieval = true;
767             enable_pz2_transform = true;
768         }
769         else if (!strcmp(element_set_name, m_p->element_raw.c_str()))
770         {
771             enable_pz2_retrieval = true;
772         }
773     }
774     
775     if (enable_pz2_retrieval)
776     {
777         if (b->sptr->request_syntax.length())
778         {
779             syntax_name = b->sptr->request_syntax.c_str();
780             const Odr_oid *syntax_oid = 
781                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
782             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
783                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
784                 assume_marc8_charset = true;
785         }
786     }
787     else if (preferredRecordSyntax)
788         syntax_name =
789             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
790
791     b->set_option("preferredRecordSyntax", syntax_name);
792
793     if (enable_pz2_retrieval)
794     {
795         element_set_name = 0;
796         if (b->sptr->element_set.length())
797             element_set_name = b->sptr->element_set.c_str();
798     }
799
800     b->set_option("elementSetName", element_set_name);
801
802     b->present(start, number_to_present, recs, error, addinfo);
803
804     Odr_int i = 0;
805     if (!*error)
806     {
807         for (i = 0; i < number_to_present; i++)
808             if (!recs[i])
809                 break;
810     }
811     if (i > 0)
812     {  // only return records if no error and at least one record
813         char *odr_database = odr_strdup(odr,
814                                         b->m_frontend_database.c_str());
815         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
816             odr_malloc(odr, sizeof(*npl));
817         *number_of_records_returned = i;
818         npl->num_records = i;
819         npl->records = (Z_NamePlusRecord **)
820             odr_malloc(odr, i * sizeof(*npl->records));
821         for (i = 0; i < number_to_present; i++)
822         {
823             Z_NamePlusRecord *npr = 0;
824             const char *addinfo;
825             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
826                                               &addinfo, 0 /* diagset */);
827                 
828             if (sur_error)
829             {
830                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
831                                             addinfo);
832             }
833             else if (enable_pz2_retrieval)
834             {
835                 char rec_type_str[100];
836                 const char *record_encoding = 0;
837
838                 if (b->sptr->record_encoding.length())
839                     record_encoding = b->sptr->record_encoding.c_str();
840                 else if (assume_marc8_charset)
841                     record_encoding = "marc8";
842
843                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
844                 if (record_encoding)
845                 {
846                     strcat(rec_type_str, "; charset=");
847                     strcat(rec_type_str, record_encoding);
848                 }
849                 
850                 int rec_len;
851                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
852                                                       &rec_len);
853                 if (rec_buf && b->xsp && enable_pz2_transform)
854                 {
855                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
856                     if (rec_doc)
857                     { 
858                         xmlDoc *rec_res;
859                         rec_res = xsltApplyStylesheet(b->xsp, rec_doc, 0);
860
861                         if (rec_res)
862                             xsltSaveResultToString((xmlChar **) &rec_buf, &rec_len,
863                                                    rec_res, b->xsp);
864                     }
865                 }
866
867                 if (rec_buf)
868                 {
869                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
870                     npr->databaseName = odr_database;
871                     npr->which = Z_NamePlusRecord_databaseRecord;
872                     npr->u.databaseRecord =
873                         z_ext_record_xml(odr, rec_buf, rec_len);
874                 }
875                 else
876                 {
877                     npr = zget_surrogateDiagRec(
878                         odr, odr_database, 
879                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
880                         rec_type_str);
881                 }
882             }
883             else
884             {
885                 Z_External *ext =
886                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
887                 if (ext)
888                 {
889                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
890                     npr->databaseName = odr_database;
891                     npr->which = Z_NamePlusRecord_databaseRecord;
892                     npr->u.databaseRecord = ext;
893                 }
894                 else
895                 {
896                     npr = zget_surrogateDiagRec(
897                         odr, odr_database, 
898                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
899                         "ZOOM_record, type ext");
900                 }
901             }
902             npl->records[i] = npr;
903         }
904         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
905         records->which = Z_Records_DBOSD;
906         records->u.databaseOrSurDiagnostics = npl;
907     }
908     return records;
909 }
910     
911 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
912                                                     ODR odr)
913 {
914     struct cql_node *r = 0;
915     if (!cn)
916         return 0;
917     switch (cn->which)
918     {
919     case CQL_NODE_ST:
920         if (cn->u.st.index)
921         {
922             std::map<std::string,std::string>::const_iterator it;
923             it = fieldmap.find(cn->u.st.index);
924             if (it == fieldmap.end())
925                 return cn;
926             if (it->second.length())
927                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
928             else
929                 cn->u.st.index = 0;
930         }
931         break;
932     case CQL_NODE_BOOL:
933         r = convert_cql_fields(cn->u.boolean.left, odr);
934         if (!r)
935             r = convert_cql_fields(cn->u.boolean.right, odr);
936         break;
937     case CQL_NODE_SORT:
938         r = convert_cql_fields(cn->u.sort.search, odr);
939         break;
940     }
941     return r;
942 }
943
944 void yf::Zoom::Frontend::handle_search(mp::Package &package)
945 {
946     Z_GDU *gdu = package.request().get();
947     Z_APDU *apdu_req = gdu->u.z3950;
948     Z_APDU *apdu_res = 0;
949     mp::odr odr;
950     Z_SearchRequest *sr = apdu_req->u.searchRequest;
951     if (sr->num_databaseNames != 1)
952     {
953         apdu_res = odr.create_searchResponse(
954             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
955         package.response() = apdu_res;
956         return;
957     }
958
959     int error = 0;
960     char *addinfo_s = 0;
961     std::string db(sr->databaseNames[0]);
962     BackendPtr b = get_backend_from_databases(db, &error, &addinfo_s, odr);
963     if (error)
964     {
965         apdu_res = 
966             odr.create_searchResponse(
967                 apdu_req, error, addinfo_s);
968         package.response() = apdu_res;
969         return;
970     }
971
972     const char *addinfo_c = 0;
973     b->set_option("setname", "default");
974
975     Odr_int hits = 0;
976     Z_Query *query = sr->query;
977     WRBUF ccl_wrbuf = 0;
978     WRBUF pqf_wrbuf = 0;
979
980     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
981     {
982         // RPN
983         pqf_wrbuf = wrbuf_alloc();
984         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
985     }
986     else if (query->which == Z_Query_type_2)
987     {
988         // CCL
989         ccl_wrbuf = wrbuf_alloc();
990         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
991                     query->u.type_2->len);
992     }
993     else if (query->which == Z_Query_type_104 &&
994              query->u.type_104->which == Z_External_CQL)
995     {
996         // CQL
997         const char *cql = query->u.type_104->u.cql;
998         CQL_parser cp = cql_parser_create();
999         int r = cql_parser_string(cp, cql);
1000         if (r)
1001         {
1002             cql_parser_destroy(cp);
1003             apdu_res = 
1004                 odr.create_searchResponse(apdu_req, 
1005                                           YAZ_BIB1_MALFORMED_QUERY,
1006                                           "CQL syntax error");
1007             package.response() = apdu_res;
1008             return;
1009         }
1010         struct cql_node *cn = cql_parser_result(cp);
1011         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1012         if (cn_error)
1013         {
1014             // hopefully we are getting a ptr to a index+relation+term node
1015             addinfo_c = 0;
1016             if (cn_error->which == CQL_NODE_ST)
1017                 addinfo_c = cn_error->u.st.index;
1018
1019             apdu_res = 
1020                 odr.create_searchResponse(apdu_req, 
1021                                           YAZ_BIB1_UNSUPP_USE_ATTRIBUTE,
1022                                           addinfo_c);
1023             package.response() = apdu_res;
1024             return;
1025         }
1026         char ccl_buf[1024];
1027
1028         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1029         if (r == 0)
1030         {
1031             ccl_wrbuf = wrbuf_alloc();
1032             wrbuf_puts(ccl_wrbuf, ccl_buf);
1033         }
1034         cql_parser_destroy(cp);
1035         if (r)
1036         {
1037             apdu_res = 
1038                 odr.create_searchResponse(apdu_req, 
1039                                           YAZ_BIB1_MALFORMED_QUERY,
1040                                           "CQL to CCL conversion error");
1041             package.response() = apdu_res;
1042             return;
1043         }
1044     }
1045     else
1046     {
1047         apdu_res = 
1048             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
1049         package.response() = apdu_res;
1050         return;
1051     }
1052
1053     if (ccl_wrbuf)
1054     {
1055         // CCL to PQF
1056         assert(pqf_wrbuf == 0);
1057         int cerror, cpos;
1058         struct ccl_rpn_node *cn;
1059         yaz_log(YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1060         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1061                           &cerror, &cpos);
1062         wrbuf_destroy(ccl_wrbuf);
1063         if (!cn)
1064         {
1065             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1066             int z3950_diag = YAZ_BIB1_MALFORMED_QUERY;
1067
1068             switch (cerror)
1069             {
1070             case CCL_ERR_UNKNOWN_QUAL:
1071                 z3950_diag = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1072                 break;
1073             case CCL_ERR_TRUNC_NOT_LEFT: 
1074             case CCL_ERR_TRUNC_NOT_RIGHT:
1075             case CCL_ERR_TRUNC_NOT_BOTH:
1076                 z3950_diag = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
1077                 break;
1078             }
1079             apdu_res = 
1080                 odr.create_searchResponse(apdu_req, z3950_diag, addinfo);
1081             package.response() = apdu_res;
1082             return;
1083         }
1084         pqf_wrbuf = wrbuf_alloc();
1085         ccl_pquery(pqf_wrbuf, cn);
1086         ccl_rpn_delete(cn);
1087     }
1088     
1089     assert(pqf_wrbuf);
1090     if (b->get_option("sru"))
1091     {
1092         int status = 0;
1093         Z_RPNQuery *zquery;
1094         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1095         WRBUF wrb = wrbuf_alloc();
1096             
1097         if (!strcmp(b->get_option("sru"), "solr"))
1098         {
1099             solr_transform_t cqlt = solr_transform_create();
1100             
1101             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1102             
1103             solr_transform_close(cqlt);
1104         }
1105         else
1106         {
1107             cql_transform_t cqlt = cql_transform_create();
1108             
1109             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1110             
1111             cql_transform_close(cqlt);
1112         }
1113         if (status == 0)
1114         {
1115             yaz_log(YLOG_LOG, "search CQL: %s", wrbuf_cstr(wrb));
1116             b->search_cql(wrbuf_cstr(wrb), &hits, &error, &addinfo_c);
1117         }
1118         
1119         wrbuf_destroy(wrb);
1120         wrbuf_destroy(pqf_wrbuf);
1121         if (status)
1122         {
1123             apdu_res = 
1124                 odr.create_searchResponse(apdu_req, YAZ_BIB1_MALFORMED_QUERY,
1125                                           "can not convert from RPN to CQL/SOLR");
1126             package.response() = apdu_res;
1127             return;
1128         }
1129     }
1130     else
1131     {
1132         yaz_log(YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1133         b->search_pqf(wrbuf_cstr(pqf_wrbuf), &hits, &error, &addinfo_c);
1134         wrbuf_destroy(pqf_wrbuf);
1135     }
1136     
1137     
1138     const char *element_set_name = 0;
1139     Odr_int number_to_present = 0;
1140     if (!error)
1141         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1142     
1143     Odr_int number_of_records_returned = 0;
1144     Z_Records *records = get_records(
1145         0, number_to_present, &error, &addinfo_c,
1146         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1147         element_set_name);
1148     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo_c);
1149     if (records)
1150     {
1151         apdu_res->u.searchResponse->records = records;
1152         apdu_res->u.searchResponse->numberOfRecordsReturned =
1153             odr_intdup(odr, number_of_records_returned);
1154     }
1155     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1156     package.response() = apdu_res;
1157 }
1158
1159 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1160 {
1161     Z_GDU *gdu = package.request().get();
1162     Z_APDU *apdu_req = gdu->u.z3950;
1163     Z_APDU *apdu_res = 0;
1164     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1165
1166     mp::odr odr;
1167     if (!m_backend)
1168     {
1169         package.response() = odr.create_presentResponse(
1170             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1171         return;
1172     }
1173     const char *element_set_name = 0;
1174     Z_RecordComposition *comp = pr->recordComposition;
1175     if (comp && comp->which != Z_RecordComp_simple)
1176     {
1177         package.response() = odr.create_presentResponse(
1178             apdu_req, 
1179             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1180         return;
1181     }
1182     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1183         element_set_name = comp->u.simple->u.generic;
1184     Odr_int number_of_records_returned = 0;
1185     int error = 0;
1186     const char *addinfo = 0;
1187     Z_Records *records = get_records(
1188         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1189         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1190         pr->preferredRecordSyntax, element_set_name);
1191
1192     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1193     if (records)
1194     {
1195         apdu_res->u.presentResponse->records = records;
1196         apdu_res->u.presentResponse->numberOfRecordsReturned =
1197             odr_intdup(odr, number_of_records_returned);
1198     }
1199     package.response() = apdu_res;
1200 }
1201
1202 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1203 {
1204     Z_GDU *gdu = package.request().get();
1205     if (!gdu)
1206         ;
1207     else if (gdu->which == Z_GDU_Z3950)
1208     {
1209         Z_APDU *apdu_req = gdu->u.z3950;
1210         if (apdu_req->which == Z_APDU_initRequest)
1211         {
1212             mp::odr odr;
1213             package.response() = odr.create_close(
1214                 apdu_req,
1215                 Z_Close_protocolError,
1216                 "double init");
1217         }
1218         else if (apdu_req->which == Z_APDU_searchRequest)
1219         {
1220             handle_search(package);
1221         }
1222         else if (apdu_req->which == Z_APDU_presentRequest)
1223         {
1224             handle_present(package);
1225         }
1226         else
1227         {
1228             mp::odr odr;
1229             package.response() = odr.create_close(
1230                 apdu_req,
1231                 Z_Close_protocolError,
1232                 "zoom filter cannot handle this APDU");
1233             package.session().close();
1234         }
1235     }
1236     else
1237     {
1238         package.session().close();
1239     }
1240 }
1241
1242 void yf::Zoom::Impl::process(mp::Package &package)
1243 {
1244     FrontendPtr f = get_frontend(package);
1245     Z_GDU *gdu = package.request().get();
1246
1247     if (f->m_is_virtual)
1248     {
1249         f->handle_package(package);
1250     }
1251     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1252              Z_APDU_initRequest)
1253     {
1254         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1255         f->m_init_gdu = gdu;
1256         
1257         mp::odr odr;
1258         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1259         Z_InitResponse *resp = apdu->u.initResponse;
1260         
1261         int i;
1262         static const int masks[] = {
1263             Z_Options_search,
1264             Z_Options_present,
1265             -1 
1266         };
1267         for (i = 0; masks[i] != -1; i++)
1268             if (ODR_MASK_GET(req->options, masks[i]))
1269                 ODR_MASK_SET(resp->options, masks[i]);
1270         
1271         static const int versions[] = {
1272             Z_ProtocolVersion_1,
1273             Z_ProtocolVersion_2,
1274             Z_ProtocolVersion_3,
1275             -1
1276         };
1277         for (i = 0; versions[i] != -1; i++)
1278             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1279                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1280             else
1281                 break;
1282         
1283         *resp->preferredMessageSize = *req->preferredMessageSize;
1284         *resp->maximumRecordSize = *req->maximumRecordSize;
1285         
1286         package.response() = apdu;
1287         f->m_is_virtual = true;
1288     }
1289     else
1290         package.move();
1291
1292     release_frontend(package);
1293 }
1294
1295
1296 static mp::filter::Base* filter_creator()
1297 {
1298     return new mp::filter::Zoom;
1299 }
1300
1301 extern "C" {
1302     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1303         0,
1304         "zoom",
1305         filter_creator
1306     };
1307 }
1308
1309
1310 /*
1311  * Local variables:
1312  * c-basic-offset: 4
1313  * c-file-style: "Stroustrup"
1314  * indent-tabs-mode: nil
1315  * End:
1316  * vim: shiftwidth=4 tabstop=8 expandtab
1317  */
1318