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