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