zoom: new target profile element literalTransform
[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, "authentication: %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
1012 }
1013
1014 Z_Records *yf::Zoom::Frontend::get_records(Odr_int start,
1015                                            Odr_int number_to_present,
1016                                            int *error,
1017                                            char **addinfo,
1018                                            Odr_int *number_of_records_returned,
1019                                            ODR odr,
1020                                            BackendPtr b,
1021                                            Odr_oid *preferredRecordSyntax,
1022                                            const char *element_set_name)
1023 {
1024     *number_of_records_returned = 0;
1025     Z_Records *records = 0;
1026     bool enable_pz2_retrieval = false; // whether target profile is used
1027     bool enable_pz2_transform = false; // whether XSLT is used as well
1028     bool assume_marc8_charset = false;
1029
1030     prepare_elements(b, preferredRecordSyntax,
1031                      element_set_name,
1032                      enable_pz2_retrieval,
1033                      enable_pz2_transform,
1034                      assume_marc8_charset);
1035
1036     if (start < 0 || number_to_present <=0)
1037         return records;
1038     
1039     if (number_to_present > 10000)
1040         number_to_present = 10000;
1041
1042     ZOOM_record *recs = (ZOOM_record *)
1043         odr_malloc(odr, (size_t) number_to_present * sizeof(*recs));
1044
1045     b->present(start, number_to_present, recs, error, addinfo, odr);
1046
1047     int i = 0;
1048     if (!*error)
1049     {
1050         for (i = 0; i < number_to_present; i++)
1051             if (!recs[i])
1052                 break;
1053     }
1054     if (i > 0)
1055     {  // only return records if no error and at least one record
1056         char *odr_database = odr_strdup(odr,
1057                                         b->m_frontend_database.c_str());
1058         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1059             odr_malloc(odr, sizeof(*npl));
1060         *number_of_records_returned = i;
1061         npl->num_records = i;
1062         npl->records = (Z_NamePlusRecord **)
1063             odr_malloc(odr, i * sizeof(*npl->records));
1064         for (i = 0; i < number_to_present; i++)
1065         {
1066             Z_NamePlusRecord *npr = 0;
1067             const char *addinfo;
1068             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1069                                               &addinfo, 0 /* diagset */);
1070                 
1071             if (sur_error)
1072             {
1073                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1074                                             addinfo);
1075             }
1076             else if (enable_pz2_retrieval)
1077             {
1078                 char rec_type_str[100];
1079                 const char *record_encoding = 0;
1080
1081                 if (b->sptr->record_encoding.length())
1082                     record_encoding = b->sptr->record_encoding.c_str();
1083                 else if (assume_marc8_charset)
1084                     record_encoding = "marc8";
1085
1086                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1087                 if (record_encoding)
1088                 {
1089                     strcat(rec_type_str, "; charset=");
1090                     strcat(rec_type_str, record_encoding);
1091                 }
1092                 
1093                 int rec_len;
1094                 xmlChar *xmlrec_buf = 0;
1095                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1096                                                       &rec_len);
1097                 if (!rec_buf && !npr)
1098                 {
1099                     std::string addinfo("ZOOM_record_get failed for type ");
1100
1101                     addinfo += rec_type_str;
1102                     npr = zget_surrogateDiagRec(
1103                         odr, odr_database, 
1104                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1105                         addinfo.c_str());
1106                 }
1107
1108                 if (rec_buf && b->xsp && enable_pz2_transform)
1109                 {
1110                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1111                     if (!rec_doc)
1112                     {
1113                         npr = zget_surrogateDiagRec(
1114                             odr, odr_database, 
1115                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1116                             "xml parse failed for record");
1117                     }
1118                     else
1119                     { 
1120                         xmlDoc *rec_res = 
1121                             xsltApplyStylesheet(b->xsp, rec_doc, 0);
1122
1123                         if (rec_res)
1124                         {
1125                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1126                                                    rec_res, b->xsp);
1127                             rec_buf = (const char *) xmlrec_buf;
1128
1129                             xmlFreeDoc(rec_res);
1130                         }
1131                         if (!rec_buf)
1132                         {
1133                             std::string addinfo;
1134
1135                             addinfo = "xslt apply failed for "
1136                                 + b->sptr->transform_xsl_fname;
1137                             npr = zget_surrogateDiagRec(
1138                                 odr, odr_database, 
1139                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1140                                 addinfo.c_str());
1141                         }
1142                         xmlFreeDoc(rec_doc);
1143                     }
1144                 }
1145
1146                 if (rec_buf)
1147                 {
1148                     xmlDoc *doc = xmlParseMemory(rec_buf, rec_len);
1149                     std::string res = 
1150                         mp::xml::url_recipe_handle(doc, b->sptr->urlRecipe);
1151                     if (res.length() && b->content_session_id.length())
1152                     {
1153                         size_t off = res.find_first_of("://");
1154                         if (off != std::string::npos)
1155                         {
1156                             char tmp[1024];
1157                             sprintf(tmp, "%s.%s/",
1158                                     b->content_session_id.c_str(),
1159                                     m_p->content_proxy_server.c_str());
1160                             res.insert(off + 3, tmp);
1161                         }
1162                     }
1163                     if (res.length())
1164                     {
1165                         xmlNode *ptr = xmlDocGetRootElement(doc);
1166                         while (ptr && ptr->type != XML_ELEMENT_NODE)
1167                             ptr = ptr->next;
1168                         xmlNode *c = 
1169                             xmlNewChild(ptr, 0, BAD_CAST "generated-url", 0);
1170                         xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1171                         xmlAddChild(c, t);
1172
1173                         if (xmlrec_buf)
1174                             xmlFree(xmlrec_buf);
1175
1176                         xmlDocDumpMemory(doc, &xmlrec_buf, &rec_len);
1177                         rec_buf = (const char *) xmlrec_buf;
1178                     }
1179                     xmlFreeDoc(doc);
1180                 }
1181                 if (!npr)
1182                 {
1183                     if (!rec_buf)
1184                         npr = zget_surrogateDiagRec(
1185                             odr, odr_database, 
1186                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1187                             rec_type_str);
1188                     else
1189                     {
1190                         npr = (Z_NamePlusRecord *)
1191                             odr_malloc(odr, sizeof(*npr));
1192                         npr->databaseName = odr_database;
1193                         npr->which = Z_NamePlusRecord_databaseRecord;
1194                         npr->u.databaseRecord =
1195                             z_ext_record_xml(odr, rec_buf, rec_len);
1196                     }
1197                 }
1198                 if (xmlrec_buf)
1199                     xmlFree(xmlrec_buf);
1200             }
1201             else
1202             {
1203                 Z_External *ext =
1204                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1205                 if (ext)
1206                 {
1207                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1208                     npr->databaseName = odr_database;
1209                     npr->which = Z_NamePlusRecord_databaseRecord;
1210                     npr->u.databaseRecord = ext;
1211                 }
1212                 else
1213                 {
1214                     npr = zget_surrogateDiagRec(
1215                         odr, odr_database, 
1216                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1217                         "ZOOM_record, type ext");
1218                 }
1219             }
1220             npl->records[i] = npr;
1221         }
1222         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1223         records->which = Z_Records_DBOSD;
1224         records->u.databaseOrSurDiagnostics = npl;
1225     }
1226     return records;
1227 }
1228
1229 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1230                                                     ODR odr)
1231 {
1232     struct cql_node *r = 0;
1233     if (!cn)
1234         return 0;
1235     switch (cn->which)
1236     {
1237     case CQL_NODE_ST:
1238         if (cn->u.st.index)
1239         {
1240             std::map<std::string,std::string>::const_iterator it;
1241             it = fieldmap.find(cn->u.st.index);
1242             if (it == fieldmap.end())
1243                 return cn;
1244             if (it->second.length())
1245                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1246             else
1247                 cn->u.st.index = 0;
1248         }
1249         break;
1250     case CQL_NODE_BOOL:
1251         r = convert_cql_fields(cn->u.boolean.left, odr);
1252         if (!r)
1253             r = convert_cql_fields(cn->u.boolean.right, odr);
1254         break;
1255     case CQL_NODE_SORT:
1256         r = convert_cql_fields(cn->u.sort.search, odr);
1257         break;
1258     }
1259     return r;
1260 }
1261
1262 static void sort_pqf_type_7(WRBUF pqf_wrbuf, const char *sru_sortkeys)
1263 {
1264     /* sortkey layour: path,schema,ascending,caseSensitive,missingValue */
1265     /* see cql_sortby_to_sortkeys of YAZ. */
1266     char **sortspec;
1267     int num_sortspec = 0;
1268     int i;
1269     NMEM nmem = nmem_create();
1270     
1271     if (sru_sortkeys)
1272         nmem_strsplit_blank(nmem, sru_sortkeys, &sortspec, &num_sortspec);
1273     if (num_sortspec > 0)
1274     {
1275         WRBUF w = wrbuf_alloc();
1276         for (i = 0; i < num_sortspec; i++)
1277         {
1278             char **arg;
1279             int num_arg;
1280             int ascending = 1;
1281             nmem_strsplitx(nmem, ",", sortspec[i], &arg, &num_arg, 0);
1282             
1283             if (num_arg > 2 && arg[2][0])
1284                 ascending = atoi(arg[2]);
1285             
1286             wrbuf_puts(w, "@or @attr 1=");
1287             yaz_encode_pqf_term(w, arg[0], strlen(arg[0]));
1288             wrbuf_printf(w, "@attr 7=%d %d ", ascending ? 1 : 2, i);
1289         }
1290         if (wrbuf_len(w))
1291         {
1292             wrbuf_puts(w, wrbuf_cstr(pqf_wrbuf));
1293             wrbuf_rewind(pqf_wrbuf);
1294             wrbuf_puts(pqf_wrbuf, wrbuf_cstr(w));
1295         }
1296         wrbuf_destroy(w);
1297     }
1298     nmem_destroy(nmem);
1299 }
1300
1301 static void sort_via_cql(WRBUF cql_sortby, const char *sru_sortkeys)
1302 {
1303     /* sortkey layour: path,schema,ascending,caseSensitive,missingValue */
1304     /* see cql_sortby_to_sortkeys of YAZ. */
1305     char **sortspec;
1306     int num_sortspec = 0;
1307     int i;
1308     NMEM nmem = nmem_create();
1309     
1310     if (sru_sortkeys)
1311         nmem_strsplit_blank(nmem, sru_sortkeys, &sortspec, &num_sortspec);
1312     if (num_sortspec > 0)
1313     {
1314         WRBUF w = wrbuf_alloc();
1315         for (i = 0; i < num_sortspec; i++)
1316         {
1317             char **arg;
1318             int num_arg;
1319             int ascending = 1;
1320             int case_sensitive = 0;
1321             const char *missing = 0;
1322             nmem_strsplitx(nmem, ",", sortspec[i], &arg, &num_arg, 0);
1323             
1324             if (num_arg > 2 && arg[2][0])
1325                 ascending = atoi(arg[2]);
1326             if (num_arg > 3 && arg[3][0])
1327                 case_sensitive = atoi(arg[3]);
1328             if (num_arg > 4 && arg[4][0])
1329                 missing = arg[4];
1330             if (i > 0)
1331                 wrbuf_puts(w, " ");
1332             else
1333                 wrbuf_puts(w, " sortby ");
1334             wrbuf_puts(w, arg[0]);  /* field */
1335             wrbuf_puts(w, "/");
1336             wrbuf_puts(w, ascending ? "ascending" : "descending");
1337             if (case_sensitive)
1338                 wrbuf_puts(w, "/respectCase");
1339             if (missing)
1340             {
1341                 if (!strcmp(missing, "omit"))
1342                     wrbuf_puts(w, "/missingOmit");
1343                 else if (!strcmp(missing, "abort"))
1344                     wrbuf_puts(w, "/missingFail");
1345                 else if (!strcmp(missing, "lowValue"))
1346                     wrbuf_puts(w, "/missingLow");
1347                 else if (!strcmp(missing, "highValue"))
1348                     wrbuf_puts(w, "/missingHigh");
1349             }
1350         }
1351         if (wrbuf_len(w))
1352             wrbuf_puts(cql_sortby, wrbuf_cstr(w));
1353         wrbuf_destroy(w);
1354     }
1355     nmem_destroy(nmem);
1356 }
1357
1358 #if YAZ_VERSIONL < 0x40206
1359 static void wrbuf_vp_puts(const char *buf, void *client_data)
1360 {
1361     WRBUF b = (WRBUF) client_data;
1362     wrbuf_puts(b, buf);
1363 }
1364 #endif
1365
1366 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1367 {
1368     Z_GDU *gdu = package.request().get();
1369     Z_APDU *apdu_req = gdu->u.z3950;
1370     Z_APDU *apdu_res = 0;
1371     mp::odr odr;
1372     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1373     if (sr->num_databaseNames != 1)
1374     {
1375         apdu_res = odr.create_searchResponse(
1376             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
1377         package.response() = apdu_res;
1378         return;
1379     }
1380
1381     int error = 0;
1382     char *addinfo = 0;
1383     std::string db(sr->databaseNames[0]);
1384     BackendPtr b = get_backend_from_databases(db, &error, &addinfo, odr);
1385     if (error)
1386     {
1387         apdu_res = 
1388             odr.create_searchResponse(apdu_req, error, addinfo);
1389         package.response() = apdu_res;
1390         return;
1391     }
1392
1393     b->set_option("setname", "default");
1394
1395     bool enable_pz2_retrieval = false;
1396     bool enable_pz2_transform = false;
1397     bool assume_marc8_charset = false;
1398     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
1399                      enable_pz2_retrieval,
1400                      enable_pz2_transform,
1401                      assume_marc8_charset);
1402
1403     Odr_int hits = 0;
1404     Z_Query *query = sr->query;
1405     WRBUF ccl_wrbuf = 0;
1406     WRBUF pqf_wrbuf = 0;
1407     std::string sru_sortkeys;
1408
1409     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1410     {
1411         // RPN
1412         pqf_wrbuf = wrbuf_alloc();
1413         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1414     }
1415     else if (query->which == Z_Query_type_2)
1416     {
1417         // CCL
1418         ccl_wrbuf = wrbuf_alloc();
1419         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1420                     query->u.type_2->len);
1421     }
1422     else if (query->which == Z_Query_type_104 &&
1423              query->u.type_104->which == Z_External_CQL)
1424     {
1425         // CQL
1426         const char *cql = query->u.type_104->u.cql;
1427         CQL_parser cp = cql_parser_create();
1428         int r = cql_parser_string(cp, cql);
1429         if (r)
1430         {
1431             cql_parser_destroy(cp);
1432             apdu_res = 
1433                 odr.create_searchResponse(apdu_req, 
1434                                           YAZ_BIB1_MALFORMED_QUERY,
1435                                           "CQL syntax error");
1436             package.response() = apdu_res;
1437             return;
1438         }
1439         struct cql_node *cn = cql_parser_result(cp);
1440         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1441         if (cn_error)
1442         {
1443             // hopefully we are getting a ptr to a index+relation+term node
1444             addinfo = 0;
1445             if (cn_error->which == CQL_NODE_ST)
1446                 addinfo = cn_error->u.st.index;
1447
1448             apdu_res = 
1449                 odr.create_searchResponse(apdu_req, 
1450                                           YAZ_BIB1_UNSUPP_USE_ATTRIBUTE,
1451                                           addinfo);
1452             package.response() = apdu_res;
1453             return;
1454         }
1455         char ccl_buf[1024];
1456
1457         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1458         if (r == 0)
1459         {
1460             ccl_wrbuf = wrbuf_alloc();
1461             wrbuf_puts(ccl_wrbuf, ccl_buf);
1462             
1463             WRBUF sru_sortkeys_wrbuf = wrbuf_alloc();
1464
1465             cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf);
1466
1467             sru_sortkeys.assign(wrbuf_cstr(sru_sortkeys_wrbuf));
1468             wrbuf_destroy(sru_sortkeys_wrbuf);
1469         }
1470         cql_parser_destroy(cp);
1471         if (r)
1472         {
1473             apdu_res = 
1474                 odr.create_searchResponse(apdu_req, 
1475                                           YAZ_BIB1_MALFORMED_QUERY,
1476                                           "CQL to CCL conversion error");
1477             package.response() = apdu_res;
1478             return;
1479         }
1480     }
1481     else
1482     {
1483         apdu_res = 
1484             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
1485         package.response() = apdu_res;
1486         return;
1487     }
1488
1489     if (ccl_wrbuf)
1490     {
1491         // CCL to PQF
1492         assert(pqf_wrbuf == 0);
1493         int cerror, cpos;
1494         struct ccl_rpn_node *cn;
1495         yaz_log(YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1496         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1497                           &cerror, &cpos);
1498         wrbuf_destroy(ccl_wrbuf);
1499         if (!cn)
1500         {
1501             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1502             int z3950_diag = YAZ_BIB1_MALFORMED_QUERY;
1503
1504             switch (cerror)
1505             {
1506             case CCL_ERR_UNKNOWN_QUAL:
1507                 z3950_diag = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1508                 break;
1509             case CCL_ERR_TRUNC_NOT_LEFT: 
1510             case CCL_ERR_TRUNC_NOT_RIGHT:
1511             case CCL_ERR_TRUNC_NOT_BOTH:
1512                 z3950_diag = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
1513                 break;
1514             }
1515             apdu_res = 
1516                 odr.create_searchResponse(apdu_req, z3950_diag, addinfo);
1517             package.response() = apdu_res;
1518             return;
1519         }
1520         pqf_wrbuf = wrbuf_alloc();
1521         ccl_pquery(pqf_wrbuf, cn);
1522         ccl_rpn_delete(cn);
1523     }
1524     
1525     assert(pqf_wrbuf);
1526     if (b->get_option("sru"))
1527     {
1528         int status = 0;
1529         Z_RPNQuery *zquery;
1530         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1531         WRBUF wrb = wrbuf_alloc();
1532             
1533         if (!strcmp(b->get_option("sru"), "solr"))
1534         {
1535             solr_transform_t cqlt = solr_transform_create();
1536             
1537             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1538             
1539             solr_transform_close(cqlt);
1540         }
1541         else
1542         {
1543             cql_transform_t cqlt = cql_transform_create();
1544             
1545             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1546             
1547             cql_transform_close(cqlt);
1548
1549             if (status == 0)
1550                 sort_via_cql(wrb, sru_sortkeys.c_str());
1551         }
1552         if (status == 0)
1553         {
1554             yaz_log(YLOG_LOG, "search CQL: %s", wrbuf_cstr(wrb));
1555             b->search_cql(wrbuf_cstr(wrb), &hits, &error, &addinfo, odr);
1556         }
1557         
1558         wrbuf_destroy(wrb);
1559         wrbuf_destroy(pqf_wrbuf);
1560         if (status)
1561         {
1562             apdu_res = 
1563                 odr.create_searchResponse(apdu_req, YAZ_BIB1_MALFORMED_QUERY,
1564                                           "can not convert from RPN to CQL/SOLR");
1565             package.response() = apdu_res;
1566             return;
1567         }
1568     }
1569     else
1570     {
1571         sort_pqf_type_7(pqf_wrbuf, sru_sortkeys.c_str());
1572
1573         yaz_log(YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1574         b->search_pqf(wrbuf_cstr(pqf_wrbuf), &hits, &error, &addinfo, odr);
1575         wrbuf_destroy(pqf_wrbuf);
1576     }
1577
1578     const char *element_set_name = 0;
1579     Odr_int number_to_present = 0;
1580     if (!error)
1581         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1582     
1583     Odr_int number_of_records_returned = 0;
1584     Z_Records *records = get_records(
1585         0, number_to_present, &error, &addinfo,
1586         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1587         element_set_name);
1588     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1589     if (records)
1590     {
1591         apdu_res->u.searchResponse->records = records;
1592         apdu_res->u.searchResponse->numberOfRecordsReturned =
1593             odr_intdup(odr, number_of_records_returned);
1594     }
1595     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1596     package.response() = apdu_res;
1597 }
1598
1599 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1600 {
1601     Z_GDU *gdu = package.request().get();
1602     Z_APDU *apdu_req = gdu->u.z3950;
1603     Z_APDU *apdu_res = 0;
1604     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1605
1606     mp::odr odr;
1607     if (!m_backend)
1608     {
1609         package.response() = odr.create_presentResponse(
1610             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1611         return;
1612     }
1613     const char *element_set_name = 0;
1614     Z_RecordComposition *comp = pr->recordComposition;
1615     if (comp && comp->which != Z_RecordComp_simple)
1616     {
1617         package.response() = odr.create_presentResponse(
1618             apdu_req, 
1619             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1620         return;
1621     }
1622     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1623         element_set_name = comp->u.simple->u.generic;
1624     Odr_int number_of_records_returned = 0;
1625     int error = 0;
1626     char *addinfo = 0;
1627     Z_Records *records = get_records(
1628         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1629         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1630         pr->preferredRecordSyntax, element_set_name);
1631
1632     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1633     if (records)
1634     {
1635         apdu_res->u.presentResponse->records = records;
1636         apdu_res->u.presentResponse->numberOfRecordsReturned =
1637             odr_intdup(odr, number_of_records_returned);
1638     }
1639     package.response() = apdu_res;
1640 }
1641
1642 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1643 {
1644     Z_GDU *gdu = package.request().get();
1645     if (!gdu)
1646         ;
1647     else if (gdu->which == Z_GDU_Z3950)
1648     {
1649         Z_APDU *apdu_req = gdu->u.z3950;
1650         if (apdu_req->which == Z_APDU_initRequest)
1651         {
1652             mp::odr odr;
1653             package.response() = odr.create_close(
1654                 apdu_req,
1655                 Z_Close_protocolError,
1656                 "double init");
1657         }
1658         else if (apdu_req->which == Z_APDU_searchRequest)
1659         {
1660             handle_search(package);
1661         }
1662         else if (apdu_req->which == Z_APDU_presentRequest)
1663         {
1664             handle_present(package);
1665         }
1666         else
1667         {
1668             mp::odr odr;
1669             package.response() = odr.create_close(
1670                 apdu_req,
1671                 Z_Close_protocolError,
1672                 "zoom filter cannot handle this APDU");
1673             package.session().close();
1674         }
1675     }
1676     else
1677     {
1678         package.session().close();
1679     }
1680 }
1681
1682 void yf::Zoom::Impl::process(mp::Package &package)
1683 {
1684     FrontendPtr f = get_frontend(package);
1685     Z_GDU *gdu = package.request().get();
1686
1687     if (f->m_is_virtual)
1688     {
1689         f->handle_package(package);
1690     }
1691     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1692              Z_APDU_initRequest)
1693     {
1694         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1695         f->m_init_gdu = gdu;
1696         
1697         mp::odr odr;
1698         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1699         Z_InitResponse *resp = apdu->u.initResponse;
1700         
1701         int i;
1702         static const int masks[] = {
1703             Z_Options_search,
1704             Z_Options_present,
1705             -1 
1706         };
1707         for (i = 0; masks[i] != -1; i++)
1708             if (ODR_MASK_GET(req->options, masks[i]))
1709                 ODR_MASK_SET(resp->options, masks[i]);
1710         
1711         static const int versions[] = {
1712             Z_ProtocolVersion_1,
1713             Z_ProtocolVersion_2,
1714             Z_ProtocolVersion_3,
1715             -1
1716         };
1717         for (i = 0; versions[i] != -1; i++)
1718             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1719                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1720             else
1721                 break;
1722         
1723         *resp->preferredMessageSize = *req->preferredMessageSize;
1724         *resp->maximumRecordSize = *req->maximumRecordSize;
1725         
1726         package.response() = apdu;
1727         f->m_is_virtual = true;
1728     }
1729     else
1730         package.move();
1731
1732     release_frontend(package);
1733 }
1734
1735
1736 static mp::filter::Base* filter_creator()
1737 {
1738     return new mp::filter::Zoom;
1739 }
1740
1741 extern "C" {
1742     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1743         0,
1744         "zoom",
1745         filter_creator
1746     };
1747 }
1748
1749
1750 /*
1751  * Local variables:
1752  * c-basic-offset: 4
1753  * c-file-style: "Stroustrup"
1754  * indent-tabs-mode: nil
1755  * End:
1756  * vim: shiftwidth=4 tabstop=8 expandtab
1757  */
1758