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