z3950_client: fixup multiple NSD's too
[metaproxy-moved-to-github.git] / src / filter_z3950_client.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2012 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
21 #include "filter_z3950_client.hpp"
22 #include <metaproxy/package.hpp>
23 #include <metaproxy/util.hpp>
24
25 #include <map>
26 #include <stdexcept>
27 #include <list>
28 #include <iostream>
29
30 #include <boost/thread/mutex.hpp>
31 #include <boost/thread/condition.hpp>
32 #include <boost/thread/xtime.hpp>
33
34 #include <yaz/zgdu.h>
35 #include <yaz/log.h>
36 #include <yaz/otherinfo.h>
37 #include <yaz/diagbib1.h>
38
39 #include <yazpp/socket-manager.h>
40 #include <yazpp/pdu-assoc.h>
41 #include <yazpp/z-assoc.h>
42
43 namespace mp = metaproxy_1;
44 namespace yf = mp::filter;
45
46 namespace metaproxy_1 {
47     namespace filter {
48         class Z3950Client::Assoc : public yazpp_1::Z_Assoc{
49             friend class Rep;
50             Assoc(yazpp_1::SocketManager *socket_manager,
51                   yazpp_1::IPDU_Observable *PDU_Observable,
52                   std::string host, int timeout);
53             ~Assoc();
54             void connectNotify();
55             void failNotify();
56             void timeoutNotify();
57             void recv_GDU(Z_GDU *gdu, int len);
58             void fixup_nsd(ODR odr, Z_Records *records);
59             void fixup_nsd(ODR odr, Z_DefaultDiagFormat *nsd);
60             void fixup_init(ODR odr, Z_InitResponse *initrs);
61             yazpp_1::IPDU_Observer* sessionNotify(
62                 yazpp_1::IPDU_Observable *the_PDU_Observable,
63                 int fd);
64
65             yazpp_1::SocketManager *m_socket_manager;
66             yazpp_1::IPDU_Observable *m_PDU_Observable;
67             Package *m_package;
68             bool m_in_use;
69             bool m_waiting;
70             bool m_destroyed;
71             bool m_connected;
72             bool m_has_closed;
73             int m_queue_len;
74             int m_time_elapsed;
75             int m_time_max;
76             int m_time_connect_max;
77             std::string m_host;
78         };
79
80         class Z3950Client::Rep {
81         public:
82             // number of seconds to wait before we give up request
83             int m_timeout_sec;
84             int m_max_sockets;
85             bool m_force_close;
86             std::string m_default_target;
87             std::string m_force_target;
88             boost::mutex m_mutex;
89             boost::condition m_cond_session_ready;
90             std::map<mp::Session,Z3950Client::Assoc *> m_clients;
91             Z3950Client::Assoc *get_assoc(Package &package);
92             void send_and_receive(Package &package,
93                                   yf::Z3950Client::Assoc *c);
94             void release_assoc(Package &package);
95         };
96     }
97 }
98
99 using namespace mp;
100
101 yf::Z3950Client::Assoc::Assoc(yazpp_1::SocketManager *socket_manager,
102                               yazpp_1::IPDU_Observable *PDU_Observable,
103                               std::string host, int timeout_sec)
104     :  Z_Assoc(PDU_Observable),
105        m_socket_manager(socket_manager), m_PDU_Observable(PDU_Observable),
106        m_package(0), m_in_use(true), m_waiting(false),
107        m_destroyed(false), m_connected(false), m_has_closed(false),
108        m_queue_len(1),
109        m_time_elapsed(0), m_time_max(timeout_sec),  m_time_connect_max(10),
110        m_host(host)
111 {
112     // std::cout << "create assoc " << this << "\n";
113 }
114
115 yf::Z3950Client::Assoc::~Assoc()
116 {
117     // std::cout << "destroy assoc " << this << "\n";
118 }
119
120 void yf::Z3950Client::Assoc::connectNotify()
121 {
122     m_waiting = false;
123
124     m_connected = true;
125 }
126
127 void yf::Z3950Client::Assoc::failNotify()
128 {
129     m_waiting = false;
130
131     mp::odr odr;
132
133     if (m_package)
134     {
135         Z_GDU *gdu = m_package->request().get();
136         Z_APDU *apdu = 0;
137         if (gdu && gdu->which == Z_GDU_Z3950)
138             apdu = gdu->u.z3950;
139
140         m_package->response() = odr.create_close(apdu, Z_Close_peerAbort, 0);
141         m_package->session().close();
142     }
143 }
144
145 void yf::Z3950Client::Assoc::timeoutNotify()
146 {
147     m_time_elapsed++;
148     if ((m_connected && m_time_elapsed >= m_time_max)
149         || (!m_connected && m_time_elapsed >= m_time_connect_max))
150     {
151         m_waiting = false;
152
153         mp::odr odr;
154
155         if (m_package)
156         {
157             Z_GDU *gdu = m_package->request().get();
158             Z_APDU *apdu = 0;
159             if (gdu && gdu->which == Z_GDU_Z3950)
160                 apdu = gdu->u.z3950;
161
162             if (m_connected)
163                 m_package->response() =
164                     odr.create_close(apdu, Z_Close_lackOfActivity, 0);
165             else
166                 m_package->response() =
167                     odr.create_close(apdu, Z_Close_peerAbort, 0);
168
169             m_package->session().close();
170         }
171     }
172 }
173
174 void yf::Z3950Client::Assoc::fixup_nsd(ODR odr, Z_DefaultDiagFormat *nsd)
175 {
176     std::string addinfo;
177
178     // should really check for nsd->which.. But union has two members
179     // containing almost same data
180     const char *v2Addinfo = nsd->u.v2Addinfo;
181     //  Z_InternationalString *v3Addinfo;
182     if (v2Addinfo && *v2Addinfo)
183     {
184         addinfo.assign(nsd->u.v2Addinfo);
185         addinfo += " ";
186     }
187     addinfo += "(backend=" + m_host + ")";
188     nsd->u.v2Addinfo = odr_strdup(odr, addinfo.c_str());
189 }
190
191 void yf::Z3950Client::Assoc::fixup_nsd(ODR odr, Z_Records *records)
192 {
193     if (records && records->which == Z_Records_NSD)
194     {
195         fixup_nsd(odr, records->u.nonSurrogateDiagnostic);
196     }
197     if (records && records->which == Z_Records_multipleNSD)
198     {
199         Z_DiagRecs *drecs = records->u.multipleNonSurDiagnostics;
200         int i;
201         for (i = 0; i < drecs->num_diagRecs; i++)
202         {
203             Z_DiagRec *dr = drecs->diagRecs[i];
204
205             if (dr->which == Z_DiagRec_defaultFormat)
206                 fixup_nsd(odr, dr->u.defaultFormat);
207         }
208     }
209 }
210
211 void yf::Z3950Client::Assoc::fixup_init(ODR odr, Z_InitResponse *initrs)
212 {
213     Z_External *uif = initrs->userInformationField;
214
215     if (uif && uif->which == Z_External_userInfo1)
216     {
217         Z_OtherInformation *ui = uif->u.userInfo1;
218         int i;
219         for (i = 0; i < ui->num_elements; i++)
220         {
221             Z_OtherInformationUnit *unit = ui->list[i];
222             if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
223                 unit->information.externallyDefinedInfo &&
224                 unit->information.externallyDefinedInfo->which ==
225                 Z_External_diag1)
226             {
227                 Z_DiagnosticFormat *diag =
228                     unit->information.externallyDefinedInfo->u.diag1;
229                 int j;
230                 for (j = 0; j < diag->num; j++)
231                 {
232                     Z_DiagnosticFormat_s *ds = diag->elements[j];
233                     if (ds->which == Z_DiagnosticFormat_s_defaultDiagRec)
234                     {
235                         Z_DefaultDiagFormat *r = ds->u.defaultDiagRec;
236                         char *oaddinfo = r->u.v2Addinfo;
237                         char *naddinfo = (char *) odr_malloc(
238                             odr,
239                             (oaddinfo ? strlen(oaddinfo) : 0) + 20 +
240                             m_host.length());
241                         if (oaddinfo && *oaddinfo)
242                         {
243                             strcpy(naddinfo, oaddinfo);
244                             strcat(naddinfo, " ");
245                         }
246                         strcat(naddinfo, "(backend=");
247                         strcat(naddinfo, m_host.c_str());
248                         strcat(naddinfo, ")");
249
250                         r->u.v2Addinfo = naddinfo;
251                     }
252                 }
253             }
254         }
255     }
256 }
257
258 void yf::Z3950Client::Assoc::recv_GDU(Z_GDU *gdu, int len)
259 {
260     m_waiting = false;
261
262     if (m_package)
263     {
264         mp::odr odr; // must be in scope for response() = assignment
265         if (gdu && gdu->which == Z_GDU_Z3950)
266         {
267             Z_APDU *apdu = gdu->u.z3950;
268             switch (apdu->which)
269             {
270             case Z_APDU_searchResponse:
271                 fixup_nsd(odr, apdu->u.searchResponse->records);
272                 break;
273             case Z_APDU_presentResponse:
274                 fixup_nsd(odr, apdu->u.presentResponse->records);
275                 break;
276             case Z_APDU_initResponse:
277                 fixup_init(odr, apdu->u.initResponse);
278                 break;
279             }
280         }
281         m_package->response() = gdu;
282     }
283 }
284
285 yazpp_1::IPDU_Observer *yf::Z3950Client::Assoc::sessionNotify(
286     yazpp_1::IPDU_Observable *the_PDU_Observable,
287     int fd)
288 {
289     return 0;
290 }
291
292
293 yf::Z3950Client::Z3950Client() :  m_p(new yf::Z3950Client::Rep)
294 {
295     m_p->m_timeout_sec = 30;
296     m_p->m_max_sockets = 0;
297     m_p->m_force_close = false;
298 }
299
300 yf::Z3950Client::~Z3950Client() {
301 }
302
303 yf::Z3950Client::Assoc *yf::Z3950Client::Rep::get_assoc(Package &package)
304 {
305     // only one thread messes with the clients list at a time
306     boost::mutex::scoped_lock lock(m_mutex);
307
308     std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
309
310     Z_GDU *gdu = package.request().get();
311
312     int max_sockets = package.origin().get_max_sockets();
313     if (max_sockets == 0)
314         max_sockets = m_max_sockets;
315
316     it = m_clients.find(package.session());
317     if (it != m_clients.end())
318     {
319         it->second->m_queue_len++;
320         while (true)
321         {
322 #if 0
323             // double init .. NOT working yet
324             if (gdu && gdu->which == Z_GDU_Z3950 &&
325                 gdu->u.z3950->which == Z_APDU_initRequest)
326             {
327                 yazpp_1::SocketManager *s = it->second->m_socket_manager;
328                 delete it->second;  // destroy Z_Assoc
329                 delete s;    // then manager
330                 m_clients.erase(it);
331                 break;
332             }
333 #endif
334             if (!it->second->m_in_use)
335             {
336                 it->second->m_in_use = true;
337                 return it->second;
338             }
339             m_cond_session_ready.wait(lock);
340         }
341     }
342     if (!gdu || gdu->which != Z_GDU_Z3950)
343     {
344         package.move();
345         return 0;
346     }
347     // new Z39.50 session ..
348     Z_APDU *apdu = gdu->u.z3950;
349     // check that it is init. If not, close
350     if (apdu->which != Z_APDU_initRequest)
351     {
352         mp::odr odr;
353
354         package.response() = odr.create_close(apdu,
355                                               Z_Close_protocolError,
356                                               "First PDU was not an "
357                                               "Initialize Request");
358         package.session().close();
359         return 0;
360     }
361     std::string target = m_force_target;
362     if (!target.length())
363     {
364         target = m_default_target;
365         std::list<std::string> vhosts;
366         mp::util::remove_vhost_otherinfo(&apdu->u.initRequest->otherInfo,
367                                              vhosts);
368         size_t no_vhosts = vhosts.size();
369         if (no_vhosts == 1)
370         {
371             std::list<std::string>::const_iterator v_it = vhosts.begin();
372             target = *v_it;
373         }
374         else if (no_vhosts == 0)
375         {
376             if (!target.length())
377             {
378                 // no default target. So we don't know where to connect
379                 mp::odr odr;
380                 package.response() = odr.create_initResponse(
381                     apdu,
382                     YAZ_BIB1_INIT_NEGOTIATION_OPTION_REQUIRED,
383                     "z3950_client: No vhost given");
384
385                 package.session().close();
386                 return 0;
387             }
388         }
389         else if (no_vhosts > 1)
390         {
391             mp::odr odr;
392             package.response() = odr.create_initResponse(
393                 apdu,
394                 YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP,
395                 "z3950_client: Can not cope with multiple vhosts");
396             package.session().close();
397             return 0;
398         }
399     }
400
401     // see if we have reached max number of clients (max-sockets)
402
403     while (max_sockets)
404     {
405         int no_not_in_use = 0;
406         int number = 0;
407         it = m_clients.begin();
408         for (; it != m_clients.end(); it++)
409         {
410             yf::Z3950Client::Assoc *as = it->second;
411             if (!strcmp(as->m_host.c_str(), target.c_str()))
412             {
413                 number++;
414                 if (!as->m_in_use)
415                     no_not_in_use++;
416             }
417         }
418         yaz_log(YLOG_LOG, "Found %d/%d connections for %s", number, max_sockets,
419                 target.c_str());
420         if (number < max_sockets)
421             break;
422         if (no_not_in_use == 0) // all in use..
423         {
424             mp::odr odr;
425
426             package.response() = odr.create_initResponse(
427                 apdu, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "max sessions");
428             package.session().close();
429             return 0;
430         }
431         boost::xtime xt;
432         xtime_get(&xt, boost::TIME_UTC);
433
434         xt.sec += 15;
435         if (!m_cond_session_ready.timed_wait(lock, xt))
436         {
437             mp::odr odr;
438
439             package.response() = odr.create_initResponse(
440                 apdu, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "max sessions");
441             package.session().close();
442             return 0;
443         }
444     }
445
446     yazpp_1::SocketManager *sm = new yazpp_1::SocketManager;
447     yazpp_1::PDU_Assoc *pdu_as = new yazpp_1::PDU_Assoc(sm);
448     yf::Z3950Client::Assoc *as = new yf::Z3950Client::Assoc(sm, pdu_as,
449                                                             target.c_str(),
450                                                             m_timeout_sec);
451     m_clients[package.session()] = as;
452     return as;
453 }
454
455 void yf::Z3950Client::Rep::send_and_receive(Package &package,
456                                             yf::Z3950Client::Assoc *c)
457 {
458     if (c->m_destroyed)
459         return;
460
461     c->m_package = &package;
462
463     if (package.session().is_closed() && c->m_connected && !c->m_has_closed
464         && m_force_close)
465     {
466         mp::odr odr;
467
468         package.request() = odr.create_close(
469             0, Z_Close_finished, "z3950_client");
470         c->m_package = 0; // don't inspect response
471     }
472     Z_GDU *gdu = package.request().get();
473
474     if (!gdu || gdu->which != Z_GDU_Z3950)
475         return;
476
477     if (gdu->u.z3950->which == Z_APDU_close)
478         c->m_has_closed = true;
479
480     // prepare connect
481     c->m_time_elapsed = 0;
482     c->m_waiting = true;
483     if (!c->m_connected)
484     {
485         if (c->client(c->m_host.c_str()))
486         {
487             mp::odr odr;
488             package.response() =
489                 odr.create_close(gdu->u.z3950, Z_Close_peerAbort, 0);
490             package.session().close();
491             return;
492         }
493         c->timeout(1);  // so timeoutNotify gets called once per second
494
495
496         while (!c->m_destroyed && c->m_waiting
497                && c->m_socket_manager->processEvent() > 0)
498             ;
499     }
500     if (!c->m_connected)
501     {
502         return;
503     }
504
505     // prepare response
506     c->m_time_elapsed = 0;
507     c->m_waiting = true;
508
509     // relay the package  ..
510     int len;
511     c->send_GDU(gdu, &len);
512
513     switch (gdu->u.z3950->which)
514     {
515     case Z_APDU_triggerResourceControlRequest:
516         // request only..
517         break;
518     default:
519         // for the rest: wait for a response PDU
520         while (!c->m_destroyed && c->m_waiting
521                && c->m_socket_manager->processEvent() > 0)
522             ;
523         break;
524     }
525 }
526
527 void yf::Z3950Client::Rep::release_assoc(Package &package)
528 {
529     boost::mutex::scoped_lock lock(m_mutex);
530     std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
531
532     it = m_clients.find(package.session());
533     if (it != m_clients.end())
534     {
535         it->second->m_in_use = false;
536         it->second->m_queue_len--;
537
538         if (package.session().is_closed())
539         {
540             // destroy hint (send_and_receive)
541             it->second->m_destroyed = true;
542             if (it->second->m_queue_len == 0)
543             {
544                 yazpp_1::SocketManager *s = it->second->m_socket_manager;
545                 delete it->second;  // destroy Z_Assoc
546                 delete s;    // then manager
547                 m_clients.erase(it);
548             }
549         }
550         m_cond_session_ready.notify_all();
551     }
552 }
553
554 void yf::Z3950Client::process(Package &package) const
555 {
556     yf::Z3950Client::Assoc *c = m_p->get_assoc(package);
557     if (c)
558     {
559         m_p->send_and_receive(package, c);
560         m_p->release_assoc(package);
561     }
562 }
563
564 void yf::Z3950Client::configure(const xmlNode *ptr, bool test_only,
565                                 const char *path)
566 {
567     for (ptr = ptr->children; ptr; ptr = ptr->next)
568     {
569         if (ptr->type != XML_ELEMENT_NODE)
570             continue;
571         if (!strcmp((const char *) ptr->name, "timeout"))
572         {
573             m_p->m_timeout_sec = mp::xml::get_int(ptr, 30);
574         }
575         else if (!strcmp((const char *) ptr->name, "default_target"))
576         {
577             m_p->m_default_target = mp::xml::get_text(ptr);
578         }
579         else if (!strcmp((const char *) ptr->name, "force_target"))
580         {
581             m_p->m_force_target = mp::xml::get_text(ptr);
582         }
583         else if (!strcmp((const char *) ptr->name, "max-sockets"))
584         {
585             m_p->m_max_sockets = mp::xml::get_int(ptr, 0);
586         }
587         else if (!strcmp((const char *) ptr->name, "force_close"))
588         {
589             m_p->m_force_close = mp::xml::get_bool(ptr, 0);
590         }
591         else
592         {
593             throw mp::filter::FilterException("Bad element "
594                                                + std::string((const char *)
595                                                              ptr->name));
596         }
597     }
598 }
599
600 static mp::filter::Base* filter_creator()
601 {
602     return new mp::filter::Z3950Client;
603 }
604
605 extern "C" {
606     struct metaproxy_1_filter_struct metaproxy_1_filter_z3950_client = {
607         0,
608         "z3950_client",
609         filter_creator
610     };
611 }
612
613 /*
614  * Local variables:
615  * c-basic-offset: 4
616  * c-file-style: "Stroustrup"
617  * indent-tabs-mode: nil
618  * End:
619  * vim: shiftwidth=4 tabstop=8 expandtab
620  */
621