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