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