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