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