cd233b55233fbbda6b65f53ad09f8b671bf85204
[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 && !npr)
995                 {
996                     std::string addinfo("ZOOM_record_get failed for type ");
997
998                     addinfo += rec_type_str;
999                     npr = zget_surrogateDiagRec(
1000                         odr, odr_database, 
1001                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1002                         addinfo.c_str());
1003                 }
1004
1005                 if (rec_buf && b->xsp && enable_pz2_transform)
1006                 {
1007                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1008                     if (!rec_doc)
1009                     {
1010                         npr = zget_surrogateDiagRec(
1011                             odr, odr_database, 
1012                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1013                             "xml parse failed for record");
1014                     }
1015                     else
1016                     { 
1017                         xmlDoc *rec_res = 
1018                             xsltApplyStylesheet(b->xsp, rec_doc, 0);
1019
1020                         if (rec_res)
1021                         {
1022                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1023                                                    rec_res, b->xsp);
1024                             rec_buf = (const char *) xmlrec_buf;
1025
1026                             xmlFreeDoc(rec_res);
1027                         }
1028                         if (!rec_buf)
1029                         {
1030                             std::string addinfo;
1031
1032                             addinfo = "xslt apply failed for "
1033                                 + b->sptr->transform_xsl_fname;
1034                             npr = zget_surrogateDiagRec(
1035                                 odr, odr_database, 
1036                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1037                                 addinfo.c_str());
1038                         }
1039                         xmlFreeDoc(rec_doc);
1040                     }
1041                 }
1042
1043                 if (rec_buf)
1044                 {
1045                     xmlDoc *doc = xmlParseMemory(rec_buf, rec_len);
1046                     std::string res = 
1047                         mp::xml::url_recipe_handle(doc, b->sptr->urlRecipe);
1048                     if (res.length() && b->content_session_id.length())
1049                     {
1050                         size_t off = res.find_first_of("://");
1051                         if (off != std::string::npos)
1052                         {
1053                             char tmp[1024];
1054                             sprintf(tmp, "%s.%s/",
1055                                     b->content_session_id.c_str(),
1056                                     m_p->content_proxy_server.c_str());
1057                             res.insert(off + 3, tmp);
1058                         }
1059                     }
1060                     if (res.length())
1061                     {
1062                         xmlNode *ptr = xmlDocGetRootElement(doc);
1063                         while (ptr && ptr->type != XML_ELEMENT_NODE)
1064                             ptr = ptr->next;
1065                         xmlNode *c = 
1066                             xmlNewChild(ptr, 0, BAD_CAST "generated-url", 0);
1067                         xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1068                         xmlAddChild(c, t);
1069
1070                         if (xmlrec_buf)
1071                             xmlFree(xmlrec_buf);
1072
1073                         xmlDocDumpMemory(doc, &xmlrec_buf, &rec_len);
1074                         rec_buf = (const char *) xmlrec_buf;
1075                     }
1076                     xmlFreeDoc(doc);
1077                 }
1078                 if (!npr)
1079                 {
1080                     if (!rec_buf)
1081                         npr = zget_surrogateDiagRec(
1082                             odr, odr_database, 
1083                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1084                             rec_type_str);
1085                     else
1086                     {
1087                         npr = (Z_NamePlusRecord *)
1088                             odr_malloc(odr, sizeof(*npr));
1089                         npr->databaseName = odr_database;
1090                         npr->which = Z_NamePlusRecord_databaseRecord;
1091                         npr->u.databaseRecord =
1092                             z_ext_record_xml(odr, rec_buf, rec_len);
1093                     }
1094                 }
1095                 if (xmlrec_buf)
1096                     xmlFree(xmlrec_buf);
1097             }
1098             else
1099             {
1100                 Z_External *ext =
1101                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1102                 if (ext)
1103                 {
1104                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1105                     npr->databaseName = odr_database;
1106                     npr->which = Z_NamePlusRecord_databaseRecord;
1107                     npr->u.databaseRecord = ext;
1108                 }
1109                 else
1110                 {
1111                     npr = zget_surrogateDiagRec(
1112                         odr, odr_database, 
1113                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1114                         "ZOOM_record, type ext");
1115                 }
1116             }
1117             npl->records[i] = npr;
1118         }
1119         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1120         records->which = Z_Records_DBOSD;
1121         records->u.databaseOrSurDiagnostics = npl;
1122     }
1123     return records;
1124 }
1125     
1126 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1127                                                     ODR odr)
1128 {
1129     struct cql_node *r = 0;
1130     if (!cn)
1131         return 0;
1132     switch (cn->which)
1133     {
1134     case CQL_NODE_ST:
1135         if (cn->u.st.index)
1136         {
1137             std::map<std::string,std::string>::const_iterator it;
1138             it = fieldmap.find(cn->u.st.index);
1139             if (it == fieldmap.end())
1140                 return cn;
1141             if (it->second.length())
1142                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1143             else
1144                 cn->u.st.index = 0;
1145         }
1146         break;
1147     case CQL_NODE_BOOL:
1148         r = convert_cql_fields(cn->u.boolean.left, odr);
1149         if (!r)
1150             r = convert_cql_fields(cn->u.boolean.right, odr);
1151         break;
1152     case CQL_NODE_SORT:
1153         r = convert_cql_fields(cn->u.sort.search, odr);
1154         break;
1155     }
1156     return r;
1157 }
1158
1159 static void sort_pqf_type_7(WRBUF pqf_wrbuf, const char *sru_sortkeys)
1160 {
1161     /* sortkey layour: path,schema,ascending,caseSensitive,missingValue */
1162     /* see cql_sortby_to_sortkeys of YAZ. */
1163     char **sortspec;
1164     int num_sortspec = 0;
1165     int i;
1166     NMEM nmem = nmem_create();
1167     
1168     if (sru_sortkeys)
1169         nmem_strsplit_blank(nmem, sru_sortkeys, &sortspec, &num_sortspec);
1170     if (num_sortspec > 0)
1171     {
1172         WRBUF w = wrbuf_alloc();
1173         for (i = 0; i < num_sortspec; i++)
1174         {
1175             char **arg;
1176             int num_arg;
1177             int ascending = 1;
1178             nmem_strsplitx(nmem, ",", sortspec[i], &arg, &num_arg, 0);
1179             
1180             if (num_arg > 2 && arg[2][0])
1181                 ascending = atoi(arg[2]);
1182             
1183             wrbuf_puts(w, "@or @attr 1=");
1184             yaz_encode_pqf_term(w, arg[0], strlen(arg[0]));
1185             wrbuf_printf(w, "@attr 7=%d %d ", ascending ? 1 : 2, i);
1186         }
1187         if (wrbuf_len(w))
1188         {
1189             wrbuf_puts(w, wrbuf_cstr(pqf_wrbuf));
1190             wrbuf_rewind(pqf_wrbuf);
1191             wrbuf_puts(pqf_wrbuf, wrbuf_cstr(w));
1192         }
1193         wrbuf_destroy(w);
1194     }
1195     nmem_destroy(nmem);
1196 }
1197
1198 static void sort_via_cql(WRBUF cql_sortby, const char *sru_sortkeys)
1199 {
1200     /* sortkey layour: path,schema,ascending,caseSensitive,missingValue */
1201     /* see cql_sortby_to_sortkeys of YAZ. */
1202     char **sortspec;
1203     int num_sortspec = 0;
1204     int i;
1205     NMEM nmem = nmem_create();
1206     
1207     if (sru_sortkeys)
1208         nmem_strsplit_blank(nmem, sru_sortkeys, &sortspec, &num_sortspec);
1209     if (num_sortspec > 0)
1210     {
1211         WRBUF w = wrbuf_alloc();
1212         for (i = 0; i < num_sortspec; i++)
1213         {
1214             char **arg;
1215             int num_arg;
1216             int ascending = 1;
1217             int case_sensitive = 0;
1218             const char *missing = 0;
1219             nmem_strsplitx(nmem, ",", sortspec[i], &arg, &num_arg, 0);
1220             
1221             if (num_arg > 2 && arg[2][0])
1222                 ascending = atoi(arg[2]);
1223             if (num_arg > 3 && arg[3][0])
1224                 case_sensitive = atoi(arg[3]);
1225             if (num_arg > 4 && arg[4][0])
1226                 missing = arg[4];
1227             if (i > 0)
1228                 wrbuf_puts(w, " ");
1229             else
1230                 wrbuf_puts(w, " sortby ");
1231             wrbuf_puts(w, arg[0]);  /* field */
1232             wrbuf_puts(w, "/");
1233             wrbuf_puts(w, ascending ? "ascending" : "descending");
1234             if (case_sensitive)
1235                 wrbuf_puts(w, "/respectCase");
1236             if (missing)
1237             {
1238                 if (!strcmp(missing, "omit"))
1239                     wrbuf_puts(w, "/missingOmit");
1240                 else if (!strcmp(missing, "abort"))
1241                     wrbuf_puts(w, "/missingFail");
1242                 else if (!strcmp(missing, "lowValue"))
1243                     wrbuf_puts(w, "/missingLow");
1244                 else if (!strcmp(missing, "highValue"))
1245                     wrbuf_puts(w, "/missingHigh");
1246             }
1247         }
1248         if (wrbuf_len(w))
1249             wrbuf_puts(cql_sortby, wrbuf_cstr(w));
1250         wrbuf_destroy(w);
1251     }
1252     nmem_destroy(nmem);
1253 }
1254
1255 #if YAZ_VERSIONL < 0x40206
1256 static void wrbuf_vp_puts(const char *buf, void *client_data)
1257 {
1258     WRBUF b = (WRBUF) client_data;
1259     wrbuf_puts(b, buf);
1260 }
1261 #endif
1262
1263 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1264 {
1265     Z_GDU *gdu = package.request().get();
1266     Z_APDU *apdu_req = gdu->u.z3950;
1267     Z_APDU *apdu_res = 0;
1268     mp::odr odr;
1269     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1270     if (sr->num_databaseNames != 1)
1271     {
1272         apdu_res = odr.create_searchResponse(
1273             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
1274         package.response() = apdu_res;
1275         return;
1276     }
1277
1278     int error = 0;
1279     char *addinfo = 0;
1280     std::string db(sr->databaseNames[0]);
1281     BackendPtr b = get_backend_from_databases(db, &error, &addinfo, odr);
1282     if (error)
1283     {
1284         apdu_res = 
1285             odr.create_searchResponse(apdu_req, error, addinfo);
1286         package.response() = apdu_res;
1287         return;
1288     }
1289
1290     b->set_option("setname", "default");
1291
1292     Odr_int hits = 0;
1293     Z_Query *query = sr->query;
1294     WRBUF ccl_wrbuf = 0;
1295     WRBUF pqf_wrbuf = 0;
1296     std::string sru_sortkeys;
1297
1298     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1299     {
1300         // RPN
1301         pqf_wrbuf = wrbuf_alloc();
1302         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1303     }
1304     else if (query->which == Z_Query_type_2)
1305     {
1306         // CCL
1307         ccl_wrbuf = wrbuf_alloc();
1308         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1309                     query->u.type_2->len);
1310     }
1311     else if (query->which == Z_Query_type_104 &&
1312              query->u.type_104->which == Z_External_CQL)
1313     {
1314         // CQL
1315         const char *cql = query->u.type_104->u.cql;
1316         CQL_parser cp = cql_parser_create();
1317         int r = cql_parser_string(cp, cql);
1318         if (r)
1319         {
1320             cql_parser_destroy(cp);
1321             apdu_res = 
1322                 odr.create_searchResponse(apdu_req, 
1323                                           YAZ_BIB1_MALFORMED_QUERY,
1324                                           "CQL syntax error");
1325             package.response() = apdu_res;
1326             return;
1327         }
1328         struct cql_node *cn = cql_parser_result(cp);
1329         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1330         if (cn_error)
1331         {
1332             // hopefully we are getting a ptr to a index+relation+term node
1333             addinfo = 0;
1334             if (cn_error->which == CQL_NODE_ST)
1335                 addinfo = cn_error->u.st.index;
1336
1337             apdu_res = 
1338                 odr.create_searchResponse(apdu_req, 
1339                                           YAZ_BIB1_UNSUPP_USE_ATTRIBUTE,
1340                                           addinfo);
1341             package.response() = apdu_res;
1342             return;
1343         }
1344         char ccl_buf[1024];
1345
1346         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1347         if (r == 0)
1348         {
1349             ccl_wrbuf = wrbuf_alloc();
1350             wrbuf_puts(ccl_wrbuf, ccl_buf);
1351             
1352             WRBUF sru_sortkeys_wrbuf = wrbuf_alloc();
1353
1354             cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf);
1355
1356             sru_sortkeys.assign(wrbuf_cstr(sru_sortkeys_wrbuf));
1357             wrbuf_destroy(sru_sortkeys_wrbuf);
1358         }
1359         cql_parser_destroy(cp);
1360         if (r)
1361         {
1362             apdu_res = 
1363                 odr.create_searchResponse(apdu_req, 
1364                                           YAZ_BIB1_MALFORMED_QUERY,
1365                                           "CQL to CCL conversion error");
1366             package.response() = apdu_res;
1367             return;
1368         }
1369     }
1370     else
1371     {
1372         apdu_res = 
1373             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
1374         package.response() = apdu_res;
1375         return;
1376     }
1377
1378     if (ccl_wrbuf)
1379     {
1380         // CCL to PQF
1381         assert(pqf_wrbuf == 0);
1382         int cerror, cpos;
1383         struct ccl_rpn_node *cn;
1384         yaz_log(YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1385         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1386                           &cerror, &cpos);
1387         wrbuf_destroy(ccl_wrbuf);
1388         if (!cn)
1389         {
1390             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1391             int z3950_diag = YAZ_BIB1_MALFORMED_QUERY;
1392
1393             switch (cerror)
1394             {
1395             case CCL_ERR_UNKNOWN_QUAL:
1396                 z3950_diag = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1397                 break;
1398             case CCL_ERR_TRUNC_NOT_LEFT: 
1399             case CCL_ERR_TRUNC_NOT_RIGHT:
1400             case CCL_ERR_TRUNC_NOT_BOTH:
1401                 z3950_diag = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
1402                 break;
1403             }
1404             apdu_res = 
1405                 odr.create_searchResponse(apdu_req, z3950_diag, addinfo);
1406             package.response() = apdu_res;
1407             return;
1408         }
1409         pqf_wrbuf = wrbuf_alloc();
1410         ccl_pquery(pqf_wrbuf, cn);
1411         ccl_rpn_delete(cn);
1412     }
1413     
1414     assert(pqf_wrbuf);
1415     if (b->get_option("sru"))
1416     {
1417         int status = 0;
1418         Z_RPNQuery *zquery;
1419         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1420         WRBUF wrb = wrbuf_alloc();
1421             
1422         if (!strcmp(b->get_option("sru"), "solr"))
1423         {
1424             solr_transform_t cqlt = solr_transform_create();
1425             
1426             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1427             
1428             solr_transform_close(cqlt);
1429         }
1430         else
1431         {
1432             cql_transform_t cqlt = cql_transform_create();
1433             
1434             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1435             
1436             cql_transform_close(cqlt);
1437
1438             if (status == 0)
1439                 sort_via_cql(wrb, sru_sortkeys.c_str());
1440         }
1441         if (status == 0)
1442         {
1443             yaz_log(YLOG_LOG, "search CQL: %s", wrbuf_cstr(wrb));
1444             b->search_cql(wrbuf_cstr(wrb), &hits, &error, &addinfo, odr);
1445         }
1446         
1447         wrbuf_destroy(wrb);
1448         wrbuf_destroy(pqf_wrbuf);
1449         if (status)
1450         {
1451             apdu_res = 
1452                 odr.create_searchResponse(apdu_req, YAZ_BIB1_MALFORMED_QUERY,
1453                                           "can not convert from RPN to CQL/SOLR");
1454             package.response() = apdu_res;
1455             return;
1456         }
1457     }
1458     else
1459     {
1460         sort_pqf_type_7(pqf_wrbuf, sru_sortkeys.c_str());
1461
1462         yaz_log(YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1463         b->search_pqf(wrbuf_cstr(pqf_wrbuf), &hits, &error, &addinfo, odr);
1464         wrbuf_destroy(pqf_wrbuf);
1465     }
1466
1467     const char *element_set_name = 0;
1468     Odr_int number_to_present = 0;
1469     if (!error)
1470         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1471     
1472     Odr_int number_of_records_returned = 0;
1473     Z_Records *records = get_records(
1474         0, number_to_present, &error, &addinfo,
1475         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1476         element_set_name);
1477     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1478     if (records)
1479     {
1480         apdu_res->u.searchResponse->records = records;
1481         apdu_res->u.searchResponse->numberOfRecordsReturned =
1482             odr_intdup(odr, number_of_records_returned);
1483     }
1484     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1485     package.response() = apdu_res;
1486 }
1487
1488 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1489 {
1490     Z_GDU *gdu = package.request().get();
1491     Z_APDU *apdu_req = gdu->u.z3950;
1492     Z_APDU *apdu_res = 0;
1493     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1494
1495     mp::odr odr;
1496     if (!m_backend)
1497     {
1498         package.response() = odr.create_presentResponse(
1499             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1500         return;
1501     }
1502     const char *element_set_name = 0;
1503     Z_RecordComposition *comp = pr->recordComposition;
1504     if (comp && comp->which != Z_RecordComp_simple)
1505     {
1506         package.response() = odr.create_presentResponse(
1507             apdu_req, 
1508             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1509         return;
1510     }
1511     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1512         element_set_name = comp->u.simple->u.generic;
1513     Odr_int number_of_records_returned = 0;
1514     int error = 0;
1515     char *addinfo = 0;
1516     Z_Records *records = get_records(
1517         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1518         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1519         pr->preferredRecordSyntax, element_set_name);
1520
1521     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1522     if (records)
1523     {
1524         apdu_res->u.presentResponse->records = records;
1525         apdu_res->u.presentResponse->numberOfRecordsReturned =
1526             odr_intdup(odr, number_of_records_returned);
1527     }
1528     package.response() = apdu_res;
1529 }
1530
1531 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1532 {
1533     Z_GDU *gdu = package.request().get();
1534     if (!gdu)
1535         ;
1536     else if (gdu->which == Z_GDU_Z3950)
1537     {
1538         Z_APDU *apdu_req = gdu->u.z3950;
1539         if (apdu_req->which == Z_APDU_initRequest)
1540         {
1541             mp::odr odr;
1542             package.response() = odr.create_close(
1543                 apdu_req,
1544                 Z_Close_protocolError,
1545                 "double init");
1546         }
1547         else if (apdu_req->which == Z_APDU_searchRequest)
1548         {
1549             handle_search(package);
1550         }
1551         else if (apdu_req->which == Z_APDU_presentRequest)
1552         {
1553             handle_present(package);
1554         }
1555         else
1556         {
1557             mp::odr odr;
1558             package.response() = odr.create_close(
1559                 apdu_req,
1560                 Z_Close_protocolError,
1561                 "zoom filter cannot handle this APDU");
1562             package.session().close();
1563         }
1564     }
1565     else
1566     {
1567         package.session().close();
1568     }
1569 }
1570
1571 void yf::Zoom::Impl::process(mp::Package &package)
1572 {
1573     FrontendPtr f = get_frontend(package);
1574     Z_GDU *gdu = package.request().get();
1575
1576     if (f->m_is_virtual)
1577     {
1578         f->handle_package(package);
1579     }
1580     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1581              Z_APDU_initRequest)
1582     {
1583         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1584         f->m_init_gdu = gdu;
1585         
1586         mp::odr odr;
1587         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1588         Z_InitResponse *resp = apdu->u.initResponse;
1589         
1590         int i;
1591         static const int masks[] = {
1592             Z_Options_search,
1593             Z_Options_present,
1594             -1 
1595         };
1596         for (i = 0; masks[i] != -1; i++)
1597             if (ODR_MASK_GET(req->options, masks[i]))
1598                 ODR_MASK_SET(resp->options, masks[i]);
1599         
1600         static const int versions[] = {
1601             Z_ProtocolVersion_1,
1602             Z_ProtocolVersion_2,
1603             Z_ProtocolVersion_3,
1604             -1
1605         };
1606         for (i = 0; versions[i] != -1; i++)
1607             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1608                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1609             else
1610                 break;
1611         
1612         *resp->preferredMessageSize = *req->preferredMessageSize;
1613         *resp->maximumRecordSize = *req->maximumRecordSize;
1614         
1615         package.response() = apdu;
1616         f->m_is_virtual = true;
1617     }
1618     else
1619         package.move();
1620
1621     release_frontend(package);
1622 }
1623
1624
1625 static mp::filter::Base* filter_creator()
1626 {
1627     return new mp::filter::Zoom;
1628 }
1629
1630 extern "C" {
1631     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1632         0,
1633         "zoom",
1634         filter_creator
1635     };
1636 }
1637
1638
1639 /*
1640  * Local variables:
1641  * c-basic-offset: 4
1642  * c-file-style: "Stroustrup"
1643  * indent-tabs-mode: nil
1644  * End:
1645  * vim: shiftwidth=4 tabstop=8 expandtab
1646  */
1647