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