z3950_client: mark non-surrogate diagnostics from backend
[metaproxy-moved-to-github.git] / src / filter_z3950_client.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) 2005-2011 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         if (nsd->which == Z_DiagRec_defaultFormat)
178         {
179             std::string addinfo;
180
181             if (nsd->u.v2Addinfo)
182             {
183                 addinfo.assign(nsd->u.v2Addinfo);
184                 addinfo += " ";
185             }
186             addinfo += "(backend=" + m_host + ")";
187             nsd->u.v2Addinfo = odr_strdup(odr, addinfo.c_str());
188         }
189     }
190 }
191
192 void yf::Z3950Client::Assoc::recv_GDU(Z_GDU *gdu, int len)
193 {
194     m_waiting = false;
195
196     if (m_package)
197     { 
198         mp::odr odr; // must be in scope for response() = assignment
199         if (gdu && gdu->which == Z_GDU_Z3950)
200         {
201             Z_APDU *apdu = gdu->u.z3950;
202             switch (apdu->which)
203             {
204             case Z_APDU_searchResponse:
205                 fixup_nsd(odr, apdu->u.searchResponse->records);
206                 break;
207             case Z_APDU_presentResponse:
208                 fixup_nsd(odr, apdu->u.presentResponse->records);
209                 break;
210             }
211         }
212         m_package->response() = gdu;
213     }
214 }
215
216 yazpp_1::IPDU_Observer *yf::Z3950Client::Assoc::sessionNotify(
217     yazpp_1::IPDU_Observable *the_PDU_Observable,
218     int fd)
219 {
220     return 0;
221 }
222
223
224 yf::Z3950Client::Z3950Client() :  m_p(new yf::Z3950Client::Rep)
225 {
226     m_p->m_timeout_sec = 30;
227     m_p->m_max_sockets = 0;
228     m_p->m_force_close = false;
229 }
230
231 yf::Z3950Client::~Z3950Client() {
232 }
233
234 yf::Z3950Client::Assoc *yf::Z3950Client::Rep::get_assoc(Package &package) 
235 {
236     // only one thread messes with the clients list at a time
237     boost::mutex::scoped_lock lock(m_mutex);
238
239     std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
240     
241     Z_GDU *gdu = package.request().get();
242     
243     int max_sockets = package.origin().get_max_sockets();
244     if (max_sockets == 0)
245         max_sockets = m_max_sockets;
246     
247     std::string host;
248
249     it = m_clients.find(package.session());
250     if (it != m_clients.end())
251     {
252         it->second->m_queue_len++;
253         while (true)
254         {
255 #if 0
256             // double init .. NOT working yet
257             if (gdu && gdu->which == Z_GDU_Z3950 &&
258                 gdu->u.z3950->which == Z_APDU_initRequest)
259             {
260                 yazpp_1::SocketManager *s = it->second->m_socket_manager;
261                 delete it->second;  // destroy Z_Assoc
262                 delete s;    // then manager
263                 m_clients.erase(it);
264                 break;
265             }
266 #endif
267             if (!it->second->m_in_use)
268             {
269                 it->second->m_in_use = true;
270                 return it->second;
271             }
272             m_cond_session_ready.wait(lock);
273         }
274     }
275     if (!gdu || gdu->which != Z_GDU_Z3950)
276     {
277         package.move();
278         return 0;
279     }
280     // new Z39.50 session ..
281     Z_APDU *apdu = gdu->u.z3950;
282     // check that it is init. If not, close
283     if (apdu->which != Z_APDU_initRequest)
284     {
285         mp::odr odr;
286         
287         package.response() = odr.create_close(apdu,
288                                               Z_Close_protocolError,
289                                               "First PDU was not an "
290                                               "Initialize Request");
291         package.session().close();
292         return 0;
293     }
294     std::string target = m_force_target;
295     if (!target.length())
296     {
297         target = m_default_target;
298         std::list<std::string> vhosts;
299         mp::util::remove_vhost_otherinfo(&apdu->u.initRequest->otherInfo,
300                                              vhosts);
301         size_t no_vhosts = vhosts.size();
302         if (no_vhosts == 1)
303         {
304             std::list<std::string>::const_iterator v_it = vhosts.begin();
305             target = *v_it;
306         }
307         else if (no_vhosts == 0)
308         {
309             if (!target.length())
310             {
311                 // no default target. So we don't know where to connect
312                 mp::odr odr;
313                 package.response() = odr.create_initResponse(
314                     apdu,
315                     YAZ_BIB1_INIT_NEGOTIATION_OPTION_REQUIRED,
316                     "z3950_client: No vhost given");
317                 
318                 package.session().close();
319                 return 0;
320             }
321         }
322         else if (no_vhosts > 1)
323         {
324             mp::odr odr;
325             package.response() = odr.create_initResponse(
326                 apdu,
327                 YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP,
328                 "z3950_client: Can not cope with multiple vhosts");
329             package.session().close();
330             return 0;
331         }
332     }
333     
334     std::list<std::string> dblist;
335     mp::util::split_zurl(target, host, dblist);
336     
337     if (dblist.size())
338     {
339         ; // z3950_client: Databases in vhost ignored
340     }
341     
342     // see if we have reached max number of clients (max-sockets)
343
344     while (max_sockets)
345     {
346         int no_not_in_use = 0;
347         int number = 0;
348         it = m_clients.begin();
349         for (; it != m_clients.end(); it++)
350         {
351             yf::Z3950Client::Assoc *as = it->second;
352             if (!strcmp(as->m_host.c_str(), host.c_str()))
353             {
354                 number++;
355                 if (!as->m_in_use)
356                     no_not_in_use++;
357             }
358         }
359         yaz_log(YLOG_LOG, "Found %d/%d connections for %s", number, max_sockets,
360                 host.c_str());
361         if (number < max_sockets)
362             break;
363         if (no_not_in_use == 0) // all in use..
364         {
365             mp::odr odr;
366             
367             package.response() = odr.create_initResponse(
368                 apdu, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "max sessions");
369             package.session().close();
370             return 0;
371         }
372         boost::xtime xt;
373         xtime_get(&xt, boost::TIME_UTC);
374         
375         xt.sec += 15;
376         if (!m_cond_session_ready.timed_wait(lock, xt))
377         {
378             mp::odr odr;
379             
380             package.response() = odr.create_initResponse(
381                 apdu, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "max sessions");
382             package.session().close();
383             return 0;
384         }
385     }
386
387     yazpp_1::SocketManager *sm = new yazpp_1::SocketManager;
388     yazpp_1::PDU_Assoc *pdu_as = new yazpp_1::PDU_Assoc(sm);
389     yf::Z3950Client::Assoc *as = new yf::Z3950Client::Assoc(sm, pdu_as,
390                                                             host.c_str(),
391                                                             m_timeout_sec);
392     m_clients[package.session()] = as;
393     return as;
394 }
395
396 void yf::Z3950Client::Rep::send_and_receive(Package &package,
397                                             yf::Z3950Client::Assoc *c)
398 {
399     if (c->m_destroyed)
400         return;
401
402     c->m_package = &package;
403
404     if (package.session().is_closed() && c->m_connected && !c->m_has_closed
405         && m_force_close)
406     {
407         mp::odr odr;
408             
409         package.request() = odr.create_close(
410             0, Z_Close_finished, "z3950_client");
411         c->m_package = 0; // don't inspect response
412     }
413     Z_GDU *gdu = package.request().get();
414
415     if (!gdu || gdu->which != Z_GDU_Z3950)
416         return;
417
418     if (gdu->u.z3950->which == Z_APDU_close)
419         c->m_has_closed = true;
420
421     // prepare connect
422     c->m_time_elapsed = 0;
423     c->m_waiting = true;
424     if (!c->m_connected)
425     {
426         if (c->client(c->m_host.c_str()))
427         {
428             mp::odr odr;
429             package.response() =
430                 odr.create_close(gdu->u.z3950, Z_Close_peerAbort, 0);
431             package.session().close();
432             return;
433         }
434         c->timeout(1);  // so timeoutNotify gets called once per second
435         
436
437         while (!c->m_destroyed && c->m_waiting 
438                && c->m_socket_manager->processEvent() > 0)
439             ;
440     }
441     if (!c->m_connected)
442     {
443         return;
444     }
445
446     // prepare response
447     c->m_time_elapsed = 0;
448     c->m_waiting = true;
449     
450     // relay the package  ..
451     int len;
452     c->send_GDU(gdu, &len);
453
454     switch (gdu->u.z3950->which)
455     {
456     case Z_APDU_triggerResourceControlRequest:
457         // request only..
458         break;
459     default:
460         // for the rest: wait for a response PDU
461         while (!c->m_destroyed && c->m_waiting
462                && c->m_socket_manager->processEvent() > 0)
463             ;
464         break;
465     }
466 }
467
468 void yf::Z3950Client::Rep::release_assoc(Package &package)
469 {
470     boost::mutex::scoped_lock lock(m_mutex);
471     std::map<mp::Session,yf::Z3950Client::Assoc *>::iterator it;
472     
473     it = m_clients.find(package.session());
474     if (it != m_clients.end())
475     {
476         it->second->m_in_use = false;
477         it->second->m_queue_len--;
478
479         if (package.session().is_closed())
480         {
481             // destroy hint (send_and_receive)
482             it->second->m_destroyed = true;
483             if (it->second->m_queue_len == 0)
484             {
485                 yazpp_1::SocketManager *s = it->second->m_socket_manager;
486                 delete it->second;  // destroy Z_Assoc
487                 delete s;    // then manager
488                 m_clients.erase(it);
489             }
490         }
491         m_cond_session_ready.notify_all();
492     }
493 }
494
495 void yf::Z3950Client::process(Package &package) const
496 {
497     yf::Z3950Client::Assoc *c = m_p->get_assoc(package);
498     if (c)
499     {
500         m_p->send_and_receive(package, c);
501         m_p->release_assoc(package);
502     }
503 }
504
505 void yf::Z3950Client::configure(const xmlNode *ptr, bool test_only,
506                                 const char *path)
507 {
508     for (ptr = ptr->children; ptr; ptr = ptr->next)
509     {
510         if (ptr->type != XML_ELEMENT_NODE)
511             continue;
512         if (!strcmp((const char *) ptr->name, "timeout"))
513         {
514             m_p->m_timeout_sec = mp::xml::get_int(ptr, 30);
515         }
516         else if (!strcmp((const char *) ptr->name, "default_target"))
517         {
518             m_p->m_default_target = mp::xml::get_text(ptr);
519         }
520         else if (!strcmp((const char *) ptr->name, "force_target"))
521         {
522             m_p->m_force_target = mp::xml::get_text(ptr);
523         }
524         else if (!strcmp((const char *) ptr->name, "max-sockets"))
525         {
526             m_p->m_max_sockets = mp::xml::get_int(ptr, 0);
527         }
528         else if (!strcmp((const char *) ptr->name, "force_close"))
529         {
530             m_p->m_force_close = mp::xml::get_bool(ptr, 0);
531         }
532         else
533         {
534             throw mp::filter::FilterException("Bad element " 
535                                                + std::string((const char *)
536                                                              ptr->name));
537         }
538     }
539 }
540
541 static mp::filter::Base* filter_creator()
542 {
543     return new mp::filter::Z3950Client;
544 }
545
546 extern "C" {
547     struct metaproxy_1_filter_struct metaproxy_1_filter_z3950_client = {
548         0,
549         "z3950_client",
550         filter_creator
551     };
552 }
553
554 /*
555  * Local variables:
556  * c-basic-offset: 4
557  * c-file-style: "Stroustrup"
558  * indent-tabs-mode: nil
559  * End:
560  * vim: shiftwidth=4 tabstop=8 expandtab
561  */
562