Refactor database URL logic
[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     std::string db_args;
599     std::string torus_db;
600     size_t db_arg_pos = database.find(',');
601     if (db_arg_pos != std::string::npos)
602     {
603         torus_db = database.substr(0, db_arg_pos);
604         db_args = database.substr(db_arg_pos + 1);
605     }
606     else
607         torus_db = database;
608  
609     SearchablePtr sptr;
610
611     std::map<std::string,SearchablePtr>::iterator it;
612     it = m_p->s_map.find(torus_db);
613     if (it != m_p->s_map.end())
614         sptr = it->second;
615     else
616     {
617         xmlDoc *doc = mp::get_searchable(m_p->torus_url, torus_db);
618         if (!doc)
619         {
620             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
621             *addinfo = odr_strdup(odr, database.c_str());
622             BackendPtr b;
623             return b;
624         }
625         const xmlNode *ptr = xmlDocGetRootElement(doc);
626         if (ptr)
627         {   // presumably ptr is a records element node
628             // parse first record in document
629             for (ptr = ptr->children; ptr; ptr = ptr->next)
630             {
631                 if (ptr->type == XML_ELEMENT_NODE
632                     && !strcmp((const char *) ptr->name, "record"))
633                 {
634                     sptr = m_p->parse_torus_record(ptr);
635                     break;
636                 }
637             }
638         }
639         xmlFreeDoc(doc);
640     }
641
642     if (!sptr)
643     {
644         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
645         *addinfo = odr_strdup(odr, database.c_str());
646         BackendPtr b;
647         return b;
648     }
649         
650     xsltStylesheetPtr xsp = 0;
651     if (sptr->transform_xsl_fname.length())
652     {
653         const char *path = 0;
654
655         if (m_p->xsldir.length())
656             path = m_p->xsldir.c_str();
657         else
658             path = m_p->file_path.c_str();
659         std::string fname;
660
661         char fullpath[1024];
662         char *cp = yaz_filepath_resolve(sptr->transform_xsl_fname.c_str(),
663                                         path, 0, fullpath);
664         if (cp)
665             fname.assign(cp);
666         else
667         {
668             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
669             *addinfo = (char *)
670                 odr_malloc(odr, 40 + sptr->transform_xsl_fname.length());
671             sprintf(*addinfo, "File could not be read: %s", 
672                     sptr->transform_xsl_fname.c_str());
673             BackendPtr b;
674             return b;
675         }
676         xmlDoc *xsp_doc = xmlParseFile(fname.c_str());
677         if (!xsp_doc)
678         {
679             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
680             *addinfo = (char *) odr_malloc(odr, 40 + fname.length());
681             sprintf(*addinfo, "xmlParseFile failed. File: %s", fname.c_str());
682             BackendPtr b;
683             return b;
684         }
685         xsp = xsltParseStylesheetDoc(xsp_doc);
686         if (!xsp)
687         {
688             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
689             *addinfo = odr_strdup(odr, "xsltParseStylesheetDoc failed");
690             BackendPtr b;
691             xmlFreeDoc(xsp_doc);
692             return b;
693         }
694     }
695
696     m_backend.reset();
697
698     BackendPtr b(new Backend(sptr));
699
700     b->xsp = xsp;
701     b->m_frontend_database = database;
702
703     if (sptr->query_encoding.length())
704         b->set_option("rpnCharset", sptr->query_encoding.c_str());
705
706     b->set_option("timeout", "40");
707
708
709     std::string authentication = sptr->authentication;
710     std::string proxy = sptr->cfProxy;
711         
712     const char *param_user = 0;
713     const char *param_password = 0;
714     const char *param_proxy = 0;
715     if (db_args.length())
716     {
717         char **names;
718         char **values;
719         int i;
720         int no_parms = yaz_uri_to_array(db_args.c_str(),
721                                         odr, &names, &values);
722         for (i = 0; i < no_parms; i++)
723         {
724             const char *name = names[i];
725             const char *value = values[i];
726             if (!strcmp(name, "user"))
727                 param_user = value;
728             else if (!strcmp(name, "password"))
729                 param_password = value;
730             else if (!strcmp(name, "proxy"))
731                 param_proxy = value;
732             else
733             {
734                 BackendPtr notfound;
735                 char *msg = (char*) odr_malloc(odr, strlen(name) + 30);
736                 *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
737                 sprintf(msg, "Bad database argument: %s", name);
738                 *addinfo = msg;
739                 return notfound;
740             }
741         }
742         if (param_user && param_password)
743         {
744             authentication = std::string(param_user)
745                 + "/" + std::string(param_password);
746         }
747         if (param_proxy)
748             proxy = param_proxy;
749     }
750
751     if (sptr->cfAuth.length())
752     {
753         // A CF target
754         b->set_option("user", sptr->cfAuth.c_str());
755         if (!param_user && !param_password && authentication.length())
756         {
757             if (db_args.length())
758                 db_args += "&";
759             // no database (auth) args specified already.. and the
760             // Torus authentication has it.. Generate the args that CF
761             // understands..
762             size_t found = authentication.find('/');
763             if (found != std::string::npos)
764             {
765                 db_args += "user=" +
766                     mp::util::uri_encode(authentication.substr(0, found))
767                     + "&password=" +
768                     mp::util::uri_encode(authentication.substr(found+1));
769             }
770             else
771                 db_args += "user=" + mp::util::uri_encode(authentication);
772         }
773         if (!param_proxy && proxy.length())
774         {
775             if (db_args.length())
776                 db_args += "&";
777             db_args += "proxy=" + mp::util::uri_encode(proxy);
778         }
779         if (sptr->cfSubDb.length())
780         {
781             if (db_args.length())
782                 db_args += "&";
783             db_args += "subdatabase=" + mp::util::uri_encode(sptr->cfSubDb);
784         }
785     }
786     else
787     {
788         db_args.clear(); // no arguments to be passed (non-CF)
789
790         if (authentication.length())
791             b->set_option("user", authentication.c_str());
792         if (proxy.length())
793             b->set_option("proxy", proxy.c_str());
794     }
795     if (b->sptr->contentConnector.length())
796     {
797         int fd;
798         
799         char *fname = (char *) xmalloc(m_p->content_tmp_file.length() + 8);
800         strcpy(fname, m_p->content_tmp_file.c_str());
801         strcat(fname, "XXXXXX");
802         fd = mkstemp(fname);
803         
804         if (fd == -1)
805         {
806             yaz_log(YLOG_WARN|YLOG_ERRNO, "create %s", fname);
807             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
808             *addinfo = (char *)  odr_malloc(odr, 40 + strlen(fname));
809             sprintf(*addinfo, "Could not create %s", fname);
810             xfree(fname);
811             BackendPtr backend_null;
812             return backend_null;
813         }
814         b->content_session_id.assign(fname + (strlen(fname) - 6));
815         WRBUF w = wrbuf_alloc();
816         wrbuf_puts(w, "#content_proxy\n");
817         if (authentication.length())
818             wrbuf_printf(w, "authentication: %s\n", authentication.c_str());
819         if (proxy.length())
820             wrbuf_printf(w, "proxy: %s\n", proxy.c_str());
821         if (sptr->cfAuth.length())
822             wrbuf_printf(w, "cfauth: %s\n", sptr->cfAuth.c_str());
823         if (sptr->cfProxy.length())
824             wrbuf_printf(w, "cfproxy: %s\n", sptr->cfProxy.c_str());
825
826         write(fd, wrbuf_buf(w), wrbuf_len(w));
827         close(fd);
828         yaz_log(YLOG_LOG, "file %s created\n", fname);
829         xfree(fname);
830     }
831     
832
833     std::string url;
834     if (sptr->sru.length())
835     {
836         url = "http://" + sptr->target;
837         b->set_option("sru", sptr->sru.c_str());
838     }
839     else
840     {
841         url = sptr->target;
842     }
843     if (db_args.length())
844         url += "," + db_args;
845     yaz_log(YLOG_LOG, "url=%s", url.c_str());
846     b->connect(url, error, addinfo, odr);
847     if (*error == 0)
848     {
849         m_backend = b;
850     }
851     return b;
852 }
853
854 Z_Records *yf::Zoom::Frontend::get_records(Odr_int start,
855                                            Odr_int number_to_present,
856                                            int *error,
857                                            char **addinfo,
858                                            Odr_int *number_of_records_returned,
859                                            ODR odr,
860                                            BackendPtr b,
861                                            Odr_oid *preferredRecordSyntax,
862                                            const char *element_set_name)
863 {
864     *number_of_records_returned = 0;
865     Z_Records *records = 0;
866     bool enable_pz2_retrieval = false; // whether target profile is used
867     bool enable_pz2_transform = false; // whether XSLT is used as well
868     bool assume_marc8_charset = false;
869
870     if (start < 0 || number_to_present <= 0)
871         return records;
872     
873     if (number_to_present > 10000)
874         number_to_present = 10000;
875     
876     ZOOM_record *recs = (ZOOM_record *)
877         odr_malloc(odr, number_to_present * sizeof(*recs));
878
879     char oid_name_str[OID_STR_MAX];
880     const char *syntax_name = 0;
881     
882     if (preferredRecordSyntax &&
883         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
884         && element_set_name)
885     {
886         if (!strcmp(element_set_name, m_p->element_transform.c_str()))
887         {
888             enable_pz2_retrieval = true;
889             enable_pz2_transform = true;
890         }
891         else if (!strcmp(element_set_name, m_p->element_raw.c_str()))
892         {
893             enable_pz2_retrieval = true;
894         }
895     }
896     
897     if (enable_pz2_retrieval)
898     {
899         if (b->sptr->request_syntax.length())
900         {
901             syntax_name = b->sptr->request_syntax.c_str();
902             const Odr_oid *syntax_oid = 
903                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
904             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
905                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
906                 assume_marc8_charset = true;
907         }
908     }
909     else if (preferredRecordSyntax)
910         syntax_name =
911             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
912
913     b->set_option("preferredRecordSyntax", syntax_name);
914
915     if (enable_pz2_retrieval)
916     {
917         element_set_name = 0;
918         if (b->sptr->element_set.length())
919             element_set_name = b->sptr->element_set.c_str();
920     }
921
922     b->set_option("elementSetName", element_set_name);
923
924     b->present(start, number_to_present, recs, error, addinfo, odr);
925
926     Odr_int i = 0;
927     if (!*error)
928     {
929         for (i = 0; i < number_to_present; i++)
930             if (!recs[i])
931                 break;
932     }
933     if (i > 0)
934     {  // only return records if no error and at least one record
935         char *odr_database = odr_strdup(odr,
936                                         b->m_frontend_database.c_str());
937         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
938             odr_malloc(odr, sizeof(*npl));
939         *number_of_records_returned = i;
940         npl->num_records = i;
941         npl->records = (Z_NamePlusRecord **)
942             odr_malloc(odr, i * sizeof(*npl->records));
943         for (i = 0; i < number_to_present; i++)
944         {
945             Z_NamePlusRecord *npr = 0;
946             const char *addinfo;
947             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
948                                               &addinfo, 0 /* diagset */);
949                 
950             if (sur_error)
951             {
952                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
953                                             addinfo);
954             }
955             else if (enable_pz2_retrieval)
956             {
957                 char rec_type_str[100];
958                 const char *record_encoding = 0;
959
960                 if (b->sptr->record_encoding.length())
961                     record_encoding = b->sptr->record_encoding.c_str();
962                 else if (assume_marc8_charset)
963                     record_encoding = "marc8";
964
965                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
966                 if (record_encoding)
967                 {
968                     strcat(rec_type_str, "; charset=");
969                     strcat(rec_type_str, record_encoding);
970                 }
971                 
972                 int rec_len;
973                 xmlChar *xmlrec_buf = 0;
974                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
975                                                       &rec_len);
976                 if (rec_buf && b->xsp && enable_pz2_transform)
977                 {
978                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
979                     if (rec_doc)
980                     { 
981                         xmlDoc *rec_res;
982                         rec_res = xsltApplyStylesheet(b->xsp, rec_doc, 0);
983
984                         if (rec_res)
985                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
986                                                    rec_res, b->xsp);
987                         rec_buf = (const char *) xmlrec_buf;
988                         xmlFreeDoc(rec_doc);
989                         xmlFreeDoc(rec_res);
990                     }
991                 }
992
993                 if (rec_buf)
994                 {
995                     xmlDoc *doc = xmlParseMemory(rec_buf, rec_len);
996                     std::string res = 
997                         mp::xml::url_recipe_handle(doc, b->sptr->urlRecipe);
998                     if (res.length() && b->content_session_id.length())
999                     {
1000                         size_t off = res.find_first_of("://");
1001                         if (off != std::string::npos)
1002                         {
1003                             char tmp[1024];
1004                             sprintf(tmp, "%s.%s/",
1005                                     b->content_session_id.c_str(),
1006                                     m_p->content_proxy_server.c_str());
1007                             res.insert(off + 3, tmp);
1008                         }
1009                     }
1010                     if (res.length())
1011                     {
1012                         xmlNode *ptr = xmlDocGetRootElement(doc);
1013                         while (ptr && ptr->type != XML_ELEMENT_NODE)
1014                             ptr = ptr->next;
1015                         xmlNode *c = 
1016                             xmlNewChild(ptr, 0, BAD_CAST "generated-url", 0);
1017                         xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1018                         xmlAddChild(c, t);
1019
1020                         if (xmlrec_buf)
1021                             xmlFree(xmlrec_buf);
1022
1023                         xmlDocDumpMemory(doc, &xmlrec_buf, &rec_len);
1024                         rec_buf = (const char *) xmlrec_buf;
1025                     }
1026                     xmlFreeDoc(doc);
1027                 }
1028                 if (rec_buf)
1029                 {
1030                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1031                     npr->databaseName = odr_database;
1032                     npr->which = Z_NamePlusRecord_databaseRecord;
1033                     npr->u.databaseRecord =
1034                         z_ext_record_xml(odr, rec_buf, rec_len);
1035                 }
1036                 else
1037                 {
1038                     npr = zget_surrogateDiagRec(
1039                         odr, odr_database, 
1040                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1041                         rec_type_str);
1042                 }
1043                 if (xmlrec_buf)
1044                     xmlFree(xmlrec_buf);
1045             }
1046             else
1047             {
1048                 Z_External *ext =
1049                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1050                 if (ext)
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 = ext;
1056                 }
1057                 else
1058                 {
1059                     npr = zget_surrogateDiagRec(
1060                         odr, odr_database, 
1061                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1062                         "ZOOM_record, type ext");
1063                 }
1064             }
1065             npl->records[i] = npr;
1066         }
1067         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1068         records->which = Z_Records_DBOSD;
1069         records->u.databaseOrSurDiagnostics = npl;
1070     }
1071     return records;
1072 }
1073     
1074 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1075                                                     ODR odr)
1076 {
1077     struct cql_node *r = 0;
1078     if (!cn)
1079         return 0;
1080     switch (cn->which)
1081     {
1082     case CQL_NODE_ST:
1083         if (cn->u.st.index)
1084         {
1085             std::map<std::string,std::string>::const_iterator it;
1086             it = fieldmap.find(cn->u.st.index);
1087             if (it == fieldmap.end())
1088                 return cn;
1089             if (it->second.length())
1090                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1091             else
1092                 cn->u.st.index = 0;
1093         }
1094         break;
1095     case CQL_NODE_BOOL:
1096         r = convert_cql_fields(cn->u.boolean.left, odr);
1097         if (!r)
1098             r = convert_cql_fields(cn->u.boolean.right, odr);
1099         break;
1100     case CQL_NODE_SORT:
1101         r = convert_cql_fields(cn->u.sort.search, odr);
1102         break;
1103     }
1104     return r;
1105 }
1106
1107 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1108 {
1109     Z_GDU *gdu = package.request().get();
1110     Z_APDU *apdu_req = gdu->u.z3950;
1111     Z_APDU *apdu_res = 0;
1112     mp::odr odr;
1113     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1114     if (sr->num_databaseNames != 1)
1115     {
1116         apdu_res = odr.create_searchResponse(
1117             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
1118         package.response() = apdu_res;
1119         return;
1120     }
1121
1122     int error = 0;
1123     char *addinfo = 0;
1124     std::string db(sr->databaseNames[0]);
1125     BackendPtr b = get_backend_from_databases(db, &error, &addinfo, odr);
1126     if (error)
1127     {
1128         apdu_res = 
1129             odr.create_searchResponse(apdu_req, error, addinfo);
1130         package.response() = apdu_res;
1131         return;
1132     }
1133
1134     b->set_option("setname", "default");
1135
1136     Odr_int hits = 0;
1137     Z_Query *query = sr->query;
1138     WRBUF ccl_wrbuf = 0;
1139     WRBUF pqf_wrbuf = 0;
1140
1141     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1142     {
1143         // RPN
1144         pqf_wrbuf = wrbuf_alloc();
1145         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1146     }
1147     else if (query->which == Z_Query_type_2)
1148     {
1149         // CCL
1150         ccl_wrbuf = wrbuf_alloc();
1151         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1152                     query->u.type_2->len);
1153     }
1154     else if (query->which == Z_Query_type_104 &&
1155              query->u.type_104->which == Z_External_CQL)
1156     {
1157         // CQL
1158         const char *cql = query->u.type_104->u.cql;
1159         CQL_parser cp = cql_parser_create();
1160         int r = cql_parser_string(cp, cql);
1161         if (r)
1162         {
1163             cql_parser_destroy(cp);
1164             apdu_res = 
1165                 odr.create_searchResponse(apdu_req, 
1166                                           YAZ_BIB1_MALFORMED_QUERY,
1167                                           "CQL syntax error");
1168             package.response() = apdu_res;
1169             return;
1170         }
1171         struct cql_node *cn = cql_parser_result(cp);
1172         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1173         if (cn_error)
1174         {
1175             // hopefully we are getting a ptr to a index+relation+term node
1176             addinfo = 0;
1177             if (cn_error->which == CQL_NODE_ST)
1178                 addinfo = cn_error->u.st.index;
1179
1180             apdu_res = 
1181                 odr.create_searchResponse(apdu_req, 
1182                                           YAZ_BIB1_UNSUPP_USE_ATTRIBUTE,
1183                                           addinfo);
1184             package.response() = apdu_res;
1185             return;
1186         }
1187         char ccl_buf[1024];
1188
1189         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1190         if (r == 0)
1191         {
1192             ccl_wrbuf = wrbuf_alloc();
1193             wrbuf_puts(ccl_wrbuf, ccl_buf);
1194         }
1195         cql_parser_destroy(cp);
1196         if (r)
1197         {
1198             apdu_res = 
1199                 odr.create_searchResponse(apdu_req, 
1200                                           YAZ_BIB1_MALFORMED_QUERY,
1201                                           "CQL to CCL conversion error");
1202             package.response() = apdu_res;
1203             return;
1204         }
1205     }
1206     else
1207     {
1208         apdu_res = 
1209             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
1210         package.response() = apdu_res;
1211         return;
1212     }
1213
1214     if (ccl_wrbuf)
1215     {
1216         // CCL to PQF
1217         assert(pqf_wrbuf == 0);
1218         int cerror, cpos;
1219         struct ccl_rpn_node *cn;
1220         yaz_log(YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1221         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1222                           &cerror, &cpos);
1223         wrbuf_destroy(ccl_wrbuf);
1224         if (!cn)
1225         {
1226             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1227             int z3950_diag = YAZ_BIB1_MALFORMED_QUERY;
1228
1229             switch (cerror)
1230             {
1231             case CCL_ERR_UNKNOWN_QUAL:
1232                 z3950_diag = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1233                 break;
1234             case CCL_ERR_TRUNC_NOT_LEFT: 
1235             case CCL_ERR_TRUNC_NOT_RIGHT:
1236             case CCL_ERR_TRUNC_NOT_BOTH:
1237                 z3950_diag = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
1238                 break;
1239             }
1240             apdu_res = 
1241                 odr.create_searchResponse(apdu_req, z3950_diag, addinfo);
1242             package.response() = apdu_res;
1243             return;
1244         }
1245         pqf_wrbuf = wrbuf_alloc();
1246         ccl_pquery(pqf_wrbuf, cn);
1247         ccl_rpn_delete(cn);
1248     }
1249     
1250     assert(pqf_wrbuf);
1251     if (b->get_option("sru"))
1252     {
1253         int status = 0;
1254         Z_RPNQuery *zquery;
1255         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1256         WRBUF wrb = wrbuf_alloc();
1257             
1258         if (!strcmp(b->get_option("sru"), "solr"))
1259         {
1260             solr_transform_t cqlt = solr_transform_create();
1261             
1262             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1263             
1264             solr_transform_close(cqlt);
1265         }
1266         else
1267         {
1268             cql_transform_t cqlt = cql_transform_create();
1269             
1270             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1271             
1272             cql_transform_close(cqlt);
1273         }
1274         if (status == 0)
1275         {
1276             yaz_log(YLOG_LOG, "search CQL: %s", wrbuf_cstr(wrb));
1277             b->search_cql(wrbuf_cstr(wrb), &hits, &error, &addinfo, odr);
1278         }
1279         
1280         wrbuf_destroy(wrb);
1281         wrbuf_destroy(pqf_wrbuf);
1282         if (status)
1283         {
1284             apdu_res = 
1285                 odr.create_searchResponse(apdu_req, YAZ_BIB1_MALFORMED_QUERY,
1286                                           "can not convert from RPN to CQL/SOLR");
1287             package.response() = apdu_res;
1288             return;
1289         }
1290     }
1291     else
1292     {
1293         yaz_log(YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1294         b->search_pqf(wrbuf_cstr(pqf_wrbuf), &hits, &error, &addinfo, odr);
1295         wrbuf_destroy(pqf_wrbuf);
1296     }
1297     
1298     
1299     const char *element_set_name = 0;
1300     Odr_int number_to_present = 0;
1301     if (!error)
1302         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1303     
1304     Odr_int number_of_records_returned = 0;
1305     Z_Records *records = get_records(
1306         0, number_to_present, &error, &addinfo,
1307         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1308         element_set_name);
1309     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1310     if (records)
1311     {
1312         apdu_res->u.searchResponse->records = records;
1313         apdu_res->u.searchResponse->numberOfRecordsReturned =
1314             odr_intdup(odr, number_of_records_returned);
1315     }
1316     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1317     package.response() = apdu_res;
1318 }
1319
1320 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1321 {
1322     Z_GDU *gdu = package.request().get();
1323     Z_APDU *apdu_req = gdu->u.z3950;
1324     Z_APDU *apdu_res = 0;
1325     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1326
1327     mp::odr odr;
1328     if (!m_backend)
1329     {
1330         package.response() = odr.create_presentResponse(
1331             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1332         return;
1333     }
1334     const char *element_set_name = 0;
1335     Z_RecordComposition *comp = pr->recordComposition;
1336     if (comp && comp->which != Z_RecordComp_simple)
1337     {
1338         package.response() = odr.create_presentResponse(
1339             apdu_req, 
1340             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1341         return;
1342     }
1343     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1344         element_set_name = comp->u.simple->u.generic;
1345     Odr_int number_of_records_returned = 0;
1346     int error = 0;
1347     char *addinfo = 0;
1348     Z_Records *records = get_records(
1349         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1350         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1351         pr->preferredRecordSyntax, element_set_name);
1352
1353     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1354     if (records)
1355     {
1356         apdu_res->u.presentResponse->records = records;
1357         apdu_res->u.presentResponse->numberOfRecordsReturned =
1358             odr_intdup(odr, number_of_records_returned);
1359     }
1360     package.response() = apdu_res;
1361 }
1362
1363 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1364 {
1365     Z_GDU *gdu = package.request().get();
1366     if (!gdu)
1367         ;
1368     else if (gdu->which == Z_GDU_Z3950)
1369     {
1370         Z_APDU *apdu_req = gdu->u.z3950;
1371         if (apdu_req->which == Z_APDU_initRequest)
1372         {
1373             mp::odr odr;
1374             package.response() = odr.create_close(
1375                 apdu_req,
1376                 Z_Close_protocolError,
1377                 "double init");
1378         }
1379         else if (apdu_req->which == Z_APDU_searchRequest)
1380         {
1381             handle_search(package);
1382         }
1383         else if (apdu_req->which == Z_APDU_presentRequest)
1384         {
1385             handle_present(package);
1386         }
1387         else
1388         {
1389             mp::odr odr;
1390             package.response() = odr.create_close(
1391                 apdu_req,
1392                 Z_Close_protocolError,
1393                 "zoom filter cannot handle this APDU");
1394             package.session().close();
1395         }
1396     }
1397     else
1398     {
1399         package.session().close();
1400     }
1401 }
1402
1403 void yf::Zoom::Impl::process(mp::Package &package)
1404 {
1405     FrontendPtr f = get_frontend(package);
1406     Z_GDU *gdu = package.request().get();
1407
1408     if (f->m_is_virtual)
1409     {
1410         f->handle_package(package);
1411     }
1412     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1413              Z_APDU_initRequest)
1414     {
1415         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1416         f->m_init_gdu = gdu;
1417         
1418         mp::odr odr;
1419         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1420         Z_InitResponse *resp = apdu->u.initResponse;
1421         
1422         int i;
1423         static const int masks[] = {
1424             Z_Options_search,
1425             Z_Options_present,
1426             -1 
1427         };
1428         for (i = 0; masks[i] != -1; i++)
1429             if (ODR_MASK_GET(req->options, masks[i]))
1430                 ODR_MASK_SET(resp->options, masks[i]);
1431         
1432         static const int versions[] = {
1433             Z_ProtocolVersion_1,
1434             Z_ProtocolVersion_2,
1435             Z_ProtocolVersion_3,
1436             -1
1437         };
1438         for (i = 0; versions[i] != -1; i++)
1439             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1440                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1441             else
1442                 break;
1443         
1444         *resp->preferredMessageSize = *req->preferredMessageSize;
1445         *resp->maximumRecordSize = *req->maximumRecordSize;
1446         
1447         package.response() = apdu;
1448         f->m_is_virtual = true;
1449     }
1450     else
1451         package.move();
1452
1453     release_frontend(package);
1454 }
1455
1456
1457 static mp::filter::Base* filter_creator()
1458 {
1459     return new mp::filter::Zoom;
1460 }
1461
1462 extern "C" {
1463     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1464         0,
1465         "zoom",
1466         filter_creator
1467     };
1468 }
1469
1470
1471 /*
1472  * Local variables:
1473  * c-basic-offset: 4
1474  * c-file-style: "Stroustrup"
1475  * indent-tabs-mode: nil
1476  * End:
1477  * vim: shiftwidth=4 tabstop=8 expandtab
1478  */
1479