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