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