Version 1.3.3
[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 <fcntl.h>
24 #include "filter_zoom.hpp"
25 #include <yaz/zoom.h>
26 #include <yaz/yaz-version.h>
27 #include <yaz/tpath.h>
28 #include <yaz/srw.h>
29 #include <metaproxy/package.hpp>
30 #include <metaproxy/util.hpp>
31 #include <metaproxy/xmlutil.hpp>
32 #include "torus.hpp"
33
34 #include <libxslt/xsltutils.h>
35 #include <libxslt/transform.h>
36
37 #include <boost/thread/mutex.hpp>
38 #include <boost/thread/condition.hpp>
39 #include <yaz/ccl_xml.h>
40 #include <yaz/ccl.h>
41 #include <yaz/rpn2cql.h>
42 #include <yaz/rpn2solr.h>
43 #include <yaz/pquery.h>
44 #include <yaz/cql.h>
45 #include <yaz/oid_db.h>
46 #include <yaz/diagbib1.h>
47 #include <yaz/log.h>
48 #include <yaz/zgdu.h>
49 #include <yaz/querytowrbuf.h>
50
51 namespace mp = metaproxy_1;
52 namespace yf = mp::filter;
53
54 namespace metaproxy_1 {
55     namespace filter {
56         struct Zoom::Searchable : boost::noncopyable {
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(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     std::string authentication = sptr->authentication;
742     std::string proxy = sptr->cfProxy;
743         
744     const char *param_user = 0;
745     const char *param_password = 0;
746     const char *param_proxy = 0;
747     if (db_args.length())
748     {
749         char **names;
750         char **values;
751         int i;
752         int no_parms = yaz_uri_to_array(db_args.c_str(),
753                                         odr, &names, &values);
754         for (i = 0; i < no_parms; i++)
755         {
756             const char *name = names[i];
757             const char *value = values[i];
758             if (!strcmp(name, "user"))
759                 param_user = value;
760             else if (!strcmp(name, "password"))
761                 param_password = value;
762             else if (!strcmp(name, "proxy"))
763                 param_proxy = value;
764             else if (!strcmp(name, "cproxysession"))
765                 ;
766             else
767             {
768                 BackendPtr notfound;
769                 char *msg = (char*) odr_malloc(odr, strlen(name) + 30);
770                 *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
771                 sprintf(msg, "Bad database argument: %s", name);
772                 *addinfo = msg;
773                 return notfound;
774             }
775         }
776         if (param_user)
777         {
778             authentication = std::string(param_user);
779             if (param_password)
780                 authentication += "/" + std::string(param_password);
781         }
782         if (param_proxy)
783             proxy = param_proxy;
784     }
785
786     if (sptr->cfAuth.length())
787     {
788         // A CF target
789         b->set_option("user", sptr->cfAuth);
790         if (!param_user && !param_password && authentication.length())
791         {
792             if (db_args.length())
793                 db_args += "&";
794             // no database (auth) args specified already.. and the
795             // Torus authentication has it.. Generate the args that CF
796             // understands..
797             size_t found = authentication.find('/');
798             if (found != std::string::npos)
799             {
800                 db_args += "user=" +
801                     mp::util::uri_encode(authentication.substr(0, found))
802                     + "&password=" +
803                     mp::util::uri_encode(authentication.substr(found+1));
804             }
805             else
806                 db_args += "user=" + mp::util::uri_encode(authentication);
807         }
808         if (!param_proxy && proxy.length())
809         {
810             if (db_args.length())
811                 db_args += "&";
812             db_args += "proxy=" + mp::util::uri_encode(proxy);
813         }
814         if (sptr->cfSubDb.length())
815         {
816             if (db_args.length())
817                 db_args += "&";
818             db_args += "subdatabase=" + mp::util::uri_encode(sptr->cfSubDb);
819         }
820     }
821     else
822     {
823         db_args.clear(); // no arguments to be passed (non-CF)
824
825         size_t found = authentication.find('/');
826         
827         if (sptr->sru.length() && found != std::string::npos)
828         {
829             b->set_option("user", authentication.substr(0, found));
830             b->set_option("password", authentication.substr(found+1));
831         }
832         else
833             b->set_option("user", authentication);
834
835         if (proxy.length())
836             b->set_option("proxy", proxy);
837     }
838     if (b->sptr->contentConnector.length())
839     {
840         char *fname = (char *) xmalloc(m_p->content_tmp_file.length() + 8);
841         strcpy(fname, m_p->content_tmp_file.c_str());
842         int suffixlen;
843         char *xx = strstr(fname, "XXXXXX");
844         if (xx)
845             suffixlen = strlen(xx) - 6;
846         else
847         {
848             suffixlen = 0;
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         int fd = creat(fname, 0666);
857         if (fd == -1)
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->cfAuth.length())
876             wrbuf_printf(w, "cfauth: %s\n", sptr->cfAuth.c_str());
877         if (sptr->cfProxy.length())
878             wrbuf_printf(w, "cfproxy: %s\n", sptr->cfProxy.c_str());
879
880         write(fd, wrbuf_buf(w), wrbuf_len(w));
881         close(fd);
882         yaz_log(YLOG_LOG, "file %s created\n", fname);
883         xfree(fname);
884     }
885
886     std::string url;
887     if (sptr->sru.length())
888     {
889         url = "http://" + sptr->target;
890         b->set_option("sru", sptr->sru);
891     }
892     else
893     {
894         url = sptr->target;
895     }
896     if (db_args.length())
897         url += "," + db_args;
898     yaz_log(YLOG_LOG, "url=%s", url.c_str());
899     b->connect(url, error, addinfo, odr);
900     if (*error == 0)
901     {
902         m_backend = b;
903     }
904     return b;
905 }
906
907 Z_Records *yf::Zoom::Frontend::get_records(Odr_int start,
908                                            Odr_int number_to_present,
909                                            int *error,
910                                            char **addinfo,
911                                            Odr_int *number_of_records_returned,
912                                            ODR odr,
913                                            BackendPtr b,
914                                            Odr_oid *preferredRecordSyntax,
915                                            const char *element_set_name)
916 {
917     *number_of_records_returned = 0;
918     Z_Records *records = 0;
919     bool enable_pz2_retrieval = false; // whether target profile is used
920     bool enable_pz2_transform = false; // whether XSLT is used as well
921     bool assume_marc8_charset = false;
922
923     if (start < 0 || number_to_present <= 0)
924         return records;
925     
926     if (number_to_present > 10000)
927         number_to_present = 10000;
928     
929     ZOOM_record *recs = (ZOOM_record *)
930         odr_malloc(odr, number_to_present * sizeof(*recs));
931
932     char oid_name_str[OID_STR_MAX];
933     const char *syntax_name = 0;
934     
935     if (preferredRecordSyntax &&
936         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
937         && element_set_name)
938     {
939         if (!strcmp(element_set_name, m_p->element_transform.c_str()))
940         {
941             enable_pz2_retrieval = true;
942             enable_pz2_transform = true;
943         }
944         else if (!strcmp(element_set_name, m_p->element_raw.c_str()))
945         {
946             enable_pz2_retrieval = true;
947         }
948     }
949     
950     if (enable_pz2_retrieval)
951     {
952         if (b->sptr->request_syntax.length())
953         {
954             syntax_name = b->sptr->request_syntax.c_str();
955             const Odr_oid *syntax_oid = 
956                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
957             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
958                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
959                 assume_marc8_charset = true;
960         }
961     }
962     else if (preferredRecordSyntax)
963         syntax_name =
964             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
965
966     b->set_option("preferredRecordSyntax", syntax_name);
967
968     if (enable_pz2_retrieval)
969     {
970         element_set_name = 0;
971         if (b->sptr->element_set.length())
972             element_set_name = b->sptr->element_set.c_str();
973     }
974
975     b->set_option("elementSetName", element_set_name);
976
977     b->present(start, number_to_present, recs, error, addinfo, odr);
978
979     Odr_int i = 0;
980     if (!*error)
981     {
982         for (i = 0; i < number_to_present; i++)
983             if (!recs[i])
984                 break;
985     }
986     if (i > 0)
987     {  // only return records if no error and at least one record
988         char *odr_database = odr_strdup(odr,
989                                         b->m_frontend_database.c_str());
990         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
991             odr_malloc(odr, sizeof(*npl));
992         *number_of_records_returned = i;
993         npl->num_records = i;
994         npl->records = (Z_NamePlusRecord **)
995             odr_malloc(odr, i * sizeof(*npl->records));
996         for (i = 0; i < number_to_present; i++)
997         {
998             Z_NamePlusRecord *npr = 0;
999             const char *addinfo;
1000             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1001                                               &addinfo, 0 /* diagset */);
1002                 
1003             if (sur_error)
1004             {
1005                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1006                                             addinfo);
1007             }
1008             else if (enable_pz2_retrieval)
1009             {
1010                 char rec_type_str[100];
1011                 const char *record_encoding = 0;
1012
1013                 if (b->sptr->record_encoding.length())
1014                     record_encoding = b->sptr->record_encoding.c_str();
1015                 else if (assume_marc8_charset)
1016                     record_encoding = "marc8";
1017
1018                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1019                 if (record_encoding)
1020                 {
1021                     strcat(rec_type_str, "; charset=");
1022                     strcat(rec_type_str, record_encoding);
1023                 }
1024                 
1025                 int rec_len;
1026                 xmlChar *xmlrec_buf = 0;
1027                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1028                                                       &rec_len);
1029                 if (!rec_buf && !npr)
1030                 {
1031                     std::string addinfo("ZOOM_record_get failed for type ");
1032
1033                     addinfo += rec_type_str;
1034                     npr = zget_surrogateDiagRec(
1035                         odr, odr_database, 
1036                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1037                         addinfo.c_str());
1038                 }
1039
1040                 if (rec_buf && b->xsp && enable_pz2_transform)
1041                 {
1042                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1043                     if (!rec_doc)
1044                     {
1045                         npr = zget_surrogateDiagRec(
1046                             odr, odr_database, 
1047                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1048                             "xml parse failed for record");
1049                     }
1050                     else
1051                     { 
1052                         xmlDoc *rec_res = 
1053                             xsltApplyStylesheet(b->xsp, rec_doc, 0);
1054
1055                         if (rec_res)
1056                         {
1057                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1058                                                    rec_res, b->xsp);
1059                             rec_buf = (const char *) xmlrec_buf;
1060
1061                             xmlFreeDoc(rec_res);
1062                         }
1063                         if (!rec_buf)
1064                         {
1065                             std::string addinfo;
1066
1067                             addinfo = "xslt apply failed for "
1068                                 + b->sptr->transform_xsl_fname;
1069                             npr = zget_surrogateDiagRec(
1070                                 odr, odr_database, 
1071                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1072                                 addinfo.c_str());
1073                         }
1074                         xmlFreeDoc(rec_doc);
1075                     }
1076                 }
1077
1078                 if (rec_buf)
1079                 {
1080                     xmlDoc *doc = xmlParseMemory(rec_buf, rec_len);
1081                     std::string res = 
1082                         mp::xml::url_recipe_handle(doc, b->sptr->urlRecipe);
1083                     if (res.length() && b->content_session_id.length())
1084                     {
1085                         size_t off = res.find_first_of("://");
1086                         if (off != std::string::npos)
1087                         {
1088                             char tmp[1024];
1089                             sprintf(tmp, "%s.%s/",
1090                                     b->content_session_id.c_str(),
1091                                     m_p->content_proxy_server.c_str());
1092                             res.insert(off + 3, tmp);
1093                         }
1094                     }
1095                     if (res.length())
1096                     {
1097                         xmlNode *ptr = xmlDocGetRootElement(doc);
1098                         while (ptr && ptr->type != XML_ELEMENT_NODE)
1099                             ptr = ptr->next;
1100                         xmlNode *c = 
1101                             xmlNewChild(ptr, 0, BAD_CAST "generated-url", 0);
1102                         xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1103                         xmlAddChild(c, t);
1104
1105                         if (xmlrec_buf)
1106                             xmlFree(xmlrec_buf);
1107
1108                         xmlDocDumpMemory(doc, &xmlrec_buf, &rec_len);
1109                         rec_buf = (const char *) xmlrec_buf;
1110                     }
1111                     xmlFreeDoc(doc);
1112                 }
1113                 if (!npr)
1114                 {
1115                     if (!rec_buf)
1116                         npr = zget_surrogateDiagRec(
1117                             odr, odr_database, 
1118                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1119                             rec_type_str);
1120                     else
1121                     {
1122                         npr = (Z_NamePlusRecord *)
1123                             odr_malloc(odr, sizeof(*npr));
1124                         npr->databaseName = odr_database;
1125                         npr->which = Z_NamePlusRecord_databaseRecord;
1126                         npr->u.databaseRecord =
1127                             z_ext_record_xml(odr, rec_buf, rec_len);
1128                     }
1129                 }
1130                 if (xmlrec_buf)
1131                     xmlFree(xmlrec_buf);
1132             }
1133             else
1134             {
1135                 Z_External *ext =
1136                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1137                 if (ext)
1138                 {
1139                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1140                     npr->databaseName = odr_database;
1141                     npr->which = Z_NamePlusRecord_databaseRecord;
1142                     npr->u.databaseRecord = ext;
1143                 }
1144                 else
1145                 {
1146                     npr = zget_surrogateDiagRec(
1147                         odr, odr_database, 
1148                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1149                         "ZOOM_record, type ext");
1150                 }
1151             }
1152             npl->records[i] = npr;
1153         }
1154         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1155         records->which = Z_Records_DBOSD;
1156         records->u.databaseOrSurDiagnostics = npl;
1157     }
1158     return records;
1159 }
1160     
1161 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1162                                                     ODR odr)
1163 {
1164     struct cql_node *r = 0;
1165     if (!cn)
1166         return 0;
1167     switch (cn->which)
1168     {
1169     case CQL_NODE_ST:
1170         if (cn->u.st.index)
1171         {
1172             std::map<std::string,std::string>::const_iterator it;
1173             it = fieldmap.find(cn->u.st.index);
1174             if (it == fieldmap.end())
1175                 return cn;
1176             if (it->second.length())
1177                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1178             else
1179                 cn->u.st.index = 0;
1180         }
1181         break;
1182     case CQL_NODE_BOOL:
1183         r = convert_cql_fields(cn->u.boolean.left, odr);
1184         if (!r)
1185             r = convert_cql_fields(cn->u.boolean.right, odr);
1186         break;
1187     case CQL_NODE_SORT:
1188         r = convert_cql_fields(cn->u.sort.search, odr);
1189         break;
1190     }
1191     return r;
1192 }
1193
1194 static void sort_pqf_type_7(WRBUF pqf_wrbuf, const char *sru_sortkeys)
1195 {
1196     /* sortkey layour: path,schema,ascending,caseSensitive,missingValue */
1197     /* see cql_sortby_to_sortkeys of YAZ. */
1198     char **sortspec;
1199     int num_sortspec = 0;
1200     int i;
1201     NMEM nmem = nmem_create();
1202     
1203     if (sru_sortkeys)
1204         nmem_strsplit_blank(nmem, sru_sortkeys, &sortspec, &num_sortspec);
1205     if (num_sortspec > 0)
1206     {
1207         WRBUF w = wrbuf_alloc();
1208         for (i = 0; i < num_sortspec; i++)
1209         {
1210             char **arg;
1211             int num_arg;
1212             int ascending = 1;
1213             nmem_strsplitx(nmem, ",", sortspec[i], &arg, &num_arg, 0);
1214             
1215             if (num_arg > 2 && arg[2][0])
1216                 ascending = atoi(arg[2]);
1217             
1218             wrbuf_puts(w, "@or @attr 1=");
1219             yaz_encode_pqf_term(w, arg[0], strlen(arg[0]));
1220             wrbuf_printf(w, "@attr 7=%d %d ", ascending ? 1 : 2, i);
1221         }
1222         if (wrbuf_len(w))
1223         {
1224             wrbuf_puts(w, wrbuf_cstr(pqf_wrbuf));
1225             wrbuf_rewind(pqf_wrbuf);
1226             wrbuf_puts(pqf_wrbuf, wrbuf_cstr(w));
1227         }
1228         wrbuf_destroy(w);
1229     }
1230     nmem_destroy(nmem);
1231 }
1232
1233 static void sort_via_cql(WRBUF cql_sortby, const char *sru_sortkeys)
1234 {
1235     /* sortkey layour: path,schema,ascending,caseSensitive,missingValue */
1236     /* see cql_sortby_to_sortkeys of YAZ. */
1237     char **sortspec;
1238     int num_sortspec = 0;
1239     int i;
1240     NMEM nmem = nmem_create();
1241     
1242     if (sru_sortkeys)
1243         nmem_strsplit_blank(nmem, sru_sortkeys, &sortspec, &num_sortspec);
1244     if (num_sortspec > 0)
1245     {
1246         WRBUF w = wrbuf_alloc();
1247         for (i = 0; i < num_sortspec; i++)
1248         {
1249             char **arg;
1250             int num_arg;
1251             int ascending = 1;
1252             int case_sensitive = 0;
1253             const char *missing = 0;
1254             nmem_strsplitx(nmem, ",", sortspec[i], &arg, &num_arg, 0);
1255             
1256             if (num_arg > 2 && arg[2][0])
1257                 ascending = atoi(arg[2]);
1258             if (num_arg > 3 && arg[3][0])
1259                 case_sensitive = atoi(arg[3]);
1260             if (num_arg > 4 && arg[4][0])
1261                 missing = arg[4];
1262             if (i > 0)
1263                 wrbuf_puts(w, " ");
1264             else
1265                 wrbuf_puts(w, " sortby ");
1266             wrbuf_puts(w, arg[0]);  /* field */
1267             wrbuf_puts(w, "/");
1268             wrbuf_puts(w, ascending ? "ascending" : "descending");
1269             if (case_sensitive)
1270                 wrbuf_puts(w, "/respectCase");
1271             if (missing)
1272             {
1273                 if (!strcmp(missing, "omit"))
1274                     wrbuf_puts(w, "/missingOmit");
1275                 else if (!strcmp(missing, "abort"))
1276                     wrbuf_puts(w, "/missingFail");
1277                 else if (!strcmp(missing, "lowValue"))
1278                     wrbuf_puts(w, "/missingLow");
1279                 else if (!strcmp(missing, "highValue"))
1280                     wrbuf_puts(w, "/missingHigh");
1281             }
1282         }
1283         if (wrbuf_len(w))
1284             wrbuf_puts(cql_sortby, wrbuf_cstr(w));
1285         wrbuf_destroy(w);
1286     }
1287     nmem_destroy(nmem);
1288 }
1289
1290 #if YAZ_VERSIONL < 0x40206
1291 static void wrbuf_vp_puts(const char *buf, void *client_data)
1292 {
1293     WRBUF b = (WRBUF) client_data;
1294     wrbuf_puts(b, buf);
1295 }
1296 #endif
1297
1298 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1299 {
1300     Z_GDU *gdu = package.request().get();
1301     Z_APDU *apdu_req = gdu->u.z3950;
1302     Z_APDU *apdu_res = 0;
1303     mp::odr odr;
1304     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1305     if (sr->num_databaseNames != 1)
1306     {
1307         apdu_res = odr.create_searchResponse(
1308             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
1309         package.response() = apdu_res;
1310         return;
1311     }
1312
1313     int error = 0;
1314     char *addinfo = 0;
1315     std::string db(sr->databaseNames[0]);
1316     BackendPtr b = get_backend_from_databases(db, &error, &addinfo, odr);
1317     if (error)
1318     {
1319         apdu_res = 
1320             odr.create_searchResponse(apdu_req, error, addinfo);
1321         package.response() = apdu_res;
1322         return;
1323     }
1324
1325     b->set_option("setname", "default");
1326
1327     Odr_int hits = 0;
1328     Z_Query *query = sr->query;
1329     WRBUF ccl_wrbuf = 0;
1330     WRBUF pqf_wrbuf = 0;
1331     std::string sru_sortkeys;
1332
1333     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1334     {
1335         // RPN
1336         pqf_wrbuf = wrbuf_alloc();
1337         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1338     }
1339     else if (query->which == Z_Query_type_2)
1340     {
1341         // CCL
1342         ccl_wrbuf = wrbuf_alloc();
1343         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1344                     query->u.type_2->len);
1345     }
1346     else if (query->which == Z_Query_type_104 &&
1347              query->u.type_104->which == Z_External_CQL)
1348     {
1349         // CQL
1350         const char *cql = query->u.type_104->u.cql;
1351         CQL_parser cp = cql_parser_create();
1352         int r = cql_parser_string(cp, cql);
1353         if (r)
1354         {
1355             cql_parser_destroy(cp);
1356             apdu_res = 
1357                 odr.create_searchResponse(apdu_req, 
1358                                           YAZ_BIB1_MALFORMED_QUERY,
1359                                           "CQL syntax error");
1360             package.response() = apdu_res;
1361             return;
1362         }
1363         struct cql_node *cn = cql_parser_result(cp);
1364         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1365         if (cn_error)
1366         {
1367             // hopefully we are getting a ptr to a index+relation+term node
1368             addinfo = 0;
1369             if (cn_error->which == CQL_NODE_ST)
1370                 addinfo = cn_error->u.st.index;
1371
1372             apdu_res = 
1373                 odr.create_searchResponse(apdu_req, 
1374                                           YAZ_BIB1_UNSUPP_USE_ATTRIBUTE,
1375                                           addinfo);
1376             package.response() = apdu_res;
1377             return;
1378         }
1379         char ccl_buf[1024];
1380
1381         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1382         if (r == 0)
1383         {
1384             ccl_wrbuf = wrbuf_alloc();
1385             wrbuf_puts(ccl_wrbuf, ccl_buf);
1386             
1387             WRBUF sru_sortkeys_wrbuf = wrbuf_alloc();
1388
1389             cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf);
1390
1391             sru_sortkeys.assign(wrbuf_cstr(sru_sortkeys_wrbuf));
1392             wrbuf_destroy(sru_sortkeys_wrbuf);
1393         }
1394         cql_parser_destroy(cp);
1395         if (r)
1396         {
1397             apdu_res = 
1398                 odr.create_searchResponse(apdu_req, 
1399                                           YAZ_BIB1_MALFORMED_QUERY,
1400                                           "CQL to CCL conversion error");
1401             package.response() = apdu_res;
1402             return;
1403         }
1404     }
1405     else
1406     {
1407         apdu_res = 
1408             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
1409         package.response() = apdu_res;
1410         return;
1411     }
1412
1413     if (ccl_wrbuf)
1414     {
1415         // CCL to PQF
1416         assert(pqf_wrbuf == 0);
1417         int cerror, cpos;
1418         struct ccl_rpn_node *cn;
1419         yaz_log(YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1420         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1421                           &cerror, &cpos);
1422         wrbuf_destroy(ccl_wrbuf);
1423         if (!cn)
1424         {
1425             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1426             int z3950_diag = YAZ_BIB1_MALFORMED_QUERY;
1427
1428             switch (cerror)
1429             {
1430             case CCL_ERR_UNKNOWN_QUAL:
1431                 z3950_diag = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1432                 break;
1433             case CCL_ERR_TRUNC_NOT_LEFT: 
1434             case CCL_ERR_TRUNC_NOT_RIGHT:
1435             case CCL_ERR_TRUNC_NOT_BOTH:
1436                 z3950_diag = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
1437                 break;
1438             }
1439             apdu_res = 
1440                 odr.create_searchResponse(apdu_req, z3950_diag, addinfo);
1441             package.response() = apdu_res;
1442             return;
1443         }
1444         pqf_wrbuf = wrbuf_alloc();
1445         ccl_pquery(pqf_wrbuf, cn);
1446         ccl_rpn_delete(cn);
1447     }
1448     
1449     assert(pqf_wrbuf);
1450     if (b->get_option("sru"))
1451     {
1452         int status = 0;
1453         Z_RPNQuery *zquery;
1454         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1455         WRBUF wrb = wrbuf_alloc();
1456             
1457         if (!strcmp(b->get_option("sru"), "solr"))
1458         {
1459             solr_transform_t cqlt = solr_transform_create();
1460             
1461             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1462             
1463             solr_transform_close(cqlt);
1464         }
1465         else
1466         {
1467             cql_transform_t cqlt = cql_transform_create();
1468             
1469             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1470             
1471             cql_transform_close(cqlt);
1472
1473             if (status == 0)
1474                 sort_via_cql(wrb, sru_sortkeys.c_str());
1475         }
1476         if (status == 0)
1477         {
1478             yaz_log(YLOG_LOG, "search CQL: %s", wrbuf_cstr(wrb));
1479             b->search_cql(wrbuf_cstr(wrb), &hits, &error, &addinfo, odr);
1480         }
1481         
1482         wrbuf_destroy(wrb);
1483         wrbuf_destroy(pqf_wrbuf);
1484         if (status)
1485         {
1486             apdu_res = 
1487                 odr.create_searchResponse(apdu_req, YAZ_BIB1_MALFORMED_QUERY,
1488                                           "can not convert from RPN to CQL/SOLR");
1489             package.response() = apdu_res;
1490             return;
1491         }
1492     }
1493     else
1494     {
1495         sort_pqf_type_7(pqf_wrbuf, sru_sortkeys.c_str());
1496
1497         yaz_log(YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1498         b->search_pqf(wrbuf_cstr(pqf_wrbuf), &hits, &error, &addinfo, odr);
1499         wrbuf_destroy(pqf_wrbuf);
1500     }
1501
1502     const char *element_set_name = 0;
1503     Odr_int number_to_present = 0;
1504     if (!error)
1505         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1506     
1507     Odr_int number_of_records_returned = 0;
1508     Z_Records *records = get_records(
1509         0, number_to_present, &error, &addinfo,
1510         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1511         element_set_name);
1512     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1513     if (records)
1514     {
1515         apdu_res->u.searchResponse->records = records;
1516         apdu_res->u.searchResponse->numberOfRecordsReturned =
1517             odr_intdup(odr, number_of_records_returned);
1518     }
1519     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1520     package.response() = apdu_res;
1521 }
1522
1523 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1524 {
1525     Z_GDU *gdu = package.request().get();
1526     Z_APDU *apdu_req = gdu->u.z3950;
1527     Z_APDU *apdu_res = 0;
1528     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1529
1530     mp::odr odr;
1531     if (!m_backend)
1532     {
1533         package.response() = odr.create_presentResponse(
1534             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1535         return;
1536     }
1537     const char *element_set_name = 0;
1538     Z_RecordComposition *comp = pr->recordComposition;
1539     if (comp && comp->which != Z_RecordComp_simple)
1540     {
1541         package.response() = odr.create_presentResponse(
1542             apdu_req, 
1543             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1544         return;
1545     }
1546     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1547         element_set_name = comp->u.simple->u.generic;
1548     Odr_int number_of_records_returned = 0;
1549     int error = 0;
1550     char *addinfo = 0;
1551     Z_Records *records = get_records(
1552         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1553         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1554         pr->preferredRecordSyntax, element_set_name);
1555
1556     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1557     if (records)
1558     {
1559         apdu_res->u.presentResponse->records = records;
1560         apdu_res->u.presentResponse->numberOfRecordsReturned =
1561             odr_intdup(odr, number_of_records_returned);
1562     }
1563     package.response() = apdu_res;
1564 }
1565
1566 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1567 {
1568     Z_GDU *gdu = package.request().get();
1569     if (!gdu)
1570         ;
1571     else if (gdu->which == Z_GDU_Z3950)
1572     {
1573         Z_APDU *apdu_req = gdu->u.z3950;
1574         if (apdu_req->which == Z_APDU_initRequest)
1575         {
1576             mp::odr odr;
1577             package.response() = odr.create_close(
1578                 apdu_req,
1579                 Z_Close_protocolError,
1580                 "double init");
1581         }
1582         else if (apdu_req->which == Z_APDU_searchRequest)
1583         {
1584             handle_search(package);
1585         }
1586         else if (apdu_req->which == Z_APDU_presentRequest)
1587         {
1588             handle_present(package);
1589         }
1590         else
1591         {
1592             mp::odr odr;
1593             package.response() = odr.create_close(
1594                 apdu_req,
1595                 Z_Close_protocolError,
1596                 "zoom filter cannot handle this APDU");
1597             package.session().close();
1598         }
1599     }
1600     else
1601     {
1602         package.session().close();
1603     }
1604 }
1605
1606 void yf::Zoom::Impl::process(mp::Package &package)
1607 {
1608     FrontendPtr f = get_frontend(package);
1609     Z_GDU *gdu = package.request().get();
1610
1611     if (f->m_is_virtual)
1612     {
1613         f->handle_package(package);
1614     }
1615     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1616              Z_APDU_initRequest)
1617     {
1618         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1619         f->m_init_gdu = gdu;
1620         
1621         mp::odr odr;
1622         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1623         Z_InitResponse *resp = apdu->u.initResponse;
1624         
1625         int i;
1626         static const int masks[] = {
1627             Z_Options_search,
1628             Z_Options_present,
1629             -1 
1630         };
1631         for (i = 0; masks[i] != -1; i++)
1632             if (ODR_MASK_GET(req->options, masks[i]))
1633                 ODR_MASK_SET(resp->options, masks[i]);
1634         
1635         static const int versions[] = {
1636             Z_ProtocolVersion_1,
1637             Z_ProtocolVersion_2,
1638             Z_ProtocolVersion_3,
1639             -1
1640         };
1641         for (i = 0; versions[i] != -1; i++)
1642             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1643                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1644             else
1645                 break;
1646         
1647         *resp->preferredMessageSize = *req->preferredMessageSize;
1648         *resp->maximumRecordSize = *req->maximumRecordSize;
1649         
1650         package.response() = apdu;
1651         f->m_is_virtual = true;
1652     }
1653     else
1654         package.move();
1655
1656     release_frontend(package);
1657 }
1658
1659
1660 static mp::filter::Base* filter_creator()
1661 {
1662     return new mp::filter::Zoom;
1663 }
1664
1665 extern "C" {
1666     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1667         0,
1668         "zoom",
1669         filter_creator
1670     };
1671 }
1672
1673
1674 /*
1675  * Local variables:
1676  * c-basic-offset: 4
1677  * c-file-style: "Stroustrup"
1678  * indent-tabs-mode: nil
1679  * End:
1680  * vim: shiftwidth=4 tabstop=8 expandtab
1681  */
1682