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