Add LICENSE file and Refer to it from the source. Include license material
[metaproxy-moved-to-github.git] / src / filter_z3950_client.cpp
1 /* $Id: filter_z3950_client.cpp,v 1.26 2006-06-10 14:29:12 adam Exp $
2    Copyright (c) 2005-2006, Index Data.
3
4    See the LICENSE file for details
5  */
6
7 #include "config.hpp"
8
9 #include "filter.hpp"
10 #include "package.hpp"
11 #include "util.hpp"
12 #include "filter_z3950_client.hpp"
13
14 #include <map>
15 #include <stdexcept>
16 #include <list>
17 #include <iostream>
18
19 #include <boost/thread/mutex.hpp>
20 #include <boost/thread/condition.hpp>
21
22 #include <yaz/zgdu.h>
23 #include <yaz/log.h>
24 #include <yaz/otherinfo.h>
25 #include <yaz/diagbib1.h>
26
27 #include <yazpp/socket-manager.h>
28 #include <yazpp/pdu-assoc.h>
29 #include <yazpp/z-assoc.h>
30
31 namespace mp = metaproxy_1;
32 namespace yf = mp::filter;
33
34 namespace metaproxy_1 {
35     namespace filter {
36         class Z3950Client::Assoc : public yazpp_1::Z_Assoc{
37             friend class Rep;
38             Assoc(yazpp_1::SocketManager *socket_manager,
39                   yazpp_1::IPDU_Observable *PDU_Observable,
40                   std::string host, int timeout);
41             ~Assoc();
42             void connectNotify();
43             void failNotify();
44             void timeoutNotify();
45             void recv_GDU(Z_GDU *gdu, int len);
46             yazpp_1::IPDU_Observer* sessionNotify(
47                 yazpp_1::IPDU_Observable *the_PDU_Observable,
48                 int fd);
49
50             yazpp_1::SocketManager *m_socket_manager;
51             yazpp_1::IPDU_Observable *m_PDU_Observable;
52             Package *m_package;
53             bool m_in_use;
54             bool m_waiting;
55             bool m_destroyed;
56             bool m_connected;
57             int m_queue_len;
58             int m_time_elapsed;
59             int m_time_max;
60             std::string m_host;
61         };
62
63         class Z3950Client::Rep {
64         public:
65             int m_timeout_sec;
66             boost::mutex m_mutex;
67             boost::condition m_cond_session_ready;
68             std::map<mp::Session,Z3950Client::Assoc *> m_clients;
69             Z3950Client::Assoc *get_assoc(Package &package);
70             void send_and_receive(Package &package,
71                                   yf::Z3950Client::Assoc *c);
72             void release_assoc(Package &package);
73         };
74     }
75 }
76
77 using namespace mp;
78
79 yf::Z3950Client::Assoc::Assoc(yazpp_1::SocketManager *socket_manager,
80                               yazpp_1::IPDU_Observable *PDU_Observable,
81                               std::string host, int timeout_sec)
82     :  Z_Assoc(PDU_Observable),
83        m_socket_manager(socket_manager), m_PDU_Observable(PDU_Observable),
84        m_package(0), m_in_use(true), m_waiting(false), 
85        m_destroyed(false), m_connected(false), m_queue_len(1),
86        m_time_elapsed(0), m_time_max(timeout_sec), 
87        m_host(host)
88 {
89     // std::cout << "create assoc " << this << "\n";
90 }
91
92 yf::Z3950Client::Assoc::~Assoc()
93 {
94     // std::cout << "destroy assoc " << this << "\n";
95 }
96
97 void yf::Z3950Client::Assoc::connectNotify()
98 {
99     m_waiting = false;
100
101     m_connected = true;
102 }
103
104 void yf::Z3950Client::Assoc::failNotify()
105 {
106     m_waiting = false;
107
108     mp::odr odr;
109
110     if (m_package)
111     {
112         Z_GDU *gdu = m_package->request().get();
113         Z_APDU *apdu = 0;
114         if (gdu && gdu->which == Z_GDU_Z3950)
115             apdu = gdu->u.z3950;
116         
117         m_package->response() = odr.create_close(apdu, Z_Close_peerAbort, 0);
118         m_package->session().close();
119     }
120 }
121
122 void yf::Z3950Client::Assoc::timeoutNotify()
123 {
124     m_time_elapsed++;
125     if (m_time_elapsed >= m_time_max)
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             if (m_connected)
139                 m_package->response() =
140                     odr.create_close(apdu, Z_Close_lackOfActivity, 0);
141             else
142                 m_package->response() = 
143                     odr.create_close(apdu, Z_Close_peerAbort, 0);
144                 
145             m_package->session().close();
146         }
147     }
148 }
149
150 void yf::Z3950Client::Assoc::recv_GDU(Z_GDU *gdu, int len)
151 {
152     m_waiting = false;
153
154     if (m_package)
155         m_package->response() = gdu;
156 }
157
158 yazpp_1::IPDU_Observer *yf::Z3950Client::Assoc::sessionNotify(
159     yazpp_1::IPDU_Observable *the_PDU_Observable,
160     int fd)
161 {
162     return 0;
163 }
164
165
166 yf::Z3950Client::Z3950Client() :  m_p(new yf::Z3950Client::Rep)
167 {
168     m_p->m_timeout_sec = 30;
169 }
170
171 yf::Z3950Client::~Z3950Client() {
172 }
173
174 yf::Z3950Client::Assoc *yf::Z3950Client::Rep::get_assoc(Package &package) 
175 {
176     // only one thread messes with the clients list at a time
177     boost::mutex::scoped_lock lock(m_mutex);
178
179     std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
180     
181     Z_GDU *gdu = package.request().get();
182     // only deal with Z39.50
183     if (!gdu || gdu->which != Z_GDU_Z3950)
184     {
185         package.move();
186         return 0;
187     }
188     it = m_clients.find(package.session());
189     if (it != m_clients.end())
190     {
191         it->second->m_queue_len++;
192         while(true)
193         {
194 #if 0
195             if (gdu && gdu->which == Z_GDU_Z3950 &&
196                 gdu->u.z3950->which == Z_APDU_initRequest)
197             {
198                 yazpp_1::SocketManager *s = it->second->m_socket_manager;
199                 delete it->second;  // destroy Z_Assoc
200                 delete s;    // then manager
201                 m_clients.erase(it);
202                 break;
203             }
204 #endif
205             if (!it->second->m_in_use)
206             {
207                 it->second->m_in_use = true;
208                 return it->second;
209             }
210             m_cond_session_ready.wait(lock);
211         }
212     }
213     // new Z39.50 session ..
214     Z_APDU *apdu = gdu->u.z3950;
215     // check that it is init. If not, close
216     if (apdu->which != Z_APDU_initRequest)
217     {
218         mp::odr odr;
219         
220         package.response() = odr.create_close(apdu,
221                                               Z_Close_protocolError,
222                                               "First PDU was not an "
223                                               "Initialize Request");
224         package.session().close();
225         return 0;
226     }
227     std::list<std::string> vhosts;
228     mp::util::get_vhost_otherinfo(&apdu->u.initRequest->otherInfo,
229                                    true, vhosts);
230     size_t no_vhosts = vhosts.size();
231     if (no_vhosts == 0)
232     {
233         mp::odr odr;
234         package.response() = odr.create_initResponse(
235             apdu,
236             YAZ_BIB1_INIT_NEGOTIATION_OPTION_REQUIRED,
237             "z3950_client: No virtal host given");
238         
239         package.session().close();
240         return 0;
241     }
242     if (no_vhosts > 1)
243     {
244         mp::odr odr;
245         package.response() = odr.create_initResponse(
246             apdu,
247             YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP,
248             "z3950_client: Can not cope with multiple vhosts");
249         package.session().close();
250         return 0;
251     }
252     std::list<std::string>::const_iterator v_it = vhosts.begin();
253     std::list<std::string> dblist;
254     std::string host;
255     mp::util::split_zurl(*v_it, host, dblist);
256     
257     if (dblist.size())
258     {
259         ; // z3950_client: Databases in vhost ignored
260     }
261
262     yazpp_1::SocketManager *sm = new yazpp_1::SocketManager;
263     yazpp_1::PDU_Assoc *pdu_as = new yazpp_1::PDU_Assoc(sm);
264     yf::Z3950Client::Assoc *as = new yf::Z3950Client::Assoc(sm, pdu_as,
265                                                             host.c_str(),
266                                                             m_timeout_sec);
267     m_clients[package.session()] = as;
268     return as;
269 }
270
271 void yf::Z3950Client::Rep::send_and_receive(Package &package,
272                                             yf::Z3950Client::Assoc *c)
273 {
274     Z_GDU *gdu = package.request().get();
275
276     if (c->m_destroyed)
277         return;
278
279     if (!gdu || gdu->which != Z_GDU_Z3950)
280         return;
281
282     c->m_time_elapsed = 0;
283     c->m_package = &package;
284     c->m_waiting = true;
285     if (!c->m_connected)
286     {
287         c->client(c->m_host.c_str());
288         c->timeout(1);
289
290         while (!c->m_destroyed && c->m_waiting 
291                && c->m_socket_manager->processEvent() > 0)
292             ;
293     }
294     if (!c->m_connected)
295     {
296         return;
297     }
298
299     // prepare response
300     c->m_time_elapsed = 0;
301     c->m_waiting = true;
302     
303     // relay the package  ..
304     int len;
305     c->send_GDU(gdu, &len);
306
307     switch(gdu->u.z3950->which)
308     {
309     case Z_APDU_triggerResourceControlRequest:
310         // request only..
311         break;
312     default:
313         // for the rest: wait for a response PDU
314         while (!c->m_destroyed && c->m_waiting
315                && c->m_socket_manager->processEvent() > 0)
316             ;
317         break;
318     }
319 }
320
321 void yf::Z3950Client::Rep::release_assoc(Package &package)
322 {
323     boost::mutex::scoped_lock lock(m_mutex);
324     std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
325     
326     it = m_clients.find(package.session());
327     if (it != m_clients.end())
328     {
329         Z_GDU *gdu = package.request().get();
330         if (gdu && gdu->which == Z_GDU_Z3950)
331         {   // only Z39.50 packages lock in get_assoc.. release it
332             it->second->m_in_use = false;
333             it->second->m_queue_len--;
334         }
335
336         if (package.session().is_closed())
337         {
338             // destroy hint (send_and_receive)
339             it->second->m_destroyed = true;
340             
341             // wait until no one is waiting for it.
342             while (it->second->m_queue_len)
343                 m_cond_session_ready.wait(lock);
344             
345             // the Z_Assoc and PDU_Assoc must be destroyed before
346             // the socket manager.. so pull that out.. first..
347             yazpp_1::SocketManager *s = it->second->m_socket_manager;
348             delete it->second;  // destroy Z_Assoc
349             delete s;    // then manager
350             m_clients.erase(it);
351         }
352         m_cond_session_ready.notify_all();
353     }
354 }
355
356 void yf::Z3950Client::process(Package &package) const
357 {
358     yf::Z3950Client::Assoc *c = m_p->get_assoc(package);
359     if (c)
360     {
361         m_p->send_and_receive(package, c);
362     }
363     m_p->release_assoc(package);
364 }
365
366 void yf::Z3950Client::configure(const xmlNode *ptr)
367 {
368     for (ptr = ptr->children; ptr; ptr = ptr->next)
369     {
370         if (ptr->type != XML_ELEMENT_NODE)
371             continue;
372         if (!strcmp((const char *) ptr->name, "timeout"))
373         {
374             std::string timeout_str = mp::xml::get_text(ptr);
375             int timeout_sec = atoi(timeout_str.c_str());
376             if (timeout_sec < 2)
377                 throw mp::filter::FilterException("Bad timeout value " 
378                                                    + timeout_str);
379             m_p->m_timeout_sec = timeout_sec;
380         }
381         else
382         {
383             throw mp::filter::FilterException("Bad element " 
384                                                + std::string((const char *)
385                                                              ptr->name));
386         }
387     }
388 }
389
390 static mp::filter::Base* filter_creator()
391 {
392     return new mp::filter::Z3950Client;
393 }
394
395 extern "C" {
396     struct metaproxy_1_filter_struct metaproxy_1_filter_z3950_client = {
397         0,
398         "z3950_client",
399         filter_creator
400     };
401 }
402
403 /*
404  * Local variables:
405  * c-basic-offset: 4
406  * indent-tabs-mode: nil
407  * c-file-style: "stroustrup"
408  * End:
409  * vim: shiftwidth=4 tabstop=8 expandtab
410  */