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