zoom: accept and relay db args x-name to CF targets
[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
21 #include <stdlib.h>
22 #include <sys/types.h>
23 #include "filter_zoom.hpp"
24 #include <yaz/zoom.h>
25 #include <yaz/yaz-version.h>
26 #include <yaz/tpath.h>
27 #include <yaz/srw.h>
28 #include <metaproxy/package.hpp>
29 #include <metaproxy/util.hpp>
30 #include <metaproxy/xmlutil.hpp>
31 #include "torus.hpp"
32
33 #include <libxslt/xsltutils.h>
34 #include <libxslt/transform.h>
35
36 #include <boost/thread/mutex.hpp>
37 #include <boost/thread/condition.hpp>
38 #include <yaz/ccl_xml.h>
39 #include <yaz/ccl.h>
40 #include <yaz/rpn2cql.h>
41 #include <yaz/rpn2solr.h>
42 #include <yaz/pquery.h>
43 #include <yaz/cql.h>
44 #include <yaz/oid_db.h>
45 #include <yaz/diagbib1.h>
46 #include <yaz/log.h>
47 #include <yaz/zgdu.h>
48 #include <yaz/querytowrbuf.h>
49 #include <yaz/sortspec.h>
50 #include <yaz/tokenizer.h>
51
52 namespace mp = metaproxy_1;
53 namespace yf = mp::filter;
54
55 namespace metaproxy_1 {
56     namespace filter {
57         class Zoom::Searchable : boost::noncopyable {
58           public:
59             std::string authentication;
60             std::string cfAuth;
61             std::string cfProxy;
62             std::string cfSubDb;
63             std::string udb;
64             std::string target;
65             std::string query_encoding;
66             std::string sru;
67             std::string request_syntax;
68             std::string element_set;
69             std::string record_encoding;
70             std::string transform_xsl_fname;
71             std::string transform_xsl_content;
72             std::string urlRecipe;
73             std::string contentConnector;
74             std::string sortStrategy;
75             bool use_turbomarc;
76             bool piggyback;
77             CCL_bibset ccl_bibset;
78             std::map<std::string, std::string> sortmap;
79             Searchable(CCL_bibset base);
80             ~Searchable();
81         };
82         class Zoom::Backend : boost::noncopyable {
83             friend class Impl;
84             friend class Frontend;
85             std::string zurl;
86             ZOOM_connection m_connection;
87             ZOOM_resultset m_resultset;
88             std::string m_frontend_database;
89             SearchablePtr sptr;
90             xsltStylesheetPtr xsp;
91             std::string content_session_id;
92         public:
93             Backend(SearchablePtr sptr);
94             ~Backend();
95             void connect(std::string zurl, int *error, char **addinfo,
96                          ODR odr);
97             void search(ZOOM_query q, Odr_int *hits,
98                         int *error, char **addinfo, ODR odr);
99             void present(Odr_int start, Odr_int number, ZOOM_record *recs,
100                          int *error, char **addinfo, ODR odr);
101             void set_option(const char *name, const char *value);
102             void set_option(const char *name, std::string value);
103             const char *get_option(const char *name);
104             void get_zoom_error(int *error, char **addinfo, ODR odr);
105         };
106         class Zoom::Frontend : boost::noncopyable {
107             friend class Impl;
108             Impl *m_p;
109             bool m_is_virtual;
110             bool m_in_use;
111             yazpp_1::GDU m_init_gdu;
112             BackendPtr m_backend;
113             void handle_package(mp::Package &package);
114             void handle_search(mp::Package &package);
115             void handle_present(mp::Package &package);
116             BackendPtr get_backend_from_databases(const mp::Package &package,
117                                                   std::string &database,
118                                                   int *error,
119                                                   char **addinfo,
120                                                   ODR odr);
121
122
123             void prepare_elements(BackendPtr b,
124                                   Odr_oid *preferredRecordSyntax,
125                                   const char *element_set_name,
126                                   bool &enable_pz2_retrieval,
127                                   bool &enable_pz2_transform,
128                                   bool &assume_marc8_charset);
129
130             Z_Records *get_records(Odr_int start,
131                                    Odr_int number_to_present,
132                                    int *error,
133                                    char **addinfo,
134                                    Odr_int *number_of_records_returned,
135                                    ODR odr, BackendPtr b,
136                                    Odr_oid *preferredRecordSyntax,
137                                    const char *element_set_name);
138         public:
139             Frontend(Impl *impl);
140             ~Frontend();
141         };
142         class Zoom::Impl {
143             friend class Frontend;
144         public:
145             Impl();
146             ~Impl();
147             void process(metaproxy_1::Package & package);
148             void configure(const xmlNode * ptr, bool test_only,
149                            const char *path);
150         private:
151             void configure_local_records(const xmlNode * ptr, bool test_only);
152             FrontendPtr get_frontend(mp::Package &package);
153             void release_frontend(mp::Package &package);
154             SearchablePtr parse_torus_record(const xmlNode *ptr);
155             struct cql_node *convert_cql_fields(struct cql_node *cn, ODR odr);
156             std::map<mp::Session, FrontendPtr> m_clients;            
157             boost::mutex m_mutex;
158             boost::condition m_cond_session_ready;
159             std::string torus_url;
160             std::map<std::string,std::string> fieldmap;
161             std::string xsldir;
162             std::string file_path;
163             std::string content_proxy_server;
164             std::string content_tmp_file;
165             bool apdu_log;
166             CCL_bibset bibset;
167             std::string element_transform;
168             std::string element_raw;
169             std::string proxy;
170             std::map<std::string,SearchablePtr> s_map;
171         };
172     }
173 }
174
175 // define Pimpl wrapper forwarding to Impl
176  
177 yf::Zoom::Zoom() : m_p(new Impl)
178 {
179 }
180
181 yf::Zoom::~Zoom()
182 {  // must have a destructor because of boost::scoped_ptr
183 }
184
185 void yf::Zoom::configure(const xmlNode *xmlnode, bool test_only,
186                          const char *path)
187 {
188     m_p->configure(xmlnode, test_only, path);
189 }
190
191 void yf::Zoom::process(mp::Package &package) const
192 {
193     m_p->process(package);
194 }
195
196
197 // define Implementation stuff
198
199 yf::Zoom::Backend::Backend(SearchablePtr ptr) : sptr(ptr)
200 {
201     m_connection = ZOOM_connection_create(0);
202     m_resultset = 0;
203     xsp = 0;
204 }
205
206 yf::Zoom::Backend::~Backend()
207 {
208     if (xsp)
209         xsltFreeStylesheet(xsp);
210     ZOOM_connection_destroy(m_connection);
211     ZOOM_resultset_destroy(m_resultset);
212 }
213
214
215 void yf::Zoom::Backend::get_zoom_error(int *error, char **addinfo,
216                                        ODR odr)
217 {
218     const char *msg = 0;
219     const char *zoom_addinfo = 0;
220     const char *dset = 0;
221     *error = ZOOM_connection_error_x(m_connection, &msg, &zoom_addinfo, &dset);
222     if (*error)
223     {
224         if (*error >= ZOOM_ERROR_CONNECT)
225         {
226             // turn ZOOM diagnostic into a Bib-1 2: with addinfo=zoom err msg
227             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
228             *addinfo = (char *) odr_malloc(
229                 odr, 20 + strlen(msg) + 
230                 (zoom_addinfo ? strlen(zoom_addinfo) : 0));
231             strcpy(*addinfo, msg);
232             if (zoom_addinfo)
233             {
234                 strcat(*addinfo, ": ");
235                 strcat(*addinfo, zoom_addinfo);
236                 strcat(*addinfo, " ");
237             }
238         }
239         else
240         {
241             if (dset && !strcmp(dset, "info:srw/diagnostic/1"))
242                 *error = yaz_diag_srw_to_bib1(*error);
243             *addinfo = (char *) odr_malloc(
244                 odr, 20 + (zoom_addinfo ? strlen(zoom_addinfo) : 0));
245             **addinfo = '\0';
246             if (zoom_addinfo && *zoom_addinfo)
247             {
248                 strcpy(*addinfo, zoom_addinfo);
249                 strcat(*addinfo, " ");
250             }
251             strcat(*addinfo, "(backend)");
252         }
253     }
254 }
255
256 void yf::Zoom::Backend::connect(std::string zurl,
257                                 int *error, char **addinfo,
258                                 ODR odr)
259 {
260     ZOOM_connection_connect(m_connection, zurl.c_str(), 0);
261     get_zoom_error(error, addinfo, odr);
262 }
263
264 void yf::Zoom::Backend::search(ZOOM_query q, Odr_int *hits,
265                                int *error, char **addinfo, ODR odr)
266 {
267     m_resultset = ZOOM_connection_search(m_connection, q);
268     get_zoom_error(error, addinfo, odr);
269     if (*error == 0)
270         *hits = ZOOM_resultset_size(m_resultset);
271     else
272         *hits = 0;
273 }
274
275 void yf::Zoom::Backend::present(Odr_int start, Odr_int number,
276                                 ZOOM_record *recs,
277                                 int *error, char **addinfo, ODR odr)
278 {
279     ZOOM_resultset_records(m_resultset, recs, start, number);
280     get_zoom_error(error, addinfo, odr);
281 }
282
283 void yf::Zoom::Backend::set_option(const char *name, const char *value)
284 {
285     ZOOM_connection_option_set(m_connection, name, value);
286     if (m_resultset)
287         ZOOM_resultset_option_set(m_resultset, name, value);
288 }
289
290 void yf::Zoom::Backend::set_option(const char *name, std::string value)
291 {
292     set_option(name, value.c_str());
293 }
294
295 const char *yf::Zoom::Backend::get_option(const char *name)
296 {
297     return ZOOM_connection_option_get(m_connection, name);
298 }
299
300 yf::Zoom::Searchable::Searchable(CCL_bibset base)
301 {
302     piggyback = true;
303     use_turbomarc = true;
304     sortStrategy = "embed";
305     ccl_bibset = ccl_qual_dup(base);
306 }
307
308 yf::Zoom::Searchable::~Searchable()
309 {
310     ccl_qual_rm(&ccl_bibset);
311 }
312
313 yf::Zoom::Frontend::Frontend(Impl *impl) : 
314     m_p(impl), m_is_virtual(false), m_in_use(true)
315 {
316 }
317
318 yf::Zoom::Frontend::~Frontend()
319 {
320 }
321
322 yf::Zoom::FrontendPtr yf::Zoom::Impl::get_frontend(mp::Package &package)
323 {
324     boost::mutex::scoped_lock lock(m_mutex);
325
326     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
327     
328     while(true)
329     {
330         it = m_clients.find(package.session());
331         if (it == m_clients.end())
332             break;
333         
334         if (!it->second->m_in_use)
335         {
336             it->second->m_in_use = true;
337             return it->second;
338         }
339         m_cond_session_ready.wait(lock);
340     }
341     FrontendPtr f(new Frontend(this));
342     m_clients[package.session()] = f;
343     f->m_in_use = true;
344     return f;
345 }
346
347 void yf::Zoom::Impl::release_frontend(mp::Package &package)
348 {
349     boost::mutex::scoped_lock lock(m_mutex);
350     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
351     
352     it = m_clients.find(package.session());
353     if (it != m_clients.end())
354     {
355         if (package.session().is_closed())
356         {
357             m_clients.erase(it);
358         }
359         else
360         {
361             it->second->m_in_use = false;
362         }
363         m_cond_session_ready.notify_all();
364     }
365 }
366
367 yf::Zoom::Impl::Impl() :
368     apdu_log(false), element_transform("pz2") , element_raw("raw")
369 {
370     bibset = ccl_qual_mk();
371
372     srand((unsigned int) time(0));
373 }
374
375 yf::Zoom::Impl::~Impl()
376
377     ccl_qual_rm(&bibset);
378 }
379
380 yf::Zoom::SearchablePtr yf::Zoom::Impl::parse_torus_record(const xmlNode *ptr)
381 {
382     Zoom::SearchablePtr s(new Searchable(bibset));
383     
384     for (ptr = ptr->children; ptr; ptr = ptr->next)
385     {
386         if (ptr->type != XML_ELEMENT_NODE)
387             continue;
388         if (!strcmp((const char *) ptr->name, "layer"))
389             ptr = ptr->children;
390         else if (!strcmp((const char *) ptr->name,
391                          "authentication"))
392         {
393             s->authentication = mp::xml::get_text(ptr);
394         }
395         else if (!strcmp((const char *) ptr->name,
396                          "cfAuth"))
397         {
398             s->cfAuth = mp::xml::get_text(ptr);
399         } 
400         else if (!strcmp((const char *) ptr->name,
401                          "cfProxy"))
402         {
403             s->cfProxy = mp::xml::get_text(ptr);
404         }  
405         else if (!strcmp((const char *) ptr->name,
406                          "cfSubDb"))
407         {
408             s->cfSubDb = mp::xml::get_text(ptr);
409         }  
410         else if (!strcmp((const char *) ptr->name,
411                          "contentConnector"))
412         {
413             s->contentConnector = mp::xml::get_text(ptr);
414         }  
415         else if (!strcmp((const char *) ptr->name, "udb"))
416         {
417             s->udb = mp::xml::get_text(ptr);
418         }
419         else if (!strcmp((const char *) ptr->name, "zurl"))
420         {
421             s->target = mp::xml::get_text(ptr);
422         }
423         else if (!strcmp((const char *) ptr->name, "sru"))
424         {
425             s->sru = mp::xml::get_text(ptr);
426         }
427         else if (!strcmp((const char *) ptr->name,
428                          "queryEncoding"))
429         {
430             s->query_encoding = mp::xml::get_text(ptr);
431         }
432         else if (!strcmp((const char *) ptr->name,
433                          "piggyback"))
434         {
435             s->piggyback = mp::xml::get_bool(ptr, true);
436         }
437         else if (!strcmp((const char *) ptr->name,
438                          "requestSyntax"))
439         {
440             s->request_syntax = mp::xml::get_text(ptr);
441         }
442         else if (!strcmp((const char *) ptr->name,
443                          "elementSet"))
444         {
445             s->element_set = mp::xml::get_text(ptr);
446         }
447         else if (!strcmp((const char *) ptr->name,
448                          "recordEncoding"))
449         {
450             s->record_encoding = mp::xml::get_text(ptr);
451         }
452         else if (!strcmp((const char *) ptr->name,
453                          "transform"))
454         {
455             s->transform_xsl_fname = mp::xml::get_text(ptr);
456         }
457         else if (!strcmp((const char *) ptr->name,
458                          "literalTransform"))
459         {
460             s->transform_xsl_content = mp::xml::get_text(ptr);
461         }
462         else if (!strcmp((const char *) ptr->name,
463                          "urlRecipe"))
464         {
465             s->urlRecipe = mp::xml::get_text(ptr);
466         }
467         else if (!strcmp((const char *) ptr->name,
468                          "useTurboMarc"))
469         {
470             ; // useTurboMarc is ignored
471         }
472         else if (!strncmp((const char *) ptr->name,
473                           "cclmap_", 7))
474         {
475             std::string value = mp::xml::get_text(ptr);
476             ccl_qual_fitem(s->ccl_bibset, value.c_str(),
477                            (const char *) ptr->name + 7);
478         }
479         else if (!strncmp((const char *) ptr->name,
480                           "sortmap_", 8))
481         {
482             std::string value = mp::xml::get_text(ptr);
483             s->sortmap[(const char *) ptr->name + 8] = value;
484         }
485         else if (!strcmp((const char *) ptr->name,
486                           "sortStrategy"))
487         {
488             s->sortStrategy = mp::xml::get_text(ptr);
489         }
490     }
491     return s;
492 }
493
494 void yf::Zoom::Impl::configure_local_records(const xmlNode *ptr, bool test_only)
495 {
496     while (ptr && ptr->type != XML_ELEMENT_NODE)
497         ptr = ptr->next;
498     
499     if (ptr)
500     {
501         if (!strcmp((const char *) ptr->name, "records"))
502         {
503             for (ptr = ptr->children; ptr; ptr = ptr->next)
504             {
505                 if (ptr->type != XML_ELEMENT_NODE)
506                     continue;
507                 if (!strcmp((const char *) ptr->name, "record"))
508                 {
509                     SearchablePtr s = parse_torus_record(ptr);
510                     if (s)
511                     {
512                         std::string udb = s->udb;
513                         if (udb.length())
514                             s_map[s->udb] = s;
515                         else
516                         {
517                             throw mp::filter::FilterException
518                                 ("No udb for local torus record");
519                         }
520                     }
521                 }
522                 else
523                 {
524                     throw mp::filter::FilterException
525                         ("Bad element " 
526                          + std::string((const char *) ptr->name)
527                          + " in zoom filter inside element "
528                          "<torus><records>");
529                 }
530             }
531         }
532         else
533         {
534             throw mp::filter::FilterException
535                 ("Bad element " 
536                  + std::string((const char *) ptr->name)
537                  + " in zoom filter inside element <torus>");
538         }
539     }
540 }
541
542 void yf::Zoom::Impl::configure(const xmlNode *ptr, bool test_only,
543                                const char *path)
544 {
545     content_tmp_file = "/tmp/cf.XXXXXX.p";
546     if (path && *path)
547     {
548         file_path = path;
549     }
550     for (ptr = ptr->children; ptr; ptr = ptr->next)
551     {
552         if (ptr->type != XML_ELEMENT_NODE)
553             continue;
554         else if (!strcmp((const char *) ptr->name, "torus"))
555         {
556             const struct _xmlAttr *attr;
557             for (attr = ptr->properties; attr; attr = attr->next)
558             {
559                 if (!strcmp((const char *) attr->name, "url"))
560                     torus_url = mp::xml::get_text(attr->children);
561                 else if (!strcmp((const char *) attr->name, "xsldir"))
562                     xsldir = mp::xml::get_text(attr->children);
563                 else if (!strcmp((const char *) attr->name, "element_transform"))
564                     element_transform = mp::xml::get_text(attr->children);
565                 else if (!strcmp((const char *) attr->name, "element_raw"))
566                     element_raw = mp::xml::get_text(attr->children);
567                 else if (!strcmp((const char *) attr->name, "proxy"))
568                     proxy = mp::xml::get_text(attr->children);
569                 else
570                     throw mp::filter::FilterException(
571                         "Bad attribute " + std::string((const char *)
572                                                        attr->name));
573             }
574             configure_local_records(ptr->children, test_only);
575         }
576         else if (!strcmp((const char *) ptr->name, "cclmap"))
577         {
578             const char *addinfo = 0;
579             ccl_xml_config(bibset, ptr, &addinfo);
580         }
581         else if (!strcmp((const char *) ptr->name, "fieldmap"))
582         {
583             const struct _xmlAttr *attr;
584             std::string ccl_field;
585             std::string cql_field;
586             for (attr = ptr->properties; attr; attr = attr->next)
587             {
588                 if (!strcmp((const char *) attr->name, "ccl"))
589                     ccl_field = mp::xml::get_text(attr->children);
590                 else if (!strcmp((const char *) attr->name, "cql"))
591                     cql_field = mp::xml::get_text(attr->children);
592                 else
593                     throw mp::filter::FilterException(
594                         "Bad attribute " + std::string((const char *)
595                                                        attr->name));
596             }
597             if (cql_field.length())
598                 fieldmap[cql_field] = ccl_field;
599         }
600         else if (!strcmp((const char *) ptr->name, "contentProxy"))
601         {
602             const struct _xmlAttr *attr;
603             for (attr = ptr->properties; attr; attr = attr->next)
604             {
605                 if (!strcmp((const char *) attr->name, "server"))
606                     content_proxy_server = mp::xml::get_text(attr->children);
607                 else if (!strcmp((const char *) attr->name, "tmp_file"))
608                     content_tmp_file = mp::xml::get_text(attr->children);
609                 else
610                     throw mp::filter::FilterException(
611                         "Bad attribute " + std::string((const char *)
612                                                        attr->name));
613             }
614         }
615         else if (!strcmp((const char *) ptr->name, "log"))
616         { 
617             const struct _xmlAttr *attr;
618             for (attr = ptr->properties; attr; attr = attr->next)
619             {
620                 if (!strcmp((const char *) attr->name, "apdu"))
621                     apdu_log = mp::xml::get_bool(attr->children, false);
622                 else
623                     throw mp::filter::FilterException(
624                         "Bad attribute " + std::string((const char *)
625                                                        attr->name));
626             }
627         }
628         else
629         {
630             throw mp::filter::FilterException
631                 ("Bad element " 
632                  + std::string((const char *) ptr->name)
633                  + " in zoom filter");
634         }
635     }
636 }
637
638 yf::Zoom::BackendPtr yf::Zoom::Frontend::get_backend_from_databases(
639     const mp::Package &package,
640     std::string &database, int *error, char **addinfo, ODR odr)
641 {
642     std::list<BackendPtr>::const_iterator map_it;
643     if (m_backend && m_backend->m_frontend_database == database)
644         return m_backend;
645
646     std::string db_args;
647     std::string torus_db;
648     size_t db_arg_pos = database.find(',');
649     if (db_arg_pos != std::string::npos)
650     {
651         torus_db = database.substr(0, db_arg_pos);
652         db_args = database.substr(db_arg_pos + 1);
653     }
654     else
655         torus_db = database;
656  
657     SearchablePtr sptr;
658
659     std::map<std::string,SearchablePtr>::iterator it;
660     it = m_p->s_map.find(torus_db);
661     if (it != m_p->s_map.end())
662         sptr = it->second;
663     else if (m_p->torus_url.length() > 0)
664     {
665         xmlDoc *doc = mp::get_searchable(m_p->torus_url, torus_db, m_p->proxy);
666         if (!doc)
667         {
668             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
669             *addinfo = odr_strdup(odr, database.c_str());
670             BackendPtr b;
671             return b;
672         }
673         const xmlNode *ptr = xmlDocGetRootElement(doc);
674         if (ptr)
675         {   // presumably ptr is a records element node
676             // parse first record in document
677             for (ptr = ptr->children; ptr; ptr = ptr->next)
678             {
679                 if (ptr->type == XML_ELEMENT_NODE
680                     && !strcmp((const char *) ptr->name, "record"))
681                 {
682                     if (sptr)
683                     {
684                         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
685                         *addinfo = (char*) odr_malloc(odr, 40 + database.length()),
686                         sprintf(*addinfo, "multiple records for udb=%s",
687                                  database.c_str());
688                         xmlFreeDoc(doc);
689                         BackendPtr b;
690                         return b;
691                     }
692                     sptr = m_p->parse_torus_record(ptr);
693                 }
694             }
695         }
696         xmlFreeDoc(doc);
697     }
698
699     if (!sptr)
700     {
701         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
702         *addinfo = odr_strdup(odr, database.c_str());
703         BackendPtr b;
704         return b;
705     }
706         
707     xsltStylesheetPtr xsp = 0;
708     if (sptr->transform_xsl_content.length())
709     {
710         xmlDoc *xsp_doc = xmlParseMemory(sptr->transform_xsl_content.c_str(),
711                                          sptr->transform_xsl_content.length());
712         if (!xsp_doc)
713         {
714             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
715             *addinfo = (char *) odr_malloc(odr, 40);
716             sprintf(*addinfo, "xmlParseMemory failed");
717             BackendPtr b;
718             return b;
719         }
720         xsp = xsltParseStylesheetDoc(xsp_doc);
721         if (!xsp)
722         {
723             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
724             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
725             BackendPtr b;
726             xmlFreeDoc(xsp_doc);
727             return b;
728         }
729     }
730     else if (sptr->transform_xsl_fname.length())
731     {
732         const char *path = 0;
733
734         if (m_p->xsldir.length())
735             path = m_p->xsldir.c_str();
736         else
737             path = m_p->file_path.c_str();
738         std::string fname;
739
740         char fullpath[1024];
741         char *cp = yaz_filepath_resolve(sptr->transform_xsl_fname.c_str(),
742                                         path, 0, fullpath);
743         if (cp)
744             fname.assign(cp);
745         else
746         {
747             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
748             *addinfo = (char *)
749                 odr_malloc(odr, 40 + sptr->transform_xsl_fname.length());
750             sprintf(*addinfo, "File could not be read: %s", 
751                     sptr->transform_xsl_fname.c_str());
752             BackendPtr b;
753             return b;
754         }
755         xmlDoc *xsp_doc = xmlParseFile(fname.c_str());
756         if (!xsp_doc)
757         {
758             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
759             *addinfo = (char *) odr_malloc(odr, 40 + fname.length());
760             sprintf(*addinfo, "xmlParseFile failed. File: %s", fname.c_str());
761             BackendPtr b;
762             return b;
763         }
764         xsp = xsltParseStylesheetDoc(xsp_doc);
765         if (!xsp)
766         {
767             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
768             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
769             BackendPtr b;
770             xmlFreeDoc(xsp_doc);
771             return b;
772         }
773     }
774
775     m_backend.reset();
776
777     BackendPtr b(new Backend(sptr));
778
779     b->xsp = xsp;
780     b->m_frontend_database = database;
781
782     if (sptr->query_encoding.length())
783         b->set_option("rpnCharset", sptr->query_encoding);
784
785     b->set_option("timeout", "40");
786     
787     if (m_p->apdu_log) 
788         b->set_option("apdulog", "1");
789
790     if (sptr->piggyback)
791         b->set_option("count", "1"); /* some SRU servers INSIST on getting
792                                         maximumRecords > 0 */
793     b->set_option("piggyback", sptr->piggyback ? "1" : "0");
794
795     std::string authentication = sptr->authentication;
796     std::string proxy = sptr->cfProxy;
797         
798     const char *param_user = 0;
799     const char *param_password = 0;
800     const char *param_proxy = 0;
801     if (db_args.length())
802     {
803         char **names;
804         char **values;
805         int i;
806         int no_parms = yaz_uri_to_array(db_args.c_str(),
807                                         odr, &names, &values);
808         for (i = 0; i < no_parms; i++)
809         {
810             const char *name = names[i];
811             const char *value = values[i];
812             if (!strcmp(name, "user"))
813                 param_user = value;
814             else if (!strcmp(name, "password"))
815                 param_password = value;
816             else if (!strcmp(name, "proxy"))
817                 param_proxy = value;
818             else if (!strcmp(name, "cproxysession"))
819                 ;
820             else if (name[0] == 'x' && name[1] == '-')
821                 ;
822             else
823             {
824                 BackendPtr notfound;
825                 char *msg = (char*) odr_malloc(odr, strlen(name) + 30);
826                 *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
827                 sprintf(msg, "Bad database argument: %s", name);
828                 *addinfo = msg;
829                 return notfound;
830             }
831         }
832         if (param_user)
833         {
834             authentication = std::string(param_user);
835             if (param_password)
836                 authentication += "/" + std::string(param_password);
837         }
838         if (param_proxy)
839             proxy = param_proxy;
840     }
841
842     if (sptr->cfAuth.length())
843     {
844         // A CF target
845         b->set_option("user", sptr->cfAuth);
846         if (!param_user && !param_password && authentication.length())
847         {
848             if (db_args.length())
849                 db_args += "&";
850             // no database (auth) args specified already.. and the
851             // Torus authentication has it.. Generate the args that CF
852             // understands..
853             size_t found = authentication.find('/');
854             if (found != std::string::npos)
855             {
856                 db_args += "user=" +
857                     mp::util::uri_encode(authentication.substr(0, found))
858                     + "&password=" +
859                     mp::util::uri_encode(authentication.substr(found+1));
860             }
861             else
862                 db_args += "user=" + mp::util::uri_encode(authentication);
863         }
864         if (!param_proxy && proxy.length())
865         {
866             if (db_args.length())
867                 db_args += "&";
868             db_args += "proxy=" + mp::util::uri_encode(proxy);
869         }
870         if (sptr->cfSubDb.length())
871         {
872             if (db_args.length())
873                 db_args += "&";
874             db_args += "subdatabase=" + mp::util::uri_encode(sptr->cfSubDb);
875         }
876     }
877     else
878     {
879         db_args.clear(); // no arguments to be passed (non-CF)
880
881         size_t found = authentication.find('/');
882         
883         if (sptr->sru.length() && found != std::string::npos)
884         {
885             b->set_option("user", authentication.substr(0, found));
886             b->set_option("password", authentication.substr(found+1));
887         }
888         else
889             b->set_option("user", authentication);
890
891         if (proxy.length())
892             b->set_option("proxy", proxy);
893     }
894     if (b->sptr->contentConnector.length())
895     {
896         char *fname = (char *) xmalloc(m_p->content_tmp_file.length() + 8);
897         strcpy(fname, m_p->content_tmp_file.c_str());
898         char *xx = strstr(fname, "XXXXXX");
899         if (!xx)
900         {
901             xx = fname + strlen(fname);
902             strcat(fname, "XXXXXX");
903         }
904         char tmp_char = xx[6];
905         sprintf(xx, "%06d", ((unsigned) rand()) % 1000000);
906         xx[6] = tmp_char;
907
908         FILE *file = fopen(fname, "w");
909         if (!file)
910         {
911             package.log("zoom", YLOG_WARN|YLOG_ERRNO, "create %s", fname);
912             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
913             *addinfo = (char *)  odr_malloc(odr, 40 + strlen(fname));
914             sprintf(*addinfo, "Could not create %s", fname);
915             xfree(fname);
916             BackendPtr backend_null;
917             return backend_null;
918         }
919         b->content_session_id.assign(xx, 6);
920         WRBUF w = wrbuf_alloc();
921         wrbuf_puts(w, "#content_proxy\n");
922         wrbuf_printf(w, "connector: %s\n", b->sptr->contentConnector.c_str());
923         if (authentication.length())
924             wrbuf_printf(w, "auth: %s\n", authentication.c_str());
925         if (proxy.length())
926             wrbuf_printf(w, "proxy: %s\n", proxy.c_str());
927         if (sptr->cfProxy.length())
928             wrbuf_printf(w, "cfproxy: %s\n", sptr->cfProxy.c_str());
929
930         fwrite(wrbuf_buf(w), 1, wrbuf_len(w), file);
931         fclose(file);
932         package.log("zoom", YLOG_LOG, "file %s created\n", fname);
933         xfree(fname);
934     }
935
936     std::string url;
937     if (sptr->sru.length())
938     {
939         url = "http://" + sptr->target;
940         b->set_option("sru", sptr->sru);
941     }
942     else
943     {
944         url = sptr->target;
945     }
946     if (db_args.length())
947         url += "," + db_args;
948     package.log("zoom", YLOG_LOG, "url=%s", url.c_str());
949     b->connect(url, error, addinfo, odr);
950     if (*error == 0)
951     {
952         m_backend = b;
953     }
954     return b;
955 }
956
957 void yf::Zoom::Frontend::prepare_elements(BackendPtr b,
958                                           Odr_oid *preferredRecordSyntax,
959                                           const char *element_set_name,
960                                           bool &enable_pz2_retrieval,
961                                           bool &enable_pz2_transform,
962                                           bool &assume_marc8_charset)
963
964 {
965     char oid_name_str[OID_STR_MAX];
966     const char *syntax_name = 0;
967     
968     if (preferredRecordSyntax &&
969         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
970         && element_set_name)
971     {
972         if (!strcmp(element_set_name, m_p->element_transform.c_str()))
973         {
974             enable_pz2_retrieval = true;
975             enable_pz2_transform = true;
976         }
977         else if (!strcmp(element_set_name, m_p->element_raw.c_str()))
978         {
979             enable_pz2_retrieval = true;
980         }
981     }
982     
983     if (enable_pz2_retrieval)
984     {
985         std::string configured_request_syntax = b->sptr->request_syntax;
986         if (configured_request_syntax.length())
987         {
988             syntax_name = configured_request_syntax.c_str();
989             const Odr_oid *syntax_oid = 
990                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
991             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
992                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
993                 assume_marc8_charset = true;
994         }
995     }
996     else if (preferredRecordSyntax)
997         syntax_name =
998             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
999
1000     if (b->sptr->sru.length())
1001         syntax_name = "XML";
1002
1003     b->set_option("preferredRecordSyntax", syntax_name);
1004
1005     if (enable_pz2_retrieval)
1006     {
1007         element_set_name = 0;
1008         if (b->sptr->element_set.length())
1009             element_set_name = b->sptr->element_set.c_str();
1010     }
1011
1012     b->set_option("elementSetName", element_set_name);
1013     if (b->sptr->sru.length() && element_set_name)
1014         b->set_option("schema", element_set_name);
1015 }
1016
1017 Z_Records *yf::Zoom::Frontend::get_records(Odr_int start,
1018                                            Odr_int number_to_present,
1019                                            int *error,
1020                                            char **addinfo,
1021                                            Odr_int *number_of_records_returned,
1022                                            ODR odr,
1023                                            BackendPtr b,
1024                                            Odr_oid *preferredRecordSyntax,
1025                                            const char *element_set_name)
1026 {
1027     *number_of_records_returned = 0;
1028     Z_Records *records = 0;
1029     bool enable_pz2_retrieval = false; // whether target profile is used
1030     bool enable_pz2_transform = false; // whether XSLT is used as well
1031     bool assume_marc8_charset = false;
1032
1033     prepare_elements(b, preferredRecordSyntax,
1034                      element_set_name,
1035                      enable_pz2_retrieval,
1036                      enable_pz2_transform,
1037                      assume_marc8_charset);
1038
1039     if (start < 0 || number_to_present <=0)
1040         return records;
1041     
1042     if (number_to_present > 10000)
1043         number_to_present = 10000;
1044
1045     ZOOM_record *recs = (ZOOM_record *)
1046         odr_malloc(odr, (size_t) number_to_present * sizeof(*recs));
1047
1048     b->present(start, number_to_present, recs, error, addinfo, odr);
1049
1050     int i = 0;
1051     if (!*error)
1052     {
1053         for (i = 0; i < number_to_present; i++)
1054             if (!recs[i])
1055                 break;
1056     }
1057     if (i > 0)
1058     {  // only return records if no error and at least one record
1059         char *odr_database = odr_strdup(odr,
1060                                         b->m_frontend_database.c_str());
1061         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1062             odr_malloc(odr, sizeof(*npl));
1063         *number_of_records_returned = i;
1064         npl->num_records = i;
1065         npl->records = (Z_NamePlusRecord **)
1066             odr_malloc(odr, i * sizeof(*npl->records));
1067         for (i = 0; i < number_to_present; i++)
1068         {
1069             Z_NamePlusRecord *npr = 0;
1070             const char *addinfo;
1071             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1072                                               &addinfo, 0 /* diagset */);
1073                 
1074             if (sur_error)
1075             {
1076                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1077                                             addinfo);
1078             }
1079             else if (enable_pz2_retrieval)
1080             {
1081                 char rec_type_str[100];
1082                 const char *record_encoding = 0;
1083
1084                 if (b->sptr->record_encoding.length())
1085                     record_encoding = b->sptr->record_encoding.c_str();
1086                 else if (assume_marc8_charset)
1087                     record_encoding = "marc8";
1088
1089                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1090                 if (record_encoding)
1091                 {
1092                     strcat(rec_type_str, "; charset=");
1093                     strcat(rec_type_str, record_encoding);
1094                 }
1095                 
1096                 int rec_len;
1097                 xmlChar *xmlrec_buf = 0;
1098                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1099                                                       &rec_len);
1100                 if (!rec_buf && !npr)
1101                 {
1102                     std::string addinfo("ZOOM_record_get failed for type ");
1103
1104                     addinfo += rec_type_str;
1105                     npr = zget_surrogateDiagRec(
1106                         odr, odr_database, 
1107                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1108                         addinfo.c_str());
1109                 }
1110
1111                 if (rec_buf && b->xsp && enable_pz2_transform)
1112                 {
1113                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1114                     if (!rec_doc)
1115                     {
1116                         npr = zget_surrogateDiagRec(
1117                             odr, odr_database, 
1118                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1119                             "xml parse failed for record");
1120                     }
1121                     else
1122                     { 
1123                         xmlDoc *rec_res = 
1124                             xsltApplyStylesheet(b->xsp, rec_doc, 0);
1125
1126                         if (rec_res)
1127                         {
1128                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1129                                                    rec_res, b->xsp);
1130                             rec_buf = (const char *) xmlrec_buf;
1131
1132                             xmlFreeDoc(rec_res);
1133                         }
1134                         if (!rec_buf)
1135                         {
1136                             std::string addinfo;
1137
1138                             addinfo = "xslt apply failed for "
1139                                 + b->sptr->transform_xsl_fname;
1140                             npr = zget_surrogateDiagRec(
1141                                 odr, odr_database, 
1142                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1143                                 addinfo.c_str());
1144                         }
1145                         xmlFreeDoc(rec_doc);
1146                     }
1147                 }
1148
1149                 if (rec_buf)
1150                 {
1151                     xmlDoc *doc = xmlParseMemory(rec_buf, rec_len);
1152                     std::string res = 
1153                         mp::xml::url_recipe_handle(doc, b->sptr->urlRecipe);
1154                     if (res.length() && b->content_session_id.length())
1155                     {
1156                         size_t off = res.find_first_of("://");
1157                         if (off != std::string::npos)
1158                         {
1159                             char tmp[1024];
1160                             sprintf(tmp, "%s.%s/",
1161                                     b->content_session_id.c_str(),
1162                                     m_p->content_proxy_server.c_str());
1163                             res.insert(off + 3, tmp);
1164                         }
1165                     }
1166                     if (res.length())
1167                     {
1168                         xmlNode *ptr = xmlDocGetRootElement(doc);
1169                         while (ptr && ptr->type != XML_ELEMENT_NODE)
1170                             ptr = ptr->next;
1171                         xmlNode *c = 
1172                             xmlNewChild(ptr, 0, BAD_CAST "metadata", 0);
1173                         xmlNewProp(c, BAD_CAST "type", BAD_CAST
1174                                    "generated-url");
1175                         xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1176                         xmlAddChild(c, t);
1177
1178                         if (xmlrec_buf)
1179                             xmlFree(xmlrec_buf);
1180
1181                         xmlDocDumpMemory(doc, &xmlrec_buf, &rec_len);
1182                         rec_buf = (const char *) xmlrec_buf;
1183                     }
1184                     xmlFreeDoc(doc);
1185                 }
1186                 if (!npr)
1187                 {
1188                     if (!rec_buf)
1189                         npr = zget_surrogateDiagRec(
1190                             odr, odr_database, 
1191                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1192                             rec_type_str);
1193                     else
1194                     {
1195                         npr = (Z_NamePlusRecord *)
1196                             odr_malloc(odr, sizeof(*npr));
1197                         npr->databaseName = odr_database;
1198                         npr->which = Z_NamePlusRecord_databaseRecord;
1199                         npr->u.databaseRecord =
1200                             z_ext_record_xml(odr, rec_buf, rec_len);
1201                     }
1202                 }
1203                 if (xmlrec_buf)
1204                     xmlFree(xmlrec_buf);
1205             }
1206             else
1207             {
1208                 Z_External *ext =
1209                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1210                 if (ext)
1211                 {
1212                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1213                     npr->databaseName = odr_database;
1214                     npr->which = Z_NamePlusRecord_databaseRecord;
1215                     npr->u.databaseRecord = ext;
1216                 }
1217                 else
1218                 {
1219                     npr = zget_surrogateDiagRec(
1220                         odr, odr_database, 
1221                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1222                         "ZOOM_record, type ext");
1223                 }
1224             }
1225             npl->records[i] = npr;
1226         }
1227         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1228         records->which = Z_Records_DBOSD;
1229         records->u.databaseOrSurDiagnostics = npl;
1230     }
1231     return records;
1232 }
1233
1234 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1235                                                     ODR odr)
1236 {
1237     struct cql_node *r = 0;
1238     if (!cn)
1239         return 0;
1240     switch (cn->which)
1241     {
1242     case CQL_NODE_ST:
1243         if (cn->u.st.index)
1244         {
1245             std::map<std::string,std::string>::const_iterator it;
1246             it = fieldmap.find(cn->u.st.index);
1247             if (it == fieldmap.end())
1248                 return cn;
1249             if (it->second.length())
1250                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1251             else
1252                 cn->u.st.index = 0;
1253         }
1254         break;
1255     case CQL_NODE_BOOL:
1256         r = convert_cql_fields(cn->u.boolean.left, odr);
1257         if (!r)
1258             r = convert_cql_fields(cn->u.boolean.right, odr);
1259         break;
1260     case CQL_NODE_SORT:
1261         r = convert_cql_fields(cn->u.sort.search, odr);
1262         break;
1263     }
1264     return r;
1265 }
1266
1267 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1268 {
1269     Z_GDU *gdu = package.request().get();
1270     Z_APDU *apdu_req = gdu->u.z3950;
1271     Z_APDU *apdu_res = 0;
1272     mp::odr odr;
1273     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1274     if (sr->num_databaseNames != 1)
1275     {
1276         apdu_res = odr.create_searchResponse(
1277             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
1278         package.response() = apdu_res;
1279         return;
1280     }
1281
1282     int error = 0;
1283     char *addinfo = 0;
1284     std::string db(sr->databaseNames[0]);
1285     BackendPtr b = get_backend_from_databases(package, db, &error,
1286                                               &addinfo, odr);
1287     if (error)
1288     {
1289         apdu_res = 
1290             odr.create_searchResponse(apdu_req, error, addinfo);
1291         package.response() = apdu_res;
1292         return;
1293     }
1294
1295     b->set_option("setname", "default");
1296
1297     bool enable_pz2_retrieval = false;
1298     bool enable_pz2_transform = false;
1299     bool assume_marc8_charset = false;
1300     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
1301                      enable_pz2_retrieval,
1302                      enable_pz2_transform,
1303                      assume_marc8_charset);
1304
1305     Odr_int hits = 0;
1306     Z_Query *query = sr->query;
1307     WRBUF ccl_wrbuf = 0;
1308     WRBUF pqf_wrbuf = 0;
1309     std::string sortkeys;
1310
1311     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1312     {
1313         // RPN
1314         pqf_wrbuf = wrbuf_alloc();
1315         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1316     }
1317     else if (query->which == Z_Query_type_2)
1318     {
1319         // CCL
1320         ccl_wrbuf = wrbuf_alloc();
1321         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1322                     query->u.type_2->len);
1323     }
1324     else if (query->which == Z_Query_type_104 &&
1325              query->u.type_104->which == Z_External_CQL)
1326     {
1327         // CQL
1328         const char *cql = query->u.type_104->u.cql;
1329         CQL_parser cp = cql_parser_create();
1330         int r = cql_parser_string(cp, cql);
1331         if (r)
1332         {
1333             cql_parser_destroy(cp);
1334             apdu_res = 
1335                 odr.create_searchResponse(apdu_req, 
1336                                           YAZ_BIB1_MALFORMED_QUERY,
1337                                           "CQL syntax error");
1338             package.response() = apdu_res;
1339             return;
1340         }
1341         struct cql_node *cn = cql_parser_result(cp);
1342         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1343         if (cn_error)
1344         {
1345             // hopefully we are getting a ptr to a index+relation+term node
1346             addinfo = 0;
1347             if (cn_error->which == CQL_NODE_ST)
1348                 addinfo = cn_error->u.st.index;
1349
1350             apdu_res = 
1351                 odr.create_searchResponse(apdu_req, 
1352                                           YAZ_BIB1_UNSUPP_USE_ATTRIBUTE,
1353                                           addinfo);
1354             package.response() = apdu_res;
1355             return;
1356         }
1357         char ccl_buf[1024];
1358
1359         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1360         if (r == 0)
1361         {
1362             ccl_wrbuf = wrbuf_alloc();
1363             wrbuf_puts(ccl_wrbuf, ccl_buf);
1364             
1365             WRBUF sru_sortkeys_wrbuf = wrbuf_alloc();
1366
1367             cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf);
1368             WRBUF sort_spec_wrbuf = wrbuf_alloc();
1369             yaz_srw_sortkeys_to_sort_spec(wrbuf_cstr(sru_sortkeys_wrbuf),
1370                                           sort_spec_wrbuf);
1371             wrbuf_destroy(sru_sortkeys_wrbuf);
1372
1373             yaz_tok_cfg_t tc = yaz_tok_cfg_create();
1374             yaz_tok_parse_t tp =
1375                 yaz_tok_parse_buf(tc, wrbuf_cstr(sort_spec_wrbuf));
1376             yaz_tok_cfg_destroy(tc);
1377
1378             /* go through sortspec and map fields */
1379             int token = yaz_tok_move(tp);
1380             while (token != YAZ_TOK_EOF)
1381             {
1382                 if (token == YAZ_TOK_STRING)
1383                 {
1384                     const char *field = yaz_tok_parse_string(tp);
1385                     std::map<std::string,std::string>::iterator it;
1386                     it = b->sptr->sortmap.find(field);
1387                     if (it != b->sptr->sortmap.end())
1388                         sortkeys += it->second;
1389                     else
1390                         sortkeys += field;
1391                 }
1392                 sortkeys += " ";
1393                 token = yaz_tok_move(tp);
1394                 if (token == YAZ_TOK_STRING)
1395                 {
1396                     sortkeys += yaz_tok_parse_string(tp);
1397                 }
1398                 if (token != YAZ_TOK_EOF)
1399                 {
1400                     sortkeys += " ";
1401                     token = yaz_tok_move(tp);
1402                 }
1403             }
1404             yaz_tok_parse_destroy(tp);
1405             wrbuf_destroy(sort_spec_wrbuf);
1406         }
1407         cql_parser_destroy(cp);
1408         if (r)
1409         {
1410             apdu_res = 
1411                 odr.create_searchResponse(apdu_req, 
1412                                           YAZ_BIB1_MALFORMED_QUERY,
1413                                           "CQL to CCL conversion error");
1414             package.response() = apdu_res;
1415             return;
1416         }
1417     }
1418     else
1419     {
1420         apdu_res = 
1421             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
1422         package.response() = apdu_res;
1423         return;
1424     }
1425
1426     if (ccl_wrbuf)
1427     {
1428         // CCL to PQF
1429         assert(pqf_wrbuf == 0);
1430         int cerror, cpos;
1431         struct ccl_rpn_node *cn;
1432         package.log("zoom", YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1433         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1434                           &cerror, &cpos);
1435         wrbuf_destroy(ccl_wrbuf);
1436         if (!cn)
1437         {
1438             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1439             int z3950_diag = YAZ_BIB1_MALFORMED_QUERY;
1440
1441             switch (cerror)
1442             {
1443             case CCL_ERR_UNKNOWN_QUAL:
1444                 z3950_diag = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1445                 break;
1446             case CCL_ERR_TRUNC_NOT_LEFT: 
1447             case CCL_ERR_TRUNC_NOT_RIGHT:
1448             case CCL_ERR_TRUNC_NOT_BOTH:
1449                 z3950_diag = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
1450                 break;
1451             }
1452             apdu_res = 
1453                 odr.create_searchResponse(apdu_req, z3950_diag, addinfo);
1454             package.response() = apdu_res;
1455             return;
1456         }
1457         pqf_wrbuf = wrbuf_alloc();
1458         ccl_pquery(pqf_wrbuf, cn);
1459         package.log("zoom", YLOG_LOG, "RPN: %s", wrbuf_cstr(pqf_wrbuf));
1460         ccl_rpn_delete(cn);
1461     }
1462     
1463     assert(pqf_wrbuf);
1464
1465     ZOOM_query q = ZOOM_query_create();
1466     ZOOM_query_sortby2(q, b->sptr->sortStrategy.c_str(), sortkeys.c_str());
1467
1468     if (b->get_option("sru"))
1469     {
1470         int status = 0;
1471         Z_RPNQuery *zquery;
1472         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1473         WRBUF wrb = wrbuf_alloc();
1474             
1475         if (!strcmp(b->get_option("sru"), "solr"))
1476         {
1477             solr_transform_t cqlt = solr_transform_create();
1478             
1479             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1480             
1481             solr_transform_close(cqlt);
1482         }
1483         else
1484         {
1485             cql_transform_t cqlt = cql_transform_create();
1486             
1487             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1488             
1489             cql_transform_close(cqlt);
1490         }
1491         if (status == 0)
1492         {
1493             ZOOM_query_cql(q, wrbuf_cstr(wrb));
1494             package.log("zoom", YLOG_LOG, "CQL: %s", wrbuf_cstr(wrb));
1495             b->search(q, &hits, &error, &addinfo, odr);
1496         }
1497         ZOOM_query_destroy(q);
1498         
1499         wrbuf_destroy(wrb);
1500         wrbuf_destroy(pqf_wrbuf);
1501         if (status)
1502         {
1503             apdu_res = 
1504                 odr.create_searchResponse(apdu_req, YAZ_BIB1_MALFORMED_QUERY,
1505                                           "can not convert from RPN to CQL/SOLR");
1506             package.response() = apdu_res;
1507             return;
1508         }
1509     }
1510     else
1511     {
1512         ZOOM_query_prefix(q, wrbuf_cstr(pqf_wrbuf));
1513         package.log("zoom", YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1514         b->search(q, &hits, &error, &addinfo, odr);
1515         ZOOM_query_destroy(q);
1516         wrbuf_destroy(pqf_wrbuf);
1517     }
1518
1519     const char *element_set_name = 0;
1520     Odr_int number_to_present = 0;
1521     if (!error)
1522         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1523     
1524     Odr_int number_of_records_returned = 0;
1525     Z_Records *records = get_records(
1526         0, number_to_present, &error, &addinfo,
1527         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1528         element_set_name);
1529     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1530     if (records)
1531     {
1532         apdu_res->u.searchResponse->records = records;
1533         apdu_res->u.searchResponse->numberOfRecordsReturned =
1534             odr_intdup(odr, number_of_records_returned);
1535     }
1536     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1537     package.response() = apdu_res;
1538 }
1539
1540 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1541 {
1542     Z_GDU *gdu = package.request().get();
1543     Z_APDU *apdu_req = gdu->u.z3950;
1544     Z_APDU *apdu_res = 0;
1545     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1546
1547     mp::odr odr;
1548     if (!m_backend)
1549     {
1550         package.response() = odr.create_presentResponse(
1551             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1552         return;
1553     }
1554     const char *element_set_name = 0;
1555     Z_RecordComposition *comp = pr->recordComposition;
1556     if (comp && comp->which != Z_RecordComp_simple)
1557     {
1558         package.response() = odr.create_presentResponse(
1559             apdu_req, 
1560             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1561         return;
1562     }
1563     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1564         element_set_name = comp->u.simple->u.generic;
1565     Odr_int number_of_records_returned = 0;
1566     int error = 0;
1567     char *addinfo = 0;
1568     Z_Records *records = get_records(
1569         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1570         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1571         pr->preferredRecordSyntax, element_set_name);
1572
1573     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1574     if (records)
1575     {
1576         apdu_res->u.presentResponse->records = records;
1577         apdu_res->u.presentResponse->numberOfRecordsReturned =
1578             odr_intdup(odr, number_of_records_returned);
1579     }
1580     package.response() = apdu_res;
1581 }
1582
1583 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1584 {
1585     Z_GDU *gdu = package.request().get();
1586     if (!gdu)
1587         ;
1588     else if (gdu->which == Z_GDU_Z3950)
1589     {
1590         Z_APDU *apdu_req = gdu->u.z3950;
1591         if (apdu_req->which == Z_APDU_initRequest)
1592         {
1593             mp::odr odr;
1594             package.response() = odr.create_close(
1595                 apdu_req,
1596                 Z_Close_protocolError,
1597                 "double init");
1598         }
1599         else if (apdu_req->which == Z_APDU_searchRequest)
1600         {
1601             handle_search(package);
1602         }
1603         else if (apdu_req->which == Z_APDU_presentRequest)
1604         {
1605             handle_present(package);
1606         }
1607         else
1608         {
1609             mp::odr odr;
1610             package.response() = odr.create_close(
1611                 apdu_req,
1612                 Z_Close_protocolError,
1613                 "zoom filter cannot handle this APDU");
1614             package.session().close();
1615         }
1616     }
1617     else
1618     {
1619         package.session().close();
1620     }
1621 }
1622
1623 void yf::Zoom::Impl::process(mp::Package &package)
1624 {
1625     FrontendPtr f = get_frontend(package);
1626     Z_GDU *gdu = package.request().get();
1627
1628     if (f->m_is_virtual)
1629     {
1630         f->handle_package(package);
1631     }
1632     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1633              Z_APDU_initRequest)
1634     {
1635         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1636         f->m_init_gdu = gdu;
1637         
1638         mp::odr odr;
1639         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1640         Z_InitResponse *resp = apdu->u.initResponse;
1641         
1642         int i;
1643         static const int masks[] = {
1644             Z_Options_search,
1645             Z_Options_present,
1646             -1 
1647         };
1648         for (i = 0; masks[i] != -1; i++)
1649             if (ODR_MASK_GET(req->options, masks[i]))
1650                 ODR_MASK_SET(resp->options, masks[i]);
1651         
1652         static const int versions[] = {
1653             Z_ProtocolVersion_1,
1654             Z_ProtocolVersion_2,
1655             Z_ProtocolVersion_3,
1656             -1
1657         };
1658         for (i = 0; versions[i] != -1; i++)
1659             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1660                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1661             else
1662                 break;
1663         
1664         *resp->preferredMessageSize = *req->preferredMessageSize;
1665         *resp->maximumRecordSize = *req->maximumRecordSize;
1666         
1667         package.response() = apdu;
1668         f->m_is_virtual = true;
1669     }
1670     else
1671         package.move();
1672
1673     release_frontend(package);
1674 }
1675
1676
1677 static mp::filter::Base* filter_creator()
1678 {
1679     return new mp::filter::Zoom;
1680 }
1681
1682 extern "C" {
1683     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1684         0,
1685         "zoom",
1686         filter_creator
1687     };
1688 }
1689
1690
1691 /*
1692  * Local variables:
1693  * c-basic-offset: 4
1694  * c-file-style: "Stroustrup"
1695  * indent-tabs-mode: nil
1696  * End:
1697  * vim: shiftwidth=4 tabstop=8 expandtab
1698  */
1699