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