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