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