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