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