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