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