zoom filter: honor cclmap_*-fields
[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 {
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 {
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 {
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                             yaz_log(YLOG_LOG, "seeing useTurboMarc");
345                             s->use_turbomarc = mp::xml::get_bool(ptr3, false);
346                             yaz_log(YLOG_LOG, "value=%s",
347                                     s->use_turbomarc ? "1" : "0");
348                                     
349                         }
350                         else if (!strncmp((const char *) ptr3->name,
351                                           "cclmap_", 7))
352                         {
353                             std::string value = mp::xml::get_text(ptr3);
354                             ccl_qual_fitem(s->ccl_bibset, value.c_str(),
355                                            (const char *) ptr3->name + 7);
356                         }
357                     }
358                     if (s->database.length() && s->target.length())
359                     {
360                         yaz_log(YLOG_LOG, "add db=%s target=%s turbomarc=%s", 
361                                 s->database.c_str(), s->target.c_str(),
362                                 s->use_turbomarc ? "1" : "0");
363                         m_searchables.push_back(s);
364                     }
365                 }
366             }
367         }
368     }
369 }
370
371
372 void yf::Zoom::Impl::configure(const xmlNode *ptr, bool test_only)
373 {
374     for (ptr = ptr->children; ptr; ptr = ptr->next)
375     {
376         if (ptr->type != XML_ELEMENT_NODE)
377             continue;
378         if (!strcmp((const char *) ptr->name, "records"))
379         {
380             parse_torus(ptr);
381         }
382         else if (!strcmp((const char *) ptr->name, "torus"))
383         {
384             std::string url;
385             const struct _xmlAttr *attr;
386             for (attr = ptr->properties; attr; attr = attr->next)
387             {
388                 if (!strcmp((const char *) attr->name, "url"))
389                     url = mp::xml::get_text(attr->children);
390                 else
391                     throw mp::filter::FilterException(
392                         "Bad attribute " + std::string((const char *)
393                                                        attr->name));
394             }
395             torus.read_searchables(url);
396             xmlDoc *doc = torus.get_doc();
397             if (doc)
398             {
399                 xmlNode *ptr = xmlDocGetRootElement(doc);
400                 parse_torus(ptr);
401             }
402         }
403         else
404         {
405             throw mp::filter::FilterException
406                 ("Bad element " 
407                  + std::string((const char *) ptr->name)
408                  + " in zoom filter");
409         }
410     }
411 }
412
413 yf::Zoom::BackendPtr yf::Zoom::Frontend::get_backend_from_databases(
414     std::string &database, int *error, const char **addinfo)
415 {
416     std::list<BackendPtr>::const_iterator map_it;
417     if (m_backend && m_backend->m_frontend_database == database)
418         return m_backend;
419
420     std::list<Zoom::SearchablePtr>::iterator map_s =
421         m_p->m_searchables.begin();
422
423     std::string c_db = mp::util::database_name_normalize(database);
424
425     while (map_s != m_p->m_searchables.end())
426     {
427         if (c_db.compare((*map_s)->database) == 0)
428             break;
429         map_s++;
430     }
431     if (map_s == m_p->m_searchables.end())
432     {
433         *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
434         *addinfo = database.c_str();
435         BackendPtr b;
436         return b;
437     }
438
439     xsltStylesheetPtr xsp = 0;
440     if ((*map_s)->transform_xsl_fname.length())
441     {
442         xmlDoc *xsp_doc = xmlParseFile((*map_s)->transform_xsl_fname.c_str());
443         if (!xsp_doc)
444         {
445             *error = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
446             *addinfo = "xmlParseFile failed";
447             BackendPtr b;
448             return b;
449         }
450         xsp = xsltParseStylesheetDoc(xsp_doc);
451         if (!xsp)
452         {
453             *error = YAZ_BIB1_DATABASE_DOES_NOT_EXIST;
454             *addinfo = "xsltParseStylesheetDoc failed";
455             BackendPtr b;
456             xmlFreeDoc(xsp_doc);
457             return b;
458         }
459     }
460
461     SearchablePtr sptr = *map_s;
462
463     m_backend.reset();
464
465     BackendPtr b(new Backend(sptr));
466
467     b->xsp = xsp;
468     b->m_frontend_database = database;
469
470     if (sptr->query_encoding.length())
471         b->set_option("rpnCharset", sptr->query_encoding.c_str());
472
473     std::string url;
474     if (sptr->sru.length())
475     {
476         url = "http://" + sptr->target;
477         b->set_option("sru", sptr->sru.c_str());
478     }
479     else
480         url = sptr->target;
481
482     b->connect(url, error, addinfo);
483     if (*error == 0)
484     {
485         m_backend = b;
486     }
487     return b;
488 }
489
490 Z_Records *yf::Zoom::Frontend::get_records(Odr_int start,
491                                            Odr_int number_to_present,
492                                            int *error,
493                                            const char **addinfo,
494                                            Odr_int *number_of_records_returned,
495                                            ODR odr,
496                                            BackendPtr b,
497                                            Odr_oid *preferredRecordSyntax,
498                                            const char *element_set_name)
499 {
500     *number_of_records_returned = 0;
501     Z_Records *records = 0;
502     bool enable_pz2_transform = false;
503
504     if (start < 0 || number_to_present <= 0)
505         return records;
506     
507     if (number_to_present > 10000)
508         number_to_present = 10000;
509     
510     ZOOM_record *recs = (ZOOM_record *)
511         odr_malloc(odr, number_to_present * sizeof(*recs));
512
513     char oid_name_str[OID_STR_MAX];
514     const char *syntax_name = 0;
515
516     if (preferredRecordSyntax)
517     {
518         if (!oid_oidcmp(preferredRecordSyntax, yaz_oid_recsyn_xml)
519             && !strcmp(element_set_name, "pz2"))
520         {
521             if (b->sptr->request_syntax.length())
522             {
523                 syntax_name = b->sptr->request_syntax.c_str();
524                 enable_pz2_transform = true;
525             }
526         }
527         else
528         {
529             syntax_name =
530                 yaz_oid_to_string_buf(preferredRecordSyntax, 0, oid_name_str);
531         }
532     }
533
534     yaz_log(YLOG_LOG, "enable_pz2_transform %s", enable_pz2_transform ?
535             "enabled" : "disabled");
536
537     b->set_option("preferredRecordSyntax", syntax_name);
538
539     if (enable_pz2_transform)
540     {
541         element_set_name = "F";
542         if (b->sptr->element_set.length())
543             element_set_name = b->sptr->element_set.c_str();
544     }
545
546     b->set_option("elementSetName", element_set_name);
547
548     b->present(start, number_to_present, recs, error, addinfo);
549
550     Odr_int i = 0;
551     if (!*error)
552     {
553         for (i = 0; i < number_to_present; i++)
554             if (!recs[i])
555                 break;
556     }
557     if (i > 0)
558     {  // only return records if no error and at least one record
559         char *odr_database = odr_strdup(odr,
560                                         b->m_frontend_database.c_str());
561         Z_NamePlusRecordList *npl = (Z_NamePlusRecordList *)
562             odr_malloc(odr, sizeof(*npl));
563         *number_of_records_returned = i;
564         npl->num_records = i;
565         npl->records = (Z_NamePlusRecord **)
566             odr_malloc(odr, i * sizeof(*npl->records));
567         for (i = 0; i < number_to_present; i++)
568         {
569             Z_NamePlusRecord *npr = 0;
570             const char *addinfo;
571             int sur_error = ZOOM_record_error(recs[i], 0 /* msg */,
572                                               &addinfo, 0 /* diagset */);
573                 
574             if (sur_error)
575             {
576                 npr = zget_surrogateDiagRec(odr, odr_database, sur_error,
577                                             addinfo);
578             }
579             else if (enable_pz2_transform)
580             {
581                 char rec_type_str[100];
582
583                 strcpy(rec_type_str, b->sptr->use_turbomarc ?
584                        "txml" : "xml");
585                 
586                 // prevent buffer overflow ...
587                 if (b->sptr->record_encoding.length() > 0 &&
588                     b->sptr->record_encoding.length() < 
589                     (sizeof(rec_type_str)-20))
590                 {
591                     strcat(rec_type_str, "; charset=");
592                     strcat(rec_type_str, b->sptr->record_encoding.c_str());
593                 }
594                 
595                 int rec_len;
596                 const char *rec_buf = ZOOM_record_get(recs[i], rec_type_str,
597                                                       &rec_len);
598                 if (rec_buf && b->xsp)
599                 {
600                     xmlDoc *rec_doc = xmlParseMemory(rec_buf, rec_len);
601                     if (rec_doc)
602                     { 
603                         xmlDoc *rec_res;
604                         rec_res = xsltApplyStylesheet(b->xsp, rec_doc, 0);
605
606                         if (rec_res)
607                             xsltSaveResultToString((xmlChar **) &rec_buf, &rec_len,
608                                                    rec_res, b->xsp);
609                     }
610                 }
611
612                 if (rec_buf)
613                 {
614                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
615                     npr->databaseName = odr_database;
616                     npr->which = Z_NamePlusRecord_databaseRecord;
617                     npr->u.databaseRecord =
618                         z_ext_record_xml(odr, rec_buf, rec_len);
619                 }
620                 else
621                 {
622                     npr = zget_surrogateDiagRec(
623                         odr, odr_database, 
624                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
625                         rec_type_str);
626                 }
627             }
628             else
629             {
630                 Z_External *ext =
631                     (Z_External *) ZOOM_record_get(recs[i], "ext", 0);
632                 if (ext)
633                 {
634                     npr = (Z_NamePlusRecord *) odr_malloc(odr, sizeof(*npr));
635                     npr->databaseName = odr_database;
636                     npr->which = Z_NamePlusRecord_databaseRecord;
637                     npr->u.databaseRecord = ext;
638                 }
639                 else
640                 {
641                     npr = zget_surrogateDiagRec(
642                         odr, odr_database, 
643                         YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS,
644                         "ZOOM_record, type ext");
645                 }
646             }
647             npl->records[i] = npr;
648         }
649         records = (Z_Records*) odr_malloc(odr, sizeof(*records));
650         records->which = Z_Records_DBOSD;
651         records->u.databaseOrSurDiagnostics = npl;
652     }
653     return records;
654 }
655     
656
657 void yf::Zoom::Frontend::handle_search(mp::Package &package)
658 {
659     Z_GDU *gdu = package.request().get();
660     Z_APDU *apdu_req = gdu->u.z3950;
661     Z_APDU *apdu_res = 0;
662     mp::odr odr;
663     Z_SearchRequest *sr = apdu_req->u.searchRequest;
664     if (sr->num_databaseNames != 1)
665     {
666         apdu_res = odr.create_searchResponse(
667             apdu_req, YAZ_BIB1_TOO_MANY_DATABASES_SPECIFIED, 0);
668         package.response() = apdu_res;
669         return;
670     }
671
672     int error = 0;
673     const char *addinfo = 0;
674     std::string db(sr->databaseNames[0]);
675     BackendPtr b = get_backend_from_databases(db, &error, &addinfo);
676     if (error)
677     {
678         apdu_res = 
679             odr.create_searchResponse(
680                 apdu_req, error, addinfo);
681         package.response() = apdu_res;
682         return;
683     }
684
685     b->set_option("setname", "default");
686
687     Odr_int hits = 0;
688     Z_Query *query = sr->query;
689     if (query->which == Z_Query_type_1 || query->which == Z_Query_type_101)
690     {
691         // RPN
692         WRBUF w = wrbuf_alloc();
693         yaz_rpnquery_to_wrbuf(w, query->u.type_1);
694
695         b->search_pqf(wrbuf_cstr(w), &hits, &error, &addinfo);
696
697         wrbuf_destroy(w);
698     }
699     else if (query->which == Z_Query_type_2)
700     {
701         // CCL
702         WRBUF w = wrbuf_alloc();
703         wrbuf_write(w, (const char *) query->u.type_2->buf,
704                     query->u.type_2->len);
705         int cerror, cpos;
706         struct ccl_rpn_node *cn;
707         cn = ccl_find_str(b->sptr->ccl_bibset, wrbuf_cstr(w), &cerror, &cpos);
708         wrbuf_destroy(w);
709
710         if (!cn)
711         {
712             char *addinfo = odr_strdup(odr, ccl_err_msg(cerror));
713
714             apdu_res = 
715                 odr.create_searchResponse(apdu_req, 
716                                           YAZ_BIB1_MALFORMED_QUERY,
717                                           addinfo);
718             package.response() = apdu_res;
719             return;
720         }
721         w = wrbuf_alloc();
722         ccl_pquery(w, cn);
723         
724         b->search_pqf(wrbuf_cstr(w), &hits, &error, &addinfo);
725         
726         ccl_rpn_delete(cn);
727         wrbuf_destroy(w);
728     }
729     else
730     {
731         apdu_res = 
732             odr.create_searchResponse(apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
733         package.response() = apdu_res;
734         return;
735     }
736     
737     const char *element_set_name = 0;
738     Odr_int number_to_present = 0;
739     if (!error)
740         mp::util::piggyback_sr(sr, hits, number_to_present, &element_set_name);
741     
742     Odr_int number_of_records_returned = 0;
743     Z_Records *records = get_records(
744         0, number_to_present, &error, &addinfo,
745         &number_of_records_returned, odr, b, sr->preferredRecordSyntax,
746         element_set_name);
747     apdu_res = odr.create_searchResponse(apdu_req, error, addinfo);
748     if (records)
749     {
750         apdu_res->u.searchResponse->records = records;
751         apdu_res->u.searchResponse->numberOfRecordsReturned =
752             odr_intdup(odr, number_of_records_returned);
753     }
754     apdu_res->u.searchResponse->resultCount = odr_intdup(odr, hits);
755     package.response() = apdu_res;
756 }
757
758 void yf::Zoom::Frontend::handle_present(mp::Package &package)
759 {
760     Z_GDU *gdu = package.request().get();
761     Z_APDU *apdu_req = gdu->u.z3950;
762     Z_APDU *apdu_res = 0;
763     Z_PresentRequest *pr = apdu_req->u.presentRequest;
764
765     mp::odr odr;
766     if (!m_backend)
767     {
768         package.response() = odr.create_presentResponse(
769             apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST, 0);
770         return;
771     }
772     const char *element_set_name = 0;
773     Z_RecordComposition *comp = pr->recordComposition;
774     if (comp && comp->which != Z_RecordComp_simple)
775     {
776         package.response() = odr.create_presentResponse(
777             apdu_req, 
778             YAZ_BIB1_PRESENT_COMP_SPEC_PARAMETER_UNSUPP, 0);
779         return;
780     }
781     if (comp && comp->u.simple->which == Z_ElementSetNames_generic)
782         element_set_name = comp->u.simple->u.generic;
783     Odr_int number_of_records_returned = 0;
784     int error = 0;
785     const char *addinfo = 0;
786     Z_Records *records = get_records(
787         *pr->resultSetStartPoint - 1, *pr->numberOfRecordsRequested,
788         &error, &addinfo, &number_of_records_returned, odr, m_backend,
789         pr->preferredRecordSyntax, element_set_name);
790
791     apdu_res = odr.create_presentResponse(apdu_req, error, addinfo);
792     if (records)
793     {
794         apdu_res->u.presentResponse->records = records;
795         apdu_res->u.presentResponse->numberOfRecordsReturned =
796             odr_intdup(odr, number_of_records_returned);
797     }
798     package.response() = apdu_res;
799 }
800
801 void yf::Zoom::Frontend::handle_package(mp::Package &package)
802 {
803     Z_GDU *gdu = package.request().get();
804     if (!gdu)
805         ;
806     else if (gdu->which == Z_GDU_Z3950)
807     {
808         Z_APDU *apdu_req = gdu->u.z3950;
809         if (apdu_req->which == Z_APDU_initRequest)
810         {
811             mp::odr odr;
812             package.response() = odr.create_close(
813                 apdu_req,
814                 Z_Close_protocolError,
815                 "double init");
816         }
817         else if (apdu_req->which == Z_APDU_searchRequest)
818         {
819             handle_search(package);
820         }
821         else if (apdu_req->which == Z_APDU_presentRequest)
822         {
823             handle_present(package);
824         }
825         else
826         {
827             mp::odr odr;
828             package.response() = odr.create_close(
829                 apdu_req,
830                 Z_Close_protocolError,
831                 "zoom filter cannot handle this APDU");
832             package.session().close();
833         }
834     }
835     else
836     {
837         package.session().close();
838     }
839 }
840
841 void yf::Zoom::Impl::process(mp::Package &package)
842 {
843     FrontendPtr f = get_frontend(package);
844     Z_GDU *gdu = package.request().get();
845
846     if (f->m_is_virtual)
847     {
848         f->handle_package(package);
849     }
850     else if (gdu && gdu->which == Z_GDU_Z3950 && gdu->u.z3950->which ==
851              Z_APDU_initRequest)
852     {
853         Z_InitRequest *req = gdu->u.z3950->u.initRequest;
854         f->m_init_gdu = gdu;
855         
856         mp::odr odr;
857         Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950, 0, 0);
858         Z_InitResponse *resp = apdu->u.initResponse;
859         
860         int i;
861         static const int masks[] = {
862             Z_Options_search,
863             Z_Options_present,
864             -1 
865         };
866         for (i = 0; masks[i] != -1; i++)
867             if (ODR_MASK_GET(req->options, masks[i]))
868                 ODR_MASK_SET(resp->options, masks[i]);
869         
870         static const int versions[] = {
871             Z_ProtocolVersion_1,
872             Z_ProtocolVersion_2,
873             Z_ProtocolVersion_3,
874             -1
875         };
876         for (i = 0; versions[i] != -1; i++)
877             if (ODR_MASK_GET(req->protocolVersion, versions[i]))
878                 ODR_MASK_SET(resp->protocolVersion, versions[i]);
879             else
880                 break;
881         
882         *resp->preferredMessageSize = *req->preferredMessageSize;
883         *resp->maximumRecordSize = *req->maximumRecordSize;
884         
885         package.response() = apdu;
886         f->m_is_virtual = true;
887     }
888     else
889         package.move();
890
891     release_frontend(package);
892 }
893
894
895 static mp::filter::Base* filter_creator()
896 {
897     return new mp::filter::Zoom;
898 }
899
900 extern "C" {
901     struct metaproxy_1_filter_struct metaproxy_1_filter_zoom = {
902         0,
903         "zoom",
904         filter_creator
905     };
906 }
907
908
909 /*
910  * Local variables:
911  * c-basic-offset: 4
912  * c-file-style: "Stroustrup"
913  * indent-tabs-mode: nil
914  * End:
915  * vim: shiftwidth=4 tabstop=8 expandtab
916  */
917