Make 3 classes: noncopyable
[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 <metaproxy/package.hpp>
23 #include <metaproxy/util.hpp>
24 #include "torus.hpp"
25
26 #include <libxslt/xsltutils.h>
27 #include <libxslt/transform.h>
28
29 #include <boost/thread/mutex.hpp>
30 #include <boost/thread/condition.hpp>
31 #include <yaz/ccl.h>
32 #include <yaz/oid_db.h>
33 #include <yaz/diagbib1.h>
34 #include <yaz/log.h>
35 #include <yaz/zgdu.h>
36 #include <yaz/querytowrbuf.h>
37
38 namespace mp = metaproxy_1;
39 namespace yf = mp::filter;
40
41 namespace metaproxy_1 {
42     namespace filter {
43         struct Zoom::Searchable : boost::noncopyable {
44             std::string database;
45             std::string target;
46             std::string query_encoding;
47             std::string sru;
48             std::string request_syntax;
49             std::string element_set;
50             std::string record_encoding;
51             std::string transform_xsl_fname;
52             bool use_turbomarc;
53             bool piggyback;
54             CCL_bibset ccl_bibset;
55             Searchable();
56             ~Searchable();
57         };
58         class Zoom::Backend : boost::noncopyable {
59             friend class Impl;
60             friend class Frontend;
61             std::string zurl;
62             ZOOM_connection m_connection;
63             ZOOM_resultset m_resultset;
64             std::string m_frontend_database;
65             SearchablePtr sptr;
66             xsltStylesheetPtr xsp;
67         public:
68             Backend(SearchablePtr sptr);
69             ~Backend();
70             void connect(std::string zurl, int *error, const char **addinfo);
71             void search_pqf(const char *pqf, Odr_int *hits,
72                             int *error, const char **addinfo);
73             void present(Odr_int start, Odr_int number, ZOOM_record *recs,
74                          int *error, const char **addinfo);
75             void set_option(const char *name, const char *value);
76             int get_error(const char **addinfo);
77         };
78         class Zoom::Frontend : boost::noncopyable {
79             friend class Impl;
80             Impl *m_p;
81             bool m_is_virtual;
82             bool m_in_use;
83             yazpp_1::GDU m_init_gdu;
84             BackendPtr m_backend;
85             void handle_package(mp::Package &package);
86             void handle_search(mp::Package &package);
87             void handle_present(mp::Package &package);
88             BackendPtr get_backend_from_databases(std::string &database,
89                                                   int *error,
90                                                   const char **addinfo);
91             Z_Records *get_records(Odr_int start,
92                                    Odr_int number_to_present,
93                                    int *error,
94                                    const char **addinfo,
95                                    Odr_int *number_of_records_returned,
96                                    ODR odr, BackendPtr b,
97                                    Odr_oid *preferredRecordSyntax,
98                                    const char *element_set_name);
99         public:
100             Frontend(Impl *impl);
101             ~Frontend();
102         };
103         class Zoom::Impl {
104             friend class Frontend;
105         public:
106             Impl();
107             ~Impl();
108             void process(metaproxy_1::Package & package);
109             void configure(const xmlNode * ptr, bool test_only);
110         private:
111             FrontendPtr get_frontend(mp::Package &package);
112             void release_frontend(mp::Package &package);
113             void parse_torus(const xmlNode *ptr);
114
115             std::list<Zoom::SearchablePtr>m_searchables;
116
117             std::map<mp::Session, FrontendPtr> m_clients;            
118             boost::mutex m_mutex;
119             boost::condition m_cond_session_ready;
120             mp::Torus torus;
121         };
122     }
123 }
124
125 // define Pimpl wrapper forwarding to Impl
126  
127 yf::Zoom::Zoom() : m_p(new Impl)
128 {
129 }
130
131 yf::Zoom::~Zoom()
132 {  // must have a destructor because of boost::scoped_ptr
133 }
134
135 void yf::Zoom::configure(const xmlNode *xmlnode, bool test_only)
136 {
137     m_p->configure(xmlnode, test_only);
138 }
139
140 void yf::Zoom::process(mp::Package &package) const
141 {
142     m_p->process(package);
143 }
144
145
146 // define Implementation stuff
147
148 yf::Zoom::Backend::Backend(SearchablePtr ptr) : sptr(ptr)
149 {
150     m_connection = ZOOM_connection_create(0);
151     m_resultset = 0;
152     xsp = 0;
153 }
154
155 yf::Zoom::Backend::~Backend()
156 {
157     if (xsp)
158         xsltFreeStylesheet(xsp);
159     ZOOM_connection_destroy(m_connection);
160     ZOOM_resultset_destroy(m_resultset);
161 }
162
163 void yf::Zoom::Backend::connect(std::string zurl,
164                                 int *error, const char **addinfo)
165 {
166     ZOOM_connection_connect(m_connection, zurl.c_str(), 0);
167     *error = ZOOM_connection_error(m_connection, 0, addinfo);
168 }
169
170 void yf::Zoom::Backend::search_pqf(const char *pqf, Odr_int *hits,
171                                    int *error, const char **addinfo)
172 {
173     m_resultset = ZOOM_connection_search_pqf(m_connection, pqf);
174     *error = ZOOM_connection_error(m_connection, 0, addinfo);
175     if (*error == 0)
176         *hits = ZOOM_resultset_size(m_resultset);
177     else
178         *hits = 0;
179 }
180
181 void yf::Zoom::Backend::present(Odr_int start, Odr_int number,
182                                 ZOOM_record *recs,
183                                 int *error, const char **addinfo)
184 {
185     ZOOM_resultset_records(m_resultset, recs, start, number);
186     *error = ZOOM_connection_error(m_connection, 0, addinfo);
187 }
188
189 void yf::Zoom::Backend::set_option(const char *name, const char *value)
190 {
191     ZOOM_connection_option_set(m_connection, name, value);
192     if (m_resultset)
193         ZOOM_resultset_option_set(m_resultset, name, value);
194 }
195
196 int yf::Zoom::Backend::get_error(const char **addinfo)
197 {
198     return ZOOM_connection_error(m_connection, 0, addinfo);
199 }
200
201 yf::Zoom::Searchable::Searchable()
202 {
203     piggyback = true;
204     use_turbomarc = false;
205     ccl_bibset = ccl_qual_mk();
206 }
207
208 yf::Zoom::Searchable::~Searchable()
209 {
210     ccl_qual_rm(&ccl_bibset);
211 }
212
213 yf::Zoom::Frontend::Frontend(Impl *impl) : 
214     m_p(impl), m_is_virtual(false), m_in_use(true)
215 {
216 }
217
218 yf::Zoom::Frontend::~Frontend()
219 {
220 }
221
222 yf::Zoom::FrontendPtr yf::Zoom::Impl::get_frontend(mp::Package &package)
223 {
224     boost::mutex::scoped_lock lock(m_mutex);
225
226     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
227     
228     while(true)
229     {
230         it = m_clients.find(package.session());
231         if (it == m_clients.end())
232             break;
233         
234         if (!it->second->m_in_use)
235         {
236             it->second->m_in_use = true;
237             return it->second;
238         }
239         m_cond_session_ready.wait(lock);
240     }
241     FrontendPtr f(new Frontend(this));
242     m_clients[package.session()] = f;
243     f->m_in_use = true;
244     return f;
245 }
246
247 void yf::Zoom::Impl::release_frontend(mp::Package &package)
248 {
249     boost::mutex::scoped_lock lock(m_mutex);
250     std::map<mp::Session,yf::Zoom::FrontendPtr>::iterator it;
251     
252     it = m_clients.find(package.session());
253     if (it != m_clients.end())
254     {
255         if (package.session().is_closed())
256         {
257             m_clients.erase(it);
258         }
259         else
260         {
261             it->second->m_in_use = false;
262         }
263         m_cond_session_ready.notify_all();
264     }
265 }
266
267 yf::Zoom::Impl::Impl()
268 {
269 }
270
271 yf::Zoom::Impl::~Impl()
272
273 }
274
275 void yf::Zoom::Impl::parse_torus(const xmlNode *ptr1)
276 {
277     if (!ptr1)
278         return ;
279     for (ptr1 = ptr1->children; ptr1; ptr1 = ptr1->next)
280     {
281         if (ptr1->type != XML_ELEMENT_NODE)
282             continue;
283         if (!strcmp((const char *) ptr1->name, "record"))
284         {
285             const xmlNode *ptr2 = ptr1;
286             for (ptr2 = ptr2->children; ptr2; ptr2 = ptr2->next)
287             {
288                 if (ptr2->type != XML_ELEMENT_NODE)
289                     continue;
290                 if (!strcmp((const char *) ptr2->name, "layer"))
291                 {
292                     Zoom::SearchablePtr s(new Searchable);
293
294                     const xmlNode *ptr3 = ptr2;
295                     for (ptr3 = ptr3->children; ptr3; ptr3 = ptr3->next)
296                     {
297                         if (ptr3->type != XML_ELEMENT_NODE)
298                             continue;
299                         if (!strcmp((const char *) ptr3->name, "id"))
300                         {
301                             s->database = mp::xml::get_text(ptr3);
302                         }
303                         else if (!strcmp((const char *) ptr3->name, "zurl"))
304                         {
305                             s->target = mp::xml::get_text(ptr3);
306                         }
307                         else if (!strcmp((const char *) ptr3->name, "sru"))
308                         {
309                             s->sru = mp::xml::get_text(ptr3);
310                         }
311                         else if (!strcmp((const char *) ptr3->name,
312                                          "queryEncoding"))
313                         {
314                             s->query_encoding = mp::xml::get_text(ptr3);
315                         }
316                         else if (!strcmp((const char *) ptr3->name,
317                                          "piggyback"))
318                         {
319                             s->piggyback = mp::xml::get_bool(ptr3, true);
320                         }
321                         else if (!strcmp((const char *) ptr3->name,
322                                          "requestSyntax"))
323                         {
324                             s->request_syntax = mp::xml::get_text(ptr3);
325                         }
326                         else if (!strcmp((const char *) ptr3->name,
327                                          "elementSet"))
328                         {
329                             s->element_set = mp::xml::get_text(ptr3);
330                         }
331                         else if (!strcmp((const char *) ptr3->name,
332                                          "recordEncoding"))
333                         {
334                             s->record_encoding = mp::xml::get_text(ptr3);
335                         }
336                         else if (!strcmp((const char *) ptr3->name,
337                                          "transform"))
338                         {
339                             s->transform_xsl_fname = mp::xml::get_text(ptr3);
340                         }
341                         else if (!strcmp((const char *) ptr3->name,
342                                          "useTurboMarc"))
343                         {
344                             s->use_turbomarc = mp::xml::get_bool(ptr3, false);
345                         }
346                         else if (!strncmp((const char *) ptr3->name,
347                                           "cclmap_", 7))
348                         {
349                             std::string value = mp::xml::get_text(ptr3);
350                             ccl_qual_fitem(s->ccl_bibset, value.c_str(),
351                                            (const char *) ptr3->name + 7);
352                         }
353                     }
354                     if (s->database.length() && s->target.length())
355                     {
356                         yaz_log(YLOG_LOG, "add db=%s target=%s turbomarc=%s", 
357                                 s->database.c_str(), s->target.c_str(),
358                                 s->use_turbomarc ? "1" : "0");
359                         m_searchables.push_back(s);
360                     }
361                 }
362             }
363         }
364     }
365 }
366
367 void yf::Zoom::Impl::configure(const xmlNode *ptr, bool test_only)
368 {
369     for (ptr = ptr->children; ptr; ptr = ptr->next)
370     {
371         if (ptr->type != XML_ELEMENT_NODE)
372             continue;
373         if (!strcmp((const char *) ptr->name, "records"))
374         {
375             parse_torus(ptr);
376         }
377         else if (!strcmp((const char *) ptr->name, "torus"))
378         {
379             std::string url;
380             const struct _xmlAttr *attr;
381             for (attr = ptr->properties; attr; attr = attr->next)
382             {
383                 if (!strcmp((const char *) attr->name, "url"))
384                     url = mp::xml::get_text(attr->children);
385                 else
386                     throw mp::filter::FilterException(
387                         "Bad attribute " + std::string((const char *)
388                                                        attr->name));
389             }
390             torus.read_searchables(url);
391             xmlDoc *doc = torus.get_doc();
392             if (doc)
393             {
394                 xmlNode *ptr = xmlDocGetRootElement(doc);
395                 parse_torus(ptr);
396             }
397         }
398         else
399         {
400             throw mp::filter::FilterException
401                 ("Bad element " 
402                  + std::string((const char *) ptr->name)
403                  + " in zoom filter");
404         }
405     }
406 }
407
408 yf::Zoom::BackendPtr yf::Zoom::Frontend::get_backend_from_databases(
409     std::string &database, int *error, const char **addinfo)
410 {
411     std::list<BackendPtr>::const_iterator map_it;
412     if (m_backend && m_backend->m_frontend_database == database)
413         return m_backend;
414
415     std::list<Zoom::SearchablePtr>::iterator map_s =
416         m_p->m_searchables.begin();
417
418     std::string c_db = mp::util::database_name_normalize(database);
419
420     while (map_s != m_p->m_searchables.end())
421     {
422         if (c_db.compare((*map_s)->database) == 0)
423             break;
424         map_s++;
425     }
426     if (map_s == m_p->m_searchables.end())
427     {
428         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
429         *addinfo = database.c_str();
430         BackendPtr b;
431         return b;
432     }
433
434     xsltStylesheetPtr xsp = 0;
435     if ((*map_s)->transform_xsl_fname.length())
436     {
437         xmlDoc *xsp_doc = xmlParseFile((*map_s)->transform_xsl_fname.c_str());
438         if (!xsp_doc)
439         {
440             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
441             *addinfo = "xmlParseFile failed";
442             BackendPtr b;
443             return b;
444         }
445         xsp = xsltParseStylesheetDoc(xsp_doc);
446         if (!xsp)
447         {
448             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
449             *addinfo = "xsltParseStylesheetDoc failed";
450             BackendPtr b;
451             xmlFreeDoc(xsp_doc);
452             return b;
453         }
454     }
455
456     SearchablePtr sptr = *map_s;
457
458     m_backend.reset();
459
460     BackendPtr b(new Backend(sptr));
461
462     b->xsp = xsp;
463     b->m_frontend_database = database;
464
465     if (sptr->query_encoding.length())
466         b->set_option("rpnCharset", sptr->query_encoding.c_str());
467
468     std::string url;
469     if (sptr->sru.length())
470     {
471         url = "http://" + sptr->target;
472         b->set_option("sru", sptr->sru.c_str());
473     }
474     else
475         url = sptr->target;
476
477     b->connect(url, error, addinfo);
478     if (*error == 0)
479     {
480         m_backend = b;
481     }
482     return b;
483 }
484
485 Z_Records *yf::Zoom::Frontend::get_records(Odr_int start,
486                                            Odr_int number_to_present,
487                                            int *error,
488                                            const char **addinfo,
489                                            Odr_int *number_of_records_returned,
490                                            ODR odr,
491                                            BackendPtr b,
492                                            Odr_oid *preferredRecordSyntax,
493                                            const char *element_set_name)
494 {
495     *number_of_records_returned = 0;
496     Z_Records *records = 0;
497     bool enable_pz2_transform = false;
498
499     if (start < 0 || number_to_present <= 0)
500         return records;
501     
502     if (number_to_present > 10000)
503         number_to_present = 10000;
504     
505     ZOOM_record *recs = (ZOOM_record *)
506         odr_malloc(odr, number_to_present * sizeof(*recs));
507
508     char oid_name_str[OID_STR_MAX];
509     const char *syntax_name = 0;
510
511     if (preferredRecordSyntax)
512     {
513         if (!oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
514             && !strcmp(element_set_name, "pz2"))
515         {
516             if (b->sptr->request_syntax.length())
517             {
518                 syntax_name = b->sptr->request_syntax.c_str();
519                 enable_pz2_transform = true;
520             }
521         }
522         else
523         {
524             syntax_name =
525                 yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
526         }
527     }
528
529     b->set_option("preferredRecordSyntax", syntax_name);
530
531     if (enable_pz2_transform)
532     {
533         element_set_name = "F";
534         if (b->sptr->element_set.length())
535             element_set_name = b->sptr->element_set.c_str();
536     }
537
538     b->set_option("elementSetName", element_set_name);
539
540     b->present(start, number_to_present, recs, error, addinfo);
541
542     Odr_int i = 0;
543     if (!*error)
544     {
545         for (i = 0; i < number_to_present; i++)
546             if (!recs[i])
547                 break;
548     }
549     if (i > 0)
550     {  // only return records if no error and at least one record
551         char *odr_database = odr_strdup(odr,
552                                         b->m_frontend_database.c_str());
553         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
554             odr_malloc(odr, sizeof(*npl));
555         *number_of_records_returned = i;
556         npl->num_records = i;
557         npl->records = (Z_NamePlusRecord **)
558             odr_malloc(odr, i * sizeof(*npl->records));
559         for (i = 0; i < number_to_present; i++)
560         {
561             Z_NamePlusRecord *npr = 0;
562             const char *addinfo;
563             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
564                                               &addinfo, 0 /* diagset */);
565                 
566             if (sur_error)
567             {
568                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
569                                             addinfo);
570             }
571             else if (enable_pz2_transform)
572             {
573                 char rec_type_str[100];
574
575                 strcpy(rec_type_str, b->sptr->use_turbomarc ?
576                        "txml" : "xml");
577                 
578                 // prevent buffer overflow ...
579                 if (b->sptr->record_encoding.length() > 0 &&
580                     b->sptr->record_encoding.length() < 
581                     (sizeof(rec_type_str)-20))
582                 {
583                     strcat(rec_type_str, "; charset=");
584                     strcat(rec_type_str, b->sptr->record_encoding.c_str());
585                 }
586                 
587                 int rec_len;
588                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
589                                                       &rec_len);
590                 if (rec_buf && b->xsp)
591                 {
592                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
593                     if (rec_doc)
594                     { 
595                         xmlDoc *rec_res;
596                         rec_res = xsltApplyStylesheet(b->xsp, rec_doc, 0);
597
598                         if (rec_res)
599                             xsltSaveResultToString((xmlChar **) &rec_buf, &rec_len,
600                                                    rec_res, b->xsp);
601                     }
602                 }
603
604                 if (rec_buf)
605                 {
606                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
607                     npr->databaseName = odr_database;
608                     npr->which = Z_NamePlusRecord_databaseRecord;
609                     npr->u.databaseRecord =
610                         z_ext_record_xml(odr, rec_buf, rec_len);
611                 }
612                 else
613                 {
614                     npr = zget_surrogateDiagRec(
615                         odr, odr_database, 
616                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
617                         rec_type_str);
618                 }
619             }
620             else
621             {
622                 Z_External *ext =
623                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
624                 if (ext)
625                 {
626                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
627                     npr->databaseName = odr_database;
628                     npr->which = Z_NamePlusRecord_databaseRecord;
629                     npr->u.databaseRecord = ext;
630                 }
631                 else
632                 {
633                     npr = zget_surrogateDiagRec(
634                         odr, odr_database, 
635                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
636                         "ZOOM_record, type ext");
637                 }
638             }
639             npl->records[i] = npr;
640         }
641         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
642         records->which = Z_Records_DBOSD;
643         records->u.databaseOrSurDiagnostics = npl;
644     }
645     return records;
646 }
647     
648
649 void yf::Zoom::Frontend::handle_search(mp::Package &package)
650 {
651     Z_GDU *gdu = package.request().get();
652     Z_APDU *apdu_req = gdu->u.z3950;
653     Z_APDU *apdu_res = 0;
654     mp::odr odr;
655     Z_SearchRequest *sr = apdu_req->u.searchRequest;
656     if (sr->num_databaseNames != 1)
657     {
658         apdu_res = odr.create_searchResponse(
659             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
660         package.response() = apdu_res;
661         return;
662     }
663
664     int error = 0;
665     const char *addinfo = 0;
666     std::string db(sr->databaseNames[0]);
667     BackendPtr b = get_backend_from_databases(db, &error, &addinfo);
668     if (error)
669     {
670         apdu_res = 
671             odr.create_searchResponse(
672                 apdu_req, error, addinfo);
673         package.response() = apdu_res;
674         return;
675     }
676
677     b->set_option("setname", "default");
678
679     Odr_int hits = 0;
680     Z_Query *query = sr->query;
681     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
682     {
683         // RPN
684         WRBUF w = wrbuf_alloc();
685         yaz_rpnquery_to_wrbuf(w, query->u.type_1);
686
687         b->search_pqf(wrbuf_cstr(w), &hits, &error, &addinfo);
688
689         wrbuf_destroy(w);
690     }
691     else if (query->which == Z_Query_type_2)
692     {
693         // CCL
694         WRBUF w = wrbuf_alloc();
695         wrbuf_write(w, (const char *) query->u.type_2->buf,
696                     query->u.type_2->len);
697         int cerror, cpos;
698         struct ccl_rpn_node *cn;
699         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(w), &cerror, &cpos);
700         wrbuf_destroy(w);
701
702         if (!cn)
703         {
704             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
705
706             apdu_res = 
707                 odr.create_searchResponse(apdu_req, 
708                                           YAZ_BIB1_MALFORMED_QUERY,
709                                           addinfo);
710             package.response() = apdu_res;
711             return;
712         }
713         w = wrbuf_alloc();
714         ccl_pquery(w, cn);
715         
716         b->search_pqf(wrbuf_cstr(w), &hits, &error, &addinfo);
717         
718         ccl_rpn_delete(cn);
719         wrbuf_destroy(w);
720     }
721     else
722     {
723         apdu_res = 
724             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
725         package.response() = apdu_res;
726         return;
727     }
728     
729     const char *element_set_name = 0;
730     Odr_int number_to_present = 0;
731     if (!error)
732         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
733     
734     Odr_int number_of_records_returned = 0;
735     Z_Records *records = get_records(
736         0, number_to_present, &error, &addinfo,
737         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
738         element_set_name);
739     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
740     if (records)
741     {
742         apdu_res->u.searchResponse->records = records;
743         apdu_res->u.searchResponse->numberOfRecordsReturned =
744             odr_intdup(odr, number_of_records_returned);
745     }
746     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
747     package.response() = apdu_res;
748 }
749
750 void yf::Zoom::Frontend::handle_present(mp::Package &package)
751 {
752     Z_GDU *gdu = package.request().get();
753     Z_APDU *apdu_req = gdu->u.z3950;
754     Z_APDU *apdu_res = 0;
755     Z_PresentRequest *pr = apdu_req->u.presentRequest;
756
757     mp::odr odr;
758     if (!m_backend)
759     {
760         package.response() = odr.create_presentResponse(
761             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
762         return;
763     }
764     const char *element_set_name = 0;
765     Z_RecordComposition *comp = pr->recordComposition;
766     if (comp && comp->which != Z_RecordComp_simple)
767     {
768         package.response() = odr.create_presentResponse(
769             apdu_req, 
770             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
771         return;
772     }
773     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
774         element_set_name = comp->u.simple->u.generic;
775     Odr_int number_of_records_returned = 0;
776     int error = 0;
777     const char *addinfo = 0;
778     Z_Records *records = get_records(
779         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
780         &error, &addinfo, &number_of_records_returned, odr, m_backend,
781         pr->preferredRecordSyntax, element_set_name);
782
783     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
784     if (records)
785     {
786         apdu_res->u.presentResponse->records = records;
787         apdu_res->u.presentResponse->numberOfRecordsReturned =
788             odr_intdup(odr, number_of_records_returned);
789     }
790     package.response() = apdu_res;
791 }
792
793 void yf::Zoom::Frontend::handle_package(mp::Package &package)
794 {
795     Z_GDU *gdu = package.request().get();
796     if (!gdu)
797         ;
798     else if (gdu->which == Z_GDU_Z3950)
799     {
800         Z_APDU *apdu_req = gdu->u.z3950;
801         if (apdu_req->which == Z_APDU_initRequest)
802         {
803             mp::odr odr;
804             package.response() = odr.create_close(
805                 apdu_req,
806                 Z_Close_protocolError,
807                 "double init");
808         }
809         else if (apdu_req->which == Z_APDU_searchRequest)
810         {
811             handle_search(package);
812         }
813         else if (apdu_req->which == Z_APDU_presentRequest)
814         {
815             handle_present(package);
816         }
817         else
818         {
819             mp::odr odr;
820             package.response() = odr.create_close(
821                 apdu_req,
822                 Z_Close_protocolError,
823                 "zoom filter cannot handle this APDU");
824             package.session().close();
825         }
826     }
827     else
828     {
829         package.session().close();
830     }
831 }
832
833 void yf::Zoom::Impl::process(mp::Package &package)
834 {
835     FrontendPtr f = get_frontend(package);
836     Z_GDU *gdu = package.request().get();
837
838     if (f->m_is_virtual)
839     {
840         f->handle_package(package);
841     }
842     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
843              Z_APDU_initRequest)
844     {
845         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
846         f->m_init_gdu = gdu;
847         
848         mp::odr odr;
849         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
850         Z_InitResponse *resp = apdu->u.initResponse;
851         
852         int i;
853         static const int masks[] = {
854             Z_Options_search,
855             Z_Options_present,
856             -1 
857         };
858         for (i = 0; masks[i] != -1; i++)
859             if (ODR_MASK_GET(req->options, masks[i]))
860                 ODR_MASK_SET(resp->options, masks[i]);
861         
862         static const int versions[] = {
863             Z_ProtocolVersion_1,
864             Z_ProtocolVersion_2,
865             Z_ProtocolVersion_3,
866             -1
867         };
868         for (i = 0; versions[i] != -1; i++)
869             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
870                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
871             else
872                 break;
873         
874         *resp->preferredMessageSize = *req->preferredMessageSize;
875         *resp->maximumRecordSize = *req->maximumRecordSize;
876         
877         package.response() = apdu;
878         f->m_is_virtual = true;
879     }
880     else
881         package.move();
882
883     release_frontend(package);
884 }
885
886
887 static mp::filter::Base* filter_creator()
888 {
889     return new mp::filter::Zoom;
890 }
891
892 extern "C" {
893     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
894         0,
895         "zoom",
896         filter_creator
897     };
898 }
899
900
901 /*
902  * Local variables:
903  * c-basic-offset: 4
904  * c-file-style: "Stroustrup"
905  * indent-tabs-mode: nil
906  * End:
907  * vim: shiftwidth=4 tabstop=8 expandtab
908  */
909