8d623d49cdd3e69ab89961f7692d228ac78ab092
[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 <fcntl.h>
24 #include "filter_zoom.hpp"
25 #include <yaz/zoom.h>
26 #include <yaz/yaz-version.h>
27 #include <yaz/tpath.h>
28 #include <yaz/srw.h>
29 #include <metaproxy/package.hpp>
30 #include <metaproxy/util.hpp>
31 #include <metaproxy/xmlutil.hpp>
32 #include "torus.hpp"
33
34 #include <libxslt/xsltutils.h>
35 #include <libxslt/transform.h>
36
37 #include <boost/thread/mutex.hpp>
38 #include <boost/thread/condition.hpp>
39 #include <yaz/ccl_xml.h>
40 #include <yaz/ccl.h>
41 #include <yaz/rpn2cql.h>
42 #include <yaz/rpn2solr.h>
43 #include <yaz/pquery.h>
44 #include <yaz/cql.h>
45 #include <yaz/oid_db.h>
46 #include <yaz/diagbib1.h>
47 #include <yaz/log.h>
48 #include <yaz/zgdu.h>
49 #include <yaz/querytowrbuf.h>
50
51 namespace mp = metaproxy_1;
52 namespace yf = mp::filter;
53
54 namespace metaproxy_1 {
55     namespace filter {
56         struct Zoom::Searchable : boost::noncopyable {
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(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                     sptr = m_p->parse_torus_record(ptr);
665                     break;
666                 }
667             }
668         }
669         xmlFreeDoc(doc);
670     }
671
672     if (!sptr)
673     {
674         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
675         *addinfo = odr_strdup(odr, database.c_str());
676         BackendPtr b;
677         return b;
678     }
679         
680     xsltStylesheetPtr xsp = 0;
681     if (sptr->transform_xsl_fname.length())
682     {
683         const char *path = 0;
684
685         if (m_p->xsldir.length())
686             path = m_p->xsldir.c_str();
687         else
688             path = m_p->file_path.c_str();
689         std::string fname;
690
691         char fullpath[1024];
692         char *cp = yaz_filepath_resolve(sptr->transform_xsl_fname.c_str(),
693                                         path, 0, fullpath);
694         if (cp)
695             fname.assign(cp);
696         else
697         {
698             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
699             *addinfo = (char *)
700                 odr_malloc(odr, 40 + sptr->transform_xsl_fname.length());
701             sprintf(*addinfo, "File could not be read: %s", 
702                     sptr->transform_xsl_fname.c_str());
703             BackendPtr b;
704             return b;
705         }
706         xmlDoc *xsp_doc = xmlParseFile(fname.c_str());
707         if (!xsp_doc)
708         {
709             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
710             *addinfo = (char *) odr_malloc(odr, 40 + fname.length());
711             sprintf(*addinfo, "xmlParseFile failed. File: %s", fname.c_str());
712             BackendPtr b;
713             return b;
714         }
715         xsp = xsltParseStylesheetDoc(xsp_doc);
716         if (!xsp)
717         {
718             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
719             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
720             BackendPtr b;
721             xmlFreeDoc(xsp_doc);
722             return b;
723         }
724     }
725
726     m_backend.reset();
727
728     BackendPtr b(new Backend(sptr));
729
730     b->xsp = xsp;
731     b->m_frontend_database = database;
732
733     if (sptr->query_encoding.length())
734         b->set_option("rpnCharset", sptr->query_encoding);
735
736     b->set_option("timeout", "40");
737     
738     if (m_p->apdu_log) 
739         b->set_option("apdulog", "1");
740
741     if (sptr->piggyback)
742         b->set_option("count", "10");
743
744     std::string authentication = sptr->authentication;
745     std::string proxy = sptr->cfProxy;
746         
747     const char *param_user = 0;
748     const char *param_password = 0;
749     const char *param_proxy = 0;
750     if (db_args.length())
751     {
752         char **names;
753         char **values;
754         int i;
755         int no_parms = yaz_uri_to_array(db_args.c_str(),
756                                         odr, &names, &values);
757         for (i = 0; i < no_parms; i++)
758         {
759             const char *name = names[i];
760             const char *value = values[i];
761             if (!strcmp(name, "user"))
762                 param_user = value;
763             else if (!strcmp(name, "password"))
764                 param_password = value;
765             else if (!strcmp(name, "proxy"))
766                 param_proxy = value;
767             else if (!strcmp(name, "cproxysession"))
768                 ;
769             else
770             {
771                 BackendPtr notfound;
772                 char *msg = (char*) odr_malloc(odr, strlen(name) + 30);
773                 *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
774                 sprintf(msg, "Bad database argument: %s", name);
775                 *addinfo = msg;
776                 return notfound;
777             }
778         }
779         if (param_user)
780         {
781             authentication = std::string(param_user);
782             if (param_password)
783                 authentication += "/" + std::string(param_password);
784         }
785         if (param_proxy)
786             proxy = param_proxy;
787     }
788
789     if (sptr->cfAuth.length())
790     {
791         // A CF target
792         b->set_option("user", sptr->cfAuth);
793         if (!param_user && !param_password && authentication.length())
794         {
795             if (db_args.length())
796                 db_args += "&";
797             // no database (auth) args specified already.. and the
798             // Torus authentication has it.. Generate the args that CF
799             // understands..
800             size_t found = authentication.find('/');
801             if (found != std::string::npos)
802             {
803                 db_args += "user=" +
804                     mp::util::uri_encode(authentication.substr(0, found))
805                     + "&password=" +
806                     mp::util::uri_encode(authentication.substr(found+1));
807             }
808             else
809                 db_args += "user=" + mp::util::uri_encode(authentication);
810         }
811         if (!param_proxy && proxy.length())
812         {
813             if (db_args.length())
814                 db_args += "&";
815             db_args += "proxy=" + mp::util::uri_encode(proxy);
816         }
817         if (sptr->cfSubDb.length())
818         {
819             if (db_args.length())
820                 db_args += "&";
821             db_args += "subdatabase=" + mp::util::uri_encode(sptr->cfSubDb);
822         }
823     }
824     else
825     {
826         db_args.clear(); // no arguments to be passed (non-CF)
827
828         size_t found = authentication.find('/');
829         
830         if (sptr->sru.length() && found != std::string::npos)
831         {
832             b->set_option("user", authentication.substr(0, found));
833             b->set_option("password", authentication.substr(found+1));
834         }
835         else
836             b->set_option("user", authentication);
837
838         if (proxy.length())
839             b->set_option("proxy", proxy);
840     }
841     if (b->sptr->contentConnector.length())
842     {
843         char *fname = (char *) xmalloc(m_p->content_tmp_file.length() + 8);
844         strcpy(fname, m_p->content_tmp_file.c_str());
845         int suffixlen;
846         char *xx = strstr(fname, "XXXXXX");
847         if (xx)
848             suffixlen = strlen(xx) - 6;
849         else
850         {
851             suffixlen = 0;
852             xx = fname + strlen(fname);
853             strcat(fname, "XXXXXX");
854         }
855         char tmp_char = xx[6];
856         sprintf(xx, "%06d", ((unsigned) rand()) % 1000000);
857         xx[6] = tmp_char;
858
859         int fd = creat(fname, 0666);
860         if (fd == -1)
861         {
862             yaz_log(YLOG_WARN|YLOG_ERRNO, "create %s", fname);
863             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
864             *addinfo = (char *)  odr_malloc(odr, 40 + strlen(fname));
865             sprintf(*addinfo, "Could not create %s", fname);
866             xfree(fname);
867             BackendPtr backend_null;
868             return backend_null;
869         }
870         b->content_session_id.assign(xx, 6);
871         WRBUF w = wrbuf_alloc();
872         wrbuf_puts(w, "#content_proxy\n");
873         wrbuf_printf(w, "connector: %s\n", b->sptr->contentConnector.c_str());
874         if (authentication.length())
875             wrbuf_printf(w, "authentication: %s\n", authentication.c_str());
876         if (proxy.length())
877             wrbuf_printf(w, "proxy: %s\n", proxy.c_str());
878         if (sptr->cfAuth.length())
879             wrbuf_printf(w, "cfauth: %s\n", sptr->cfAuth.c_str());
880         if (sptr->cfProxy.length())
881             wrbuf_printf(w, "cfproxy: %s\n", sptr->cfProxy.c_str());
882
883         write(fd, wrbuf_buf(w), wrbuf_len(w));
884         close(fd);
885         yaz_log(YLOG_LOG, "file %s created\n", fname);
886         xfree(fname);
887     }
888
889     std::string url;
890     if (sptr->sru.length())
891     {
892         url = "http://" + sptr->target;
893         b->set_option("sru", sptr->sru);
894     }
895     else
896     {
897         url = sptr->target;
898     }
899     if (db_args.length())
900         url += "," + db_args;
901     yaz_log(YLOG_LOG, "url=%s", url.c_str());
902     b->connect(url, error, addinfo, odr);
903     if (*error == 0)
904     {
905         m_backend = b;
906     }
907     return b;
908 }
909
910 Z_Records *yf::Zoom::Frontend::get_records(Odr_int start,
911                                            Odr_int number_to_present,
912                                            int *error,
913                                            char **addinfo,
914                                            Odr_int *number_of_records_returned,
915                                            ODR odr,
916                                            BackendPtr b,
917                                            Odr_oid *preferredRecordSyntax,
918                                            const char *element_set_name)
919 {
920     *number_of_records_returned = 0;
921     Z_Records *records = 0;
922     bool enable_pz2_retrieval = false; // whether target profile is used
923     bool enable_pz2_transform = false; // whether XSLT is used as well
924     bool assume_marc8_charset = false;
925
926     if (start < 0 || number_to_present <= 0)
927         return records;
928     
929     if (number_to_present > 10000)
930         number_to_present = 10000;
931     
932     ZOOM_record *recs = (ZOOM_record *)
933         odr_malloc(odr, number_to_present * sizeof(*recs));
934
935     char oid_name_str[OID_STR_MAX];
936     const char *syntax_name = 0;
937     
938     if (preferredRecordSyntax &&
939         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
940         && element_set_name)
941     {
942         if (!strcmp(element_set_name, m_p->element_transform.c_str()))
943         {
944             enable_pz2_retrieval = true;
945             enable_pz2_transform = true;
946         }
947         else if (!strcmp(element_set_name, m_p->element_raw.c_str()))
948         {
949             enable_pz2_retrieval = true;
950         }
951     }
952     
953     if (enable_pz2_retrieval)
954     {
955         if (b->sptr->request_syntax.length())
956         {
957             syntax_name = b->sptr->request_syntax.c_str();
958             const Odr_oid *syntax_oid = 
959                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
960             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
961                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
962                 assume_marc8_charset = true;
963         }
964     }
965     else if (preferredRecordSyntax)
966         syntax_name =
967             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
968
969     b->set_option("preferredRecordSyntax", syntax_name);
970
971     if (enable_pz2_retrieval)
972     {
973         element_set_name = 0;
974         if (b->sptr->element_set.length())
975             element_set_name = b->sptr->element_set.c_str();
976     }
977
978     b->set_option("elementSetName", element_set_name);
979
980     b->present(start, number_to_present, recs, error, addinfo, odr);
981
982     Odr_int i = 0;
983     if (!*error)
984     {
985         for (i = 0; i < number_to_present; i++)
986             if (!recs[i])
987                 break;
988     }
989     if (i > 0)
990     {  // only return records if no error and at least one record
991         char *odr_database = odr_strdup(odr,
992                                         b->m_frontend_database.c_str());
993         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
994             odr_malloc(odr, sizeof(*npl));
995         *number_of_records_returned = i;
996         npl->num_records = i;
997         npl->records = (Z_NamePlusRecord **)
998             odr_malloc(odr, i * sizeof(*npl->records));
999         for (i = 0; i < number_to_present; i++)
1000         {
1001             Z_NamePlusRecord *npr = 0;
1002             const char *addinfo;
1003             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1004                                               &addinfo, 0 /* diagset */);
1005                 
1006             if (sur_error)
1007             {
1008                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1009                                             addinfo);
1010             }
1011             else if (enable_pz2_retrieval)
1012             {
1013                 char rec_type_str[100];
1014                 const char *record_encoding = 0;
1015
1016                 if (b->sptr->record_encoding.length())
1017                     record_encoding = b->sptr->record_encoding.c_str();
1018                 else if (assume_marc8_charset)
1019                     record_encoding = "marc8";
1020
1021                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1022                 if (record_encoding)
1023                 {
1024                     strcat(rec_type_str, "; charset=");
1025                     strcat(rec_type_str, record_encoding);
1026                 }
1027                 
1028                 int rec_len;
1029                 xmlChar *xmlrec_buf = 0;
1030                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1031                                                       &rec_len);
1032                 if (!rec_buf && !npr)
1033                 {
1034                     std::string addinfo("ZOOM_record_get failed for type ");
1035
1036                     addinfo += rec_type_str;
1037                     npr = zget_surrogateDiagRec(
1038                         odr, odr_database, 
1039                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1040                         addinfo.c_str());
1041                 }
1042
1043                 if (rec_buf && b->xsp && enable_pz2_transform)
1044                 {
1045                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1046                     if (!rec_doc)
1047                     {
1048                         npr = zget_surrogateDiagRec(
1049                             odr, odr_database, 
1050                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1051                             "xml parse failed for record");
1052                     }
1053                     else
1054                     { 
1055                         xmlDoc *rec_res = 
1056                             xsltApplyStylesheet(b->xsp, rec_doc, 0);
1057
1058                         if (rec_res)
1059                         {
1060                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1061                                                    rec_res, b->xsp);
1062                             rec_buf = (const char *) xmlrec_buf;
1063
1064                             xmlFreeDoc(rec_res);
1065                         }
1066                         if (!rec_buf)
1067                         {
1068                             std::string addinfo;
1069
1070                             addinfo = "xslt apply failed for "
1071                                 + b->sptr->transform_xsl_fname;
1072                             npr = zget_surrogateDiagRec(
1073                                 odr, odr_database, 
1074                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1075                                 addinfo.c_str());
1076                         }
1077                         xmlFreeDoc(rec_doc);
1078                     }
1079                 }
1080
1081                 if (rec_buf)
1082                 {
1083                     xmlDoc *doc = xmlParseMemory(rec_buf, rec_len);
1084                     std::string res = 
1085                         mp::xml::url_recipe_handle(doc, b->sptr->urlRecipe);
1086                     if (res.length() && b->content_session_id.length())
1087                     {
1088                         size_t off = res.find_first_of("://");
1089                         if (off != std::string::npos)
1090                         {
1091                             char tmp[1024];
1092                             sprintf(tmp, "%s.%s/",
1093                                     b->content_session_id.c_str(),
1094                                     m_p->content_proxy_server.c_str());
1095                             res.insert(off + 3, tmp);
1096                         }
1097                     }
1098                     if (res.length())
1099                     {
1100                         xmlNode *ptr = xmlDocGetRootElement(doc);
1101                         while (ptr && ptr->type != XML_ELEMENT_NODE)
1102                             ptr = ptr->next;
1103                         xmlNode *c = 
1104                             xmlNewChild(ptr, 0, BAD_CAST "generated-url", 0);
1105                         xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1106                         xmlAddChild(c, t);
1107
1108                         if (xmlrec_buf)
1109                             xmlFree(xmlrec_buf);
1110
1111                         xmlDocDumpMemory(doc, &xmlrec_buf, &rec_len);
1112                         rec_buf = (const char *) xmlrec_buf;
1113                     }
1114                     xmlFreeDoc(doc);
1115                 }
1116                 if (!npr)
1117                 {
1118                     if (!rec_buf)
1119                         npr = zget_surrogateDiagRec(
1120                             odr, odr_database, 
1121                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1122                             rec_type_str);
1123                     else
1124                     {
1125                         npr = (Z_NamePlusRecord *)
1126                             odr_malloc(odr, sizeof(*npr));
1127                         npr->databaseName = odr_database;
1128                         npr->which = Z_NamePlusRecord_databaseRecord;
1129                         npr->u.databaseRecord =
1130                             z_ext_record_xml(odr, rec_buf, rec_len);
1131                     }
1132                 }
1133                 if (xmlrec_buf)
1134                     xmlFree(xmlrec_buf);
1135             }
1136             else
1137             {
1138                 Z_External *ext =
1139                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1140                 if (ext)
1141                 {
1142                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1143                     npr->databaseName = odr_database;
1144                     npr->which = Z_NamePlusRecord_databaseRecord;
1145                     npr->u.databaseRecord = ext;
1146                 }
1147                 else
1148                 {
1149                     npr = zget_surrogateDiagRec(
1150                         odr, odr_database, 
1151                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1152                         "ZOOM_record, type ext");
1153                 }
1154             }
1155             npl->records[i] = npr;
1156         }
1157         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1158         records->which = Z_Records_DBOSD;
1159         records->u.databaseOrSurDiagnostics = npl;
1160     }
1161     return records;
1162 }
1163     
1164 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1165                                                     ODR odr)
1166 {
1167     struct cql_node *r = 0;
1168     if (!cn)
1169         return 0;
1170     switch (cn->which)
1171     {
1172     case CQL_NODE_ST:
1173         if (cn->u.st.index)
1174         {
1175             std::map<std::string,std::string>::const_iterator it;
1176             it = fieldmap.find(cn->u.st.index);
1177             if (it == fieldmap.end())
1178                 return cn;
1179             if (it->second.length())
1180                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1181             else
1182                 cn->u.st.index = 0;
1183         }
1184         break;
1185     case CQL_NODE_BOOL:
1186         r = convert_cql_fields(cn->u.boolean.left, odr);
1187         if (!r)
1188             r = convert_cql_fields(cn->u.boolean.right, odr);
1189         break;
1190     case CQL_NODE_SORT:
1191         r = convert_cql_fields(cn->u.sort.search, odr);
1192         break;
1193     }
1194     return r;
1195 }
1196
1197 static void sort_pqf_type_7(WRBUF pqf_wrbuf, const char *sru_sortkeys)
1198 {
1199     /* sortkey layour: path,schema,ascending,caseSensitive,missingValue */
1200     /* see cql_sortby_to_sortkeys of YAZ. */
1201     char **sortspec;
1202     int num_sortspec = 0;
1203     int i;
1204     NMEM nmem = nmem_create();
1205     
1206     if (sru_sortkeys)
1207         nmem_strsplit_blank(nmem, sru_sortkeys, &sortspec, &num_sortspec);
1208     if (num_sortspec > 0)
1209     {
1210         WRBUF w = wrbuf_alloc();
1211         for (i = 0; i < num_sortspec; i++)
1212         {
1213             char **arg;
1214             int num_arg;
1215             int ascending = 1;
1216             nmem_strsplitx(nmem, ",", sortspec[i], &arg, &num_arg, 0);
1217             
1218             if (num_arg > 2 && arg[2][0])
1219                 ascending = atoi(arg[2]);
1220             
1221             wrbuf_puts(w, "@or @attr 1=");
1222             yaz_encode_pqf_term(w, arg[0], strlen(arg[0]));
1223             wrbuf_printf(w, "@attr 7=%d %d ", ascending ? 1 : 2, i);
1224         }
1225         if (wrbuf_len(w))
1226         {
1227             wrbuf_puts(w, wrbuf_cstr(pqf_wrbuf));
1228             wrbuf_rewind(pqf_wrbuf);
1229             wrbuf_puts(pqf_wrbuf, wrbuf_cstr(w));
1230         }
1231         wrbuf_destroy(w);
1232     }
1233     nmem_destroy(nmem);
1234 }
1235
1236 static void sort_via_cql(WRBUF cql_sortby, const char *sru_sortkeys)
1237 {
1238     /* sortkey layour: path,schema,ascending,caseSensitive,missingValue */
1239     /* see cql_sortby_to_sortkeys of YAZ. */
1240     char **sortspec;
1241     int num_sortspec = 0;
1242     int i;
1243     NMEM nmem = nmem_create();
1244     
1245     if (sru_sortkeys)
1246         nmem_strsplit_blank(nmem, sru_sortkeys, &sortspec, &num_sortspec);
1247     if (num_sortspec > 0)
1248     {
1249         WRBUF w = wrbuf_alloc();
1250         for (i = 0; i < num_sortspec; i++)
1251         {
1252             char **arg;
1253             int num_arg;
1254             int ascending = 1;
1255             int case_sensitive = 0;
1256             const char *missing = 0;
1257             nmem_strsplitx(nmem, ",", sortspec[i], &arg, &num_arg, 0);
1258             
1259             if (num_arg > 2 && arg[2][0])
1260                 ascending = atoi(arg[2]);
1261             if (num_arg > 3 && arg[3][0])
1262                 case_sensitive = atoi(arg[3]);
1263             if (num_arg > 4 && arg[4][0])
1264                 missing = arg[4];
1265             if (i > 0)
1266                 wrbuf_puts(w, " ");
1267             else
1268                 wrbuf_puts(w, " sortby ");
1269             wrbuf_puts(w, arg[0]);  /* field */
1270             wrbuf_puts(w, "/");
1271             wrbuf_puts(w, ascending ? "ascending" : "descending");
1272             if (case_sensitive)
1273                 wrbuf_puts(w, "/respectCase");
1274             if (missing)
1275             {
1276                 if (!strcmp(missing, "omit"))
1277                     wrbuf_puts(w, "/missingOmit");
1278                 else if (!strcmp(missing, "abort"))
1279                     wrbuf_puts(w, "/missingFail");
1280                 else if (!strcmp(missing, "lowValue"))
1281                     wrbuf_puts(w, "/missingLow");
1282                 else if (!strcmp(missing, "highValue"))
1283                     wrbuf_puts(w, "/missingHigh");
1284             }
1285         }
1286         if (wrbuf_len(w))
1287             wrbuf_puts(cql_sortby, wrbuf_cstr(w));
1288         wrbuf_destroy(w);
1289     }
1290     nmem_destroy(nmem);
1291 }
1292
1293 #if YAZ_VERSIONL < 0x40206
1294 static void wrbuf_vp_puts(const char *buf, void *client_data)
1295 {
1296     WRBUF b = (WRBUF) client_data;
1297     wrbuf_puts(b, buf);
1298 }
1299 #endif
1300
1301 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1302 {
1303     Z_GDU *gdu = package.request().get();
1304     Z_APDU *apdu_req = gdu->u.z3950;
1305     Z_APDU *apdu_res = 0;
1306     mp::odr odr;
1307     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1308     if (sr->num_databaseNames != 1)
1309     {
1310         apdu_res = odr.create_searchResponse(
1311             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
1312         package.response() = apdu_res;
1313         return;
1314     }
1315
1316     int error = 0;
1317     char *addinfo = 0;
1318     std::string db(sr->databaseNames[0]);
1319     BackendPtr b = get_backend_from_databases(db, &error, &addinfo, odr);
1320     if (error)
1321     {
1322         apdu_res = 
1323             odr.create_searchResponse(apdu_req, error, addinfo);
1324         package.response() = apdu_res;
1325         return;
1326     }
1327
1328     b->set_option("setname", "default");
1329
1330     Odr_int hits = 0;
1331     Z_Query *query = sr->query;
1332     WRBUF ccl_wrbuf = 0;
1333     WRBUF pqf_wrbuf = 0;
1334     std::string sru_sortkeys;
1335
1336     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1337     {
1338         // RPN
1339         pqf_wrbuf = wrbuf_alloc();
1340         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1341     }
1342     else if (query->which == Z_Query_type_2)
1343     {
1344         // CCL
1345         ccl_wrbuf = wrbuf_alloc();
1346         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1347                     query->u.type_2->len);
1348     }
1349     else if (query->which == Z_Query_type_104 &&
1350              query->u.type_104->which == Z_External_CQL)
1351     {
1352         // CQL
1353         const char *cql = query->u.type_104->u.cql;
1354         CQL_parser cp = cql_parser_create();
1355         int r = cql_parser_string(cp, cql);
1356         if (r)
1357         {
1358             cql_parser_destroy(cp);
1359             apdu_res = 
1360                 odr.create_searchResponse(apdu_req, 
1361                                           YAZ_BIB1_MALFORMED_QUERY,
1362                                           "CQL syntax error");
1363             package.response() = apdu_res;
1364             return;
1365         }
1366         struct cql_node *cn = cql_parser_result(cp);
1367         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1368         if (cn_error)
1369         {
1370             // hopefully we are getting a ptr to a index+relation+term node
1371             addinfo = 0;
1372             if (cn_error->which == CQL_NODE_ST)
1373                 addinfo = cn_error->u.st.index;
1374
1375             apdu_res = 
1376                 odr.create_searchResponse(apdu_req, 
1377                                           YAZ_BIB1_UNSUPP_USE_ATTRIBUTE,
1378                                           addinfo);
1379             package.response() = apdu_res;
1380             return;
1381         }
1382         char ccl_buf[1024];
1383
1384         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1385         if (r == 0)
1386         {
1387             ccl_wrbuf = wrbuf_alloc();
1388             wrbuf_puts(ccl_wrbuf, ccl_buf);
1389             
1390             WRBUF sru_sortkeys_wrbuf = wrbuf_alloc();
1391
1392             cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf);
1393
1394             sru_sortkeys.assign(wrbuf_cstr(sru_sortkeys_wrbuf));
1395             wrbuf_destroy(sru_sortkeys_wrbuf);
1396         }
1397         cql_parser_destroy(cp);
1398         if (r)
1399         {
1400             apdu_res = 
1401                 odr.create_searchResponse(apdu_req, 
1402                                           YAZ_BIB1_MALFORMED_QUERY,
1403                                           "CQL to CCL conversion error");
1404             package.response() = apdu_res;
1405             return;
1406         }
1407     }
1408     else
1409     {
1410         apdu_res = 
1411             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
1412         package.response() = apdu_res;
1413         return;
1414     }
1415
1416     if (ccl_wrbuf)
1417     {
1418         // CCL to PQF
1419         assert(pqf_wrbuf == 0);
1420         int cerror, cpos;
1421         struct ccl_rpn_node *cn;
1422         yaz_log(YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1423         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1424                           &cerror, &cpos);
1425         wrbuf_destroy(ccl_wrbuf);
1426         if (!cn)
1427         {
1428             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1429             int z3950_diag = YAZ_BIB1_MALFORMED_QUERY;
1430
1431             switch (cerror)
1432             {
1433             case CCL_ERR_UNKNOWN_QUAL:
1434                 z3950_diag = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1435                 break;
1436             case CCL_ERR_TRUNC_NOT_LEFT: 
1437             case CCL_ERR_TRUNC_NOT_RIGHT:
1438             case CCL_ERR_TRUNC_NOT_BOTH:
1439                 z3950_diag = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
1440                 break;
1441             }
1442             apdu_res = 
1443                 odr.create_searchResponse(apdu_req, z3950_diag, addinfo);
1444             package.response() = apdu_res;
1445             return;
1446         }
1447         pqf_wrbuf = wrbuf_alloc();
1448         ccl_pquery(pqf_wrbuf, cn);
1449         ccl_rpn_delete(cn);
1450     }
1451     
1452     assert(pqf_wrbuf);
1453     if (b->get_option("sru"))
1454     {
1455         int status = 0;
1456         Z_RPNQuery *zquery;
1457         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1458         WRBUF wrb = wrbuf_alloc();
1459             
1460         if (!strcmp(b->get_option("sru"), "solr"))
1461         {
1462             solr_transform_t cqlt = solr_transform_create();
1463             
1464             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1465             
1466             solr_transform_close(cqlt);
1467         }
1468         else
1469         {
1470             cql_transform_t cqlt = cql_transform_create();
1471             
1472             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1473             
1474             cql_transform_close(cqlt);
1475
1476             if (status == 0)
1477                 sort_via_cql(wrb, sru_sortkeys.c_str());
1478         }
1479         if (status == 0)
1480         {
1481             yaz_log(YLOG_LOG, "search CQL: %s", wrbuf_cstr(wrb));
1482             b->search_cql(wrbuf_cstr(wrb), &hits, &error, &addinfo, odr);
1483         }
1484         
1485         wrbuf_destroy(wrb);
1486         wrbuf_destroy(pqf_wrbuf);
1487         if (status)
1488         {
1489             apdu_res = 
1490                 odr.create_searchResponse(apdu_req, YAZ_BIB1_MALFORMED_QUERY,
1491                                           "can not convert from RPN to CQL/SOLR");
1492             package.response() = apdu_res;
1493             return;
1494         }
1495     }
1496     else
1497     {
1498         sort_pqf_type_7(pqf_wrbuf, sru_sortkeys.c_str());
1499
1500         yaz_log(YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1501         b->search_pqf(wrbuf_cstr(pqf_wrbuf), &hits, &error, &addinfo, odr);
1502         wrbuf_destroy(pqf_wrbuf);
1503     }
1504
1505     const char *element_set_name = 0;
1506     Odr_int number_to_present = 0;
1507     if (!error)
1508         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1509     
1510     Odr_int number_of_records_returned = 0;
1511     Z_Records *records = get_records(
1512         0, number_to_present, &error, &addinfo,
1513         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1514         element_set_name);
1515     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1516     if (records)
1517     {
1518         apdu_res->u.searchResponse->records = records;
1519         apdu_res->u.searchResponse->numberOfRecordsReturned =
1520             odr_intdup(odr, number_of_records_returned);
1521     }
1522     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1523     package.response() = apdu_res;
1524 }
1525
1526 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1527 {
1528     Z_GDU *gdu = package.request().get();
1529     Z_APDU *apdu_req = gdu->u.z3950;
1530     Z_APDU *apdu_res = 0;
1531     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1532
1533     mp::odr odr;
1534     if (!m_backend)
1535     {
1536         package.response() = odr.create_presentResponse(
1537             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1538         return;
1539     }
1540     const char *element_set_name = 0;
1541     Z_RecordComposition *comp = pr->recordComposition;
1542     if (comp && comp->which != Z_RecordComp_simple)
1543     {
1544         package.response() = odr.create_presentResponse(
1545             apdu_req, 
1546             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1547         return;
1548     }
1549     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1550         element_set_name = comp->u.simple->u.generic;
1551     Odr_int number_of_records_returned = 0;
1552     int error = 0;
1553     char *addinfo = 0;
1554     Z_Records *records = get_records(
1555         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1556         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1557         pr->preferredRecordSyntax, element_set_name);
1558
1559     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1560     if (records)
1561     {
1562         apdu_res->u.presentResponse->records = records;
1563         apdu_res->u.presentResponse->numberOfRecordsReturned =
1564             odr_intdup(odr, number_of_records_returned);
1565     }
1566     package.response() = apdu_res;
1567 }
1568
1569 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1570 {
1571     Z_GDU *gdu = package.request().get();
1572     if (!gdu)
1573         ;
1574     else if (gdu->which == Z_GDU_Z3950)
1575     {
1576         Z_APDU *apdu_req = gdu->u.z3950;
1577         if (apdu_req->which == Z_APDU_initRequest)
1578         {
1579             mp::odr odr;
1580             package.response() = odr.create_close(
1581                 apdu_req,
1582                 Z_Close_protocolError,
1583                 "double init");
1584         }
1585         else if (apdu_req->which == Z_APDU_searchRequest)
1586         {
1587             handle_search(package);
1588         }
1589         else if (apdu_req->which == Z_APDU_presentRequest)
1590         {
1591             handle_present(package);
1592         }
1593         else
1594         {
1595             mp::odr odr;
1596             package.response() = odr.create_close(
1597                 apdu_req,
1598                 Z_Close_protocolError,
1599                 "zoom filter cannot handle this APDU");
1600             package.session().close();
1601         }
1602     }
1603     else
1604     {
1605         package.session().close();
1606     }
1607 }
1608
1609 void yf::Zoom::Impl::process(mp::Package &package)
1610 {
1611     FrontendPtr f = get_frontend(package);
1612     Z_GDU *gdu = package.request().get();
1613
1614     if (f->m_is_virtual)
1615     {
1616         f->handle_package(package);
1617     }
1618     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1619              Z_APDU_initRequest)
1620     {
1621         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1622         f->m_init_gdu = gdu;
1623         
1624         mp::odr odr;
1625         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1626         Z_InitResponse *resp = apdu->u.initResponse;
1627         
1628         int i;
1629         static const int masks[] = {
1630             Z_Options_search,
1631             Z_Options_present,
1632             -1 
1633         };
1634         for (i = 0; masks[i] != -1; i++)
1635             if (ODR_MASK_GET(req->options, masks[i]))
1636                 ODR_MASK_SET(resp->options, masks[i]);
1637         
1638         static const int versions[] = {
1639             Z_ProtocolVersion_1,
1640             Z_ProtocolVersion_2,
1641             Z_ProtocolVersion_3,
1642             -1
1643         };
1644         for (i = 0; versions[i] != -1; i++)
1645             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1646                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1647             else
1648                 break;
1649         
1650         *resp->preferredMessageSize = *req->preferredMessageSize;
1651         *resp->maximumRecordSize = *req->maximumRecordSize;
1652         
1653         package.response() = apdu;
1654         f->m_is_virtual = true;
1655     }
1656     else
1657         package.move();
1658
1659     release_frontend(package);
1660 }
1661
1662
1663 static mp::filter::Base* filter_creator()
1664 {
1665     return new mp::filter::Zoom;
1666 }
1667
1668 extern "C" {
1669     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1670         0,
1671         "zoom",
1672         filter_creator
1673     };
1674 }
1675
1676
1677 /*
1678  * Local variables:
1679  * c-basic-offset: 4
1680  * c-file-style: "Stroustrup"
1681  * indent-tabs-mode: nil
1682  * End:
1683  * vim: shiftwidth=4 tabstop=8 expandtab
1684  */
1685