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