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