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