Fixed memory leak(s). Added re-use of associations, rather than
[yazpp-moved-to-github.git] / src / yaz-proxy.cpp
1 /*
2  * Copyright (c) 1998-2000, Index Data.
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  * 
6  * $Log: yaz-proxy.cpp,v $
7  * Revision 1.16  2000-09-04 08:29:22  adam
8  * Fixed memory leak(s). Added re-use of associations, rather than
9  * re-init, when maximum number of targets are in use.
10  *
11  * Revision 1.15  2000/08/31 14:41:55  adam
12  * Proxy no longer generates cookies (it's up to the client). Proxy
13  * re-opens if target new op is started before previous operation finishes.
14  *
15  * Revision 1.14  2000/08/10 08:42:42  adam
16  * Fixes for {set,get}_APDU_log.
17  *
18  * Revision 1.13  2000/08/07 14:19:59  adam
19  * Fixed serious bug regarding timeouts. Improved logging for proxy.
20  *
21  * Revision 1.12  2000/07/04 13:48:49  adam
22  * Implemented upper-limit on proxy-to-target sessions.
23  *
24  * Revision 1.11  1999/12/06 13:52:45  adam
25  * Modified for new location of YAZ header files. Experimental threaded
26  * operation.
27  *
28  * Revision 1.10  1999/11/10 10:02:34  adam
29  * Work on proxy.
30  *
31  * Revision 1.9  1999/09/13 12:53:44  adam
32  * Proxy removes OtherInfo Proxy Address and Session ID. Other
33  * Otherinfo remains untouched.
34  *
35  * Revision 1.8  1999/05/04 10:53:00  adam
36  * Changed the way the PROXY behaves when lost cookie is received.
37  *
38  * Revision 1.7  1999/04/28 13:31:17  adam
39  * Better result set optimisation for proxy.
40  *
41  * Revision 1.6  1999/04/27 07:52:13  adam
42  * Improved proxy; added query match for result set re-use.
43  *
44  * Revision 1.5  1999/04/21 12:09:01  adam
45  * Many improvements. Modified to proxy server to work with "sessions"
46  * based on cookies.
47  *
48  * Revision 1.4  1999/04/20 10:30:05  adam
49  * Implemented various stuff for client and proxy. Updated calls
50  * to ODR to reflect new name parameter.
51  *
52  * Revision 1.3  1999/04/09 11:46:57  adam
53  * Added object Yaz_Z_Assoc. Much more functional client.
54  *
55  * Revision 1.2  1999/01/28 13:08:46  adam
56  * Yaz_PDU_Assoc better encapsulated. Memory leak fix in
57  * yaz-socket-manager.cc.
58  *
59  * Revision 1.1.1.1  1999/01/28 09:41:07  adam
60  * First implementation of YAZ++.
61  *
62  */
63
64 #include <assert.h>
65 #include <time.h>
66
67 #include <yaz/log.h>
68 #include <yaz-proxy.h>
69
70 Yaz_Proxy::Yaz_Proxy(IYaz_PDU_Observable *the_PDU_Observable) :
71     Yaz_Z_Assoc(the_PDU_Observable)
72 {
73     m_PDU_Observable = the_PDU_Observable;
74     m_client = 0;
75     m_parent = 0;
76     m_clientPool = 0;
77     m_seqno = 1;
78     m_keepalive = 1;
79     m_proxyTarget = 0;
80     m_max_clients = 50;
81     m_seed = time(0);
82 }
83
84 Yaz_Proxy::~Yaz_Proxy()
85 {
86     xfree (m_proxyTarget);
87 }
88
89 void Yaz_Proxy::set_proxyTarget(const char *target)
90 {
91     xfree (m_proxyTarget);
92     m_proxyTarget = 0;
93     if (target)
94         m_proxyTarget = (char *) xstrdup (target);
95 }
96
97 IYaz_PDU_Observer *Yaz_Proxy::clone(IYaz_PDU_Observable
98                                     *the_PDU_Observable)
99 {
100     Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable);
101     new_proxy->m_parent = this;
102     new_proxy->timeout(120);
103     new_proxy->set_proxyTarget(m_proxyTarget);
104     new_proxy->set_APDU_log(get_APDU_log());
105     return new_proxy;
106 }
107
108 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
109 {
110     int oid[OID_SIZE];
111     Z_OtherInformationUnit *oi;
112     struct oident ent;
113     ent.proto = PROTO_Z3950;
114     ent.oclass = CLASS_USERINFO;
115     ent.value = (oid_value) VAL_COOKIE;
116     assert (oid_ent_to_oid (&ent, oid));
117
118     if (oid_ent_to_oid (&ent, oid) && 
119         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
120         oi->which == Z_OtherInfo_characterInfo)
121         return oi->information.characterInfo;
122     return 0;
123 }
124
125 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
126 {
127     int oid[OID_SIZE];
128     Z_OtherInformationUnit *oi;
129     struct oident ent;
130     ent.proto = PROTO_Z3950;
131     ent.oclass = CLASS_USERINFO;
132     ent.value = (oid_value) VAL_PROXY;
133     if (oid_ent_to_oid (&ent, oid) &&
134         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
135         oi->which == Z_OtherInfo_characterInfo)
136         return oi->information.characterInfo;
137     return 0;
138 }
139
140 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu)
141 {
142     assert (m_parent);
143     Yaz_Proxy *parent = m_parent;
144     Z_OtherInformation **oi;
145     Yaz_ProxyClient *c = m_client;
146     
147     get_otherInfoAPDU(apdu, &oi);
148     char *cookie = get_cookie(oi);
149     logf (LOG_LOG, "Yaz_Proxy::get_client cookie=%s", cookie ? cookie :
150           "null");
151
152     const char *proxy_host = get_proxy(oi);
153     if (proxy_host)
154         set_proxyTarget(proxy_host);
155     logf (LOG_LOG, "proxy_host = %s", m_proxyTarget ? m_proxyTarget:"none");
156     
157     // no target specified at all?
158     if (!m_proxyTarget)
159         return 0;
160
161     if (cookie)
162     {
163         logf (LOG_LOG, "lookup of clients cookie=%s target=%s",
164               cookie, m_proxyTarget);
165         Yaz_ProxyClient *cc = 0;
166         
167         for (c = parent->m_clientPool; c; c = c->m_next)
168         {
169             logf (LOG_LOG, " found client cookie = %s target=%s seqno=%d",
170                   c->m_cookie, c->get_hostname(), c->m_seqno);
171             assert (c->m_prev);
172             assert (*c->m_prev == c);
173             if (!strcmp(cookie,c->m_cookie) &&
174                 !strcmp(m_proxyTarget, c->get_hostname()))
175             {
176                 logf (LOG_LOG, "found!");
177                 cc = c;
178             }
179         }
180         if (cc)
181         {
182             // found it in cache
183             c = cc;
184             // The following handles "cancel"
185             // If connection is busy (waiting for PDU) and
186             // we have an initRequest we can safely do re-open
187             if (c->m_waiting && apdu->which == Z_APDU_initRequest)
188             {
189                 logf (LOG_LOG, "reopen target=%s", c->get_hostname());
190                 c->close();
191                 c->client(m_proxyTarget);
192                 c->m_init_flag = 0;
193                 
194                 delete c->m_last_query;
195                 c->m_last_query = 0;
196                 c->m_last_resultCount = 0;
197                 c->m_sr_transform = 0;
198                 c->m_waiting = 0;
199                 c->timeout(600);
200             }
201             c->m_seqno = parent->m_seqno;
202             (parent->m_seqno)++;
203             return c;
204         }
205     }
206     if (!m_client)
207     {
208         if (apdu->which != Z_APDU_initRequest)
209         {
210             logf (LOG_LOG, "no first INIT!");
211             return 0;
212         }
213         logf (LOG_LOG, "got InitRequest");
214             
215         // go through list of clients - and find the lowest/oldest one.
216         Yaz_ProxyClient *c_min = 0;
217         int min_seq = -1;
218         int no_of_clients = 0;
219         for (c = parent->m_clientPool; c; c = c->m_next)
220         {
221             no_of_clients++;
222             if (min_seq < 0 || c->m_seqno < min_seq)
223             {
224                 min_seq = c->m_seqno;
225                 c_min = c;
226             }
227         }
228         if (no_of_clients >= parent->m_max_clients)
229         {
230             c = c_min;
231             if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
232             {
233                 logf (LOG_LOG, "Yaz_Proxy::get_client re-init session %d",
234                       c->m_seqno);
235                 if (c->m_server)
236                     delete c->m_server;
237                 c->m_server = 0;
238             }
239             else
240             {
241                 logf (LOG_LOG, "Yaz_Proxy::get_client re-use session %d to %d",
242                       c->m_seqno, parent->m_seqno);
243                 if (cookie)
244                     strcpy (c->m_cookie, cookie);
245                 else
246                     c->m_cookie[0] = '\0';
247                 c->m_seqno = parent->m_seqno;
248                 (parent->m_seqno)++;
249                 return c;
250             }
251         }
252         else
253         {
254             logf (LOG_LOG, "Yaz_Proxy::get_client making session %d",
255                   parent->m_seqno);
256             c = new Yaz_ProxyClient(m_PDU_Observable->clone());
257             c->m_next = parent->m_clientPool;
258             if (c->m_next)
259                 c->m_next->m_prev = &c->m_next;
260             parent->m_clientPool = c;
261             c->m_prev = &parent->m_clientPool;
262         }
263         if (cookie)
264             strcpy (c->m_cookie, cookie);
265         else
266             c->m_cookie[0] = '\0';
267         logf (LOG_LOG, "Yaz_Proxy::get_client connect to %s", m_proxyTarget);
268         c->m_seqno = parent->m_seqno;
269         c->client(m_proxyTarget);
270         c->m_init_flag = 0;
271
272         delete c->m_last_query;
273         c->m_last_query = 0;
274         c->m_last_resultCount = 0;
275         c->m_sr_transform = 0;
276         c->m_waiting = 0;
277         c->timeout(600);
278
279         (parent->m_seqno)++;
280     }
281     return c;
282 }
283
284 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
285 {
286     if (apdu->which != Z_APDU_searchRequest)
287         return apdu;
288     Z_SearchRequest *sr = apdu->u.searchRequest;
289     Yaz_Z_Query *this_query = new Yaz_Z_Query;
290     
291     this_query->set_Z_Query(sr->query);
292     
293     if (m_client->m_last_query &&
294         m_client->m_last_query->match(this_query))
295     {
296         delete this_query;
297         if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
298             m_client->m_last_resultCount < *sr->largeSetLowerBound)
299         {
300             // medium Set
301             logf (LOG_LOG, "Yaz_Proxy::result_set_optimize medium set");
302             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
303             Z_PresentRequest *pr = new_apdu->u.presentRequest;
304             pr->referenceId = sr->referenceId;
305             pr->resultSetId = sr->resultSetName;
306             pr->preferredRecordSyntax = sr->preferredRecordSyntax;
307             *pr->numberOfRecordsRequested = *sr->mediumSetPresentNumber;
308             if (sr->mediumSetElementSetNames)
309             {
310                 pr->recordComposition = (Z_RecordComposition *)
311                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
312                 pr->recordComposition->which = Z_RecordComp_simple;
313                 pr->recordComposition->u.simple = sr->mediumSetElementSetNames;
314             }
315             m_client->m_sr_transform = 1;
316             return new_apdu;
317         }
318         else if (m_client->m_last_resultCount > *sr->largeSetLowerBound ||
319             m_client->m_last_resultCount == 0)
320         {
321             // large set
322             logf (LOG_LOG, "Yaz_Proxy::result_set_optimize large set");
323             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
324             new_apdu->u.searchResponse->referenceId = sr->referenceId;
325             new_apdu->u.searchResponse->resultCount =
326                 &m_client->m_last_resultCount;
327             send_Z_PDU(new_apdu);
328             return 0;
329         }
330         else
331         {
332             // small set
333             logf (LOG_LOG, "Yaz_Proxy::result_set_optimize small set");
334             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
335             Z_PresentRequest *pr = new_apdu->u.presentRequest;
336             pr->referenceId = sr->referenceId;
337             pr->resultSetId = sr->resultSetName;
338             pr->preferredRecordSyntax = sr->preferredRecordSyntax;
339             *pr->numberOfRecordsRequested = m_client->m_last_resultCount;
340             if (sr->smallSetElementSetNames)
341             {
342                 pr->recordComposition = (Z_RecordComposition *)
343                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
344                 pr->recordComposition->which = Z_RecordComp_simple;
345                 pr->recordComposition->u.simple = sr->smallSetElementSetNames;
346             }
347             m_client->m_sr_transform = 1;
348             return new_apdu;
349         }
350     }
351     else
352     {
353         logf (LOG_LOG, "Yaz_Proxy::result_set_optimize new set");
354         delete m_client->m_last_query;
355         m_client->m_last_query = this_query;
356     }
357     return apdu;
358 }
359
360 void Yaz_Proxy::recv_Z_PDU(Z_APDU *apdu)
361 {
362     logf (LOG_LOG, "Yaz_Proxy::recv_Z_PDU");
363     // Determine our client.
364     m_client = get_client(apdu);
365     if (!m_client)
366     {
367         delete this;
368         return;
369     }
370     m_client->m_server = this;
371
372     if (apdu->which == Z_APDU_initRequest)
373     {
374         if (m_client->m_init_flag)
375         {
376             Z_APDU *apdu = create_Z_PDU(Z_APDU_initResponse);
377             if (m_client->m_cookie)
378                 set_otherInformationString(apdu, VAL_COOKIE, 1,
379                                            m_client->m_cookie);
380             send_Z_PDU(apdu);
381             return;
382         }
383         m_client->m_init_flag = 1;
384     }
385     apdu = result_set_optimize(apdu);
386     if (!apdu)
387         return;
388
389     logf (LOG_LOG, "Yaz_ProxyClient::send_Z_PDU %s", m_client->get_hostname());
390
391     // delete other info part from PDU before sending to target
392     Z_OtherInformation **oi;
393     get_otherInfoAPDU(apdu, &oi);
394     *oi = 0;
395
396     if (m_client->send_Z_PDU(apdu) < 0)
397     {
398         delete m_client;
399         delete this;
400     }
401     else
402         m_client->m_waiting = 1;
403 }
404
405 void Yaz_Proxy::connectNotify()
406 {
407 }
408
409 void Yaz_Proxy::shutdown()
410 {
411     logf (LOG_LOG, "shutdown (client to proxy)");
412     // only keep if keep_alive flag and cookie is set...
413     if (m_keepalive && m_client && m_client->m_cookie[0])
414     {
415         // Tell client (if any) that no server connection is there..
416         m_client->m_server = 0;
417     }
418     else
419     {
420         delete m_client;
421     }
422     delete this;
423 }
424
425 void Yaz_ProxyClient::shutdown()
426 {
427     logf (LOG_LOG, "shutdown (proxy to server) %s", get_hostname());
428     delete m_server;
429     delete this;
430 }
431
432 void Yaz_Proxy::failNotify()
433 {
434     logf (LOG_LOG, "connection closed by client");
435     shutdown();
436 }
437
438 void Yaz_ProxyClient::failNotify()
439 {
440     logf (LOG_LOG, "Yaz_ProxyClient connection closed by %s", get_hostname());
441     shutdown();
442 }
443
444 void Yaz_ProxyClient::connectNotify()
445 {
446     logf (LOG_LOG, "Yaz_ProxyClient connection accept by %s", get_hostname());
447 }
448
449 IYaz_PDU_Observer *Yaz_ProxyClient::clone(IYaz_PDU_Observable
450                                           *the_PDU_Observable)
451 {
452     return new Yaz_ProxyClient(the_PDU_Observable);
453 }
454
455 Yaz_ProxyClient::~Yaz_ProxyClient()
456 {
457     if (m_prev)
458     {
459         *m_prev = m_next;
460         if (m_next)
461             m_next->m_prev = m_prev;
462     }
463     delete m_last_query;
464 }
465
466 void Yaz_Proxy::timeoutNotify()
467 {
468     logf (LOG_LOG, "timeout (client to proxy)");
469     shutdown();
470 }
471
472 void Yaz_ProxyClient::timeoutNotify()
473 {
474     logf (LOG_LOG, "timeout (proxy to target) %s", get_hostname());
475     shutdown();
476 }
477
478 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable) :
479     Yaz_Z_Assoc (the_PDU_Observable)
480 {
481     m_cookie[0] = 0;
482     m_next = 0;
483     m_prev = 0;
484     m_init_flag = 0;
485     m_last_query = 0;
486     m_last_resultCount = 0;
487     m_sr_transform = 0;
488     m_waiting = 0;
489 }
490
491 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu)
492 {
493     m_waiting = 0;
494     logf (LOG_LOG, "Yaz_ProxyClient::recv_Z_PDU %s", get_hostname());
495     if (apdu->which == Z_APDU_searchResponse)
496         m_last_resultCount = *apdu->u.searchResponse->resultCount;
497     if (apdu->which == Z_APDU_presentResponse && m_sr_transform)
498     {
499         m_sr_transform = 0;
500         Z_PresentResponse *pr = apdu->u.presentResponse;
501         Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
502         Z_SearchResponse *sr = new_apdu->u.searchResponse;
503         sr->referenceId = pr->referenceId;
504         *sr->resultCount = m_last_resultCount;
505         sr->records = pr->records;
506         sr->nextResultSetPosition = pr->nextResultSetPosition;
507         sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
508         apdu = new_apdu;
509     }
510     if (m_cookie)
511         set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
512     if (m_server)
513     {
514         logf (LOG_LOG, "Yaz_Proxy::send_Z_PDU");
515         m_server->send_Z_PDU(apdu);
516     }
517 }