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