New log method for package class
[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
821             {
822                 BackendPtr notfound;
823                 char *msg = (char*) odr_malloc(odr, strlen(name) + 30);
824                 *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
825                 sprintf(msg, "Bad database argument: %s", name);
826                 *addinfo = msg;
827                 return notfound;
828             }
829         }
830         if (param_user)
831         {
832             authentication = std::string(param_user);
833             if (param_password)
834                 authentication += "/" + std::string(param_password);
835         }
836         if (param_proxy)
837             proxy = param_proxy;
838     }
839
840     if (sptr->cfAuth.length())
841     {
842         // A CF target
843         b->set_option("user", sptr->cfAuth);
844         if (!param_user && !param_password && authentication.length())
845         {
846             if (db_args.length())
847                 db_args += "&";
848             // no database (auth) args specified already.. and the
849             // Torus authentication has it.. Generate the args that CF
850             // understands..
851             size_t found = authentication.find('/');
852             if (found != std::string::npos)
853             {
854                 db_args += "user=" +
855                     mp::util::uri_encode(authentication.substr(0, found))
856                     + "&password=" +
857                     mp::util::uri_encode(authentication.substr(found+1));
858             }
859             else
860                 db_args += "user=" + mp::util::uri_encode(authentication);
861         }
862         if (!param_proxy && proxy.length())
863         {
864             if (db_args.length())
865                 db_args += "&";
866             db_args += "proxy=" + mp::util::uri_encode(proxy);
867         }
868         if (sptr->cfSubDb.length())
869         {
870             if (db_args.length())
871                 db_args += "&";
872             db_args += "subdatabase=" + mp::util::uri_encode(sptr->cfSubDb);
873         }
874     }
875     else
876     {
877         db_args.clear(); // no arguments to be passed (non-CF)
878
879         size_t found = authentication.find('/');
880         
881         if (sptr->sru.length() && found != std::string::npos)
882         {
883             b->set_option("user", authentication.substr(0, found));
884             b->set_option("password", authentication.substr(found+1));
885         }
886         else
887             b->set_option("user", authentication);
888
889         if (proxy.length())
890             b->set_option("proxy", proxy);
891     }
892     if (b->sptr->contentConnector.length())
893     {
894         char *fname = (char *) xmalloc(m_p->content_tmp_file.length() + 8);
895         strcpy(fname, m_p->content_tmp_file.c_str());
896         char *xx = strstr(fname, "XXXXXX");
897         if (!xx)
898         {
899             xx = fname + strlen(fname);
900             strcat(fname, "XXXXXX");
901         }
902         char tmp_char = xx[6];
903         sprintf(xx, "%06d", ((unsigned) rand()) % 1000000);
904         xx[6] = tmp_char;
905
906         FILE *file = fopen(fname, "w");
907         if (!file)
908         {
909             package.log("zoom", YLOG_WARN|YLOG_ERRNO, "create %s", fname);
910             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
911             *addinfo = (char *)  odr_malloc(odr, 40 + strlen(fname));
912             sprintf(*addinfo, "Could not create %s", fname);
913             xfree(fname);
914             BackendPtr backend_null;
915             return backend_null;
916         }
917         b->content_session_id.assign(xx, 6);
918         WRBUF w = wrbuf_alloc();
919         wrbuf_puts(w, "#content_proxy\n");
920         wrbuf_printf(w, "connector: %s\n", b->sptr->contentConnector.c_str());
921         if (authentication.length())
922             wrbuf_printf(w, "auth: %s\n", authentication.c_str());
923         if (proxy.length())
924             wrbuf_printf(w, "proxy: %s\n", proxy.c_str());
925         if (sptr->cfProxy.length())
926             wrbuf_printf(w, "cfproxy: %s\n", sptr->cfProxy.c_str());
927
928         fwrite(wrbuf_buf(w), 1, wrbuf_len(w), file);
929         fclose(file);
930         package.log("zoom", YLOG_LOG, "file %s created\n", fname);
931         xfree(fname);
932     }
933
934     std::string url;
935     if (sptr->sru.length())
936     {
937         url = "http://" + sptr->target;
938         b->set_option("sru", sptr->sru);
939     }
940     else
941     {
942         url = sptr->target;
943     }
944     if (db_args.length())
945         url += "," + db_args;
946     package.log("zoom", YLOG_LOG, "url=%s", url.c_str());
947     b->connect(url, error, addinfo, odr);
948     if (*error == 0)
949     {
950         m_backend = b;
951     }
952     return b;
953 }
954
955 void yf::Zoom::Frontend::prepare_elements(BackendPtr b,
956                                           Odr_oid *preferredRecordSyntax,
957                                           const char *element_set_name,
958                                           bool &enable_pz2_retrieval,
959                                           bool &enable_pz2_transform,
960                                           bool &assume_marc8_charset)
961
962 {
963     char oid_name_str[OID_STR_MAX];
964     const char *syntax_name = 0;
965     
966     if (preferredRecordSyntax &&
967         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
968         && element_set_name)
969     {
970         if (!strcmp(element_set_name, m_p->element_transform.c_str()))
971         {
972             enable_pz2_retrieval = true;
973             enable_pz2_transform = true;
974         }
975         else if (!strcmp(element_set_name, m_p->element_raw.c_str()))
976         {
977             enable_pz2_retrieval = true;
978         }
979     }
980     
981     if (enable_pz2_retrieval)
982     {
983         std::string configured_request_syntax = b->sptr->request_syntax;
984         if (configured_request_syntax.length())
985         {
986             syntax_name = configured_request_syntax.c_str();
987             const Odr_oid *syntax_oid = 
988                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
989             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
990                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
991                 assume_marc8_charset = true;
992         }
993     }
994     else if (preferredRecordSyntax)
995         syntax_name =
996             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
997
998     if (b->sptr->sru.length())
999         syntax_name = "XML";
1000
1001     b->set_option("preferredRecordSyntax", syntax_name);
1002
1003     if (enable_pz2_retrieval)
1004     {
1005         element_set_name = 0;
1006         if (b->sptr->element_set.length())
1007             element_set_name = b->sptr->element_set.c_str();
1008     }
1009
1010     b->set_option("elementSetName", element_set_name);
1011     if (b->sptr->sru.length() && element_set_name)
1012         b->set_option("schema", element_set_name);
1013 }
1014
1015 Z_Records *yf::Zoom::Frontend::get_records(Odr_int start,
1016                                            Odr_int number_to_present,
1017                                            int *error,
1018                                            char **addinfo,
1019                                            Odr_int *number_of_records_returned,
1020                                            ODR odr,
1021                                            BackendPtr b,
1022                                            Odr_oid *preferredRecordSyntax,
1023                                            const char *element_set_name)
1024 {
1025     *number_of_records_returned = 0;
1026     Z_Records *records = 0;
1027     bool enable_pz2_retrieval = false; // whether target profile is used
1028     bool enable_pz2_transform = false; // whether XSLT is used as well
1029     bool assume_marc8_charset = false;
1030
1031     prepare_elements(b, preferredRecordSyntax,
1032                      element_set_name,
1033                      enable_pz2_retrieval,
1034                      enable_pz2_transform,
1035                      assume_marc8_charset);
1036
1037     if (start < 0 || number_to_present <=0)
1038         return records;
1039     
1040     if (number_to_present > 10000)
1041         number_to_present = 10000;
1042
1043     ZOOM_record *recs = (ZOOM_record *)
1044         odr_malloc(odr, (size_t) number_to_present * sizeof(*recs));
1045
1046     b->present(start, number_to_present, recs, error, addinfo, odr);
1047
1048     int i = 0;
1049     if (!*error)
1050     {
1051         for (i = 0; i < number_to_present; i++)
1052             if (!recs[i])
1053                 break;
1054     }
1055     if (i > 0)
1056     {  // only return records if no error and at least one record
1057         char *odr_database = odr_strdup(odr,
1058                                         b->m_frontend_database.c_str());
1059         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1060             odr_malloc(odr, sizeof(*npl));
1061         *number_of_records_returned = i;
1062         npl->num_records = i;
1063         npl->records = (Z_NamePlusRecord **)
1064             odr_malloc(odr, i * sizeof(*npl->records));
1065         for (i = 0; i < number_to_present; i++)
1066         {
1067             Z_NamePlusRecord *npr = 0;
1068             const char *addinfo;
1069             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1070                                               &addinfo, 0 /* diagset */);
1071                 
1072             if (sur_error)
1073             {
1074                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1075                                             addinfo);
1076             }
1077             else if (enable_pz2_retrieval)
1078             {
1079                 char rec_type_str[100];
1080                 const char *record_encoding = 0;
1081
1082                 if (b->sptr->record_encoding.length())
1083                     record_encoding = b->sptr->record_encoding.c_str();
1084                 else if (assume_marc8_charset)
1085                     record_encoding = "marc8";
1086
1087                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1088                 if (record_encoding)
1089                 {
1090                     strcat(rec_type_str, "; charset=");
1091                     strcat(rec_type_str, record_encoding);
1092                 }
1093                 
1094                 int rec_len;
1095                 xmlChar *xmlrec_buf = 0;
1096                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1097                                                       &rec_len);
1098                 if (!rec_buf && !npr)
1099                 {
1100                     std::string addinfo("ZOOM_record_get failed for type ");
1101
1102                     addinfo += rec_type_str;
1103                     npr = zget_surrogateDiagRec(
1104                         odr, odr_database, 
1105                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1106                         addinfo.c_str());
1107                 }
1108
1109                 if (rec_buf && b->xsp && enable_pz2_transform)
1110                 {
1111                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1112                     if (!rec_doc)
1113                     {
1114                         npr = zget_surrogateDiagRec(
1115                             odr, odr_database, 
1116                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1117                             "xml parse failed for record");
1118                     }
1119                     else
1120                     { 
1121                         xmlDoc *rec_res = 
1122                             xsltApplyStylesheet(b->xsp, rec_doc, 0);
1123
1124                         if (rec_res)
1125                         {
1126                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1127                                                    rec_res, b->xsp);
1128                             rec_buf = (const char *) xmlrec_buf;
1129
1130                             xmlFreeDoc(rec_res);
1131                         }
1132                         if (!rec_buf)
1133                         {
1134                             std::string addinfo;
1135
1136                             addinfo = "xslt apply failed for "
1137                                 + b->sptr->transform_xsl_fname;
1138                             npr = zget_surrogateDiagRec(
1139                                 odr, odr_database, 
1140                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1141                                 addinfo.c_str());
1142                         }
1143                         xmlFreeDoc(rec_doc);
1144                     }
1145                 }
1146
1147                 if (rec_buf)
1148                 {
1149                     xmlDoc *doc = xmlParseMemory(rec_buf, rec_len);
1150                     std::string res = 
1151                         mp::xml::url_recipe_handle(doc, b->sptr->urlRecipe);
1152                     if (res.length() && b->content_session_id.length())
1153                     {
1154                         size_t off = res.find_first_of("://");
1155                         if (off != std::string::npos)
1156                         {
1157                             char tmp[1024];
1158                             sprintf(tmp, "%s.%s/",
1159                                     b->content_session_id.c_str(),
1160                                     m_p->content_proxy_server.c_str());
1161                             res.insert(off + 3, tmp);
1162                         }
1163                     }
1164                     if (res.length())
1165                     {
1166                         xmlNode *ptr = xmlDocGetRootElement(doc);
1167                         while (ptr && ptr->type != XML_ELEMENT_NODE)
1168                             ptr = ptr->next;
1169                         xmlNode *c = 
1170                             xmlNewChild(ptr, 0, BAD_CAST "metadata", 0);
1171                         xmlNewProp(c, BAD_CAST "type", BAD_CAST
1172                                    "generated-url");
1173                         xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1174                         xmlAddChild(c, t);
1175
1176                         if (xmlrec_buf)
1177                             xmlFree(xmlrec_buf);
1178
1179                         xmlDocDumpMemory(doc, &xmlrec_buf, &rec_len);
1180                         rec_buf = (const char *) xmlrec_buf;
1181                     }
1182                     xmlFreeDoc(doc);
1183                 }
1184                 if (!npr)
1185                 {
1186                     if (!rec_buf)
1187                         npr = zget_surrogateDiagRec(
1188                             odr, odr_database, 
1189                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1190                             rec_type_str);
1191                     else
1192                     {
1193                         npr = (Z_NamePlusRecord *)
1194                             odr_malloc(odr, sizeof(*npr));
1195                         npr->databaseName = odr_database;
1196                         npr->which = Z_NamePlusRecord_databaseRecord;
1197                         npr->u.databaseRecord =
1198                             z_ext_record_xml(odr, rec_buf, rec_len);
1199                     }
1200                 }
1201                 if (xmlrec_buf)
1202                     xmlFree(xmlrec_buf);
1203             }
1204             else
1205             {
1206                 Z_External *ext =
1207                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1208                 if (ext)
1209                 {
1210                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1211                     npr->databaseName = odr_database;
1212                     npr->which = Z_NamePlusRecord_databaseRecord;
1213                     npr->u.databaseRecord = ext;
1214                 }
1215                 else
1216                 {
1217                     npr = zget_surrogateDiagRec(
1218                         odr, odr_database, 
1219                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1220                         "ZOOM_record, type ext");
1221                 }
1222             }
1223             npl->records[i] = npr;
1224         }
1225         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1226         records->which = Z_Records_DBOSD;
1227         records->u.databaseOrSurDiagnostics = npl;
1228     }
1229     return records;
1230 }
1231
1232 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1233                                                     ODR odr)
1234 {
1235     struct cql_node *r = 0;
1236     if (!cn)
1237         return 0;
1238     switch (cn->which)
1239     {
1240     case CQL_NODE_ST:
1241         if (cn->u.st.index)
1242         {
1243             std::map<std::string,std::string>::const_iterator it;
1244             it = fieldmap.find(cn->u.st.index);
1245             if (it == fieldmap.end())
1246                 return cn;
1247             if (it->second.length())
1248                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1249             else
1250                 cn->u.st.index = 0;
1251         }
1252         break;
1253     case CQL_NODE_BOOL:
1254         r = convert_cql_fields(cn->u.boolean.left, odr);
1255         if (!r)
1256             r = convert_cql_fields(cn->u.boolean.right, odr);
1257         break;
1258     case CQL_NODE_SORT:
1259         r = convert_cql_fields(cn->u.sort.search, odr);
1260         break;
1261     }
1262     return r;
1263 }
1264
1265 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1266 {
1267     Z_GDU *gdu = package.request().get();
1268     Z_APDU *apdu_req = gdu->u.z3950;
1269     Z_APDU *apdu_res = 0;
1270     mp::odr odr;
1271     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1272     if (sr->num_databaseNames != 1)
1273     {
1274         apdu_res = odr.create_searchResponse(
1275             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
1276         package.response() = apdu_res;
1277         return;
1278     }
1279
1280     int error = 0;
1281     char *addinfo = 0;
1282     std::string db(sr->databaseNames[0]);
1283     BackendPtr b = get_backend_from_databases(package, db, &error,
1284                                               &addinfo, odr);
1285     if (error)
1286     {
1287         apdu_res = 
1288             odr.create_searchResponse(apdu_req, error, addinfo);
1289         package.response() = apdu_res;
1290         return;
1291     }
1292
1293     b->set_option("setname", "default");
1294
1295     bool enable_pz2_retrieval = false;
1296     bool enable_pz2_transform = false;
1297     bool assume_marc8_charset = false;
1298     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
1299                      enable_pz2_retrieval,
1300                      enable_pz2_transform,
1301                      assume_marc8_charset);
1302
1303     Odr_int hits = 0;
1304     Z_Query *query = sr->query;
1305     WRBUF ccl_wrbuf = 0;
1306     WRBUF pqf_wrbuf = 0;
1307     std::string sortkeys;
1308
1309     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1310     {
1311         // RPN
1312         pqf_wrbuf = wrbuf_alloc();
1313         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1314     }
1315     else if (query->which == Z_Query_type_2)
1316     {
1317         // CCL
1318         ccl_wrbuf = wrbuf_alloc();
1319         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1320                     query->u.type_2->len);
1321     }
1322     else if (query->which == Z_Query_type_104 &&
1323              query->u.type_104->which == Z_External_CQL)
1324     {
1325         // CQL
1326         const char *cql = query->u.type_104->u.cql;
1327         CQL_parser cp = cql_parser_create();
1328         int r = cql_parser_string(cp, cql);
1329         if (r)
1330         {
1331             cql_parser_destroy(cp);
1332             apdu_res = 
1333                 odr.create_searchResponse(apdu_req, 
1334                                           YAZ_BIB1_MALFORMED_QUERY,
1335                                           "CQL syntax error");
1336             package.response() = apdu_res;
1337             return;
1338         }
1339         struct cql_node *cn = cql_parser_result(cp);
1340         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1341         if (cn_error)
1342         {
1343             // hopefully we are getting a ptr to a index+relation+term node
1344             addinfo = 0;
1345             if (cn_error->which == CQL_NODE_ST)
1346                 addinfo = cn_error->u.st.index;
1347
1348             apdu_res = 
1349                 odr.create_searchResponse(apdu_req, 
1350                                           YAZ_BIB1_UNSUPP_USE_ATTRIBUTE,
1351                                           addinfo);
1352             package.response() = apdu_res;
1353             return;
1354         }
1355         char ccl_buf[1024];
1356
1357         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1358         if (r == 0)
1359         {
1360             ccl_wrbuf = wrbuf_alloc();
1361             wrbuf_puts(ccl_wrbuf, ccl_buf);
1362             
1363             WRBUF sru_sortkeys_wrbuf = wrbuf_alloc();
1364
1365             cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf);
1366             WRBUF sort_spec_wrbuf = wrbuf_alloc();
1367             yaz_srw_sortkeys_to_sort_spec(wrbuf_cstr(sru_sortkeys_wrbuf),
1368                                           sort_spec_wrbuf);
1369             wrbuf_destroy(sru_sortkeys_wrbuf);
1370
1371             yaz_tok_cfg_t tc = yaz_tok_cfg_create();
1372             yaz_tok_parse_t tp =
1373                 yaz_tok_parse_buf(tc, wrbuf_cstr(sort_spec_wrbuf));
1374             yaz_tok_cfg_destroy(tc);
1375
1376             /* go through sortspec and map fields */
1377             int token = yaz_tok_move(tp);
1378             while (token != YAZ_TOK_EOF)
1379             {
1380                 if (token == YAZ_TOK_STRING)
1381                 {
1382                     const char *field = yaz_tok_parse_string(tp);
1383                     std::map<std::string,std::string>::iterator it;
1384                     it = b->sptr->sortmap.find(field);
1385                     if (it != b->sptr->sortmap.end())
1386                         sortkeys += it->second;
1387                     else
1388                         sortkeys += field;
1389                 }
1390                 sortkeys += " ";
1391                 token = yaz_tok_move(tp);
1392                 if (token == YAZ_TOK_STRING)
1393                 {
1394                     sortkeys += yaz_tok_parse_string(tp);
1395                 }
1396                 if (token != YAZ_TOK_EOF)
1397                 {
1398                     sortkeys += " ";
1399                     token = yaz_tok_move(tp);
1400                 }
1401             }
1402             yaz_tok_parse_destroy(tp);
1403             wrbuf_destroy(sort_spec_wrbuf);
1404         }
1405         cql_parser_destroy(cp);
1406         if (r)
1407         {
1408             apdu_res = 
1409                 odr.create_searchResponse(apdu_req, 
1410                                           YAZ_BIB1_MALFORMED_QUERY,
1411                                           "CQL to CCL conversion error");
1412             package.response() = apdu_res;
1413             return;
1414         }
1415     }
1416     else
1417     {
1418         apdu_res = 
1419             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
1420         package.response() = apdu_res;
1421         return;
1422     }
1423
1424     if (ccl_wrbuf)
1425     {
1426         // CCL to PQF
1427         assert(pqf_wrbuf == 0);
1428         int cerror, cpos;
1429         struct ccl_rpn_node *cn;
1430         package.log("zoom", YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1431         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1432                           &cerror, &cpos);
1433         wrbuf_destroy(ccl_wrbuf);
1434         if (!cn)
1435         {
1436             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1437             int z3950_diag = YAZ_BIB1_MALFORMED_QUERY;
1438
1439             switch (cerror)
1440             {
1441             case CCL_ERR_UNKNOWN_QUAL:
1442                 z3950_diag = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1443                 break;
1444             case CCL_ERR_TRUNC_NOT_LEFT: 
1445             case CCL_ERR_TRUNC_NOT_RIGHT:
1446             case CCL_ERR_TRUNC_NOT_BOTH:
1447                 z3950_diag = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
1448                 break;
1449             }
1450             apdu_res = 
1451                 odr.create_searchResponse(apdu_req, z3950_diag, addinfo);
1452             package.response() = apdu_res;
1453             return;
1454         }
1455         pqf_wrbuf = wrbuf_alloc();
1456         ccl_pquery(pqf_wrbuf, cn);
1457         package.log("zoom", YLOG_LOG, "RPN: %s", wrbuf_cstr(pqf_wrbuf));
1458         ccl_rpn_delete(cn);
1459     }
1460     
1461     assert(pqf_wrbuf);
1462
1463     ZOOM_query q = ZOOM_query_create();
1464     ZOOM_query_sortby2(q, b->sptr->sortStrategy.c_str(), sortkeys.c_str());
1465
1466     if (b->get_option("sru"))
1467     {
1468         int status = 0;
1469         Z_RPNQuery *zquery;
1470         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1471         WRBUF wrb = wrbuf_alloc();
1472             
1473         if (!strcmp(b->get_option("sru"), "solr"))
1474         {
1475             solr_transform_t cqlt = solr_transform_create();
1476             
1477             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1478             
1479             solr_transform_close(cqlt);
1480         }
1481         else
1482         {
1483             cql_transform_t cqlt = cql_transform_create();
1484             
1485             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1486             
1487             cql_transform_close(cqlt);
1488         }
1489         if (status == 0)
1490         {
1491             ZOOM_query_cql(q, wrbuf_cstr(wrb));
1492             package.log("zoom", YLOG_LOG, "CQL: %s", wrbuf_cstr(wrb));
1493             b->search(q, &hits, &error, &addinfo, odr);
1494         }
1495         ZOOM_query_destroy(q);
1496         
1497         wrbuf_destroy(wrb);
1498         wrbuf_destroy(pqf_wrbuf);
1499         if (status)
1500         {
1501             apdu_res = 
1502                 odr.create_searchResponse(apdu_req, YAZ_BIB1_MALFORMED_QUERY,
1503                                           "can not convert from RPN to CQL/SOLR");
1504             package.response() = apdu_res;
1505             return;
1506         }
1507     }
1508     else
1509     {
1510         ZOOM_query_prefix(q, wrbuf_cstr(pqf_wrbuf));
1511         package.log("zoom", YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1512         b->search(q, &hits, &error, &addinfo, odr);
1513         ZOOM_query_destroy(q);
1514         wrbuf_destroy(pqf_wrbuf);
1515     }
1516
1517     const char *element_set_name = 0;
1518     Odr_int number_to_present = 0;
1519     if (!error)
1520         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1521     
1522     Odr_int number_of_records_returned = 0;
1523     Z_Records *records = get_records(
1524         0, number_to_present, &error, &addinfo,
1525         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1526         element_set_name);
1527     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1528     if (records)
1529     {
1530         apdu_res->u.searchResponse->records = records;
1531         apdu_res->u.searchResponse->numberOfRecordsReturned =
1532             odr_intdup(odr, number_of_records_returned);
1533     }
1534     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1535     package.response() = apdu_res;
1536 }
1537
1538 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1539 {
1540     Z_GDU *gdu = package.request().get();
1541     Z_APDU *apdu_req = gdu->u.z3950;
1542     Z_APDU *apdu_res = 0;
1543     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1544
1545     mp::odr odr;
1546     if (!m_backend)
1547     {
1548         package.response() = odr.create_presentResponse(
1549             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1550         return;
1551     }
1552     const char *element_set_name = 0;
1553     Z_RecordComposition *comp = pr->recordComposition;
1554     if (comp && comp->which != Z_RecordComp_simple)
1555     {
1556         package.response() = odr.create_presentResponse(
1557             apdu_req, 
1558             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1559         return;
1560     }
1561     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1562         element_set_name = comp->u.simple->u.generic;
1563     Odr_int number_of_records_returned = 0;
1564     int error = 0;
1565     char *addinfo = 0;
1566     Z_Records *records = get_records(
1567         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1568         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1569         pr->preferredRecordSyntax, element_set_name);
1570
1571     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1572     if (records)
1573     {
1574         apdu_res->u.presentResponse->records = records;
1575         apdu_res->u.presentResponse->numberOfRecordsReturned =
1576             odr_intdup(odr, number_of_records_returned);
1577     }
1578     package.response() = apdu_res;
1579 }
1580
1581 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1582 {
1583     Z_GDU *gdu = package.request().get();
1584     if (!gdu)
1585         ;
1586     else if (gdu->which == Z_GDU_Z3950)
1587     {
1588         Z_APDU *apdu_req = gdu->u.z3950;
1589         if (apdu_req->which == Z_APDU_initRequest)
1590         {
1591             mp::odr odr;
1592             package.response() = odr.create_close(
1593                 apdu_req,
1594                 Z_Close_protocolError,
1595                 "double init");
1596         }
1597         else if (apdu_req->which == Z_APDU_searchRequest)
1598         {
1599             handle_search(package);
1600         }
1601         else if (apdu_req->which == Z_APDU_presentRequest)
1602         {
1603             handle_present(package);
1604         }
1605         else
1606         {
1607             mp::odr odr;
1608             package.response() = odr.create_close(
1609                 apdu_req,
1610                 Z_Close_protocolError,
1611                 "zoom filter cannot handle this APDU");
1612             package.session().close();
1613         }
1614     }
1615     else
1616     {
1617         package.session().close();
1618     }
1619 }
1620
1621 void yf::Zoom::Impl::process(mp::Package &package)
1622 {
1623     FrontendPtr f = get_frontend(package);
1624     Z_GDU *gdu = package.request().get();
1625
1626     if (f->m_is_virtual)
1627     {
1628         f->handle_package(package);
1629     }
1630     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1631              Z_APDU_initRequest)
1632     {
1633         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1634         f->m_init_gdu = gdu;
1635         
1636         mp::odr odr;
1637         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1638         Z_InitResponse *resp = apdu->u.initResponse;
1639         
1640         int i;
1641         static const int masks[] = {
1642             Z_Options_search,
1643             Z_Options_present,
1644             -1 
1645         };
1646         for (i = 0; masks[i] != -1; i++)
1647             if (ODR_MASK_GET(req->options, masks[i]))
1648                 ODR_MASK_SET(resp->options, masks[i]);
1649         
1650         static const int versions[] = {
1651             Z_ProtocolVersion_1,
1652             Z_ProtocolVersion_2,
1653             Z_ProtocolVersion_3,
1654             -1
1655         };
1656         for (i = 0; versions[i] != -1; i++)
1657             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1658                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1659             else
1660                 break;
1661         
1662         *resp->preferredMessageSize = *req->preferredMessageSize;
1663         *resp->maximumRecordSize = *req->maximumRecordSize;
1664         
1665         package.response() = apdu;
1666         f->m_is_virtual = true;
1667     }
1668     else
1669         package.move();
1670
1671     release_frontend(package);
1672 }
1673
1674
1675 static mp::filter::Base* filter_creator()
1676 {
1677     return new mp::filter::Zoom;
1678 }
1679
1680 extern "C" {
1681     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1682         0,
1683         "zoom",
1684         filter_creator
1685     };
1686 }
1687
1688
1689 /*
1690  * Local variables:
1691  * c-basic-offset: 4
1692  * c-file-style: "Stroustrup"
1693  * indent-tabs-mode: nil
1694  * End:
1695  * vim: shiftwidth=4 tabstop=8 expandtab
1696  */
1697