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