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