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