zoom: db arg content-{user,password} dealt with
[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 content_authentication;
727     std::string proxy;
728     std::string realm = m_p->default_realm;
729
730     const char *param_user = 0;
731     const char *param_password = 0;
732     const char *param_content_user = 0;
733     const char *param_content_password = 0;
734     int no_parms = 0;
735
736     char **names;
737     char **values;
738     int no_out_args = 0;
739     if (input_args.length())
740         no_parms = yaz_uri_to_array(input_args.c_str(),
741                                     odr, &names, &values);
742     // adding 10 because we'll be adding other URL args
743     const char **out_names = (const char **)
744         odr_malloc(odr, (10 + no_parms) * sizeof(*out_names));
745     const char **out_values = (const char **)
746         odr_malloc(odr, (10 + no_parms) * sizeof(*out_values));
747     
748     int i;
749     for (i = 0; i < no_parms; i++)
750     {
751         const char *name = names[i];
752         const char *value = values[i];
753         assert(name);
754         assert(value);
755         if (!strcmp(name, "user"))
756             param_user = value;
757         else if (!strcmp(name, "password"))
758             param_password = value;
759         else if (!strcmp(name, "content-user"))
760             param_content_user = value;
761         else if (!strcmp(name, "content-password"))
762             param_content_password = value;
763         else if (!strcmp(name, "proxy"))
764             proxy = value;
765         else if (!strcmp(name, "cproxysession"))
766         {
767             out_names[no_out_args] = name;
768             out_values[no_out_args++] = value;
769         }
770         else if (!strcmp(name, "realm"))
771             realm = value;
772         else if (name[0] == 'x' && name[1] == '-')
773         {
774             out_names[no_out_args] = name;
775             out_values[no_out_args++] = value;
776         }
777         else
778         {
779             BackendPtr notfound;
780             char *msg = (char*) odr_malloc(odr, strlen(name) + 30);
781             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
782             sprintf(msg, "Bad database argument: %s", name);
783             *addinfo = msg;
784             return notfound;
785         }
786     }
787     if (param_user)
788     {
789         authentication = std::string(param_user);
790         if (param_password)
791             authentication += "/" + std::string(param_password);
792     }
793     if (param_content_user)
794     {
795         content_authentication = std::string(param_content_user);
796         if (param_content_password)
797             content_authentication += "/" + std::string(param_content_password);
798     }
799     SearchablePtr sptr;
800
801     std::map<std::string,SearchablePtr>::iterator it;
802     it = m_p->s_map.find(torus_db);
803     if (it != m_p->s_map.end())
804         sptr = it->second;
805     else if (m_p->torus_url.length() > 0)
806     {
807         xmlDoc *doc = mp::get_searchable(m_p->torus_url, torus_db, realm,
808                                          m_p->proxy);
809         if (!doc)
810         {
811             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
812             *addinfo = odr_strdup(odr, database.c_str());
813             BackendPtr b;
814             return b;
815         }
816         const xmlNode *ptr = xmlDocGetRootElement(doc);
817         if (ptr)
818         {   // presumably ptr is a records element node
819             // parse first record in document
820             for (ptr = ptr->children; ptr; ptr = ptr->next)
821             {
822                 if (ptr->type == XML_ELEMENT_NODE
823                     && !strcmp((const char *) ptr->name, "record"))
824                 {
825                     if (sptr)
826                     {
827                         *error = YAZ_BIB1_UNSPECIFIED_ERROR;
828                         *addinfo = (char*) odr_malloc(odr, 40 + database.length()),
829                         sprintf(*addinfo, "multiple records for udb=%s",
830                                  database.c_str());
831                         xmlFreeDoc(doc);
832                         BackendPtr b;
833                         return b;
834                     }
835                     sptr = m_p->parse_torus_record(ptr);
836                 }
837             }
838         }
839         xmlFreeDoc(doc);
840     }
841
842     if (!sptr)
843     {
844         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
845         *addinfo = odr_strdup(odr, database.c_str());
846         BackendPtr b;
847         return b;
848     }
849         
850     xsltStylesheetPtr xsp = 0;
851     if (sptr->transform_xsl_content.length())
852     {
853         xmlDoc *xsp_doc = xmlParseMemory(sptr->transform_xsl_content.c_str(),
854                                          sptr->transform_xsl_content.length());
855         if (!xsp_doc)
856         {
857             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
858             *addinfo = (char *) odr_malloc(odr, 40);
859             sprintf(*addinfo, "xmlParseMemory failed");
860             BackendPtr b;
861             return b;
862         }
863         xsp = xsltParseStylesheetDoc(xsp_doc);
864         if (!xsp)
865         {
866             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
867             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
868             BackendPtr b;
869             xmlFreeDoc(xsp_doc);
870             return b;
871         }
872     }
873     else if (sptr->transform_xsl_fname.length())
874     {
875         const char *path = 0;
876
877         if (m_p->xsldir.length())
878             path = m_p->xsldir.c_str();
879         else
880             path = m_p->file_path.c_str();
881         std::string fname;
882
883         char fullpath[1024];
884         char *cp = yaz_filepath_resolve(sptr->transform_xsl_fname.c_str(),
885                                         path, 0, fullpath);
886         if (cp)
887             fname.assign(cp);
888         else
889         {
890             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
891             *addinfo = (char *)
892                 odr_malloc(odr, 40 + sptr->transform_xsl_fname.length());
893             sprintf(*addinfo, "File could not be read: %s", 
894                     sptr->transform_xsl_fname.c_str());
895             BackendPtr b;
896             return b;
897         }
898         xmlDoc *xsp_doc = xmlParseFile(fname.c_str());
899         if (!xsp_doc)
900         {
901             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
902             *addinfo = (char *) odr_malloc(odr, 40 + fname.length());
903             sprintf(*addinfo, "xmlParseFile failed. File: %s", fname.c_str());
904             BackendPtr b;
905             return b;
906         }
907         xsp = xsltParseStylesheetDoc(xsp_doc);
908         if (!xsp)
909         {
910             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
911             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
912             BackendPtr b;
913             xmlFreeDoc(xsp_doc);
914             return b;
915         }
916     }
917
918     m_backend.reset();
919
920     BackendPtr b(new Backend(sptr));
921
922     b->xsp = xsp;
923     b->m_frontend_database = database;
924
925     if (sptr->query_encoding.length())
926         b->set_option("rpnCharset", sptr->query_encoding);
927
928     b->set_option("timeout", "40");
929     
930     if (m_p->apdu_log) 
931         b->set_option("apdulog", "1");
932
933     if (sptr->piggyback)
934         b->set_option("count", "1"); /* some SRU servers INSIST on getting
935                                         maximumRecords > 0 */
936     b->set_option("piggyback", sptr->piggyback ? "1" : "0");
937
938     if (authentication.length() == 0)
939         authentication = sptr->authentication;
940
941     if (proxy.length() == 0)
942         proxy = sptr->cfProxy;
943     
944     if (sptr->cfAuth.length())
945     {
946         // A CF target
947         b->set_option("user", sptr->cfAuth);
948         if (authentication.length())
949         {
950             size_t found = authentication.find('/');
951             if (found != std::string::npos)
952             {
953                 out_names[no_out_args] = "user";
954                 out_values[no_out_args++] =
955                     odr_strdup(odr, authentication.substr(0, found).c_str());
956
957                 out_names[no_out_args] = "password";
958                 out_values[no_out_args++] =
959                     odr_strdup(odr, authentication.substr(found+1).c_str());
960             }
961             else
962             {
963                 out_names[no_out_args] = "user";
964                 out_values[no_out_args++] =
965                     odr_strdup(odr, authentication.c_str());
966             }                
967         }
968         if (proxy.length())
969         {
970             out_names[no_out_args] = "proxy";
971             out_values[no_out_args++] = odr_strdup(odr, proxy.c_str());
972         }
973         if (sptr->cfSubDB.length())
974         {
975             out_names[no_out_args] = "subdatabase";
976             out_values[no_out_args++] = odr_strdup(odr, sptr->cfSubDB.c_str());
977         }
978     }
979     else
980     {
981         size_t found = authentication.find('/');
982         
983         if (sptr->sru.length() && found != std::string::npos)
984         {
985             b->set_option("user", authentication.substr(0, found));
986             b->set_option("password", authentication.substr(found+1));
987         }
988         else
989             b->set_option("user", authentication);
990
991         if (proxy.length())
992             b->set_option("proxy", proxy);
993     }
994     std::string url;
995     if (sptr->sru.length())
996     {
997         url = "http://" + sptr->target;
998         b->set_option("sru", sptr->sru);
999
1000         if (sptr->sru_version.length())
1001             b->set_option("sru_version", sptr->sru_version);
1002     }
1003     else
1004     {
1005         url = sptr->target;
1006     }
1007     if (no_out_args)
1008     {
1009         char *x_args = 0;
1010         out_names[no_out_args] = 0; // terminate list
1011         
1012         yaz_array_to_uri(&x_args, odr, (char **) out_names,
1013                          (char **) out_values);
1014         url += "," + std::string(x_args);
1015     }
1016     package.log("zoom", YLOG_LOG, "url: %s", url.c_str());
1017     b->connect(url, error, addinfo, odr);
1018     if (*error == 0)
1019         create_content_session(package, b, error, addinfo, odr,
1020                                content_authentication.length() ?
1021                                content_authentication : authentication, proxy);
1022     if (*error == 0)
1023         m_backend = b;
1024     return b;
1025 }
1026
1027 void yf::Zoom::Frontend::prepare_elements(BackendPtr b,
1028                                           Odr_oid *preferredRecordSyntax,
1029                                           const char *element_set_name,
1030                                           bool &enable_pz2_retrieval,
1031                                           bool &enable_pz2_transform,
1032                                           bool &assume_marc8_charset)
1033
1034 {
1035     char oid_name_str[OID_STR_MAX];
1036     const char *syntax_name = 0;
1037     
1038     if (preferredRecordSyntax &&
1039         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
1040         && element_set_name)
1041     {
1042         if (!strcmp(element_set_name, m_p->element_transform.c_str()))
1043         {
1044             enable_pz2_retrieval = true;
1045             enable_pz2_transform = true;
1046         }
1047         else if (!strcmp(element_set_name, m_p->element_raw.c_str()))
1048         {
1049             enable_pz2_retrieval = true;
1050         }
1051     }
1052     
1053     if (enable_pz2_retrieval)
1054     {
1055         std::string configured_request_syntax = b->sptr->request_syntax;
1056         if (configured_request_syntax.length())
1057         {
1058             syntax_name = configured_request_syntax.c_str();
1059             const Odr_oid *syntax_oid = 
1060                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
1061             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
1062                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
1063                 assume_marc8_charset = true;
1064         }
1065     }
1066     else if (preferredRecordSyntax)
1067         syntax_name =
1068             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
1069
1070     if (b->sptr->sru.length())
1071         syntax_name = "XML";
1072
1073     b->set_option("preferredRecordSyntax", syntax_name);
1074
1075     if (enable_pz2_retrieval)
1076     {
1077         element_set_name = 0;
1078         if (b->sptr->element_set.length())
1079             element_set_name = b->sptr->element_set.c_str();
1080     }
1081
1082     b->set_option("elementSetName", element_set_name);
1083     if (b->sptr->sru.length() && element_set_name)
1084         b->set_option("schema", element_set_name);
1085 }
1086
1087 Z_Records *yf::Zoom::Frontend::get_records(Odr_int start,
1088                                            Odr_int number_to_present,
1089                                            int *error,
1090                                            char **addinfo,
1091                                            Odr_int *number_of_records_returned,
1092                                            ODR odr,
1093                                            BackendPtr b,
1094                                            Odr_oid *preferredRecordSyntax,
1095                                            const char *element_set_name)
1096 {
1097     *number_of_records_returned = 0;
1098     Z_Records *records = 0;
1099     bool enable_pz2_retrieval = false; // whether target profile is used
1100     bool enable_pz2_transform = false; // whether XSLT is used as well
1101     bool assume_marc8_charset = false;
1102
1103     prepare_elements(b, preferredRecordSyntax,
1104                      element_set_name,
1105                      enable_pz2_retrieval,
1106                      enable_pz2_transform,
1107                      assume_marc8_charset);
1108
1109     if (start < 0 || number_to_present <=0)
1110         return records;
1111     
1112     if (number_to_present > 10000)
1113         number_to_present = 10000;
1114
1115     ZOOM_record *recs = (ZOOM_record *)
1116         odr_malloc(odr, (size_t) number_to_present * sizeof(*recs));
1117
1118     b->present(start, number_to_present, recs, error, addinfo, odr);
1119
1120     int i = 0;
1121     if (!*error)
1122     {
1123         for (i = 0; i < number_to_present; i++)
1124             if (!recs[i])
1125                 break;
1126     }
1127     if (i > 0)
1128     {  // only return records if no error and at least one record
1129         char *odr_database = odr_strdup(odr,
1130                                         b->m_frontend_database.c_str());
1131         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
1132             odr_malloc(odr, sizeof(*npl));
1133         *number_of_records_returned = i;
1134         npl->num_records = i;
1135         npl->records = (Z_NamePlusRecord **)
1136             odr_malloc(odr, i * sizeof(*npl->records));
1137         for (i = 0; i < number_to_present; i++)
1138         {
1139             Z_NamePlusRecord *npr = 0;
1140             const char *addinfo;
1141             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
1142                                               &addinfo, 0 /* diagset */);
1143                 
1144             if (sur_error)
1145             {
1146                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
1147                                             addinfo);
1148             }
1149             else if (enable_pz2_retrieval)
1150             {
1151                 char rec_type_str[100];
1152                 const char *record_encoding = 0;
1153
1154                 if (b->sptr->record_encoding.length())
1155                     record_encoding = b->sptr->record_encoding.c_str();
1156                 else if (assume_marc8_charset)
1157                     record_encoding = "marc8";
1158
1159                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
1160                 if (record_encoding)
1161                 {
1162                     strcat(rec_type_str, "; charset=");
1163                     strcat(rec_type_str, record_encoding);
1164                 }
1165                 
1166                 int rec_len;
1167                 xmlChar *xmlrec_buf = 0;
1168                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
1169                                                       &rec_len);
1170                 if (!rec_buf && !npr)
1171                 {
1172                     std::string addinfo("ZOOM_record_get failed for type ");
1173
1174                     addinfo += rec_type_str;
1175                     npr = zget_surrogateDiagRec(
1176                         odr, odr_database, 
1177                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1178                         addinfo.c_str());
1179                 }
1180
1181                 if (rec_buf && b->xsp && enable_pz2_transform)
1182                 {
1183                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
1184                     if (!rec_doc)
1185                     {
1186                         npr = zget_surrogateDiagRec(
1187                             odr, odr_database, 
1188                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1189                             "xml parse failed for record");
1190                     }
1191                     else
1192                     { 
1193                         xmlDoc *rec_res = 
1194                             xsltApplyStylesheet(b->xsp, rec_doc, 0);
1195
1196                         if (rec_res)
1197                         {
1198                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
1199                                                    rec_res, b->xsp);
1200                             rec_buf = (const char *) xmlrec_buf;
1201
1202                             xmlFreeDoc(rec_res);
1203                         }
1204                         if (!rec_buf)
1205                         {
1206                             std::string addinfo;
1207
1208                             addinfo = "xslt apply failed for "
1209                                 + b->sptr->transform_xsl_fname;
1210                             npr = zget_surrogateDiagRec(
1211                                 odr, odr_database, 
1212                                 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1213                                 addinfo.c_str());
1214                         }
1215                         xmlFreeDoc(rec_doc);
1216                     }
1217                 }
1218
1219                 if (rec_buf)
1220                 {
1221                     xmlDoc *doc = xmlParseMemory(rec_buf, rec_len);
1222                     std::string res = 
1223                         mp::xml::url_recipe_handle(doc, b->sptr->urlRecipe);
1224                     if (res.length() && b->content_session_id.length())
1225                     {
1226                         size_t off = res.find_first_of("://");
1227                         if (off != std::string::npos)
1228                         {
1229                             char tmp[1024];
1230                             sprintf(tmp, "%s.%s/",
1231                                     b->content_session_id.c_str(),
1232                                     m_p->content_proxy_server.c_str());
1233                             res.insert(off + 3, tmp);
1234                         }
1235                     }
1236                     if (res.length())
1237                     {
1238                         xmlNode *ptr = xmlDocGetRootElement(doc);
1239                         while (ptr && ptr->type != XML_ELEMENT_NODE)
1240                             ptr = ptr->next;
1241                         xmlNode *c = 
1242                             xmlNewChild(ptr, 0, BAD_CAST "metadata", 0);
1243                         xmlNewProp(c, BAD_CAST "type", BAD_CAST
1244                                    "generated-url");
1245                         xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1246                         xmlAddChild(c, t);
1247
1248                         if (xmlrec_buf)
1249                             xmlFree(xmlrec_buf);
1250
1251                         xmlDocDumpMemory(doc, &xmlrec_buf, &rec_len);
1252                         rec_buf = (const char *) xmlrec_buf;
1253                     }
1254                     xmlFreeDoc(doc);
1255                 }
1256                 if (!npr)
1257                 {
1258                     if (!rec_buf)
1259                         npr = zget_surrogateDiagRec(
1260                             odr, odr_database, 
1261                             YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1262                             rec_type_str);
1263                     else
1264                     {
1265                         npr = (Z_NamePlusRecord *)
1266                             odr_malloc(odr, sizeof(*npr));
1267                         npr->databaseName = odr_database;
1268                         npr->which = Z_NamePlusRecord_databaseRecord;
1269                         npr->u.databaseRecord =
1270                             z_ext_record_xml(odr, rec_buf, rec_len);
1271                     }
1272                 }
1273                 if (xmlrec_buf)
1274                     xmlFree(xmlrec_buf);
1275             }
1276             else
1277             {
1278                 Z_External *ext =
1279                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1280                 if (ext)
1281                 {
1282                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1283                     npr->databaseName = odr_database;
1284                     npr->which = Z_NamePlusRecord_databaseRecord;
1285                     npr->u.databaseRecord = ext;
1286                 }
1287                 else
1288                 {
1289                     npr = zget_surrogateDiagRec(
1290                         odr, odr_database, 
1291                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1292                         "ZOOM_record, type ext");
1293                 }
1294             }
1295             npl->records[i] = npr;
1296         }
1297         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1298         records->which = Z_Records_DBOSD;
1299         records->u.databaseOrSurDiagnostics = npl;
1300     }
1301     return records;
1302 }
1303
1304 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1305                                                     ODR odr)
1306 {
1307     struct cql_node *r = 0;
1308     if (!cn)
1309         return 0;
1310     switch (cn->which)
1311     {
1312     case CQL_NODE_ST:
1313         if (cn->u.st.index)
1314         {
1315             std::map<std::string,std::string>::const_iterator it;
1316             it = fieldmap.find(cn->u.st.index);
1317             if (it == fieldmap.end())
1318                 return cn;
1319             if (it->second.length())
1320                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1321             else
1322                 cn->u.st.index = 0;
1323         }
1324         break;
1325     case CQL_NODE_BOOL:
1326         r = convert_cql_fields(cn->u.boolean.left, odr);
1327         if (!r)
1328             r = convert_cql_fields(cn->u.boolean.right, odr);
1329         break;
1330     case CQL_NODE_SORT:
1331         r = convert_cql_fields(cn->u.sort.search, odr);
1332         break;
1333     }
1334     return r;
1335 }
1336
1337 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1338 {
1339     Z_GDU *gdu = package.request().get();
1340     Z_APDU *apdu_req = gdu->u.z3950;
1341     Z_APDU *apdu_res = 0;
1342     mp::odr odr;
1343     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1344     if (sr->num_databaseNames != 1)
1345     {
1346         apdu_res = odr.create_searchResponse(
1347             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
1348         package.response() = apdu_res;
1349         return;
1350     }
1351
1352     int error = 0;
1353     char *addinfo = 0;
1354     std::string db(sr->databaseNames[0]);
1355     BackendPtr b = get_backend_from_databases(package, db, &error,
1356                                               &addinfo, odr);
1357     if (error)
1358     {
1359         apdu_res = 
1360             odr.create_searchResponse(apdu_req, error, addinfo);
1361         package.response() = apdu_res;
1362         return;
1363     }
1364
1365     b->set_option("setname", "default");
1366
1367     bool enable_pz2_retrieval = false;
1368     bool enable_pz2_transform = false;
1369     bool assume_marc8_charset = false;
1370     prepare_elements(b, sr->preferredRecordSyntax, 0 /*element_set_name */,
1371                      enable_pz2_retrieval,
1372                      enable_pz2_transform,
1373                      assume_marc8_charset);
1374
1375     Odr_int hits = 0;
1376     Z_Query *query = sr->query;
1377     WRBUF ccl_wrbuf = 0;
1378     WRBUF pqf_wrbuf = 0;
1379     std::string sortkeys;
1380
1381     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1382     {
1383         // RPN
1384         pqf_wrbuf = wrbuf_alloc();
1385         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1386     }
1387     else if (query->which == Z_Query_type_2)
1388     {
1389         // CCL
1390         ccl_wrbuf = wrbuf_alloc();
1391         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1392                     query->u.type_2->len);
1393     }
1394     else if (query->which == Z_Query_type_104 &&
1395              query->u.type_104->which == Z_External_CQL)
1396     {
1397         // CQL
1398         const char *cql = query->u.type_104->u.cql;
1399         CQL_parser cp = cql_parser_create();
1400         int r = cql_parser_string(cp, cql);
1401         package.log("zoom", YLOG_LOG, "CQL: %s", cql);
1402         if (r)
1403         {
1404             cql_parser_destroy(cp);
1405             package.log("zoom", YLOG_WARN, "CQL syntax error");
1406             apdu_res = 
1407                 odr.create_searchResponse(apdu_req, 
1408                                           YAZ_BIB1_MALFORMED_QUERY,
1409                                           "CQL syntax error");
1410             package.response() = apdu_res;
1411             return;
1412         }
1413         struct cql_node *cn = cql_parser_result(cp);
1414         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1415         if (cn_error)
1416         {
1417             // hopefully we are getting a ptr to a index+relation+term node
1418             addinfo = 0;
1419             if (cn_error->which == CQL_NODE_ST)
1420                 addinfo = cn_error->u.st.index;
1421
1422             apdu_res = 
1423                 odr.create_searchResponse(apdu_req, 
1424                                           YAZ_BIB1_UNSUPP_USE_ATTRIBUTE,
1425                                           addinfo);
1426             package.response() = apdu_res;
1427             return;
1428         }
1429         char ccl_buf[1024];
1430
1431         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1432         if (r == 0)
1433         {
1434             ccl_wrbuf = wrbuf_alloc();
1435             wrbuf_puts(ccl_wrbuf, ccl_buf);
1436             
1437             WRBUF sru_sortkeys_wrbuf = wrbuf_alloc();
1438
1439             cql_sortby_to_sortkeys(cn, wrbuf_vp_puts, sru_sortkeys_wrbuf);
1440             WRBUF sort_spec_wrbuf = wrbuf_alloc();
1441             yaz_srw_sortkeys_to_sort_spec(wrbuf_cstr(sru_sortkeys_wrbuf),
1442                                           sort_spec_wrbuf);
1443             wrbuf_destroy(sru_sortkeys_wrbuf);
1444
1445             yaz_tok_cfg_t tc = yaz_tok_cfg_create();
1446             yaz_tok_parse_t tp =
1447                 yaz_tok_parse_buf(tc, wrbuf_cstr(sort_spec_wrbuf));
1448             yaz_tok_cfg_destroy(tc);
1449
1450             /* go through sortspec and map fields */
1451             int token = yaz_tok_move(tp);
1452             while (token != YAZ_TOK_EOF)
1453             {
1454                 if (token == YAZ_TOK_STRING)
1455                 {
1456                     const char *field = yaz_tok_parse_string(tp);
1457                     std::map<std::string,std::string>::iterator it;
1458                     it = b->sptr->sortmap.find(field);
1459                     if (it != b->sptr->sortmap.end())
1460                         sortkeys += it->second;
1461                     else
1462                         sortkeys += field;
1463                 }
1464                 sortkeys += " ";
1465                 token = yaz_tok_move(tp);
1466                 if (token == YAZ_TOK_STRING)
1467                 {
1468                     sortkeys += yaz_tok_parse_string(tp);
1469                 }
1470                 if (token != YAZ_TOK_EOF)
1471                 {
1472                     sortkeys += " ";
1473                     token = yaz_tok_move(tp);
1474                 }
1475             }
1476             yaz_tok_parse_destroy(tp);
1477             wrbuf_destroy(sort_spec_wrbuf);
1478         }
1479         cql_parser_destroy(cp);
1480         if (r)
1481         {
1482             apdu_res = 
1483                 odr.create_searchResponse(apdu_req, 
1484                                           YAZ_BIB1_MALFORMED_QUERY,
1485                                           "CQL to CCL conversion error");
1486             package.response() = apdu_res;
1487             return;
1488         }
1489     }
1490     else
1491     {
1492         apdu_res = 
1493             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
1494         package.response() = apdu_res;
1495         return;
1496     }
1497
1498     if (ccl_wrbuf)
1499     {
1500         // CCL to PQF
1501         assert(pqf_wrbuf == 0);
1502         int cerror, cpos;
1503         struct ccl_rpn_node *cn;
1504         package.log("zoom", YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1505         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1506                           &cerror, &cpos);
1507         wrbuf_destroy(ccl_wrbuf);
1508         if (!cn)
1509         {
1510             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1511             int z3950_diag = YAZ_BIB1_MALFORMED_QUERY;
1512
1513             switch (cerror)
1514             {
1515             case CCL_ERR_UNKNOWN_QUAL:
1516                 z3950_diag = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1517                 break;
1518             case CCL_ERR_TRUNC_NOT_LEFT: 
1519             case CCL_ERR_TRUNC_NOT_RIGHT:
1520             case CCL_ERR_TRUNC_NOT_BOTH:
1521                 z3950_diag = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
1522                 break;
1523             }
1524             apdu_res = 
1525                 odr.create_searchResponse(apdu_req, z3950_diag, addinfo);
1526             package.response() = apdu_res;
1527             return;
1528         }
1529         pqf_wrbuf = wrbuf_alloc();
1530         ccl_pquery(pqf_wrbuf, cn);
1531         package.log("zoom", YLOG_LOG, "RPN: %s", wrbuf_cstr(pqf_wrbuf));
1532         ccl_rpn_delete(cn);
1533     }
1534     
1535     assert(pqf_wrbuf);
1536
1537     ZOOM_query q = ZOOM_query_create();
1538     ZOOM_query_sortby2(q, b->sptr->sortStrategy.c_str(), sortkeys.c_str());
1539
1540     if (b->get_option("sru"))
1541     {
1542         int status = 0;
1543         Z_RPNQuery *zquery;
1544         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1545         WRBUF wrb = wrbuf_alloc();
1546             
1547         if (!strcmp(b->get_option("sru"), "solr"))
1548         {
1549             solr_transform_t cqlt = solr_transform_create();
1550             
1551             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1552             
1553             solr_transform_close(cqlt);
1554         }
1555         else
1556         {
1557             cql_transform_t cqlt = cql_transform_create();
1558             
1559             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1560             
1561             cql_transform_close(cqlt);
1562         }
1563         if (status == 0)
1564         {
1565             ZOOM_query_cql(q, wrbuf_cstr(wrb));
1566             package.log("zoom", YLOG_LOG, "CQL: %s", wrbuf_cstr(wrb));
1567             b->search(q, &hits, &error, &addinfo, odr);
1568         }
1569         ZOOM_query_destroy(q);
1570         
1571         wrbuf_destroy(wrb);
1572         wrbuf_destroy(pqf_wrbuf);
1573         if (status)
1574         {
1575             apdu_res = 
1576                 odr.create_searchResponse(apdu_req, YAZ_BIB1_MALFORMED_QUERY,
1577                                           "can not convert from RPN to CQL/SOLR");
1578             package.response() = apdu_res;
1579             return;
1580         }
1581     }
1582     else
1583     {
1584         ZOOM_query_prefix(q, wrbuf_cstr(pqf_wrbuf));
1585         package.log("zoom", YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1586         b->search(q, &hits, &error, &addinfo, odr);
1587         ZOOM_query_destroy(q);
1588         wrbuf_destroy(pqf_wrbuf);
1589     }
1590
1591     const char *element_set_name = 0;
1592     Odr_int number_to_present = 0;
1593     if (!error)
1594         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1595     
1596     Odr_int number_of_records_returned = 0;
1597     Z_Records *records = get_records(
1598         0, number_to_present, &error, &addinfo,
1599         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1600         element_set_name);
1601     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1602     if (records)
1603     {
1604         apdu_res->u.searchResponse->records = records;
1605         apdu_res->u.searchResponse->numberOfRecordsReturned =
1606             odr_intdup(odr, number_of_records_returned);
1607     }
1608     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1609     package.response() = apdu_res;
1610 }
1611
1612 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1613 {
1614     Z_GDU *gdu = package.request().get();
1615     Z_APDU *apdu_req = gdu->u.z3950;
1616     Z_APDU *apdu_res = 0;
1617     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1618
1619     mp::odr odr;
1620     if (!m_backend)
1621     {
1622         package.response() = odr.create_presentResponse(
1623             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1624         return;
1625     }
1626     const char *element_set_name = 0;
1627     Z_RecordComposition *comp = pr->recordComposition;
1628     if (comp && comp->which != Z_RecordComp_simple)
1629     {
1630         package.response() = odr.create_presentResponse(
1631             apdu_req, 
1632             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1633         return;
1634     }
1635     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1636         element_set_name = comp->u.simple->u.generic;
1637     Odr_int number_of_records_returned = 0;
1638     int error = 0;
1639     char *addinfo = 0;
1640     Z_Records *records = get_records(
1641         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1642         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1643         pr->preferredRecordSyntax, element_set_name);
1644
1645     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1646     if (records)
1647     {
1648         apdu_res->u.presentResponse->records = records;
1649         apdu_res->u.presentResponse->numberOfRecordsReturned =
1650             odr_intdup(odr, number_of_records_returned);
1651     }
1652     package.response() = apdu_res;
1653 }
1654
1655 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1656 {
1657     Z_GDU *gdu = package.request().get();
1658     if (!gdu)
1659         ;
1660     else if (gdu->which == Z_GDU_Z3950)
1661     {
1662         Z_APDU *apdu_req = gdu->u.z3950;
1663
1664         if (m_backend)
1665             wrbuf_rewind(m_backend->m_apdu_wrbuf);
1666         if (apdu_req->which == Z_APDU_initRequest)
1667         {
1668             mp::odr odr;
1669             package.response() = odr.create_close(
1670                 apdu_req,
1671                 Z_Close_protocolError,
1672                 "double init");
1673         }
1674         else if (apdu_req->which == Z_APDU_searchRequest)
1675         {
1676             handle_search(package);
1677         }
1678         else if (apdu_req->which == Z_APDU_presentRequest)
1679         {
1680             handle_present(package);
1681         }
1682         else
1683         {
1684             mp::odr odr;
1685             package.response() = odr.create_close(
1686                 apdu_req,
1687                 Z_Close_protocolError,
1688                 "zoom filter cannot handle this APDU");
1689             package.session().close();
1690         }
1691         if (m_backend)
1692         {
1693             WRBUF w = m_backend->m_apdu_wrbuf;
1694             package.log_write(wrbuf_buf(w), wrbuf_len(w));
1695         }
1696     }
1697     else
1698     {
1699         package.session().close();
1700     }
1701 }
1702
1703 void yf::Zoom::Impl::process(mp::Package &package)
1704 {
1705     FrontendPtr f = get_frontend(package);
1706     Z_GDU *gdu = package.request().get();
1707
1708     if (f->m_is_virtual)
1709     {
1710         f->handle_package(package);
1711     }
1712     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1713              Z_APDU_initRequest)
1714     {
1715         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1716         f->m_init_gdu = gdu;
1717         
1718         mp::odr odr;
1719         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1720         Z_InitResponse *resp = apdu->u.initResponse;
1721         
1722         int i;
1723         static const int masks[] = {
1724             Z_Options_search,
1725             Z_Options_present,
1726             -1 
1727         };
1728         for (i = 0; masks[i] != -1; i++)
1729             if (ODR_MASK_GET(req->options, masks[i]))
1730                 ODR_MASK_SET(resp->options, masks[i]);
1731         
1732         static const int versions[] = {
1733             Z_ProtocolVersion_1,
1734             Z_ProtocolVersion_2,
1735             Z_ProtocolVersion_3,
1736             -1
1737         };
1738         for (i = 0; versions[i] != -1; i++)
1739             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1740                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1741             else
1742                 break;
1743         
1744         *resp->preferredMessageSize = *req->preferredMessageSize;
1745         *resp->maximumRecordSize = *req->maximumRecordSize;
1746         
1747         package.response() = apdu;
1748         f->m_is_virtual = true;
1749     }
1750     else
1751         package.move();
1752
1753     release_frontend(package);
1754 }
1755
1756
1757 static mp::filter::Base* filter_creator()
1758 {
1759     return new mp::filter::Zoom;
1760 }
1761
1762 extern "C" {
1763     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1764         0,
1765         "zoom",
1766         filter_creator
1767     };
1768 }
1769
1770
1771 /*
1772  * Local variables:
1773  * c-basic-offset: 4
1774  * c-file-style: "Stroustrup"
1775  * indent-tabs-mode: nil
1776  * End:
1777  * vim: shiftwidth=4 tabstop=8 expandtab
1778  */
1779