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