zoom: put contentConnector in temp 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     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         wrbuf_printf(w, "connector: %s\n", b->sptr->contentConnector.c_str());
818         if (authentication.length())
819             wrbuf_printf(w, "authentication: %s\n", authentication.c_str());
820         if (proxy.length())
821             wrbuf_printf(w, "proxy: %s\n", proxy.c_str());
822         if (sptr->cfAuth.length())
823             wrbuf_printf(w, "cfauth: %s\n", sptr->cfAuth.c_str());
824         if (sptr->cfProxy.length())
825             wrbuf_printf(w, "cfproxy: %s\n", sptr->cfProxy.c_str());
826
827         write(fd, wrbuf_buf(w), wrbuf_len(w));
828         close(fd);
829         yaz_log(YLOG_LOG, "file %s created\n", fname);
830         xfree(fname);
831     }
832     
833
834     std::string url;
835     if (sptr->sru.length())
836     {
837         url = "http://" + sptr->target;
838         b->set_option("sru", sptr->sru.c_str());
839     }
840     else
841     {
842         url = sptr->target;
843     }
844     if (db_args.length())
845         url += "," + db_args;
846     yaz_log(YLOG_LOG, "url=%s", url.c_str());
847     b->connect(url, error, addinfo, odr);
848     if (*error == 0)
849     {
850         m_backend = b;
851     }
852     return b;
853 }
854
855 Z_Records *yf::Zoom::Frontend::get_records(Odr_int start,
856                                            Odr_int number_to_present,
857                                            int *error,
858                                            char **addinfo,
859                                            Odr_int *number_of_records_returned,
860                                            ODR odr,
861                                            BackendPtr b,
862                                            Odr_oid *preferredRecordSyntax,
863                                            const char *element_set_name)
864 {
865     *number_of_records_returned = 0;
866     Z_Records *records = 0;
867     bool enable_pz2_retrieval = false; // whether target profile is used
868     bool enable_pz2_transform = false; // whether XSLT is used as well
869     bool assume_marc8_charset = false;
870
871     if (start < 0 || number_to_present <= 0)
872         return records;
873     
874     if (number_to_present > 10000)
875         number_to_present = 10000;
876     
877     ZOOM_record *recs = (ZOOM_record *)
878         odr_malloc(odr, number_to_present * sizeof(*recs));
879
880     char oid_name_str[OID_STR_MAX];
881     const char *syntax_name = 0;
882     
883     if (preferredRecordSyntax &&
884         !oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
885         && element_set_name)
886     {
887         if (!strcmp(element_set_name, m_p->element_transform.c_str()))
888         {
889             enable_pz2_retrieval = true;
890             enable_pz2_transform = true;
891         }
892         else if (!strcmp(element_set_name, m_p->element_raw.c_str()))
893         {
894             enable_pz2_retrieval = true;
895         }
896     }
897     
898     if (enable_pz2_retrieval)
899     {
900         if (b->sptr->request_syntax.length())
901         {
902             syntax_name = b->sptr->request_syntax.c_str();
903             const Odr_oid *syntax_oid = 
904                 yaz_string_to_oid(yaz_oid_std(), CLASS_RECSYN, syntax_name);
905             if (!oid_oidcmp(syntax_oid, yaz_oid_recsyn_usmarc)
906                 || !oid_oidcmp(syntax_oid, yaz_oid_recsyn_opac))
907                 assume_marc8_charset = true;
908         }
909     }
910     else if (preferredRecordSyntax)
911         syntax_name =
912             yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
913
914     b->set_option("preferredRecordSyntax", syntax_name);
915
916     if (enable_pz2_retrieval)
917     {
918         element_set_name = 0;
919         if (b->sptr->element_set.length())
920             element_set_name = b->sptr->element_set.c_str();
921     }
922
923     b->set_option("elementSetName", element_set_name);
924
925     b->present(start, number_to_present, recs, error, addinfo, odr);
926
927     Odr_int i = 0;
928     if (!*error)
929     {
930         for (i = 0; i < number_to_present; i++)
931             if (!recs[i])
932                 break;
933     }
934     if (i > 0)
935     {  // only return records if no error and at least one record
936         char *odr_database = odr_strdup(odr,
937                                         b->m_frontend_database.c_str());
938         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
939             odr_malloc(odr, sizeof(*npl));
940         *number_of_records_returned = i;
941         npl->num_records = i;
942         npl->records = (Z_NamePlusRecord **)
943             odr_malloc(odr, i * sizeof(*npl->records));
944         for (i = 0; i < number_to_present; i++)
945         {
946             Z_NamePlusRecord *npr = 0;
947             const char *addinfo;
948             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
949                                               &addinfo, 0 /* diagset */);
950                 
951             if (sur_error)
952             {
953                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
954                                             addinfo);
955             }
956             else if (enable_pz2_retrieval)
957             {
958                 char rec_type_str[100];
959                 const char *record_encoding = 0;
960
961                 if (b->sptr->record_encoding.length())
962                     record_encoding = b->sptr->record_encoding.c_str();
963                 else if (assume_marc8_charset)
964                     record_encoding = "marc8";
965
966                 strcpy(rec_type_str, b->sptr->use_turbomarc ? "txml" : "xml");
967                 if (record_encoding)
968                 {
969                     strcat(rec_type_str, "; charset=");
970                     strcat(rec_type_str, record_encoding);
971                 }
972                 
973                 int rec_len;
974                 xmlChar *xmlrec_buf = 0;
975                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
976                                                       &rec_len);
977                 if (rec_buf && b->xsp && enable_pz2_transform)
978                 {
979                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
980                     if (rec_doc)
981                     { 
982                         xmlDoc *rec_res;
983                         rec_res = xsltApplyStylesheet(b->xsp, rec_doc, 0);
984
985                         if (rec_res)
986                             xsltSaveResultToString(&xmlrec_buf, &rec_len,
987                                                    rec_res, b->xsp);
988                         rec_buf = (const char *) xmlrec_buf;
989                         xmlFreeDoc(rec_doc);
990                         xmlFreeDoc(rec_res);
991                     }
992                 }
993
994                 if (rec_buf)
995                 {
996                     xmlDoc *doc = xmlParseMemory(rec_buf, rec_len);
997                     std::string res = 
998                         mp::xml::url_recipe_handle(doc, b->sptr->urlRecipe);
999                     if (res.length() && b->content_session_id.length())
1000                     {
1001                         size_t off = res.find_first_of("://");
1002                         if (off != std::string::npos)
1003                         {
1004                             char tmp[1024];
1005                             sprintf(tmp, "%s.%s/",
1006                                     b->content_session_id.c_str(),
1007                                     m_p->content_proxy_server.c_str());
1008                             res.insert(off + 3, tmp);
1009                         }
1010                     }
1011                     if (res.length())
1012                     {
1013                         xmlNode *ptr = xmlDocGetRootElement(doc);
1014                         while (ptr && ptr->type != XML_ELEMENT_NODE)
1015                             ptr = ptr->next;
1016                         xmlNode *c = 
1017                             xmlNewChild(ptr, 0, BAD_CAST "generated-url", 0);
1018                         xmlNode * t = xmlNewText(BAD_CAST res.c_str());
1019                         xmlAddChild(c, t);
1020
1021                         if (xmlrec_buf)
1022                             xmlFree(xmlrec_buf);
1023
1024                         xmlDocDumpMemory(doc, &xmlrec_buf, &rec_len);
1025                         rec_buf = (const char *) xmlrec_buf;
1026                     }
1027                     xmlFreeDoc(doc);
1028                 }
1029                 if (rec_buf)
1030                 {
1031                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1032                     npr->databaseName = odr_database;
1033                     npr->which = Z_NamePlusRecord_databaseRecord;
1034                     npr->u.databaseRecord =
1035                         z_ext_record_xml(odr, rec_buf, rec_len);
1036                 }
1037                 else
1038                 {
1039                     npr = zget_surrogateDiagRec(
1040                         odr, odr_database, 
1041                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1042                         rec_type_str);
1043                 }
1044                 if (xmlrec_buf)
1045                     xmlFree(xmlrec_buf);
1046             }
1047             else
1048             {
1049                 Z_External *ext =
1050                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
1051                 if (ext)
1052                 {
1053                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
1054                     npr->databaseName = odr_database;
1055                     npr->which = Z_NamePlusRecord_databaseRecord;
1056                     npr->u.databaseRecord = ext;
1057                 }
1058                 else
1059                 {
1060                     npr = zget_surrogateDiagRec(
1061                         odr, odr_database, 
1062                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
1063                         "ZOOM_record, type ext");
1064                 }
1065             }
1066             npl->records[i] = npr;
1067         }
1068         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
1069         records->which = Z_Records_DBOSD;
1070         records->u.databaseOrSurDiagnostics = npl;
1071     }
1072     return records;
1073 }
1074     
1075 struct cql_node *yf::Zoom::Impl::convert_cql_fields(struct cql_node *cn,
1076                                                     ODR odr)
1077 {
1078     struct cql_node *r = 0;
1079     if (!cn)
1080         return 0;
1081     switch (cn->which)
1082     {
1083     case CQL_NODE_ST:
1084         if (cn->u.st.index)
1085         {
1086             std::map<std::string,std::string>::const_iterator it;
1087             it = fieldmap.find(cn->u.st.index);
1088             if (it == fieldmap.end())
1089                 return cn;
1090             if (it->second.length())
1091                 cn->u.st.index = odr_strdup(odr, it->second.c_str());
1092             else
1093                 cn->u.st.index = 0;
1094         }
1095         break;
1096     case CQL_NODE_BOOL:
1097         r = convert_cql_fields(cn->u.boolean.left, odr);
1098         if (!r)
1099             r = convert_cql_fields(cn->u.boolean.right, odr);
1100         break;
1101     case CQL_NODE_SORT:
1102         r = convert_cql_fields(cn->u.sort.search, odr);
1103         break;
1104     }
1105     return r;
1106 }
1107
1108 void yf::Zoom::Frontend::handle_search(mp::Package &package)
1109 {
1110     Z_GDU *gdu = package.request().get();
1111     Z_APDU *apdu_req = gdu->u.z3950;
1112     Z_APDU *apdu_res = 0;
1113     mp::odr odr;
1114     Z_SearchRequest *sr = apdu_req->u.searchRequest;
1115     if (sr->num_databaseNames != 1)
1116     {
1117         apdu_res = odr.create_searchResponse(
1118             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
1119         package.response() = apdu_res;
1120         return;
1121     }
1122
1123     int error = 0;
1124     char *addinfo = 0;
1125     std::string db(sr->databaseNames[0]);
1126     BackendPtr b = get_backend_from_databases(db, &error, &addinfo, odr);
1127     if (error)
1128     {
1129         apdu_res = 
1130             odr.create_searchResponse(apdu_req, error, addinfo);
1131         package.response() = apdu_res;
1132         return;
1133     }
1134
1135     b->set_option("setname", "default");
1136
1137     Odr_int hits = 0;
1138     Z_Query *query = sr->query;
1139     WRBUF ccl_wrbuf = 0;
1140     WRBUF pqf_wrbuf = 0;
1141
1142     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
1143     {
1144         // RPN
1145         pqf_wrbuf = wrbuf_alloc();
1146         yaz_rpnquery_to_wrbuf(pqf_wrbuf, query->u.type_1);
1147     }
1148     else if (query->which == Z_Query_type_2)
1149     {
1150         // CCL
1151         ccl_wrbuf = wrbuf_alloc();
1152         wrbuf_write(ccl_wrbuf, (const char *) query->u.type_2->buf,
1153                     query->u.type_2->len);
1154     }
1155     else if (query->which == Z_Query_type_104 &&
1156              query->u.type_104->which == Z_External_CQL)
1157     {
1158         // CQL
1159         const char *cql = query->u.type_104->u.cql;
1160         CQL_parser cp = cql_parser_create();
1161         int r = cql_parser_string(cp, cql);
1162         if (r)
1163         {
1164             cql_parser_destroy(cp);
1165             apdu_res = 
1166                 odr.create_searchResponse(apdu_req, 
1167                                           YAZ_BIB1_MALFORMED_QUERY,
1168                                           "CQL syntax error");
1169             package.response() = apdu_res;
1170             return;
1171         }
1172         struct cql_node *cn = cql_parser_result(cp);
1173         struct cql_node *cn_error = m_p->convert_cql_fields(cn, odr);
1174         if (cn_error)
1175         {
1176             // hopefully we are getting a ptr to a index+relation+term node
1177             addinfo = 0;
1178             if (cn_error->which == CQL_NODE_ST)
1179                 addinfo = cn_error->u.st.index;
1180
1181             apdu_res = 
1182                 odr.create_searchResponse(apdu_req, 
1183                                           YAZ_BIB1_UNSUPP_USE_ATTRIBUTE,
1184                                           addinfo);
1185             package.response() = apdu_res;
1186             return;
1187         }
1188         char ccl_buf[1024];
1189
1190         r = cql_to_ccl_buf(cn, ccl_buf, sizeof(ccl_buf));
1191         if (r == 0)
1192         {
1193             ccl_wrbuf = wrbuf_alloc();
1194             wrbuf_puts(ccl_wrbuf, ccl_buf);
1195         }
1196         cql_parser_destroy(cp);
1197         if (r)
1198         {
1199             apdu_res = 
1200                 odr.create_searchResponse(apdu_req, 
1201                                           YAZ_BIB1_MALFORMED_QUERY,
1202                                           "CQL to CCL conversion error");
1203             package.response() = apdu_res;
1204             return;
1205         }
1206     }
1207     else
1208     {
1209         apdu_res = 
1210             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
1211         package.response() = apdu_res;
1212         return;
1213     }
1214
1215     if (ccl_wrbuf)
1216     {
1217         // CCL to PQF
1218         assert(pqf_wrbuf == 0);
1219         int cerror, cpos;
1220         struct ccl_rpn_node *cn;
1221         yaz_log(YLOG_LOG, "CCL: %s", wrbuf_cstr(ccl_wrbuf));
1222         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(ccl_wrbuf),
1223                           &cerror, &cpos);
1224         wrbuf_destroy(ccl_wrbuf);
1225         if (!cn)
1226         {
1227             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
1228             int z3950_diag = YAZ_BIB1_MALFORMED_QUERY;
1229
1230             switch (cerror)
1231             {
1232             case CCL_ERR_UNKNOWN_QUAL:
1233                 z3950_diag = YAZ_BIB1_UNSUPP_USE_ATTRIBUTE;
1234                 break;
1235             case CCL_ERR_TRUNC_NOT_LEFT: 
1236             case CCL_ERR_TRUNC_NOT_RIGHT:
1237             case CCL_ERR_TRUNC_NOT_BOTH:
1238                 z3950_diag = YAZ_BIB1_UNSUPP_TRUNCATION_ATTRIBUTE;
1239                 break;
1240             }
1241             apdu_res = 
1242                 odr.create_searchResponse(apdu_req, z3950_diag, addinfo);
1243             package.response() = apdu_res;
1244             return;
1245         }
1246         pqf_wrbuf = wrbuf_alloc();
1247         ccl_pquery(pqf_wrbuf, cn);
1248         ccl_rpn_delete(cn);
1249     }
1250     
1251     assert(pqf_wrbuf);
1252     if (b->get_option("sru"))
1253     {
1254         int status = 0;
1255         Z_RPNQuery *zquery;
1256         zquery = p_query_rpn(odr, wrbuf_cstr(pqf_wrbuf));
1257         WRBUF wrb = wrbuf_alloc();
1258             
1259         if (!strcmp(b->get_option("sru"), "solr"))
1260         {
1261             solr_transform_t cqlt = solr_transform_create();
1262             
1263             status = solr_transform_rpn2solr_wrbuf(cqlt, wrb, zquery);
1264             
1265             solr_transform_close(cqlt);
1266         }
1267         else
1268         {
1269             cql_transform_t cqlt = cql_transform_create();
1270             
1271             status = cql_transform_rpn2cql_wrbuf(cqlt, wrb, zquery);
1272             
1273             cql_transform_close(cqlt);
1274         }
1275         if (status == 0)
1276         {
1277             yaz_log(YLOG_LOG, "search CQL: %s", wrbuf_cstr(wrb));
1278             b->search_cql(wrbuf_cstr(wrb), &hits, &error, &addinfo, odr);
1279         }
1280         
1281         wrbuf_destroy(wrb);
1282         wrbuf_destroy(pqf_wrbuf);
1283         if (status)
1284         {
1285             apdu_res = 
1286                 odr.create_searchResponse(apdu_req, YAZ_BIB1_MALFORMED_QUERY,
1287                                           "can not convert from RPN to CQL/SOLR");
1288             package.response() = apdu_res;
1289             return;
1290         }
1291     }
1292     else
1293     {
1294         yaz_log(YLOG_LOG, "search PQF: %s", wrbuf_cstr(pqf_wrbuf));
1295         b->search_pqf(wrbuf_cstr(pqf_wrbuf), &hits, &error, &addinfo, odr);
1296         wrbuf_destroy(pqf_wrbuf);
1297     }
1298     
1299     
1300     const char *element_set_name = 0;
1301     Odr_int number_to_present = 0;
1302     if (!error)
1303         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
1304     
1305     Odr_int number_of_records_returned = 0;
1306     Z_Records *records = get_records(
1307         0, number_to_present, &error, &addinfo,
1308         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
1309         element_set_name);
1310     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
1311     if (records)
1312     {
1313         apdu_res->u.searchResponse->records = records;
1314         apdu_res->u.searchResponse->numberOfRecordsReturned =
1315             odr_intdup(odr, number_of_records_returned);
1316     }
1317     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
1318     package.response() = apdu_res;
1319 }
1320
1321 void yf::Zoom::Frontend::handle_present(mp::Package &package)
1322 {
1323     Z_GDU *gdu = package.request().get();
1324     Z_APDU *apdu_req = gdu->u.z3950;
1325     Z_APDU *apdu_res = 0;
1326     Z_PresentRequest *pr = apdu_req->u.presentRequest;
1327
1328     mp::odr odr;
1329     if (!m_backend)
1330     {
1331         package.response() = odr.create_presentResponse(
1332             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
1333         return;
1334     }
1335     const char *element_set_name = 0;
1336     Z_RecordComposition *comp = pr->recordComposition;
1337     if (comp && comp->which != Z_RecordComp_simple)
1338     {
1339         package.response() = odr.create_presentResponse(
1340             apdu_req, 
1341             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
1342         return;
1343     }
1344     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
1345         element_set_name = comp->u.simple->u.generic;
1346     Odr_int number_of_records_returned = 0;
1347     int error = 0;
1348     char *addinfo = 0;
1349     Z_Records *records = get_records(
1350         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
1351         &error, &addinfo, &number_of_records_returned, odr, m_backend,
1352         pr->preferredRecordSyntax, element_set_name);
1353
1354     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
1355     if (records)
1356     {
1357         apdu_res->u.presentResponse->records = records;
1358         apdu_res->u.presentResponse->numberOfRecordsReturned =
1359             odr_intdup(odr, number_of_records_returned);
1360     }
1361     package.response() = apdu_res;
1362 }
1363
1364 void yf::Zoom::Frontend::handle_package(mp::Package &package)
1365 {
1366     Z_GDU *gdu = package.request().get();
1367     if (!gdu)
1368         ;
1369     else if (gdu->which == Z_GDU_Z3950)
1370     {
1371         Z_APDU *apdu_req = gdu->u.z3950;
1372         if (apdu_req->which == Z_APDU_initRequest)
1373         {
1374             mp::odr odr;
1375             package.response() = odr.create_close(
1376                 apdu_req,
1377                 Z_Close_protocolError,
1378                 "double init");
1379         }
1380         else if (apdu_req->which == Z_APDU_searchRequest)
1381         {
1382             handle_search(package);
1383         }
1384         else if (apdu_req->which == Z_APDU_presentRequest)
1385         {
1386             handle_present(package);
1387         }
1388         else
1389         {
1390             mp::odr odr;
1391             package.response() = odr.create_close(
1392                 apdu_req,
1393                 Z_Close_protocolError,
1394                 "zoom filter cannot handle this APDU");
1395             package.session().close();
1396         }
1397     }
1398     else
1399     {
1400         package.session().close();
1401     }
1402 }
1403
1404 void yf::Zoom::Impl::process(mp::Package &package)
1405 {
1406     FrontendPtr f = get_frontend(package);
1407     Z_GDU *gdu = package.request().get();
1408
1409     if (f->m_is_virtual)
1410     {
1411         f->handle_package(package);
1412     }
1413     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
1414              Z_APDU_initRequest)
1415     {
1416         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
1417         f->m_init_gdu = gdu;
1418         
1419         mp::odr odr;
1420         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
1421         Z_InitResponse *resp = apdu->u.initResponse;
1422         
1423         int i;
1424         static const int masks[] = {
1425             Z_Options_search,
1426             Z_Options_present,
1427             -1 
1428         };
1429         for (i = 0; masks[i] != -1; i++)
1430             if (ODR_MASK_GET(req->options, masks[i]))
1431                 ODR_MASK_SET(resp->options, masks[i]);
1432         
1433         static const int versions[] = {
1434             Z_ProtocolVersion_1,
1435             Z_ProtocolVersion_2,
1436             Z_ProtocolVersion_3,
1437             -1
1438         };
1439         for (i = 0; versions[i] != -1; i++)
1440             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
1441                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
1442             else
1443                 break;
1444         
1445         *resp->preferredMessageSize = *req->preferredMessageSize;
1446         *resp->maximumRecordSize = *req->maximumRecordSize;
1447         
1448         package.response() = apdu;
1449         f->m_is_virtual = true;
1450     }
1451     else
1452         package.move();
1453
1454     release_frontend(package);
1455 }
1456
1457
1458 static mp::filter::Base* filter_creator()
1459 {
1460     return new mp::filter::Zoom;
1461 }
1462
1463 extern "C" {
1464     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
1465         0,
1466         "zoom",
1467         filter_creator
1468     };
1469 }
1470
1471
1472 /*
1473  * Local variables:
1474  * c-basic-offset: 4
1475  * c-file-style: "Stroustrup"
1476  * indent-tabs-mode: nil
1477  * End:
1478  * vim: shiftwidth=4 tabstop=8 expandtab
1479  */
1480