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