Do not require requestsyntax to be set for pp2 transforms
[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                 syntax_name = b->sptr->request_syntax.c_str();
654             enable_pz2_transform = true;
655         }
656         else
657         {
658             syntax_name =
659                 yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
660         }
661     }
662
663     b->set_option("preferredRecordSyntax", syntax_name);
664
665     if (enable_pz2_transform)
666     {
667         element_set_name = "F";
668         if (b->sptr->element_set.length())
669             element_set_name = b->sptr->element_set.c_str();
670     }
671
672     b->set_option("elementSetName", element_set_name);
673
674     b->present(start, number_to_present, recs, error, addinfo);
675
676     Odr_int i = 0;
677     if (!*error)
678     {
679         for (i = 0; i < number_to_present; i++)
680             if (!recs[i])
681                 break;
682     }
683     if (i > 0)
684     {  // only return records if no error and at least one record
685         char *odr_database = odr_strdup(odr,
686                                         b->m_frontend_database.c_str());
687         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
688             odr_malloc(odr, sizeof(*npl));
689         *number_of_records_returned = i;
690         npl->num_records = i;
691         npl->records = (Z_NamePlusRecord **)
692             odr_malloc(odr, i * sizeof(*npl->records));
693         for (i = 0; i < number_to_present; i++)
694         {
695             Z_NamePlusRecord *npr = 0;
696             const char *addinfo;
697             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
698                                               &addinfo, 0 /* diagset */);
699                 
700             if (sur_error)
701             {
702                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
703                                             addinfo);
704             }
705             else if (enable_pz2_transform)
706             {
707                 char rec_type_str[100];
708
709                 strcpy(rec_type_str, b->sptr->use_turbomarc ?
710                        "txml" : "xml");
711                 
712                 // prevent buffer overflow ...
713                 if (b->sptr->record_encoding.length() > 0 &&
714                     b->sptr->record_encoding.length() < 
715                     (sizeof(rec_type_str)-20))
716                 {
717                     strcat(rec_type_str, "; charset=");
718                     strcat(rec_type_str, b->sptr->record_encoding.c_str());
719                 }
720                 
721                 int rec_len;
722                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
723                                                       &rec_len);
724                 if (rec_buf && b->xsp)
725                 {
726                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
727                     if (rec_doc)
728                     { 
729                         xmlDoc *rec_res;
730                         rec_res = xsltApplyStylesheet(b->xsp, rec_doc, 0);
731
732                         if (rec_res)
733                             xsltSaveResultToString((xmlChar **) &rec_buf, &rec_len,
734                                                    rec_res, b->xsp);
735                     }
736                 }
737
738                 if (rec_buf)
739                 {
740                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
741                     npr->databaseName = odr_database;
742                     npr->which = Z_NamePlusRecord_databaseRecord;
743                     npr->u.databaseRecord =
744                         z_ext_record_xml(odr, rec_buf, rec_len);
745                 }
746                 else
747                 {
748                     npr = zget_surrogateDiagRec(
749                         odr, odr_database, 
750                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
751                         rec_type_str);
752                 }
753             }
754             else
755             {
756                 Z_External *ext =
757                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
758                 if (ext)
759                 {
760                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
761                     npr->databaseName = odr_database;
762                     npr->which = Z_NamePlusRecord_databaseRecord;
763                     npr->u.databaseRecord = ext;
764                 }
765                 else
766                 {
767                     npr = zget_surrogateDiagRec(
768                         odr, odr_database, 
769                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
770                         "ZOOM_record, type ext");
771                 }
772             }
773             npl->records[i] = npr;
774         }
775         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
776         records->which = Z_Records_DBOSD;
777         records->u.databaseOrSurDiagnostics = npl;
778     }
779     return records;
780 }
781     
782 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
783                                                     ODR odr)
784 {
785     struct cql_node *r = 0;
786     if (!cn)
787         return 0;
788     switch (cn->which)
789     {
790     case CQL_NODE_ST:
791         if (cn->u.st.index)
792         {
793             std::map<std::string,std::string>::const_iterator it;
794             it = fieldmap.find(cn->u.st.index);
795             if (it == fieldmap.end())
796                 return cn;
797             if (it->second.length())
798                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
799             else
800                 cn->u.st.index = 0;
801         }
802         break;
803     case CQL_NODE_BOOL:
804         r = convert_cql_fields(cn->u.boolean.left, odr);
805         if (!r)
806             r = convert_cql_fields(cn->u.boolean.right, odr);
807         break;
808     case CQL_NODE_SORT:
809         r = convert_cql_fields(cn->u.sort.search, odr);
810         break;
811     }
812     return r;
813 }
814
815 void yf::Zoom::Frontend::handle_search(mp::Package &package)
816 {
817     Z_GDU *gdu = package.request().get();
818     Z_APDU *apdu_req = gdu->u.z3950;
819     Z_APDU *apdu_res = 0;
820     mp::odr odr;
821     Z_SearchRequest *sr = apdu_req->u.searchRequest;
822     if (sr->num_databaseNames != 1)
823     {
824         apdu_res = odr.create_searchResponse(
825             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
826         package.response() = apdu_res;
827         return;
828     }
829
830     int error = 0;
831     const char *addinfo = 0;
832     std::string db(sr->databaseNames[0]);
833     BackendPtr b = get_backend_from_databases(db, &error, &addinfo);
834     if (error)
835     {
836         apdu_res = 
837             odr.create_searchResponse(
838                 apdu_req, error, addinfo);
839         package.response() = apdu_res;
840         return;
841     }
842
843     b->set_option("setname", "default");
844
845     Odr_int hits = 0;
846     Z_Query *query = sr->query;
847     WRBUF ccl_wrbuf = 0;
848     WRBUF pqf_wrbuf = 0;
849
850     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
851     {
852         // RPN
853         pqf_wrbuf = wrbuf_alloc();
854         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
855     }
856     else if (query->which == Z_Query_type_2)
857     {
858         // CCL
859         ccl_wrbuf = wrbuf_alloc();
860         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
861                     query->u.type_2->len);
862     }
863     else if (query->which == Z_Query_type_104 &&
864              query->u.type_104->which == Z_External_CQL)
865     {
866         // CQL
867         const char *cql = query->u.type_104->u.cql;
868         CQL_parser cp = cql_parser_create();
869         int r = cql_parser_string(cp, cql);
870         if (r)
871         {
872             cql_parser_destroy(cp);
873             apdu_res = 
874                 odr.create_searchResponse(apdu_req, 
875                                           YAZ_BIB1_MALFORMED_QUERY,
876                                           "CQL syntax error");
877             package.response() = apdu_res;
878             return;
879         }
880         struct cql_node *cn = cql_parser_result(cp);
881         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
882         if (cn_error)
883         {
884             // hopefully we are getting a ptr to a index+relation+term node
885             addinfo = 0;
886             if (cn_error->which == CQL_NODE_ST)
887                 addinfo = cn_error->u.st.index;
888
889             apdu_res = 
890                 odr.create_searchResponse(apdu_req, 
891                                           YAZ_BIB1_UNSUPP_USE_ATTRIBUTE,
892                                           addinfo);
893             package.response() = apdu_res;
894             return;
895         }
896         char ccl_buf[1024];
897
898         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
899         if (r == 0)
900         {
901             ccl_wrbuf = wrbuf_alloc();
902             wrbuf_puts(ccl_wrbuf, ccl_buf);
903         }
904         cql_parser_destroy(cp);
905         if (r)
906         {
907             apdu_res = 
908                 odr.create_searchResponse(apdu_req, 
909                                           YAZ_BIB1_MALFORMED_QUERY,
910                                           "CQL to CCL conversion error");
911             package.response() = apdu_res;
912             return;
913         }
914     }
915     else
916     {
917         apdu_res = 
918             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
919         package.response() = apdu_res;
920         return;
921     }
922
923     if (ccl_wrbuf)
924     {
925         // CCL to PQF
926         assert(pqf_wrbuf == 0);
927         int cerror, cpos;
928         struct ccl_rpn_node *cn;
929         yaz_log(YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
930         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
931                           &cerror, &cpos);
932         wrbuf_destroy(ccl_wrbuf);
933         if (!cn)
934         {
935             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
936             int z3950_diag = YAZ_BIB1_MALFORMED_QUERY;
937
938             switch (cerror)
939             {
940             case CCL_ERR_UNKNOWN_QUAL:
941                 z3950_diag = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
942                 break;
943             case CCL_ERR_TRUNC_NOT_LEFT: 
944             case CCL_ERR_TRUNC_NOT_RIGHT:
945             case CCL_ERR_TRUNC_NOT_BOTH:
946                 z3950_diag = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
947                 break;
948             }
949             apdu_res = 
950                 odr.create_searchResponse(apdu_req, z3950_diag, addinfo);
951             package.response() = apdu_res;
952             return;
953         }
954         pqf_wrbuf = wrbuf_alloc();
955         ccl_pquery(pqf_wrbuf, cn);
956         ccl_rpn_delete(cn);
957     }
958     
959     assert(pqf_wrbuf);
960     if (b->get_option("sru"))
961     {
962         int status = 0;
963         Z_RPNQuery *zquery;
964         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
965         WRBUF wrb = wrbuf_alloc();
966             
967         if (!strcmp(b->get_option("sru"), "solr"))
968         {
969             solr_transform_t cqlt = solr_transform_create();
970             
971             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
972             
973             solr_transform_close(cqlt);
974         }
975         else
976         {
977             cql_transform_t cqlt = cql_transform_create();
978             
979             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
980             
981             cql_transform_close(cqlt);
982         }
983         if (status == 0)
984         {
985             yaz_log(YLOG_LOG, "search CQL: %s", wrbuf_cstr(wrb));
986             b->search_cql(wrbuf_cstr(wrb), &hits, &error, &addinfo);
987         }
988         
989         wrbuf_destroy(wrb);
990         wrbuf_destroy(pqf_wrbuf);
991         if (status)
992         {
993             apdu_res = 
994                 odr.create_searchResponse(apdu_req, YAZ_BIB1_MALFORMED_QUERY,
995                                           "can not convert from RPN to CQL/SOLR");
996             package.response() = apdu_res;
997             return;
998         }
999     }
1000     else
1001     {
1002         yaz_log(YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1003         b->search_pqf(wrbuf_cstr(pqf_wrbuf), &hits, &error, &addinfo);
1004         wrbuf_destroy(pqf_wrbuf);
1005     }
1006     
1007     
1008     const char *element_set_name = 0;
1009     Odr_int number_to_present = 0;
1010     if (!error)
1011         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1012     
1013     Odr_int number_of_records_returned = 0;
1014     Z_Records *records = get_records(
1015         0, number_to_present, &error, &addinfo,
1016         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1017         element_set_name);
1018     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1019     if (records)
1020     {
1021         apdu_res->u.searchResponse->records = records;
1022         apdu_res->u.searchResponse->numberOfRecordsReturned =
1023             odr_intdup(odr, number_of_records_returned);
1024     }
1025     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1026     package.response() = apdu_res;
1027 }
1028
1029 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1030 {
1031     Z_GDU *gdu = package.request().get();
1032     Z_APDU *apdu_req = gdu->u.z3950;
1033     Z_APDU *apdu_res = 0;
1034     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1035
1036     mp::odr odr;
1037     if (!m_backend)
1038     {
1039         package.response() = odr.create_presentResponse(
1040             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1041         return;
1042     }
1043     const char *element_set_name = 0;
1044     Z_RecordComposition *comp = pr->recordComposition;
1045     if (comp && comp->which != Z_RecordComp_simple)
1046     {
1047         package.response() = odr.create_presentResponse(
1048             apdu_req, 
1049             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1050         return;
1051     }
1052     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1053         element_set_name = comp->u.simple->u.generic;
1054     Odr_int number_of_records_returned = 0;
1055     int error = 0;
1056     const char *addinfo = 0;
1057     Z_Records *records = get_records(
1058         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1059         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1060         pr->preferredRecordSyntax, element_set_name);
1061
1062     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1063     if (records)
1064     {
1065         apdu_res->u.presentResponse->records = records;
1066         apdu_res->u.presentResponse->numberOfRecordsReturned =
1067             odr_intdup(odr, number_of_records_returned);
1068     }
1069     package.response() = apdu_res;
1070 }
1071
1072 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1073 {
1074     Z_GDU *gdu = package.request().get();
1075     if (!gdu)
1076         ;
1077     else if (gdu->which == Z_GDU_Z3950)
1078     {
1079         Z_APDU *apdu_req = gdu->u.z3950;
1080         if (apdu_req->which == Z_APDU_initRequest)
1081         {
1082             mp::odr odr;
1083             package.response() = odr.create_close(
1084                 apdu_req,
1085                 Z_Close_protocolError,
1086                 "double init");
1087         }
1088         else if (apdu_req->which == Z_APDU_searchRequest)
1089         {
1090             handle_search(package);
1091         }
1092         else if (apdu_req->which == Z_APDU_presentRequest)
1093         {
1094             handle_present(package);
1095         }
1096         else
1097         {
1098             mp::odr odr;
1099             package.response() = odr.create_close(
1100                 apdu_req,
1101                 Z_Close_protocolError,
1102                 "zoom filter cannot handle this APDU");
1103             package.session().close();
1104         }
1105     }
1106     else
1107     {
1108         package.session().close();
1109     }
1110 }
1111
1112 void yf::Zoom::Impl::process(mp::Package &package)
1113 {
1114     FrontendPtr f = get_frontend(package);
1115     Z_GDU *gdu = package.request().get();
1116
1117     if (f->m_is_virtual)
1118     {
1119         f->handle_package(package);
1120     }
1121     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1122              Z_APDU_initRequest)
1123     {
1124         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1125         f->m_init_gdu = gdu;
1126         
1127         mp::odr odr;
1128         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1129         Z_InitResponse *resp = apdu->u.initResponse;
1130         
1131         int i;
1132         static const int masks[] = {
1133             Z_Options_search,
1134             Z_Options_present,
1135             -1 
1136         };
1137         for (i = 0; masks[i] != -1; i++)
1138             if (ODR_MASK_GET(req->options, masks[i]))
1139                 ODR_MASK_SET(resp->options, masks[i]);
1140         
1141         static const int versions[] = {
1142             Z_ProtocolVersion_1,
1143             Z_ProtocolVersion_2,
1144             Z_ProtocolVersion_3,
1145             -1
1146         };
1147         for (i = 0; versions[i] != -1; i++)
1148             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1149                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1150             else
1151                 break;
1152         
1153         *resp->preferredMessageSize = *req->preferredMessageSize;
1154         *resp->maximumRecordSize = *req->maximumRecordSize;
1155         
1156         package.response() = apdu;
1157         f->m_is_virtual = true;
1158     }
1159     else
1160         package.move();
1161
1162     release_frontend(package);
1163 }
1164
1165
1166 static mp::filter::Base* filter_creator()
1167 {
1168     return new mp::filter::Zoom;
1169 }
1170
1171 extern "C" {
1172     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1173         0,
1174         "zoom",
1175         filter_creator
1176     };
1177 }
1178
1179
1180 /*
1181  * Local variables:
1182  * c-basic-offset: 4
1183  * c-file-style: "Stroustrup"
1184  * indent-tabs-mode: nil
1185  * End:
1186  * vim: shiftwidth=4 tabstop=8 expandtab
1187  */
1188