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