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