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