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