Logging options may be configured in config file
[yazpp-moved-to-github.git] / src / yaz-proxy.cpp
1 /*
2  * Copyright (c) 1998-2003, Index Data.
3  * See the file LICENSE for details.
4  * 
5  * $Id: yaz-proxy.cpp,v 1.62 2003-10-16 16:10:43 adam Exp $
6  */
7
8 #include <assert.h>
9 #include <time.h>
10
11 #include <yaz/marcdisp.h>
12 #include <yaz/yaz-iconv.h>
13 #include <yaz/log.h>
14 #include <yaz/diagbib1.h>
15 #include <yaz++/proxy.h>
16
17 static const char *apdu_name(Z_APDU *apdu)
18 {
19     switch (apdu->which)
20     {
21     case Z_APDU_initRequest:
22         return "initRequest";
23     case Z_APDU_initResponse:
24         return "initResponse";
25     case Z_APDU_searchRequest:
26         return "searchRequest";
27     case Z_APDU_searchResponse:
28         return "searchResponse";
29     case Z_APDU_presentRequest:
30         return "presentRequest";
31     case Z_APDU_presentResponse:
32         return "presentResponse";
33     case Z_APDU_deleteResultSetRequest:
34         return "deleteResultSetRequest";
35     case Z_APDU_deleteResultSetResponse:
36         return "deleteResultSetResponse";
37     case Z_APDU_scanRequest:
38         return "scanRequest";
39     case Z_APDU_scanResponse:
40         return "scanResponse";
41     case Z_APDU_sortRequest:
42         return "sortRequest";
43     case Z_APDU_sortResponse:
44         return "sortResponse";
45     case Z_APDU_extendedServicesRequest:
46         return "extendedServicesRequest";
47     case Z_APDU_extendedServicesResponse:
48         return "extendedServicesResponse";
49     case Z_APDU_close:
50         return "close";
51     }
52     return "other";
53 }
54
55 Yaz_Proxy::Yaz_Proxy(IYaz_PDU_Observable *the_PDU_Observable,
56                      Yaz_Proxy *parent) :
57     Yaz_Z_Assoc(the_PDU_Observable), m_bw_stat(60), m_pdu_stat(60)
58 {
59     m_PDU_Observable = the_PDU_Observable;
60     m_client = 0;
61     m_parent = parent;
62     m_clientPool = 0;
63     m_seqno = 1;
64     m_keepalive_limit_bw = 500000;
65     m_keepalive_limit_pdu = 1000;
66     m_proxyTarget = 0;
67     m_default_target = 0;
68     m_proxy_authentication = 0;
69     m_max_clients = 150;
70     m_log_mask = 0;
71     m_seed = time(0);
72     m_client_idletime = 600;
73     m_target_idletime = 600;
74     m_optimize = xstrdup ("1");
75     strcpy(m_session_str, "0");
76     m_session_no=0;
77     m_bytes_sent = m_bytes_recv = 0;
78     m_bw_hold_PDU = 0;
79     m_bw_max = 0;
80     m_pdu_max = 0;
81     m_max_record_retrieve = 0;
82     m_reconfig_flag = 0;
83     m_config_fname = 0;
84     m_request_no = 0;
85     m_invalid_session = 0;
86     m_config = 0;
87     m_marcxml_flag = 0;
88 }
89
90 Yaz_Proxy::~Yaz_Proxy()
91 {
92     yaz_log(LOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
93             m_bytes_sent, m_bytes_recv);
94     xfree (m_proxyTarget);
95     xfree (m_default_target);
96     xfree (m_proxy_authentication);
97     xfree (m_optimize);
98     delete m_config;
99 }
100
101 int Yaz_Proxy::set_config(const char *config)
102 {
103     delete m_config;
104     m_config = new Yaz_ProxyConfig();
105     xfree(m_config_fname);
106     m_config_fname = xstrdup(config);
107     int r = m_config->read_xml(config);
108     if (!r)
109         m_config->get_generic_info(&m_log_mask, &m_max_clients);
110     return r;
111 }
112
113 void Yaz_Proxy::set_default_target(const char *target)
114 {
115     xfree (m_default_target);
116     m_default_target = 0;
117     if (target)
118         m_default_target = (char *) xstrdup (target);
119 }
120
121 void Yaz_Proxy::set_proxy_authentication (const char *auth)
122 {
123     xfree (m_proxy_authentication);
124     m_proxy_authentication = 0;
125     if (auth)
126         m_proxy_authentication = (char *) xstrdup (auth);
127 }
128
129 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
130 {
131     if (m_parent)
132         return m_parent->check_reconfigure();
133
134     Yaz_ProxyConfig *cfg = m_config;
135     if (m_reconfig_flag)
136     {
137         yaz_log(LOG_LOG, "reconfigure");
138         yaz_log_reopen();
139         if (m_config_fname && cfg)
140         {
141             yaz_log(LOG_LOG, "reconfigure config %s", m_config_fname);
142             int r = cfg->read_xml(m_config_fname);
143             if (r)
144                 yaz_log(LOG_WARN, "reconfigure failed");
145             else
146             {
147                 m_log_mask = 0;
148                 cfg->get_generic_info(&m_log_mask, &m_max_clients);
149             }
150         }
151         else
152             yaz_log(LOG_LOG, "reconfigure");
153         m_reconfig_flag = 0;
154     }
155     return cfg;
156 }
157
158 IYaz_PDU_Observer *Yaz_Proxy::sessionNotify(IYaz_PDU_Observable
159                                             *the_PDU_Observable, int fd)
160 {
161     check_reconfigure();
162     Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable, this);
163     new_proxy->m_config = 0;
164     new_proxy->m_config_fname = 0;
165     new_proxy->timeout(m_client_idletime);
166     new_proxy->m_target_idletime = m_target_idletime;
167     new_proxy->set_default_target(m_default_target);
168     new_proxy->m_max_clients = m_max_clients;
169     new_proxy->m_log_mask = m_log_mask;
170     new_proxy->set_APDU_log(get_APDU_log());
171     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
172         new_proxy->set_APDU_yazlog(1);
173     else
174         new_proxy->set_APDU_yazlog(0);
175     new_proxy->set_proxy_authentication(m_proxy_authentication);
176     sprintf(new_proxy->m_session_str, "%ld:%d ", (long) time(0), m_session_no);
177     m_session_no++;
178     yaz_log (LOG_LOG, "%sNew session %s", new_proxy->m_session_str,
179              the_PDU_Observable->getpeername());
180     return new_proxy;
181 }
182
183 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
184 {
185     int oid[OID_SIZE];
186     Z_OtherInformationUnit *oi;
187     struct oident ent;
188     ent.proto = PROTO_Z3950;
189     ent.oclass = CLASS_USERINFO;
190     ent.value = (oid_value) VAL_COOKIE;
191     assert (oid_ent_to_oid (&ent, oid));
192
193     if (oid_ent_to_oid (&ent, oid) && 
194         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
195         oi->which == Z_OtherInfo_characterInfo)
196         return oi->information.characterInfo;
197     return 0;
198 }
199
200 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
201 {
202     int oid[OID_SIZE];
203     Z_OtherInformationUnit *oi;
204     struct oident ent;
205     ent.proto = PROTO_Z3950;
206     ent.oclass = CLASS_USERINFO;
207     ent.value = (oid_value) VAL_PROXY;
208     if (oid_ent_to_oid (&ent, oid) &&
209         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
210         oi->which == Z_OtherInfo_characterInfo)
211         return oi->information.characterInfo;
212     return 0;
213 }
214
215 const char *Yaz_Proxy::load_balance(const char **url)
216 {
217     int zurl_in_use[MAX_ZURL_PLEX];
218     Yaz_ProxyClient *c;
219     int i;
220
221     for (i = 0; i<MAX_ZURL_PLEX; i++)
222         zurl_in_use[i] = 0;
223     for (c = m_parent->m_clientPool; c; c = c->m_next)
224     {
225         for (i = 0; url[i]; i++)
226             if (!strcmp(url[i], c->get_hostname()))
227                 zurl_in_use[i]++;
228     }
229     int min = 100000;
230     const char *ret = 0;
231     for (i = 0; url[i]; i++)
232     {
233         yaz_log(LOG_DEBUG, "%szurl=%s use=%d",
234                 m_session_str, url[i], zurl_in_use[i]);
235         if (min > zurl_in_use[i])
236         {
237             ret = url[i];
238             min = zurl_in_use[i];
239         }
240     }
241     return ret;
242 }
243
244 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu)
245 {
246     assert (m_parent);
247     Yaz_Proxy *parent = m_parent;
248     Z_OtherInformation **oi;
249     Yaz_ProxyClient *c = m_client;
250     
251     get_otherInfoAPDU(apdu, &oi);
252     char *cookie = get_cookie(oi);
253
254     if (!m_proxyTarget)
255     {
256         const char *url[MAX_ZURL_PLEX];
257         const char *proxy_host = get_proxy(oi);
258         Yaz_ProxyConfig *cfg = check_reconfigure();
259         if (proxy_host)
260         {
261             xfree(m_default_target);
262             m_default_target = xstrdup(proxy_host);
263             proxy_host = m_default_target;
264         }
265         int client_idletime = -1;
266         url[0] = m_default_target;
267         url[1] = 0;
268         if (cfg)
269         {
270             int pre_init = 0;
271             cfg->get_target_info(proxy_host, url, &m_bw_max,
272                                  &m_pdu_max, &m_max_record_retrieve,
273                                  &m_target_idletime, &client_idletime,
274                                  &parent->m_max_clients,
275                                  &m_keepalive_limit_bw,
276                                  &m_keepalive_limit_pdu,
277                                  &pre_init);
278         }
279         if (client_idletime != -1)
280         {
281             m_client_idletime = client_idletime;
282             timeout(m_client_idletime);
283         }
284         if (!url[0])
285         {
286             yaz_log(LOG_LOG, "%sNo default target", m_session_str);
287             return 0;
288         }
289         // we don't handle multiplexing for cookie session, so we just
290         // pick the first one in this case (anonymous users will be able
291         // to use any backend)
292         if (cookie && *cookie)
293             m_proxyTarget = (char*) xstrdup(url[0]);
294         else
295             m_proxyTarget = (char*) xstrdup(load_balance(url));
296     }
297     if (cookie && *cookie)
298     {   // search in sessions with a cookie
299         for (c = parent->m_clientPool; c; c = c->m_next)
300         {
301             assert (c->m_prev);
302             assert (*c->m_prev == c);
303             if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
304                 !strcmp(m_proxyTarget, c->get_hostname()))
305             {
306                 // Found it in cache
307                 // The following handles "cancel"
308                 // If connection is busy (waiting for PDU) and
309                 // we have an initRequest we can safely do re-open
310                 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
311                 {
312                     yaz_log (LOG_LOG, "%s REOPEN target=%s", m_session_str,
313                              c->get_hostname());
314                     c->close();
315                     c->m_init_flag = 0;
316                     
317                     c->m_last_ok = 0;
318                     c->m_cache.clear();
319                     c->m_last_resultCount = 0;
320                     c->m_sr_transform = 0;
321                     c->m_waiting = 0;
322                     c->m_resultSetStartPoint = 0;
323                     c->m_target_idletime = m_target_idletime;
324                     if (c->client(m_proxyTarget))
325                     {
326                         delete c;
327                         return 0;
328                     }
329                     c->timeout(30); 
330                 }
331                 c->m_seqno = parent->m_seqno;
332                 if (c->m_server && c->m_server != this)
333                     c->m_server->m_client = 0;
334                 c->m_server = this;
335                 (parent->m_seqno)++;
336                 yaz_log (LOG_DEBUG, "get_client 1 %p %p", this, c);
337                 return c;
338             }
339         }
340     }
341     else if (!c)
342     {
343         // don't have a client session yet. Search in session w/o cookie
344         for (c = parent->m_clientPool; c; c = c->m_next)
345         {
346             assert (c->m_prev);
347             assert (*c->m_prev == c);
348             if (c->m_server == 0 && c->m_cookie == 0 && 
349                 c->m_waiting == 0 &&
350                 !strcmp(m_proxyTarget, c->get_hostname()))
351             {
352                 // found it in cache
353                 yaz_log (LOG_LOG, "%sREUSE %d %d %s",
354                          m_session_str,
355                          c->m_seqno, parent->m_seqno, c->get_hostname());
356                 
357                 c->m_seqno = parent->m_seqno;
358                 assert(c->m_server == 0);
359                 c->m_server = this;
360
361                 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
362                     c->set_APDU_yazlog(1);
363                 else
364                     c->set_APDU_yazlog(0);
365
366                 (parent->m_seqno)++;
367                 
368                 parent->pre_init();
369                 
370                 return c;
371             }
372         }
373     }
374     if (!m_client)
375     {
376         if (apdu->which != Z_APDU_initRequest)
377         {
378             yaz_log (LOG_LOG, "no first INIT!");
379             return 0;
380         }
381         Z_InitRequest *initRequest = apdu->u.initRequest;
382
383         if (!initRequest->idAuthentication)
384         {
385             if (m_proxy_authentication)
386             {
387                 initRequest->idAuthentication =
388                     (Z_IdAuthentication *)
389                     odr_malloc (odr_encode(),
390                                 sizeof(*initRequest->idAuthentication));
391                 initRequest->idAuthentication->which =
392                     Z_IdAuthentication_open;
393                 initRequest->idAuthentication->u.open =
394                     odr_strdup (odr_encode(), m_proxy_authentication);
395             }
396         }
397
398         // go through list of clients - and find the lowest/oldest one.
399         Yaz_ProxyClient *c_min = 0;
400         int min_seq = -1;
401         int no_of_clients = 0;
402         if (parent->m_clientPool)
403             yaz_log (LOG_DEBUG, "Existing sessions");
404         for (c = parent->m_clientPool; c; c = c->m_next)
405         {
406             yaz_log (LOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
407                                c->m_waiting, c->get_hostname(),
408                                c->m_cookie ? c->m_cookie : "");
409             no_of_clients++;
410             if (min_seq < 0 || c->m_seqno < min_seq)
411             {
412                 min_seq = c->m_seqno;
413                 c_min = c;
414             }
415         }
416         if (no_of_clients >= parent->m_max_clients)
417         {
418             c = c_min;
419             if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
420             {
421                 yaz_log (LOG_LOG, "%sMAXCLIENTS Destroy %d",
422                          m_session_str, c->m_seqno);
423                 if (c->m_server && c->m_server != this)
424                     delete c->m_server;
425                 c->m_server = 0;
426             }
427             else
428             {
429                 yaz_log (LOG_LOG, "%sMAXCLIENTS Reuse %d %d %s",
430                          m_session_str,
431                          c->m_seqno, parent->m_seqno, c->get_hostname());
432                 xfree (c->m_cookie);
433                 c->m_cookie = 0;
434                 if (cookie)
435                     c->m_cookie = xstrdup(cookie);
436                 c->m_seqno = parent->m_seqno;
437                 if (c->m_server && c->m_server != this)
438                 {
439                     c->m_server->m_client = 0;
440                     delete c->m_server;
441                 }
442                 (parent->m_seqno)++;
443                 c->m_target_idletime = m_target_idletime;
444                 c->timeout(m_target_idletime);
445                 
446                 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
447                     c->set_APDU_yazlog(1);
448                 else
449                     c->set_APDU_yazlog(0);
450
451                 return c;
452             }
453         }
454         else
455         {
456             yaz_log (LOG_LOG, "%sNEW %d %s",
457                      m_session_str, parent->m_seqno, m_proxyTarget);
458             c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
459             c->m_next = parent->m_clientPool;
460             if (c->m_next)
461                 c->m_next->m_prev = &c->m_next;
462             parent->m_clientPool = c;
463             c->m_prev = &parent->m_clientPool;
464         }
465
466         xfree (c->m_cookie);
467         c->m_cookie = 0;
468         if (cookie)
469             c->m_cookie = xstrdup(cookie);
470
471         c->m_seqno = parent->m_seqno;
472         c->m_init_flag = 0;
473         c->m_last_resultCount = 0;
474         c->m_last_ok = 0;
475         c->m_cache.clear();
476         c->m_sr_transform = 0;
477         c->m_waiting = 0;
478         c->m_resultSetStartPoint = 0;
479         (parent->m_seqno)++;
480         if (c->client(m_proxyTarget))
481         {
482             delete c;
483             return 0;
484         }
485         c->m_target_idletime = m_target_idletime;
486         c->timeout(30);
487
488         if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
489             c->set_APDU_yazlog(1);
490         else
491             c->set_APDU_yazlog(0);
492     }
493     yaz_log (LOG_DEBUG, "get_client 3 %p %p", this, c);
494     return c;
495 }
496
497 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
498 {
499     int i;
500     for (i = 0; i<num; i++)
501     {
502         oident *ent;
503         Z_DefaultDiagFormat *r;
504         Z_DiagRec *p = pp[i];
505         if (p->which != Z_DiagRec_defaultFormat)
506         {
507             yaz_log(LOG_LOG, "%sError no diagnostics", m_session_str);
508             return;
509         }
510         else
511             r = p->u.defaultFormat;
512         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
513             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
514             yaz_log(LOG_LOG, "%sError unknown diagnostic set", m_session_str);
515         switch (r->which)
516         {
517         case Z_DefaultDiagFormat_v2Addinfo:
518             yaz_log(LOG_LOG, "%sError %d %s:%s",
519                     m_session_str,
520                     *r->condition, diagbib1_str(*r->condition),
521                     r->u.v2Addinfo);
522             break;
523         case Z_DefaultDiagFormat_v3Addinfo:
524             yaz_log(LOG_LOG, "%sError %d %s:%s",
525                     m_session_str,
526                     *r->condition, diagbib1_str(*r->condition),
527                     r->u.v3Addinfo);
528             break;
529         }
530     }
531 }
532
533 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p)
534 {
535     int i;
536
537     yaz_marc_t mt = yaz_marc_create();
538     yaz_marc_xml(mt, YAZ_MARC_MARCXML);
539     for (i = 0; i < p->num_records; i++)
540     {
541         Z_NamePlusRecord *npr = p->records[i];
542         if (npr->which == Z_NamePlusRecord_databaseRecord)
543         {
544             Z_External *r = npr->u.databaseRecord;
545             if (r->which == Z_External_octet)
546             {
547                 int rlen;
548                 char *result;
549                 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
550                                         r->u.octet_aligned->len,
551                                         &result, &rlen))
552                 {
553                     yaz_iconv_t cd = yaz_iconv_open("UTF-8", "MARC-8");
554                     WRBUF wrbuf = wrbuf_alloc();
555                     
556                     char outbuf[120];
557                     size_t inbytesleft = rlen;
558                     const char *inp = result;
559                     while (cd && inbytesleft)
560                     {
561                         size_t outbytesleft = sizeof(outbuf);
562                         char *outp = outbuf;
563                         size_t r;
564                         
565                         r = yaz_iconv (cd, (char**) &inp,
566                                        &inbytesleft,
567                                        &outp, &outbytesleft);
568                         if (r == (size_t) (-1))
569                         {
570                             int e = yaz_iconv_error(cd);
571                             if (e != YAZ_ICONV_E2BIG)
572                             {
573                                 yaz_log(LOG_WARN, "conversion failure");
574                                 break;
575                             }
576                         }
577                         wrbuf_write(wrbuf, outbuf, outp - outbuf);
578                     }
579                     if (cd)
580                         yaz_iconv_close(cd);
581
582                     npr->u.databaseRecord = z_ext_record(odr_encode(),
583                                                          VAL_TEXT_XML,
584                                                          wrbuf_buf(wrbuf),
585                                                          wrbuf_len(wrbuf));
586                     wrbuf_free(wrbuf, 1);
587                 }
588             }
589         }
590     }
591     yaz_marc_destroy(mt);
592 }
593
594 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
595 {
596     int len = 0;
597     if (apdu->which == Z_APDU_searchResponse)
598     {
599         Z_SearchResponse *sr = apdu->u.searchResponse;
600         Z_Records *p = sr->records;
601         if (p && p->which == Z_Records_NSD)
602         {
603             Z_DiagRec dr, *dr_p = &dr;
604             dr.which = Z_DiagRec_defaultFormat;
605             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
606
607             display_diagrecs(&dr_p, 1);
608         }
609         else
610         {
611             if (m_marcxml_flag && p && p->which == Z_Records_DBOSD)
612                 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
613             if (sr->resultCount)
614             {
615                 yaz_log(LOG_LOG, "%s%d hits", m_session_str,
616                         *sr->resultCount);
617                 if (*sr->resultCount < 0)
618                     m_invalid_session = 1;
619             }
620         }
621     }
622     else if (apdu->which == Z_APDU_presentResponse)
623     {
624         Z_PresentResponse *sr = apdu->u.presentResponse;
625         Z_Records *p = sr->records;
626         if (p && p->which == Z_Records_NSD)
627         {
628             Z_DiagRec dr, *dr_p = &dr;
629             dr.which = Z_DiagRec_defaultFormat;
630             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
631
632             display_diagrecs(&dr_p, 1);
633         }
634         if (m_marcxml_flag && p && p->which == Z_Records_DBOSD)
635             convert_to_marcxml(p->u.databaseOrSurDiagnostics);
636     }
637     int r = send_Z_PDU(apdu, &len);
638     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
639         yaz_log (LOG_DEBUG, "%sSending %s to client %d bytes", m_session_str,
640                  apdu_name(apdu), len);
641     m_bytes_sent += len;
642     m_bw_stat.add_bytes(len);
643     return r;
644 }
645
646 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
647 {
648     int len = 0;
649     int r = send_Z_PDU(apdu, &len);
650     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
651         yaz_log (LOG_LOG, "%sSending %s to %s %d bytes",
652                  get_session_str(),
653                  apdu_name(apdu), get_hostname(), len);
654     m_bytes_sent += len;
655     return r;
656 }
657
658 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
659 {
660     if (apdu->which == Z_APDU_presentRequest)
661     {
662         Z_PresentRequest *pr = apdu->u.presentRequest;
663         Z_NamePlusRecordList *npr;
664         int toget = *pr->numberOfRecordsRequested;
665         int start = *pr->resultSetStartPoint;
666
667         yaz_log(LOG_LOG, "%sPresent %s %d+%d", m_session_str,
668                 pr->resultSetId, start, toget);
669
670         if (*m_parent->m_optimize == '0')
671             return apdu;
672
673         if (!m_client->m_last_resultSetId)
674         {
675             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
676             new_apdu->u.presentResponse->records =
677                 create_nonSurrogateDiagnostics(odr_encode(), 30,
678                                                pr->resultSetId);
679             send_to_client(new_apdu);
680             return 0;
681         }
682         if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
683         {
684             if (start+toget-1 > m_client->m_last_resultCount)
685             {
686                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
687                 new_apdu->u.presentResponse->records =
688                     create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
689                 send_to_client(new_apdu);
690                 return 0;
691             }
692             if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
693                                           pr->preferredRecordSyntax,
694                                           pr->recordComposition))
695             {
696                 yaz_log (LOG_LOG, "%sReturned cached records for present request", 
697                          m_session_str);
698                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
699                 new_apdu->u.presentResponse->referenceId = pr->referenceId;
700                 
701                 new_apdu->u.presentResponse->numberOfRecordsReturned
702                     = odr_intdup(odr_encode(), toget);
703                                                                  
704                 new_apdu->u.presentResponse->records = (Z_Records*)
705                     odr_malloc(odr_encode(), sizeof(Z_Records));
706                 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
707                 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
708                 new_apdu->u.presentResponse->nextResultSetPosition =
709                     odr_intdup(odr_encode(), start+toget);
710
711                 send_to_client(new_apdu);
712                 return 0;
713             }
714         }
715     }
716
717     if (apdu->which != Z_APDU_searchRequest)
718         return apdu;
719     Z_SearchRequest *sr = apdu->u.searchRequest;
720     Yaz_Z_Query *this_query = new Yaz_Z_Query;
721     Yaz_Z_Databases this_databases;
722
723     this_databases.set(sr->num_databaseNames, (const char **)
724                        sr->databaseNames);
725     
726     this_query->set_Z_Query(sr->query);
727
728     char query_str[120];
729     this_query->print(query_str, sizeof(query_str)-1);
730     yaz_log(LOG_LOG, "%sSearch %s", m_session_str, query_str);
731
732     if (*m_parent->m_optimize != '0' &&
733         m_client->m_last_ok && m_client->m_last_query &&
734         m_client->m_last_query->match(this_query) &&
735         !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
736         m_client->m_last_databases.match(this_databases))
737     {
738         delete this_query;
739         if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
740             m_client->m_last_resultCount < *sr->largeSetLowerBound)
741         {
742             Z_NamePlusRecordList *npr;
743             int toget = *sr->mediumSetPresentNumber;
744             Z_RecordComposition *comp = 0;
745
746             if (toget > m_client->m_last_resultCount)
747                 toget = m_client->m_last_resultCount;
748             
749             if (sr->mediumSetElementSetNames)
750             {
751                 comp = (Z_RecordComposition *)
752                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
753                 comp->which = Z_RecordComp_simple;
754                 comp->u.simple = sr->mediumSetElementSetNames;
755             }
756  
757             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
758                                           sr->preferredRecordSyntax, comp))
759             {
760                 yaz_log (LOG_LOG, "%sReturned cached records for medium set",
761                          m_session_str);
762                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
763                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
764                 new_apdu->u.searchResponse->resultCount =
765                     &m_client->m_last_resultCount;
766                 
767                 new_apdu->u.searchResponse->numberOfRecordsReturned
768                     = odr_intdup(odr_encode(), toget);
769                                                         
770                 new_apdu->u.searchResponse->presentStatus =
771                     odr_intdup(odr_encode(), Z_PresentStatus_success);
772                 new_apdu->u.searchResponse->records = (Z_Records*)
773                     odr_malloc(odr_encode(), sizeof(Z_Records));
774                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
775                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
776                 new_apdu->u.searchResponse->nextResultSetPosition =
777                     odr_intdup(odr_encode(), toget+1);
778                 send_to_client(new_apdu);
779                 return 0;
780             }
781             else
782             {
783                 // medium Set
784                 // send present request (medium size)
785                 yaz_log (LOG_LOG, "%sOptimizing search for medium set",
786                          m_session_str);
787
788                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
789                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
790                 pr->referenceId = sr->referenceId;
791                 pr->resultSetId = sr->resultSetName;
792                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
793                 *pr->numberOfRecordsRequested = toget;
794                 pr->recordComposition = comp;
795                 m_client->m_sr_transform = 1;
796                 return new_apdu;
797             }
798         }
799         else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
800             m_client->m_last_resultCount <= 0)
801         {
802             // large set. Return pseudo-search response immediately
803             yaz_log (LOG_LOG, "%sOptimizing search for large set",
804                      m_session_str);
805             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
806             new_apdu->u.searchResponse->referenceId = sr->referenceId;
807             new_apdu->u.searchResponse->resultCount =
808                 &m_client->m_last_resultCount;
809             send_to_client(new_apdu);
810             return 0;
811         }
812         else
813         {
814             Z_NamePlusRecordList *npr;
815             int toget = m_client->m_last_resultCount;
816             Z_RecordComposition *comp = 0;
817             // small set
818             // send a present request (small set)
819             
820             if (sr->smallSetElementSetNames)
821             {
822                 comp = (Z_RecordComposition *)
823                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
824                 comp->which = Z_RecordComp_simple;
825                 comp->u.simple = sr->smallSetElementSetNames;
826             }
827
828             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
829                                           sr->preferredRecordSyntax, comp))
830             {
831                 yaz_log (LOG_LOG, "%sReturned cached records for small set",
832                          m_session_str);
833                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
834                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
835                 new_apdu->u.searchResponse->resultCount =
836                     &m_client->m_last_resultCount;
837                 
838                 new_apdu->u.searchResponse->numberOfRecordsReturned
839                     = odr_intdup(odr_encode(), toget);
840                                                                  
841                 new_apdu->u.searchResponse->presentStatus =
842                     odr_intdup(odr_encode(), Z_PresentStatus_success);
843                 new_apdu->u.searchResponse->records = (Z_Records*)
844                     odr_malloc(odr_encode(), sizeof(Z_Records));
845                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
846                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
847                 new_apdu->u.searchResponse->nextResultSetPosition =
848                     odr_intdup(odr_encode(), toget+1);
849                 send_to_client(new_apdu);
850                 return 0;
851             }
852             else
853             {
854                 yaz_log (LOG_LOG, "%sOptimizing search for small set",
855                          m_session_str);
856                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
857                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
858                 pr->referenceId = sr->referenceId;
859                 pr->resultSetId = sr->resultSetName;
860                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
861                 *pr->numberOfRecordsRequested = toget;
862                 pr->recordComposition = comp;
863                 m_client->m_sr_transform = 1;
864                 return new_apdu;
865             }
866         }
867     }
868     else  // query doesn't match
869     {
870         delete m_client->m_last_query;
871         m_client->m_last_query = this_query;
872         m_client->m_last_ok = 0;
873         m_client->m_cache.clear();
874         m_client->m_resultSetStartPoint = 0;
875
876         xfree (m_client->m_last_resultSetId);
877         m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
878
879         m_client->m_last_databases.set(sr->num_databaseNames,
880                                        (const char **) sr->databaseNames);
881     }
882     return apdu;
883 }
884
885
886 void Yaz_Proxy::recv_Z_PDU(Z_APDU *apdu, int len)
887 {
888     char *cp = strchr(m_session_str, ' ');
889     m_request_no++;
890     if (cp)
891         sprintf(cp+1, "%d ", m_request_no);
892
893     int reduce = 0;
894     m_bytes_recv += len;
895     
896     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
897         yaz_log (LOG_DEBUG, "%sReceiving %s from client %d bytes",
898                  m_session_str, apdu_name(apdu), len);
899
900     if (m_bw_hold_PDU)     // double incoming PDU. shutdown now.
901         shutdown();
902
903     m_bw_stat.add_bytes(len);
904     m_pdu_stat.add_bytes(1);
905
906     int bw_total = m_bw_stat.get_total();
907     int pdu_total = m_pdu_stat.get_total();
908
909     yaz_log(LOG_LOG, "%sstat bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
910             m_session_str, bw_total, pdu_total, m_bw_max, m_pdu_max);
911     if (m_bw_max)
912     {
913         if (bw_total > m_bw_max)
914         {
915             reduce = (bw_total/m_bw_max);
916         }
917     }
918     if (m_pdu_max)
919     {
920         if (pdu_total > m_pdu_max)
921         {
922             int nreduce = (60/m_pdu_max);
923             reduce = (reduce > nreduce) ? reduce : nreduce;
924         }
925     }
926     if (reduce)  
927     {
928         yaz_log(LOG_LOG, "%sLimit delay=%d", m_session_str, reduce);
929         m_bw_hold_PDU = apdu;  // save PDU and signal "on hold"
930         timeout(reduce);       // call us reduce seconds later
931     }
932     else
933         recv_Z_PDU_0(apdu);    // all fine. Proceed receive PDU as usual
934 }
935
936 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
937 {
938     if (m_max_record_retrieve)
939     {
940         if (apdu->which == Z_APDU_presentRequest)
941         {
942             Z_PresentRequest *pr = apdu->u.presentRequest;
943             if (pr->numberOfRecordsRequested && 
944                 *pr->numberOfRecordsRequested > m_max_record_retrieve)
945                 *pr->numberOfRecordsRequested = m_max_record_retrieve;
946         }
947     }
948 }
949
950 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
951                                                      int error,
952                                                      const char *addinfo)
953 {
954     Z_Records *rec = (Z_Records *)
955         odr_malloc (odr, sizeof(*rec));
956     int *err = (int *)
957         odr_malloc (odr, sizeof(*err));
958     Z_DiagRec *drec = (Z_DiagRec *)
959         odr_malloc (odr, sizeof(*drec));
960     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
961         odr_malloc (odr, sizeof(*dr));
962     *err = error;
963     rec->which = Z_Records_NSD;
964     rec->u.nonSurrogateDiagnostic = dr;
965     dr->diagnosticSetId =
966         yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
967     dr->condition = err;
968     dr->which = Z_DefaultDiagFormat_v2Addinfo;
969     dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
970     return rec;
971 }
972
973 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
974 {
975     if (apdu->which == Z_APDU_searchRequest)
976     {
977         Z_SearchRequest *sr = apdu->u.searchRequest;
978         int err = 0;
979         char *addinfo = 0;
980
981         Yaz_ProxyConfig *cfg = check_reconfigure();
982         if (cfg)
983             err = cfg->check_query(odr_encode(), m_default_target,
984                                    sr->query, &addinfo);
985         if (err)
986         {
987             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
988
989             new_apdu->u.searchResponse->referenceId = sr->referenceId;
990             new_apdu->u.searchResponse->records =
991                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
992             *new_apdu->u.searchResponse->searchStatus = 0;
993
994             send_to_client(new_apdu);
995
996             return 0;
997         }
998     }
999     return apdu;
1000 }
1001
1002 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
1003 {
1004     m_marcxml_flag = 0;
1005     if (apdu->which == Z_APDU_searchRequest)
1006     {
1007         Z_SearchRequest *sr = apdu->u.searchRequest;
1008         if (*sr->smallSetUpperBound > 0 || *sr->mediumSetPresentNumber > 0)
1009         {
1010             int err = 0;
1011             char *addinfo = 0;
1012             Yaz_ProxyConfig *cfg = check_reconfigure();
1013
1014             if (cfg)
1015                 err = cfg->check_syntax(odr_encode(),
1016                                         m_default_target,
1017                                         sr->preferredRecordSyntax,
1018                                         &addinfo);
1019             if (err == -1)
1020             {
1021                 sr->preferredRecordSyntax =
1022                     yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN,
1023                                            VAL_USMARC);
1024                 m_marcxml_flag = 1;
1025             }
1026             else if (err)
1027             {
1028                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1029                 
1030                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1031                 new_apdu->u.searchResponse->records =
1032                     create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1033                 *new_apdu->u.searchResponse->searchStatus = 0;
1034                 
1035                 send_to_client(new_apdu);
1036                 
1037                 return 0;
1038             }
1039         }
1040     }
1041     else if (apdu->which == Z_APDU_presentRequest)
1042     {
1043         Z_PresentRequest *pr = apdu->u.presentRequest;
1044         int err = 0;
1045         char *addinfo = 0;
1046         Yaz_ProxyConfig *cfg = check_reconfigure();
1047
1048         if (cfg)
1049             err = cfg->check_syntax(odr_encode(), m_default_target,
1050                                     pr->preferredRecordSyntax,
1051                                     &addinfo);
1052         if (err == -1)
1053         {
1054             pr->preferredRecordSyntax =
1055                 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN,
1056                                        VAL_USMARC);
1057             m_marcxml_flag = 1;
1058         }
1059         else if (err)
1060         {
1061             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1062             
1063             new_apdu->u.presentResponse->referenceId = pr->referenceId;
1064             new_apdu->u.presentResponse->records =
1065                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1066             *new_apdu->u.presentResponse->presentStatus =
1067                 Z_PresentStatus_failure;
1068             
1069             send_to_client(new_apdu);
1070             
1071             return 0;
1072         }
1073     }
1074     return apdu;
1075 }
1076
1077 void Yaz_Proxy::recv_Z_PDU_0(Z_APDU *apdu)
1078 {
1079     // Determine our client.
1080     m_client = get_client(apdu);
1081     if (!m_client)
1082     {
1083         delete this;
1084         return;
1085     }
1086     m_client->m_server = this;
1087
1088     if (apdu->which == Z_APDU_initRequest)
1089     {
1090         if (apdu->u.initRequest->implementationId)
1091             yaz_log(LOG_LOG, "%simplementationId: %s",
1092                     m_session_str, apdu->u.initRequest->implementationId);
1093         if (apdu->u.initRequest->implementationName)
1094             yaz_log(LOG_LOG, "%simplementationName: %s",
1095                     m_session_str, apdu->u.initRequest->implementationName);
1096         if (apdu->u.initRequest->implementationVersion)
1097             yaz_log(LOG_LOG, "%simplementationVersion: %s",
1098                     m_session_str, apdu->u.initRequest->implementationVersion);
1099         if (m_client->m_init_flag)
1100         {
1101             Z_APDU *apdu = m_client->m_initResponse;
1102             apdu->u.initResponse->otherInfo = 0;
1103             if (m_client->m_cookie && *m_client->m_cookie)
1104                 set_otherInformationString(apdu, VAL_COOKIE, 1,
1105                                            m_client->m_cookie);
1106             send_to_client(apdu);
1107             return;
1108         }
1109         m_client->m_init_flag = 1;
1110     }
1111     handle_max_record_retrieve(apdu);
1112
1113     if (apdu)
1114         apdu = handle_syntax_validation(apdu);
1115
1116     if (apdu)
1117         apdu = handle_query_validation(apdu);
1118
1119     if (apdu)
1120         apdu = result_set_optimize(apdu);
1121     if (!apdu)
1122     {
1123         m_client->timeout(m_target_idletime);  // mark it active even 
1124         // though we didn't use it
1125         return;
1126     }
1127
1128     // delete other info part from PDU before sending to target
1129     Z_OtherInformation **oi;
1130     get_otherInfoAPDU(apdu, &oi);
1131     if (oi)
1132         *oi = 0;
1133
1134     if (apdu->which == Z_APDU_presentRequest &&
1135         m_client->m_resultSetStartPoint == 0)
1136     {
1137         Z_PresentRequest *pr = apdu->u.presentRequest;
1138         m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
1139         m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
1140     } else {
1141         m_client->m_resultSetStartPoint = 0;
1142     }
1143     if (m_client->send_to_target(apdu) < 0)
1144     {
1145         delete m_client;
1146         m_client = 0;
1147         delete this;
1148     }
1149     else
1150         m_client->m_waiting = 1;
1151 }
1152
1153 void Yaz_Proxy::connectNotify()
1154 {
1155 }
1156
1157 void Yaz_Proxy::shutdown()
1158 {
1159     // only keep if keep_alive flag is set...
1160     if (m_client && 
1161         !m_invalid_session &&
1162         m_client->m_pdu_recv < m_keepalive_limit_pdu &&
1163         m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
1164         m_client->m_waiting == 0)
1165     {
1166         yaz_log(LOG_LOG, "%sShutdown (client to proxy) keepalive %s",
1167                  m_session_str,
1168                  m_client->get_hostname());
1169         yaz_log(LOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1170                 m_session_str, m_client->m_pdu_recv,
1171                 m_client->m_bytes_sent + m_client->m_bytes_recv,
1172                 m_keepalive_limit_bw, m_keepalive_limit_pdu);
1173         assert (m_client->m_waiting != 2);
1174         // Tell client (if any) that no server connection is there..
1175         m_client->m_server = 0;
1176     }
1177     else if (m_client)
1178     {
1179         yaz_log (LOG_LOG, "%sShutdown (client to proxy) close %s",
1180                  m_session_str,
1181                  m_client->get_hostname());
1182         assert (m_client->m_waiting != 2);
1183         delete m_client;
1184     }
1185     else if (!m_parent)
1186     {
1187         yaz_log (LOG_LOG, "%sshutdown (client to proxy) bad state",
1188                  m_session_str);
1189         assert (m_parent);
1190     }
1191     else 
1192     {
1193         yaz_log (LOG_LOG, "%sShutdown (client to proxy)",
1194                  m_session_str);
1195     }
1196     if (m_parent)
1197         m_parent->pre_init();
1198     delete this;
1199 }
1200
1201 const char *Yaz_ProxyClient::get_session_str() 
1202 {
1203     if (!m_server)
1204         return "0 ";
1205     return m_server->get_session_str();
1206 }
1207
1208 void Yaz_ProxyClient::shutdown()
1209 {
1210     yaz_log (LOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
1211              get_hostname());
1212     delete m_server;
1213     delete this;
1214 }
1215
1216 void Yaz_Proxy::failNotify()
1217 {
1218     yaz_log (LOG_LOG, "%sConnection closed by client",
1219              get_session_str());
1220     shutdown();
1221 }
1222
1223 void Yaz_ProxyClient::failNotify()
1224 {
1225     yaz_log (LOG_LOG, "%sConnection closed by target %s", 
1226              get_session_str(), get_hostname());
1227     shutdown();
1228 }
1229
1230 void Yaz_ProxyClient::connectNotify()
1231 {
1232     const char *s = get_session_str();
1233     const char *h = get_hostname();
1234     yaz_log (LOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
1235              m_target_idletime);
1236     timeout(m_target_idletime);
1237     if (!m_server)
1238         pre_init_client();
1239 }
1240
1241 IYaz_PDU_Observer *Yaz_ProxyClient::sessionNotify(IYaz_PDU_Observable
1242                                                   *the_PDU_Observable, int fd)
1243 {
1244     return new Yaz_ProxyClient(the_PDU_Observable, 0);
1245 }
1246
1247 Yaz_ProxyClient::~Yaz_ProxyClient()
1248 {
1249     if (m_prev)
1250         *m_prev = m_next;
1251     if (m_next)
1252         m_next->m_prev = m_prev;
1253     m_waiting = 2;     // for debugging purposes only.
1254     odr_destroy(m_init_odr);
1255     delete m_last_query;
1256     xfree (m_last_resultSetId);
1257     xfree (m_cookie);
1258 }
1259
1260 void Yaz_ProxyClient::pre_init_client()
1261 {
1262     Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
1263     Z_InitRequest *req = apdu->u.initRequest;
1264     
1265     ODR_MASK_SET(req->options, Z_Options_search);
1266     ODR_MASK_SET(req->options, Z_Options_present);
1267     ODR_MASK_SET(req->options, Z_Options_namedResultSets);
1268     ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
1269     ODR_MASK_SET(req->options, Z_Options_scan);
1270     ODR_MASK_SET(req->options, Z_Options_sort);
1271     ODR_MASK_SET(req->options, Z_Options_extendedServices);
1272     ODR_MASK_SET(req->options, Z_Options_delSet);
1273     
1274     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
1275     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
1276     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
1277     
1278     if (send_to_target(apdu) < 0)
1279     {
1280         delete this;
1281     }
1282     else
1283     {
1284         m_waiting = 1;
1285         m_init_flag = 1;
1286     }
1287 }
1288
1289 void Yaz_Proxy::pre_init()
1290 {
1291     int i;
1292     const char *name = 0;
1293     const char *zurl_in_use[MAX_ZURL_PLEX];
1294     int limit_bw, limit_pdu, limit_req;
1295     int target_idletime, client_idletime;
1296     int max_clients;
1297     int keepalive_limit_bw, keepalive_limit_pdu;
1298     int pre_init;
1299
1300     Yaz_ProxyConfig *cfg = check_reconfigure();
1301
1302     zurl_in_use[0] = 0;
1303
1304     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
1305         set_APDU_yazlog(1);
1306     else
1307         set_APDU_yazlog(0);
1308
1309     for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
1310                                           &limit_bw, &limit_pdu, &limit_req,
1311                                           &target_idletime, &client_idletime,
1312                                           &max_clients, 
1313                                           &keepalive_limit_bw,
1314                                           &keepalive_limit_pdu,
1315                                           &pre_init) ; i++)
1316     {
1317         if (pre_init)
1318         {
1319             int j;
1320             for (j = 0; zurl_in_use[j]; j++)
1321             {
1322                 Yaz_ProxyClient *c;
1323                 int spare = 0;
1324                 for (c = m_clientPool; c; c = c->m_next)
1325                 {
1326                     if (!strcmp(zurl_in_use[j], c->get_hostname())
1327                         && c->m_server == 0 && c->m_cookie == 0)
1328                         spare++;
1329                 }
1330                 yaz_log(LOG_LOG, "%s pre-init %s %s spare=%d pre_init=%d",
1331                         m_session_str,
1332                         name, zurl_in_use[j], spare, pre_init);
1333                 if (spare < pre_init)
1334                 {
1335                     c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
1336                     c->m_next = m_clientPool;
1337                     if (c->m_next)
1338                         c->m_next->m_prev = &c->m_next;
1339                     m_clientPool = c;
1340                     c->m_prev = &m_clientPool;
1341                     
1342                     if (m_log_mask & PROXY_LOG_APDU_SERVER)
1343                         c->set_APDU_yazlog(1);
1344                     else
1345                         c->set_APDU_yazlog(0);
1346
1347                     if (c->client(zurl_in_use[j]))
1348                     {
1349                         timeout(60);
1350                         delete c;
1351                         return;
1352                     }
1353                     c->timeout(30);
1354                     c->m_waiting = 1;
1355                     c->m_target_idletime = target_idletime;
1356                     c->m_seqno = m_seqno++;
1357                 }
1358             }
1359         }
1360     }
1361 }
1362
1363 void Yaz_Proxy::timeoutNotify()
1364 {
1365     if (m_parent)
1366     {
1367         if (m_bw_hold_PDU)
1368         {
1369             timeout(m_client_idletime);
1370             Z_APDU *apdu = m_bw_hold_PDU;
1371             m_bw_hold_PDU = 0;
1372             recv_Z_PDU_0(apdu);
1373         }
1374         else
1375         {
1376             yaz_log (LOG_LOG, "%sTimeout (client to proxy)", m_session_str);
1377             shutdown();
1378         }
1379     }
1380     else
1381     {
1382         timeout(600);
1383         pre_init();
1384     }
1385 }
1386
1387 void Yaz_ProxyClient::timeoutNotify()
1388 {
1389     yaz_log (LOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
1390              get_hostname());
1391     m_waiting = 1;
1392     m_root->pre_init();
1393     shutdown();
1394 }
1395
1396 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable,
1397                                  Yaz_Proxy *parent) :
1398     Yaz_Z_Assoc (the_PDU_Observable)
1399 {
1400     m_cookie = 0;
1401     m_next = 0;
1402     m_prev = 0;
1403     m_init_flag = 0;
1404     m_last_query = 0;
1405     m_last_resultSetId = 0;
1406     m_last_resultCount = 0;
1407     m_last_ok = 0;
1408     m_sr_transform = 0;
1409     m_waiting = 0;
1410     m_init_odr = odr_createmem (ODR_DECODE);
1411     m_initResponse = 0;
1412     m_resultSetStartPoint = 0;
1413     m_bytes_sent = m_bytes_recv = 0;
1414     m_pdu_recv = 0;
1415     m_server = 0;
1416     m_seqno = 0;
1417     m_target_idletime = 600;
1418     m_root = parent;
1419 }
1420
1421 const char *Yaz_Proxy::option(const char *name, const char *value)
1422 {
1423     if (!strcmp (name, "optimize")) {
1424         if (value) {
1425             xfree (m_optimize); 
1426             m_optimize = xstrdup (value);
1427         }
1428         return m_optimize;
1429     }
1430     return 0;
1431 }
1432
1433 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
1434 {
1435     m_bytes_recv += len;
1436     m_pdu_recv++;
1437     m_waiting = 0;
1438     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1439         yaz_log (LOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
1440                  apdu_name(apdu), get_hostname(), len);
1441     if (apdu->which == Z_APDU_initResponse)
1442     {
1443         if (!m_server)  // if this is a pre init session , check for more
1444             m_root->pre_init();
1445         NMEM nmem = odr_extract_mem (odr_decode());
1446         odr_reset (m_init_odr);
1447         nmem_transfer (m_init_odr->mem, nmem);
1448         m_initResponse = apdu;
1449
1450         Z_InitResponse *ir = apdu->u.initResponse;
1451         char *im0 = ir->implementationName;
1452         
1453         char *im1 = (char*) 
1454             odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
1455         *im1 = '\0';
1456         if (im0)
1457         {
1458             strcat(im1, im0);
1459             strcat(im1, " ");
1460         }
1461         strcat(im1, "(YAZ Proxy)");
1462         ir->implementationName = im1;
1463
1464         nmem_destroy (nmem);
1465     }
1466     if (apdu->which == Z_APDU_searchResponse)
1467     {
1468         Z_SearchResponse *sr = apdu->u.searchResponse;
1469         m_last_resultCount = *sr->resultCount;
1470         int status = *sr->searchStatus;
1471         if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
1472         {
1473             m_last_ok = 1;
1474             
1475             if (sr->records && sr->records->which == Z_Records_DBOSD)
1476             {
1477                 m_cache.add(odr_decode(),
1478                             sr->records->u.databaseOrSurDiagnostics, 1,
1479                             *sr->resultCount);
1480             }
1481         }
1482     }
1483     if (apdu->which == Z_APDU_presentResponse)
1484     {
1485         Z_PresentResponse *pr = apdu->u.presentResponse;
1486         if (m_sr_transform)
1487         {
1488             m_sr_transform = 0;
1489             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1490             Z_SearchResponse *sr = new_apdu->u.searchResponse;
1491             sr->referenceId = pr->referenceId;
1492             *sr->resultCount = m_last_resultCount;
1493             sr->records = pr->records;
1494             sr->nextResultSetPosition = pr->nextResultSetPosition;
1495             sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
1496             apdu = new_apdu;
1497         }
1498         if (pr->records && 
1499             pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
1500         {
1501             m_cache.add(odr_decode(),
1502                         pr->records->u.databaseOrSurDiagnostics,
1503                         m_resultSetStartPoint, -1);
1504             m_resultSetStartPoint = 0;
1505         }
1506     }
1507     if (m_cookie)
1508         set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
1509     if (m_server)
1510     {
1511         m_server->send_to_client(apdu);
1512     }
1513     if (apdu->which == Z_APDU_close)
1514     {
1515         shutdown();
1516     }
1517 }
1518
1519 void Yaz_Proxy::server(const char *addr)
1520 {
1521     Yaz_Z_Assoc::server(addr);
1522
1523     timeout(1);
1524 }
1525