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