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