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