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