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