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