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