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