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