Take into account spare sessions in load_balance
[yazpp-moved-to-github.git] / src / yaz-proxy.cpp
1 /*
2  * Copyright (c) 1998-2004, Index Data.
3  * See the file LICENSE for details.
4  * 
5  * $Id: yaz-proxy.cpp,v 1.104 2004-02-26 23:43:07 adam Exp $
6  */
7
8 #include <assert.h>
9 #include <time.h>
10
11 #include <yaz/srw.h>
12 #include <yaz/marcdisp.h>
13 #include <yaz/yaz-iconv.h>
14 #include <yaz/log.h>
15 #include <yaz/diagbib1.h>
16 #include <yaz++/proxy.h>
17 #include <yaz/pquery.h>
18
19 static const char *apdu_name(Z_APDU *apdu)
20 {
21     switch (apdu->which)
22     {
23     case Z_APDU_initRequest:
24         return "initRequest";
25     case Z_APDU_initResponse:
26         return "initResponse";
27     case Z_APDU_searchRequest:
28         return "searchRequest";
29     case Z_APDU_searchResponse:
30         return "searchResponse";
31     case Z_APDU_presentRequest:
32         return "presentRequest";
33     case Z_APDU_presentResponse:
34         return "presentResponse";
35     case Z_APDU_deleteResultSetRequest:
36         return "deleteResultSetRequest";
37     case Z_APDU_deleteResultSetResponse:
38         return "deleteResultSetResponse";
39     case Z_APDU_scanRequest:
40         return "scanRequest";
41     case Z_APDU_scanResponse:
42         return "scanResponse";
43     case Z_APDU_sortRequest:
44         return "sortRequest";
45     case Z_APDU_sortResponse:
46         return "sortResponse";
47     case Z_APDU_extendedServicesRequest:
48         return "extendedServicesRequest";
49     case Z_APDU_extendedServicesResponse:
50         return "extendedServicesResponse";
51     case Z_APDU_close:
52         return "close";
53     }
54     return "other";
55 }
56
57 static const char *gdu_name(Z_GDU *gdu)
58 {
59     switch(gdu->which)
60     {
61     case Z_GDU_Z3950:
62         return apdu_name(gdu->u.z3950);
63     case Z_GDU_HTTP_Request:
64         return "HTTP Request";
65     case Z_GDU_HTTP_Response:
66         return "HTTP Response";
67     }
68     return "Unknown request/response";
69 }
70
71 Yaz_Proxy::Yaz_Proxy(IYaz_PDU_Observable *the_PDU_Observable,
72                      Yaz_Proxy *parent) :
73     Yaz_Z_Assoc(the_PDU_Observable), m_bw_stat(60), m_pdu_stat(60)
74 {
75     m_PDU_Observable = the_PDU_Observable;
76     m_client = 0;
77     m_parent = parent;
78     m_clientPool = 0;
79     m_seqno = 1;
80     m_keepalive_limit_bw = 500000;
81     m_keepalive_limit_pdu = 1000;
82     m_proxyTarget = 0;
83     m_default_target = 0;
84     m_proxy_authentication = 0;
85     m_max_clients = 150;
86     m_log_mask = 0;
87     m_seed = time(0);
88     m_client_idletime = 600;
89     m_target_idletime = 600;
90     m_optimize = xstrdup ("1");
91     strcpy(m_session_str, "0 ");
92     m_session_no=0;
93     m_bytes_sent = 0;
94     m_bytes_recv = 0;
95     m_bw_hold_PDU = 0;
96     m_bw_max = 0;
97     m_pdu_max = 0;
98     m_max_record_retrieve = 0;
99     m_reconfig_flag = 0;
100     m_config_fname = 0;
101     m_request_no = 0;
102     m_invalid_session = 0;
103     m_referenceId = 0;
104     m_referenceId_mem = nmem_create();
105     m_config = 0;
106     m_marcxml_flag = 0;
107     m_stylesheet_xsp = 0;
108     m_stylesheet_nprl = 0;
109     m_s2z_stylesheet = 0;
110     m_s2z_database = 0;
111     m_schema = 0;
112     m_initRequest_apdu = 0;
113     m_initRequest_mem = 0;
114     m_initRequest_preferredMessageSize = 0;
115     m_initRequest_maximumRecordSize = 0;
116     m_initRequest_options = 0;
117     m_initRequest_version = 0;
118     m_apdu_invalid_session = 0;
119     m_mem_invalid_session = 0;
120     m_s2z_odr_init = 0;
121     m_s2z_odr_search = 0;
122     m_s2z_init_apdu = 0;
123     m_s2z_search_apdu = 0;
124     m_s2z_present_apdu = 0;
125     m_http_keepalive = 0;
126     m_http_version = 0;
127     m_soap_ns = 0;
128     m_s2z_packing = Z_SRW_recordPacking_string;
129     m_time_tv.tv_sec = 0;
130     m_time_tv.tv_usec = 0;
131 }
132
133 Yaz_Proxy::~Yaz_Proxy()
134 {
135     yaz_log(LOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
136             m_bytes_sent, m_bytes_recv);
137     nmem_destroy(m_initRequest_mem);
138     nmem_destroy(m_mem_invalid_session);
139     nmem_destroy(m_referenceId_mem);
140
141     xfree (m_proxyTarget);
142     xfree (m_default_target);
143     xfree (m_proxy_authentication);
144     xfree (m_optimize);
145
146     if (m_stylesheet_xsp)
147         xsltFreeStylesheet(m_stylesheet_xsp);
148
149     xfree (m_schema);
150     if (m_s2z_odr_init)
151         odr_destroy(m_s2z_odr_init);
152     if (m_s2z_odr_search)
153         odr_destroy(m_s2z_odr_search);
154     delete m_config;
155 }
156
157 int Yaz_Proxy::set_config(const char *config)
158 {
159     delete m_config;
160     m_config = new Yaz_ProxyConfig();
161     xfree(m_config_fname);
162     m_config_fname = xstrdup(config);
163     int r = m_config->read_xml(config);
164     if (!r)
165         m_config->get_generic_info(&m_log_mask, &m_max_clients);
166     return r;
167 }
168
169 void Yaz_Proxy::set_default_target(const char *target)
170 {
171     xfree (m_default_target);
172     m_default_target = 0;
173     if (target)
174         m_default_target = (char *) xstrdup (target);
175 }
176
177 void Yaz_Proxy::set_proxy_authentication (const char *auth)
178 {
179     xfree (m_proxy_authentication);
180     m_proxy_authentication = 0;
181     if (auth)
182         m_proxy_authentication = (char *) xstrdup (auth);
183 }
184
185 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
186 {
187     if (m_parent)
188         return m_parent->check_reconfigure();
189
190     Yaz_ProxyConfig *cfg = m_config;
191     if (m_reconfig_flag)
192     {
193         yaz_log(LOG_LOG, "reconfigure");
194         yaz_log_reopen();
195         if (m_config_fname && cfg)
196         {
197             yaz_log(LOG_LOG, "reconfigure config %s", m_config_fname);
198             int r = cfg->read_xml(m_config_fname);
199             if (r)
200                 yaz_log(LOG_WARN, "reconfigure failed");
201             else
202             {
203                 m_log_mask = 0;
204                 cfg->get_generic_info(&m_log_mask, &m_max_clients);
205             }
206         }
207         else
208             yaz_log(LOG_LOG, "reconfigure");
209         m_reconfig_flag = 0;
210     }
211     return cfg;
212 }
213
214 IYaz_PDU_Observer *Yaz_Proxy::sessionNotify(IYaz_PDU_Observable
215                                             *the_PDU_Observable, int fd)
216 {
217     check_reconfigure();
218     Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable, this);
219     new_proxy->m_config = 0;
220     new_proxy->m_config_fname = 0;
221     new_proxy->timeout(m_client_idletime);
222     new_proxy->m_target_idletime = m_target_idletime;
223     new_proxy->set_default_target(m_default_target);
224     new_proxy->m_max_clients = m_max_clients;
225     new_proxy->m_log_mask = m_log_mask;
226     new_proxy->set_APDU_log(get_APDU_log());
227     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
228         new_proxy->set_APDU_yazlog(1);
229     else
230         new_proxy->set_APDU_yazlog(0);
231     new_proxy->set_proxy_authentication(m_proxy_authentication);
232     sprintf(new_proxy->m_session_str, "%ld:%d ", (long) time(0), m_session_no);
233     m_session_no++;
234     yaz_log (LOG_LOG, "%sNew session %s", new_proxy->m_session_str,
235              the_PDU_Observable->getpeername());
236     return new_proxy;
237 }
238
239 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
240 {
241     int oid[OID_SIZE];
242     Z_OtherInformationUnit *oi;
243     struct oident ent;
244     ent.proto = PROTO_Z3950;
245     ent.oclass = CLASS_USERINFO;
246     ent.value = (oid_value) VAL_COOKIE;
247     assert (oid_ent_to_oid (&ent, oid));
248
249     if (oid_ent_to_oid (&ent, oid) && 
250         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
251         oi->which == Z_OtherInfo_characterInfo)
252         return oi->information.characterInfo;
253     return 0;
254 }
255
256 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
257 {
258     int oid[OID_SIZE];
259     Z_OtherInformationUnit *oi;
260     struct oident ent;
261     ent.proto = PROTO_Z3950;
262     ent.oclass = CLASS_USERINFO;
263     ent.value = (oid_value) VAL_PROXY;
264     if (oid_ent_to_oid (&ent, oid) &&
265         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
266         oi->which == Z_OtherInfo_characterInfo)
267         return oi->information.characterInfo;
268     return 0;
269 }
270
271 const char *Yaz_Proxy::load_balance(const char **url)
272 {
273     int zurl_in_use[MAX_ZURL_PLEX];
274     int zurl_in_spare[MAX_ZURL_PLEX];
275     Yaz_ProxyClient *c;
276     int i;
277
278     for (i = 0; i<MAX_ZURL_PLEX; i++)
279     {
280         zurl_in_use[i] = 0;
281         zurl_in_spare[i] = 0;
282     }
283     for (c = m_parent->m_clientPool; c; c = c->m_next)
284     {
285         for (i = 0; url[i]; i++)
286             if (!strcmp(url[i], c->get_hostname()))
287             {
288                 zurl_in_use[i]++;
289                 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
290                     zurl_in_spare[i]++;
291             }
292     }
293     int min_use = 100000;
294     int spare_for_min = 0;
295     int max_spare = 0;
296     const char *ret_min = 0;
297     const char *ret_spare = 0;
298     for (i = 0; url[i]; i++)
299     {
300         yaz_log(LOG_DEBUG, "%szurl=%s use=%d spare=%d",
301                 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
302         if (min_use > zurl_in_use[i])
303         {
304             ret_min = url[i];
305             min_use = zurl_in_use[i];
306             spare_for_min = zurl_in_spare[i];
307         }
308         if (max_spare < zurl_in_spare[i]) 
309         {
310             ret_spare = url[i];
311             max_spare = zurl_in_spare[i];
312         }
313     }
314     // use the one with minimum connections if spare is > 3
315     if (spare_for_min > 3)
316         return ret_min;
317     // use one with most spares (if any)
318     if (max_spare > 0)
319         return ret_spare;
320     return ret_min;
321 }
322
323 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
324                                        const char *proxy_host)
325 {
326     assert (m_parent);
327     Yaz_Proxy *parent = m_parent;
328     Yaz_ProxyClient *c = m_client;
329     
330     if (!m_proxyTarget)
331     {
332         const char *url[MAX_ZURL_PLEX];
333         Yaz_ProxyConfig *cfg = check_reconfigure();
334         if (proxy_host)
335         {
336 #if 1
337 /* only to be enabled for debugging... */
338             if (!strcmp(proxy_host, "stop"))
339                 exit(0);
340 #endif
341             xfree(m_default_target);
342             m_default_target = xstrdup(proxy_host);
343             proxy_host = m_default_target;
344         }
345         int client_idletime = -1;
346         const char *cql2rpn_fname = 0;
347         url[0] = m_default_target;
348         url[1] = 0;
349         if (cfg)
350         {
351             int pre_init = 0;
352             cfg->get_target_info(proxy_host, url, &m_bw_max,
353                                  &m_pdu_max, &m_max_record_retrieve,
354                                  &m_target_idletime, &client_idletime,
355                                  &parent->m_max_clients,
356                                  &m_keepalive_limit_bw,
357                                  &m_keepalive_limit_pdu,
358                                  &pre_init,
359                                  &cql2rpn_fname);
360         }
361         if (client_idletime != -1)
362         {
363             m_client_idletime = client_idletime;
364             timeout(m_client_idletime);
365         }
366         if (cql2rpn_fname)
367             m_cql2rpn.set_pqf_file(cql2rpn_fname);
368         if (!url[0])
369         {
370             yaz_log(LOG_LOG, "%sNo default target", m_session_str);
371             return 0;
372         }
373         // we don't handle multiplexing for cookie session, so we just
374         // pick the first one in this case (anonymous users will be able
375         // to use any backend)
376         if (cookie && *cookie)
377             m_proxyTarget = (char*) xstrdup(url[0]);
378         else
379             m_proxyTarget = (char*) xstrdup(load_balance(url));
380     }
381     if (cookie && *cookie)
382     {   // search in sessions with a cookie
383         for (c = parent->m_clientPool; c; c = c->m_next)
384         {
385             assert (c->m_prev);
386             assert (*c->m_prev == c);
387             if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
388                 !strcmp(m_proxyTarget, c->get_hostname()))
389             {
390                 // Found it in cache
391                 // The following handles "cancel"
392                 // If connection is busy (waiting for PDU) and
393                 // we have an initRequest we can safely do re-open
394                 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
395                 {
396                     yaz_log (LOG_LOG, "%s REOPEN target=%s", m_session_str,
397                              c->get_hostname());
398                     c->close();
399                     c->m_init_flag = 0;
400                     
401                     c->m_last_ok = 0;
402                     c->m_cache.clear();
403                     c->m_last_resultCount = 0;
404                     c->m_sr_transform = 0;
405                     c->m_waiting = 0;
406                     c->m_resultSetStartPoint = 0;
407                     c->m_target_idletime = m_target_idletime;
408                     if (c->client(m_proxyTarget))
409                     {
410                         delete c;
411                         return 0;
412                     }
413                     c->timeout(30); 
414                 }
415                 c->m_seqno = parent->m_seqno;
416                 if (c->m_server && c->m_server != this)
417                     c->m_server->m_client = 0;
418                 c->m_server = this;
419                 (parent->m_seqno)++;
420                 yaz_log (LOG_DEBUG, "get_client 1 %p %p", this, c);
421                 return c;
422             }
423         }
424     }
425     else if (!c)
426     {
427         // don't have a client session yet. Search in session w/o cookie
428         for (c = parent->m_clientPool; c; c = c->m_next)
429         {
430             assert (c->m_prev);
431             assert (*c->m_prev == c);
432             if (c->m_server == 0 && c->m_cookie == 0 && 
433                 c->m_waiting == 0 &&
434                 !strcmp(m_proxyTarget, c->get_hostname()))
435             {
436                 // found it in cache
437                 yaz_log (LOG_LOG, "%sREUSE %d %s",
438                          m_session_str, parent->m_seqno, c->get_hostname());
439                 
440                 c->m_seqno = parent->m_seqno;
441                 assert(c->m_server == 0);
442                 c->m_server = this;
443
444                 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
445                     c->set_APDU_yazlog(1);
446                 else
447                     c->set_APDU_yazlog(0);
448
449                 (parent->m_seqno)++;
450                 
451                 parent->pre_init();
452                 
453                 return c;
454             }
455         }
456     }
457     if (!m_client)
458     {
459         if (apdu->which != Z_APDU_initRequest)
460         {
461             yaz_log (LOG_LOG, "%sno init request as first PDU", m_session_str);
462             return 0;
463         }
464         Z_InitRequest *initRequest = apdu->u.initRequest;
465
466         if (!initRequest->idAuthentication)
467         {
468             if (m_proxy_authentication)
469             {
470                 initRequest->idAuthentication =
471                     (Z_IdAuthentication *)
472                     odr_malloc (odr_encode(),
473                                 sizeof(*initRequest->idAuthentication));
474                 initRequest->idAuthentication->which =
475                     Z_IdAuthentication_open;
476                 initRequest->idAuthentication->u.open =
477                     odr_strdup (odr_encode(), m_proxy_authentication);
478             }
479         }
480         // go through list of clients - and find the lowest/oldest one.
481         Yaz_ProxyClient *c_min = 0;
482         int min_seq = -1;
483         int no_of_clients = 0;
484         if (parent->m_clientPool)
485             yaz_log (LOG_DEBUG, "Existing sessions");
486         for (c = parent->m_clientPool; c; c = c->m_next)
487         {
488             yaz_log (LOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
489                                c->m_waiting, c->get_hostname(),
490                                c->m_cookie ? c->m_cookie : "");
491             no_of_clients++;
492             if (min_seq < 0 || c->m_seqno < min_seq)
493             {
494                 min_seq = c->m_seqno;
495                 c_min = c;
496             }
497         }
498         if (no_of_clients >= parent->m_max_clients)
499         {
500             c = c_min;
501             if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
502             {
503                 yaz_log (LOG_LOG, "%sMAXCLIENTS %d Destroy %d",
504                          m_session_str, parent->m_max_clients, c->m_seqno);
505                 if (c->m_server && c->m_server != this)
506                     delete c->m_server;
507                 c->m_server = 0;
508             }
509             else
510             {
511                 yaz_log (LOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
512                          m_session_str, parent->m_max_clients,
513                          c->m_seqno, parent->m_seqno, c->get_hostname());
514                 xfree (c->m_cookie);
515                 c->m_cookie = 0;
516                 if (cookie)
517                     c->m_cookie = xstrdup(cookie);
518                 c->m_seqno = parent->m_seqno;
519                 if (c->m_server && c->m_server != this)
520                 {
521                     c->m_server->m_client = 0;
522                     delete c->m_server;
523                 }
524                 (parent->m_seqno)++;
525                 c->m_target_idletime = m_target_idletime;
526                 c->timeout(m_target_idletime);
527                 
528                 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
529                     c->set_APDU_yazlog(1);
530                 else
531                     c->set_APDU_yazlog(0);
532
533                 return c;
534             }
535         }
536         else
537         {
538             yaz_log (LOG_LOG, "%sNEW %d %s",
539                      m_session_str, parent->m_seqno, m_proxyTarget);
540             c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
541             c->m_next = parent->m_clientPool;
542             if (c->m_next)
543                 c->m_next->m_prev = &c->m_next;
544             parent->m_clientPool = c;
545             c->m_prev = &parent->m_clientPool;
546         }
547
548         xfree (c->m_cookie);
549         c->m_cookie = 0;
550         if (cookie)
551             c->m_cookie = xstrdup(cookie);
552
553         c->m_seqno = parent->m_seqno;
554         c->m_init_flag = 0;
555         c->m_last_resultCount = 0;
556         c->m_last_ok = 0;
557         c->m_cache.clear();
558         c->m_sr_transform = 0;
559         c->m_waiting = 0;
560         c->m_resultSetStartPoint = 0;
561         (parent->m_seqno)++;
562         if (c->client(m_proxyTarget))
563         {
564             delete c;
565             return 0;
566         }
567         c->m_target_idletime = m_target_idletime;
568         c->timeout(30);
569
570         if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
571             c->set_APDU_yazlog(1);
572         else
573             c->set_APDU_yazlog(0);
574     }
575     yaz_log (LOG_DEBUG, "get_client 3 %p %p", this, c);
576     return c;
577 }
578
579 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
580 {
581     int i;
582     for (i = 0; i<num; i++)
583     {
584         oident *ent;
585         Z_DefaultDiagFormat *r;
586         Z_DiagRec *p = pp[i];
587         if (p->which != Z_DiagRec_defaultFormat)
588         {
589             yaz_log(LOG_LOG, "%sError no diagnostics", m_session_str);
590             return;
591         }
592         else
593             r = p->u.defaultFormat;
594         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
595             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
596             yaz_log(LOG_LOG, "%sError unknown diagnostic set", m_session_str);
597         switch (r->which)
598         {
599         case Z_DefaultDiagFormat_v2Addinfo:
600             yaz_log(LOG_LOG, "%sError %d %s:%s",
601                     m_session_str,
602                     *r->condition, diagbib1_str(*r->condition),
603                     r->u.v2Addinfo);
604             break;
605         case Z_DefaultDiagFormat_v3Addinfo:
606             yaz_log(LOG_LOG, "%sError %d %s:%s",
607                     m_session_str,
608                     *r->condition, diagbib1_str(*r->condition),
609                     r->u.v3Addinfo);
610             break;
611         }
612     }
613 }
614
615 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
616 {
617     if (!m_stylesheet_xsp || p->num_records <= 0)
618         return 0;  /* no XSLT to be done ... */
619
620     m_stylesheet_offset = 0;
621     m_stylesheet_nprl = p;
622     m_stylesheet_apdu = apdu;
623     timeout(0);
624     return 1;
625 }
626
627 void Yaz_Proxy::convert_xsl_delay()
628 {
629     Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
630     if (npr->which == Z_NamePlusRecord_databaseRecord)
631     {
632         Z_External *r = npr->u.databaseRecord;
633         if (r->which == Z_External_octet)
634         {
635             xmlDocPtr res, doc = xmlParseMemory(
636                 (char*) r->u.octet_aligned->buf,
637                 r->u.octet_aligned->len);
638             
639             yaz_log(LOG_LOG, "%sXSLT convert %d",
640                     m_session_str, m_stylesheet_offset);
641             res = xsltApplyStylesheet(m_stylesheet_xsp, doc, 0);
642             if (res)
643             {
644                 xmlChar *out_buf;
645                 int out_len;
646                 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
647                 
648                 m_stylesheet_nprl->records[m_stylesheet_offset]->
649                     u.databaseRecord = 
650                     z_ext_record(odr_encode(), VAL_TEXT_XML,
651                                  (char*) out_buf, out_len);
652                 xmlFree(out_buf);
653                 xmlFreeDoc(res);
654             }
655             xmlFreeDoc(doc);
656         }
657     }
658     m_stylesheet_offset++;
659     if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
660     {
661         m_stylesheet_nprl = 0;
662         if (m_stylesheet_xsp)
663             xsltFreeStylesheet(m_stylesheet_xsp);
664         m_stylesheet_xsp = 0;
665         timeout(m_client_idletime);
666         send_PDU_convert(m_stylesheet_apdu);
667     }
668     else
669         timeout(0);
670 }
671
672 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p)
673 {
674     int i;
675
676     yaz_marc_t mt = yaz_marc_create();
677     yaz_marc_xml(mt, YAZ_MARC_MARCXML);
678     for (i = 0; i < p->num_records; i++)
679     {
680         Z_NamePlusRecord *npr = p->records[i];
681         if (npr->which == Z_NamePlusRecord_databaseRecord)
682         {
683             Z_External *r = npr->u.databaseRecord;
684             if (r->which == Z_External_octet)
685             {
686                 int rlen;
687                 char *result;
688                 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
689                                         r->u.octet_aligned->len,
690                                         &result, &rlen))
691                 {
692                     yaz_iconv_t cd = yaz_iconv_open("UTF-8", "MARC-8");
693                     WRBUF wrbuf = wrbuf_alloc();
694                     
695                     char outbuf[120];
696                     size_t inbytesleft = rlen;
697                     const char *inp = result;
698                     while (cd && inbytesleft)
699                     {
700                         size_t outbytesleft = sizeof(outbuf);
701                         char *outp = outbuf;
702                         size_t r;
703                         
704                         r = yaz_iconv (cd, (char**) &inp,
705                                        &inbytesleft,
706                                        &outp, &outbytesleft);
707                         if (r == (size_t) (-1))
708                         {
709                             int e = yaz_iconv_error(cd);
710                             if (e != YAZ_ICONV_E2BIG)
711                             {
712                                 yaz_log(LOG_WARN, "conversion failure");
713                                 break;
714                             }
715                         }
716                         wrbuf_write(wrbuf, outbuf, outp - outbuf);
717                     }
718                     if (cd)
719                         yaz_iconv_close(cd);
720
721                     npr->u.databaseRecord = z_ext_record(odr_encode(),
722                                                          VAL_TEXT_XML,
723                                                          wrbuf_buf(wrbuf),
724                                                          wrbuf_len(wrbuf));
725                     wrbuf_free(wrbuf, 1);
726                 }
727             }
728         }
729     }
730     yaz_marc_destroy(mt);
731 }
732
733 void Yaz_Proxy::logtime()
734 {
735     if (m_time_tv.tv_sec)
736     {
737         struct timeval tv;
738         gettimeofday(&tv, 0);
739         long diff = (tv.tv_sec - m_time_tv.tv_sec)*1000000 +
740             (tv.tv_usec - m_time_tv.tv_usec);
741         if (diff >= 0)
742             yaz_log(LOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
743                     diff/1000000, (diff/1000)%1000);
744     }
745     m_time_tv.tv_sec = 0;
746     m_time_tv.tv_usec = 0;
747 }
748
749 int Yaz_Proxy::send_http_response(int code)
750 {
751     ODR o = odr_encode();
752     Z_GDU *gdu = z_get_HTTP_Response(o, code);
753     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
754     if (m_http_version)
755         hres->version = odr_strdup(o, m_http_version);
756     if (m_http_keepalive)
757         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
758     else
759         timeout(0);
760     
761     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
762     {
763         yaz_log (LOG_LOG, "%sSending %s to client", m_session_str,
764                  gdu_name(gdu));
765     }
766     int len;
767     int r = send_GDU(gdu, &len);
768     m_bytes_sent += len;
769     m_bw_stat.add_bytes(len);
770     logtime();
771     return r;
772 }
773
774 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu)
775 {
776     ODR o = odr_encode();
777     const char *ctype = "text/xml";
778     Z_GDU *gdu = z_get_HTTP_Response(o, 200);
779     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
780     if (m_http_version)
781         hres->version = odr_strdup(o, m_http_version);
782     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
783     if (m_http_keepalive)
784         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
785     else
786         timeout(0);
787
788     static Z_SOAP_Handler soap_handlers[2] = {
789 #if HAVE_XSLT
790         {"http://www.loc.gov/zing/srw/", 0,
791          (Z_SOAP_fun) yaz_srw_codec},
792 #endif
793         {0, 0, 0}
794     };
795     
796     Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
797     soap_package->which = Z_SOAP_generic;
798     soap_package->u.generic = 
799         (Z_SOAP_Generic *) odr_malloc(o,  sizeof(*soap_package->u.generic));
800     soap_package->u.generic->no = 0;
801     soap_package->u.generic->ns = soap_handlers[0].ns;
802     soap_package->u.generic->p = (void *) srw_pdu;
803     soap_package->ns = m_soap_ns;
804     z_soap_codec_enc_xsl(o, &soap_package,
805                          &hres->content_buf, &hres->content_len,
806                          soap_handlers, 0, m_s2z_stylesheet);
807     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
808     {
809         yaz_log (LOG_LOG, "%sSending %s to client", m_session_str,
810                  gdu_name(gdu));
811     }
812     int len;
813     int r = send_GDU(gdu, &len);
814     m_bytes_sent += len;
815     m_bw_stat.add_bytes(len);
816     logtime();
817     return r;
818 }
819
820 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
821 {
822     ODR o = odr_encode();
823     Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
824     Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
825
826     srw_res->num_diagnostics = 1;
827     srw_res->diagnostics = (Z_SRW_diagnostic *)
828         odr_malloc(o, sizeof(*srw_res->diagnostics));
829     yaz_mk_std_diagnostic(o, srw_res->diagnostics, srw_error, add);
830     return send_srw_response(srw_pdu);
831 }
832
833 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
834                              Z_DefaultDiagFormat *ddf)
835 {
836     int bib1_code = *ddf->condition;
837     if (bib1_code == 109)
838         return 404;
839     srw_res->num_diagnostics = 1;
840     srw_res->diagnostics = (Z_SRW_diagnostic *)
841         odr_malloc(o, sizeof(*srw_res->diagnostics));
842     yaz_mk_std_diagnostic(o, srw_res->diagnostics,
843                           yaz_diag_bib1_to_srw(*ddf->condition), 
844                           ddf->u.v2Addinfo);
845     return 0;
846 }
847
848 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
849 {
850     ODR o = odr_encode();
851     Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
852     Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
853
854     srw_res->numberOfRecords = odr_intdup (o, hits);
855     if (records && records->which == Z_Records_DBOSD)
856     {
857         srw_res->num_records =
858             records->u.databaseOrSurDiagnostics->num_records;
859         int i;
860         srw_res->records = (Z_SRW_record *)
861             odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
862         for (i = 0; i < srw_res->num_records; i++)
863         {
864             Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
865             if (npr->which != Z_NamePlusRecord_databaseRecord)
866             {
867                 srw_res->records[i].recordSchema = "diagnostic";
868                 srw_res->records[i].recordPacking = m_s2z_packing;
869                 srw_res->records[i].recordData_buf = "67";
870                 srw_res->records[i].recordData_len = 2;
871                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
872                 continue;
873             }
874             Z_External *r = npr->u.databaseRecord;
875             oident *ent = oid_getentbyoid(r->direct_reference);
876             if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
877             {
878                 srw_res->records[i].recordSchema = m_schema;
879                 srw_res->records[i].recordPacking = m_s2z_packing;
880                 srw_res->records[i].recordData_buf = (char*) 
881                     r->u.octet_aligned->buf;
882                 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
883                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
884             }
885             else
886             {
887                 srw_res->records[i].recordSchema = "diagnostic";
888                 srw_res->records[i].recordPacking = m_s2z_packing;
889                 srw_res->records[i].recordData_buf = "67";
890                 srw_res->records[i].recordData_len = 2;
891                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
892             }
893         }
894     }
895     if (records && records->which == Z_Records_NSD)
896     {
897         int http_code;
898         http_code = z_to_srw_diag(odr_encode(), srw_res,
899                                    records->u.nonSurrogateDiagnostic);
900         if (http_code)
901             return send_http_response(http_code);
902     }
903     return send_srw_response(srw_pdu);
904     
905 }
906
907 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
908                                         int num_diagnostics)
909 {
910     Yaz_ProxyConfig *cfg = check_reconfigure();
911     if (cfg)
912     {
913         int len;
914         char *b = cfg->get_explain(odr_encode(), 0 /* target */,
915                                    m_s2z_database, &len);
916         if (b)
917         {
918             Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
919             Z_SRW_explainResponse *er = res->u.explain_response;
920
921             er->record.recordData_buf = b;
922             er->record.recordData_len = len;
923             er->record.recordPacking = m_s2z_packing;
924             er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
925
926             er->diagnostics = diagnostics;
927             er->num_diagnostics = num_diagnostics;
928             return send_srw_response(res);
929         }
930     }
931     return send_http_response(404);
932 }
933
934 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
935 {
936     if (m_http_version)
937     {
938         if (apdu->which == Z_APDU_initResponse)
939         {
940             Z_InitResponse *res = apdu->u.initResponse;
941             if (*res->result == 0)
942             {
943                 send_to_srw_client_error(3, 0);
944             }
945             else if (!m_s2z_search_apdu)
946             {
947                 send_srw_explain_response(0, 0);
948             }
949             else
950             {
951                 handle_incoming_Z_PDU(m_s2z_search_apdu);
952             }
953         }
954         else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
955         {
956             m_s2z_search_apdu = 0;
957             Z_SearchResponse *res = apdu->u.searchResponse;
958             m_s2z_hit_count = *res->resultCount;
959             if (res->records && res->records->which == Z_Records_NSD)
960             {
961                 send_to_srw_client_ok(0, res->records, 1);
962             }
963             else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
964             {
965                 // adjust 
966                 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
967                 
968                 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
969                 {
970                     if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
971                         > m_s2z_hit_count)
972                         *pr->numberOfRecordsRequested =
973                             1 + m_s2z_hit_count - *pr->resultSetStartPoint;
974                 }
975                 handle_incoming_Z_PDU(m_s2z_present_apdu);
976             }
977             else
978             {
979                 m_s2z_present_apdu = 0;
980                 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
981             }
982         }
983         else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
984         {
985             int start = 
986                 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
987
988             m_s2z_present_apdu = 0;
989             Z_PresentResponse *res = apdu->u.presentResponse;
990             send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
991         }
992     }
993     else
994     {
995         int len = 0;
996         if (m_log_mask & PROXY_LOG_REQ_CLIENT)
997             yaz_log (LOG_LOG, "%sSending %s to client", m_session_str,
998                      apdu_name(apdu));
999         int r = send_Z_PDU(apdu, &len);
1000         m_bytes_sent += len;
1001         m_bw_stat.add_bytes(len);
1002         logtime();
1003         return r;
1004     }
1005     return 0;
1006 }
1007
1008 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1009 {
1010     int kill_session = 0;
1011     Z_ReferenceId **new_id = get_referenceIdP(apdu);
1012
1013     if (new_id && m_referenceId)
1014         *new_id = m_referenceId;
1015     
1016     if (apdu->which == Z_APDU_searchResponse)
1017     {
1018         Z_SearchResponse *sr = apdu->u.searchResponse;
1019         Z_Records *p = sr->records;
1020         if (p && p->which == Z_Records_NSD)
1021         {
1022             Z_DiagRec dr, *dr_p = &dr;
1023             dr.which = Z_DiagRec_defaultFormat;
1024             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1025
1026             *sr->searchStatus = 0;
1027             display_diagrecs(&dr_p, 1);
1028         }
1029         else
1030         {
1031             if (p && p->which == Z_Records_DBOSD)
1032             {
1033                 if (m_marcxml_flag)
1034                     convert_to_marcxml(p->u.databaseOrSurDiagnostics);
1035                 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1036                     return 0;
1037                     
1038             }
1039             if (sr->resultCount)
1040             {
1041                 yaz_log(LOG_LOG, "%s%d hits", m_session_str,
1042                         *sr->resultCount);
1043                 if (*sr->resultCount < 0)
1044                 {
1045                     m_invalid_session = 1;
1046                     kill_session = 1;
1047
1048                     *sr->searchStatus = 0;
1049                     sr->records =
1050                         create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1051                     *sr->resultCount = 0;
1052                 }
1053             }
1054         }
1055     }
1056     else if (apdu->which == Z_APDU_presentResponse)
1057     {
1058         Z_PresentResponse *sr = apdu->u.presentResponse;
1059         Z_Records *p = sr->records;
1060         if (p && p->which == Z_Records_NSD)
1061         {
1062             Z_DiagRec dr, *dr_p = &dr;
1063             dr.which = Z_DiagRec_defaultFormat;
1064             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1065             if (*sr->presentStatus == Z_PresentStatus_success)
1066                 *sr->presentStatus = Z_PresentStatus_failure;
1067             display_diagrecs(&dr_p, 1);
1068         }
1069         if (p && p->which == Z_Records_DBOSD)
1070         {
1071             if (m_marcxml_flag)
1072                 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
1073             if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1074                 return 0;
1075         }
1076     }
1077     else if (apdu->which == Z_APDU_initResponse)
1078     {
1079         if (m_initRequest_options)
1080         {
1081             Z_Options *nopt = 
1082                 (Odr_bitmask *)odr_malloc(odr_encode(),
1083                                           sizeof(Odr_bitmask));
1084             ODR_MASK_ZERO(nopt);
1085
1086             int i;
1087             for (i = 0; i<24; i++)
1088                 if (ODR_MASK_GET(m_initRequest_options, i) &&
1089                     ODR_MASK_GET(apdu->u.initResponse->options, i))
1090                     ODR_MASK_SET(nopt, i);
1091             apdu->u.initResponse->options = nopt;           
1092         }
1093         if (m_initRequest_version)
1094         {
1095             Z_ProtocolVersion *nopt = 
1096                 (Odr_bitmask *)odr_malloc(odr_encode(),
1097                                           sizeof(Odr_bitmask));
1098             ODR_MASK_ZERO(nopt);
1099
1100             int i;
1101             for (i = 0; i<8; i++)
1102                 if (ODR_MASK_GET(m_initRequest_version, i) &&
1103                     ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1104                     ODR_MASK_SET(nopt, i);
1105             apdu->u.initResponse->protocolVersion = nopt;           
1106         }
1107         apdu->u.initResponse->preferredMessageSize =
1108             odr_intdup(odr_encode(),
1109                        m_client->m_initResponse_preferredMessageSize >
1110                        m_initRequest_preferredMessageSize ?
1111                        m_initRequest_preferredMessageSize :
1112                        m_client->m_initResponse_preferredMessageSize);
1113         apdu->u.initResponse->maximumRecordSize =
1114             odr_intdup(odr_encode(),
1115                        m_client->m_initResponse_maximumRecordSize >
1116                        m_initRequest_maximumRecordSize ?
1117                        m_initRequest_maximumRecordSize :
1118                        m_client->m_initResponse_maximumRecordSize);
1119     }
1120     int r = send_PDU_convert(apdu);
1121     if (r)
1122         return r;
1123     if (kill_session)
1124     {
1125         delete m_client;
1126         m_client = 0;
1127         m_parent->pre_init();
1128     }
1129     return r;
1130 }
1131
1132 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1133 {
1134     int len = 0;
1135     const char *apdu_name_tmp = apdu_name(apdu);
1136     int r = send_Z_PDU(apdu, &len);
1137     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1138         yaz_log (LOG_LOG, "%sSending %s to %s %d bytes",
1139                  get_session_str(),
1140                  apdu_name_tmp, get_hostname(), len);
1141     m_bytes_sent += len;
1142     return r;
1143 }
1144
1145 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1146 {
1147     if (apdu->which == Z_APDU_presentRequest)
1148     {
1149         Z_PresentRequest *pr = apdu->u.presentRequest;
1150         int toget = *pr->numberOfRecordsRequested;
1151         int start = *pr->resultSetStartPoint;
1152
1153         yaz_log(LOG_LOG, "%sPresent %s %d+%d", m_session_str,
1154                 pr->resultSetId, start, toget);
1155
1156         if (*m_parent->m_optimize == '0')
1157             return apdu;
1158
1159         if (!m_client->m_last_resultSetId)
1160         {
1161             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1162             new_apdu->u.presentResponse->records =
1163                 create_nonSurrogateDiagnostics(odr_encode(), 30,
1164                                                pr->resultSetId);
1165             send_to_client(new_apdu);
1166             return 0;
1167         }
1168         if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1169         {
1170             if (start+toget-1 > m_client->m_last_resultCount)
1171             {
1172                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1173                 new_apdu->u.presentResponse->records =
1174                     create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
1175                 send_to_client(new_apdu);
1176                 return 0;
1177             }
1178             Z_NamePlusRecordList *npr;
1179             if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1180                                           pr->preferredRecordSyntax,
1181                                           pr->recordComposition))
1182             {
1183                 yaz_log (LOG_LOG, "%sReturned cached records for present request", 
1184                          m_session_str);
1185                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1186                 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1187                 
1188                 new_apdu->u.presentResponse->numberOfRecordsReturned
1189                     = odr_intdup(odr_encode(), toget);
1190                                                                  
1191                 new_apdu->u.presentResponse->records = (Z_Records*)
1192                     odr_malloc(odr_encode(), sizeof(Z_Records));
1193                 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1194                 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1195                 new_apdu->u.presentResponse->nextResultSetPosition =
1196                     odr_intdup(odr_encode(), start+toget);
1197
1198                 send_to_client(new_apdu);
1199                 return 0;
1200             }
1201         }
1202     }
1203
1204     if (apdu->which != Z_APDU_searchRequest)
1205         return apdu;
1206     Z_SearchRequest *sr = apdu->u.searchRequest;
1207     Yaz_Z_Query *this_query = new Yaz_Z_Query;
1208     Yaz_Z_Databases this_databases;
1209
1210     this_databases.set(sr->num_databaseNames, (const char **)
1211                        sr->databaseNames);
1212     
1213     this_query->set_Z_Query(sr->query);
1214
1215     char query_str[120];
1216     this_query->print(query_str, sizeof(query_str)-1);
1217     yaz_log(LOG_LOG, "%sSearch %s", m_session_str, query_str);
1218
1219     if (*m_parent->m_optimize != '0' &&
1220         m_client->m_last_ok && m_client->m_last_query &&
1221         m_client->m_last_query->match(this_query) &&
1222         !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1223         m_client->m_last_databases.match(this_databases))
1224     {
1225         delete this_query;
1226         if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1227             m_client->m_last_resultCount < *sr->largeSetLowerBound)
1228         {
1229             Z_NamePlusRecordList *npr;
1230             int toget = *sr->mediumSetPresentNumber;
1231             Z_RecordComposition *comp = 0;
1232
1233             if (toget > m_client->m_last_resultCount)
1234                 toget = m_client->m_last_resultCount;
1235             
1236             if (sr->mediumSetElementSetNames)
1237             {
1238                 comp = (Z_RecordComposition *)
1239                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1240                 comp->which = Z_RecordComp_simple;
1241                 comp->u.simple = sr->mediumSetElementSetNames;
1242             }
1243  
1244             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1245                                           sr->preferredRecordSyntax, comp))
1246             {
1247                 yaz_log (LOG_LOG, "%sReturned cached records for medium set",
1248                          m_session_str);
1249                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1250                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1251                 new_apdu->u.searchResponse->resultCount =
1252                     &m_client->m_last_resultCount;
1253                 
1254                 new_apdu->u.searchResponse->numberOfRecordsReturned
1255                     = odr_intdup(odr_encode(), toget);
1256                                                         
1257                 new_apdu->u.searchResponse->presentStatus =
1258                     odr_intdup(odr_encode(), Z_PresentStatus_success);
1259                 new_apdu->u.searchResponse->records = (Z_Records*)
1260                     odr_malloc(odr_encode(), sizeof(Z_Records));
1261                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1262                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1263                 new_apdu->u.searchResponse->nextResultSetPosition =
1264                     odr_intdup(odr_encode(), toget+1);
1265                 send_to_client(new_apdu);
1266                 return 0;
1267             }
1268             else
1269             {
1270                 // medium Set
1271                 // send present request (medium size)
1272                 yaz_log (LOG_LOG, "%sOptimizing search for medium set",
1273                          m_session_str);
1274
1275                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1276                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1277                 pr->referenceId = sr->referenceId;
1278                 pr->resultSetId = sr->resultSetName;
1279                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1280                 *pr->numberOfRecordsRequested = toget;
1281                 pr->recordComposition = comp;
1282                 m_client->m_sr_transform = 1;
1283                 return new_apdu;
1284             }
1285         }
1286         else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1287             m_client->m_last_resultCount <= 0)
1288         {
1289             // large set. Return pseudo-search response immediately
1290             yaz_log (LOG_LOG, "%sOptimizing search for large set",
1291                      m_session_str);
1292             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1293             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1294             new_apdu->u.searchResponse->resultCount =
1295                 &m_client->m_last_resultCount;
1296             send_to_client(new_apdu);
1297             return 0;
1298         }
1299         else
1300         {
1301             Z_NamePlusRecordList *npr;
1302             int toget = m_client->m_last_resultCount;
1303             Z_RecordComposition *comp = 0;
1304             // small set
1305             // send a present request (small set)
1306             
1307             if (sr->smallSetElementSetNames)
1308             {
1309                 comp = (Z_RecordComposition *)
1310                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1311                 comp->which = Z_RecordComp_simple;
1312                 comp->u.simple = sr->smallSetElementSetNames;
1313             }
1314
1315             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1316                                           sr->preferredRecordSyntax, comp))
1317             {
1318                 yaz_log (LOG_LOG, "%sReturned cached records for small set",
1319                          m_session_str);
1320                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1321                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1322                 new_apdu->u.searchResponse->resultCount =
1323                     &m_client->m_last_resultCount;
1324                 
1325                 new_apdu->u.searchResponse->numberOfRecordsReturned
1326                     = odr_intdup(odr_encode(), toget);
1327                                                                  
1328                 new_apdu->u.searchResponse->presentStatus =
1329                     odr_intdup(odr_encode(), Z_PresentStatus_success);
1330                 new_apdu->u.searchResponse->records = (Z_Records*)
1331                     odr_malloc(odr_encode(), sizeof(Z_Records));
1332                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1333                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1334                 new_apdu->u.searchResponse->nextResultSetPosition =
1335                     odr_intdup(odr_encode(), toget+1);
1336                 send_to_client(new_apdu);
1337                 return 0;
1338             }
1339             else
1340             {
1341                 yaz_log (LOG_LOG, "%sOptimizing search for small set",
1342                          m_session_str);
1343                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1344                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1345                 pr->referenceId = sr->referenceId;
1346                 pr->resultSetId = sr->resultSetName;
1347                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1348                 *pr->numberOfRecordsRequested = toget;
1349                 pr->recordComposition = comp;
1350                 m_client->m_sr_transform = 1;
1351                 return new_apdu;
1352             }
1353         }
1354     }
1355     else  // query doesn't match
1356     {
1357         delete m_client->m_last_query;
1358         m_client->m_last_query = this_query;
1359         m_client->m_last_ok = 0;
1360         m_client->m_cache.clear();
1361         m_client->m_resultSetStartPoint = 0;
1362
1363         xfree (m_client->m_last_resultSetId);
1364         m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1365
1366         m_client->m_last_databases.set(sr->num_databaseNames,
1367                                        (const char **) sr->databaseNames);
1368     }
1369     return apdu;
1370 }
1371
1372
1373 void Yaz_Proxy::inc_request_no()
1374 {
1375     char *cp = strchr(m_session_str, ' ');
1376     m_request_no++;
1377     if (cp)
1378         sprintf(cp+1, "%d ", m_request_no);
1379 }
1380
1381 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1382 {
1383     inc_request_no();
1384
1385     m_bytes_recv += len;
1386     
1387     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
1388         yaz_log (LOG_DEBUG, "%sReceiving %s from client %d bytes",
1389                  m_session_str, gdu_name(apdu), len);
1390
1391     if (m_bw_hold_PDU)     // double incoming PDU. shutdown now.
1392         shutdown();
1393
1394     m_bw_stat.add_bytes(len);
1395     m_pdu_stat.add_bytes(1);
1396
1397     gettimeofday(&m_time_tv, 0);
1398
1399     int bw_total = m_bw_stat.get_total();
1400     int pdu_total = m_pdu_stat.get_total();
1401
1402     int reduce = 0;
1403     if (m_bw_max)
1404     {
1405         if (bw_total > m_bw_max)
1406         {
1407             reduce = (bw_total/m_bw_max);
1408         }
1409     }
1410     if (m_pdu_max)
1411     {
1412         if (pdu_total > m_pdu_max)
1413         {
1414             int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1415             reduce = (reduce > nreduce) ? reduce : nreduce;
1416         }
1417     }
1418     if (reduce)  
1419     {
1420         yaz_log(LOG_LOG, "%sdelay=%d bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1421                 m_session_str, reduce, bw_total, pdu_total,
1422                 m_bw_max, m_pdu_max);
1423         
1424         m_bw_hold_PDU = apdu;  // save PDU and signal "on hold"
1425         timeout(reduce);       // call us reduce seconds later
1426     }
1427     else if (apdu->which == Z_GDU_Z3950)
1428         handle_incoming_Z_PDU(apdu->u.z3950);
1429     else if (apdu->which == Z_GDU_HTTP_Request)
1430         handle_incoming_HTTP(apdu->u.HTTP_Request);
1431 }
1432
1433 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
1434 {
1435     if (m_max_record_retrieve)
1436     {
1437         if (apdu->which == Z_APDU_presentRequest)
1438         {
1439             Z_PresentRequest *pr = apdu->u.presentRequest;
1440             if (pr->numberOfRecordsRequested && 
1441                 *pr->numberOfRecordsRequested > m_max_record_retrieve)
1442                 *pr->numberOfRecordsRequested = m_max_record_retrieve;
1443         }
1444     }
1445 }
1446
1447 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
1448                                                      int error,
1449                                                      const char *addinfo)
1450 {
1451     Z_Records *rec = (Z_Records *)
1452         odr_malloc (odr, sizeof(*rec));
1453     int *err = (int *)
1454         odr_malloc (odr, sizeof(*err));
1455     Z_DiagRec *drec = (Z_DiagRec *)
1456         odr_malloc (odr, sizeof(*drec));
1457     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1458         odr_malloc (odr, sizeof(*dr));
1459     *err = error;
1460     rec->which = Z_Records_NSD;
1461     rec->u.nonSurrogateDiagnostic = dr;
1462     dr->diagnosticSetId =
1463         yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
1464     dr->condition = err;
1465     dr->which = Z_DefaultDiagFormat_v2Addinfo;
1466     dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1467     return rec;
1468 }
1469
1470 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
1471 {
1472     if (apdu->which == Z_APDU_searchRequest &&
1473         apdu->u.searchRequest->query &&
1474         apdu->u.searchRequest->query->which == Z_Query_type_104 &&
1475         apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
1476     {
1477         Z_RPNQuery *rpnquery = 0;
1478         Z_SearchRequest *sr = apdu->u.searchRequest;
1479         char *addinfo = 0;
1480         
1481         yaz_log(LOG_LOG, "%sCQL: %s", m_session_str,
1482                 sr->query->u.type_104->u.cql);
1483
1484         int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
1485                                           &rpnquery, odr_encode(),
1486                                           &addinfo);
1487         if (r == -3)
1488             yaz_log(LOG_LOG, "%sNo CQL to RPN table", m_session_str);
1489         else if (r)
1490         {
1491             yaz_log(LOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
1492             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1493
1494             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1495             new_apdu->u.searchResponse->records =
1496                 create_nonSurrogateDiagnostics(odr_encode(),
1497                                                yaz_diag_srw_to_bib1(r),
1498                                                addinfo);
1499             *new_apdu->u.searchResponse->searchStatus = 0;
1500
1501             send_to_client(new_apdu);
1502
1503             return 0;
1504         }
1505         else
1506         {
1507             sr->query->which = Z_Query_type_1;
1508             sr->query->u.type_1 = rpnquery;
1509         }
1510         return apdu;
1511     }
1512     return apdu;
1513 }
1514
1515 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
1516 {
1517     if (apdu->which == Z_APDU_searchRequest)
1518     {
1519         Z_SearchRequest *sr = apdu->u.searchRequest;
1520         int err = 0;
1521         char *addinfo = 0;
1522
1523         Yaz_ProxyConfig *cfg = check_reconfigure();
1524         if (cfg)
1525             err = cfg->check_query(odr_encode(), m_default_target,
1526                                    sr->query, &addinfo);
1527         if (err)
1528         {
1529             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1530
1531             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1532             new_apdu->u.searchResponse->records =
1533                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1534             *new_apdu->u.searchResponse->searchStatus = 0;
1535
1536             send_to_client(new_apdu);
1537
1538             return 0;
1539         }
1540     }
1541     return apdu;
1542 }
1543
1544 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
1545 {
1546     m_marcxml_flag = 0;
1547     if (apdu->which == Z_APDU_searchRequest)
1548     {
1549         Z_SearchRequest *sr = apdu->u.searchRequest;
1550         int err = 0;
1551         char *addinfo = 0;
1552         Yaz_ProxyConfig *cfg = check_reconfigure();
1553
1554         Z_RecordComposition rc_temp, *rc = 0;
1555         if (sr->smallSetElementSetNames)
1556         {
1557             rc_temp.which = Z_RecordComp_simple;
1558             rc_temp.u.simple = sr->smallSetElementSetNames;
1559             rc = &rc_temp;
1560         }
1561
1562         char *stylesheet_name = 0;
1563         if (cfg)
1564             err = cfg->check_syntax(odr_encode(),
1565                                     m_default_target,
1566                                     sr->preferredRecordSyntax, rc,
1567                                     &addinfo, &stylesheet_name, &m_schema);
1568         if (stylesheet_name)
1569         {
1570             if (m_stylesheet_xsp)
1571                 xsltFreeStylesheet(m_stylesheet_xsp);
1572             m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
1573                                                        stylesheet_name);
1574             m_stylesheet_offset = 0;
1575             xfree(stylesheet_name);
1576         }
1577         if (err == -1)
1578         {
1579             sr->preferredRecordSyntax =
1580                 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN, VAL_USMARC);
1581             m_marcxml_flag = 1;
1582         }
1583         else if (err)
1584         {
1585             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1586             
1587             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1588             new_apdu->u.searchResponse->records =
1589                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1590             *new_apdu->u.searchResponse->searchStatus = 0;
1591             
1592             send_to_client(new_apdu);
1593             
1594             return 0;
1595         }
1596     }
1597     else if (apdu->which == Z_APDU_presentRequest)
1598     {
1599         Z_PresentRequest *pr = apdu->u.presentRequest;
1600         int err = 0;
1601         char *addinfo = 0;
1602         Yaz_ProxyConfig *cfg = check_reconfigure();
1603
1604         char *stylesheet_name = 0;
1605         if (cfg)
1606             err = cfg->check_syntax(odr_encode(), m_default_target,
1607                                     pr->preferredRecordSyntax,
1608                                     pr->recordComposition,
1609                                     &addinfo, &stylesheet_name, &m_schema);
1610         if (stylesheet_name)
1611         {
1612             if (m_stylesheet_xsp)
1613                 xsltFreeStylesheet(m_stylesheet_xsp);
1614             m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
1615                                                        stylesheet_name);
1616             m_stylesheet_offset = 0;
1617             xfree(stylesheet_name);
1618         }
1619         if (err == -1)
1620         {
1621             pr->preferredRecordSyntax =
1622                 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN, VAL_USMARC);
1623             m_marcxml_flag = 1;
1624         }
1625         else if (err)
1626         {
1627             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1628             
1629             new_apdu->u.presentResponse->referenceId = pr->referenceId;
1630             new_apdu->u.presentResponse->records =
1631                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1632             *new_apdu->u.presentResponse->presentStatus =
1633                 Z_PresentStatus_failure;
1634             
1635             send_to_client(new_apdu);
1636             
1637             return 0;
1638         }
1639     }
1640     return apdu;
1641 }
1642
1643 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
1644 {
1645     if (!schema)
1646         return 0;
1647     Z_ElementSetNames *esn = (Z_ElementSetNames *)
1648         odr_malloc(o, sizeof(Z_ElementSetNames));
1649     esn->which = Z_ElementSetNames_generic;
1650     esn->u.generic = odr_strdup(o, schema);
1651     return esn;
1652 }
1653
1654 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
1655 {
1656     if (m_s2z_odr_init)
1657     {
1658         odr_destroy(m_s2z_odr_init);
1659         m_s2z_odr_init = 0;
1660     }
1661     if (m_s2z_odr_search)
1662     {
1663         odr_destroy(m_s2z_odr_search);
1664         m_s2z_odr_search = 0;
1665     }
1666
1667     m_http_keepalive = 0;
1668     m_http_version = 0;
1669     if (!strcmp(hreq->version, "1.0")) 
1670     {
1671         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1672         if (v && !strcmp(v, "Keep-Alive"))
1673             m_http_keepalive = 1;
1674         else
1675             m_http_keepalive = 0;
1676         m_http_version = "1.0";
1677     }
1678     else
1679     {
1680         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1681         if (v && !strcmp(v, "close"))
1682             m_http_keepalive = 0;
1683         else
1684             m_http_keepalive = 1;
1685         m_http_version = "1.1";
1686     }
1687
1688     Z_SRW_PDU *srw_pdu = 0;
1689     Z_SOAP *soap_package = 0;
1690     char *charset = 0;
1691     Z_SRW_diagnostic *diagnostic = 0;
1692     int num_diagnostic = 0;
1693     if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
1694                        &charset) == 0
1695         || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
1696                           &charset, &diagnostic, &num_diagnostic) == 0)
1697     {
1698         m_s2z_odr_init = odr_createmem(ODR_ENCODE);
1699         m_s2z_odr_search = odr_createmem(ODR_ENCODE);
1700         m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
1701         m_s2z_init_apdu = 0;
1702         m_s2z_search_apdu = 0;
1703         m_s2z_present_apdu = 0;
1704
1705         m_s2z_stylesheet = 0;
1706         
1707         if (srw_pdu->which == Z_SRW_searchRetrieve_request)
1708         {
1709             Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
1710
1711             m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
1712             // recordXPath unsupported.
1713             if (srw_req->recordXPath)
1714             {
1715                 yaz_add_srw_diagnostic(odr_decode(),
1716                                        &diagnostic, &num_diagnostic,
1717                                        72, 0);
1718             }
1719             // must have a query
1720             if (!srw_req->query.cql)
1721             {
1722                 yaz_add_srw_diagnostic(odr_decode(),
1723                                        &diagnostic, &num_diagnostic,
1724                                        7, "query");
1725             }
1726             // sort unsupported
1727             if (srw_req->sort_type != Z_SRW_sort_type_none)
1728             {
1729                 yaz_add_srw_diagnostic(odr_decode(),
1730                                        &diagnostic, &num_diagnostic,
1731                                        80, 0);
1732             }
1733             // save stylesheet
1734             if (srw_req->stylesheet)
1735                 m_s2z_stylesheet =
1736                     odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
1737                                               
1738             // set packing for response records ..
1739             if (srw_req->recordPacking &&
1740                 !strcmp(srw_req->recordPacking, "xml"))
1741                 m_s2z_packing = Z_SRW_recordPacking_XML;
1742             else
1743                 m_s2z_packing = Z_SRW_recordPacking_string;
1744
1745             if (num_diagnostic)
1746             {
1747                 Z_SRW_PDU *srw_pdu =
1748                     yaz_srw_get(odr_encode(),
1749                                 Z_SRW_searchRetrieve_response);
1750                 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1751                 
1752                 srw_res->diagnostics = diagnostic;
1753                 srw_res->num_diagnostics = num_diagnostic;
1754                 send_srw_response(srw_pdu);
1755                 return;
1756             }
1757
1758             // prepare search PDU
1759             m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
1760                                           Z_APDU_searchRequest);
1761             Z_SearchRequest *z_searchRequest =
1762                 m_s2z_search_apdu->u.searchRequest;
1763
1764             z_searchRequest->num_databaseNames = 1;
1765             z_searchRequest->databaseNames = (char**)
1766                 odr_malloc(m_s2z_odr_search, sizeof(char *));
1767             z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
1768                                                            srw_req->database);
1769             
1770             // query transformation
1771             Z_Query *query = (Z_Query *)
1772                 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
1773             z_searchRequest->query = query;
1774             
1775             if (srw_req->query_type == Z_SRW_query_type_cql)
1776             {
1777                 Z_External *ext = (Z_External *) 
1778                     odr_malloc(m_s2z_odr_search, sizeof(*ext));
1779                 ext->direct_reference = 
1780                     odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
1781                 ext->indirect_reference = 0;
1782                 ext->descriptor = 0;
1783                 ext->which = Z_External_CQL;
1784                 ext->u.cql = srw_req->query.cql;
1785                 
1786                 query->which = Z_Query_type_104;
1787                 query->u.type_104 =  ext;
1788             }
1789             else if (srw_req->query_type == Z_SRW_query_type_pqf)
1790             {
1791                 Z_RPNQuery *RPNquery;
1792                 YAZ_PQF_Parser pqf_parser;
1793                 
1794                 pqf_parser = yaz_pqf_create ();
1795                 
1796                 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
1797                                           srw_req->query.pqf);
1798                 if (!RPNquery)
1799                 {
1800                     const char *pqf_msg;
1801                     size_t off;
1802                     int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1803                     yaz_log(LOG_LOG, "%*s^\n", off+4, "");
1804                     yaz_log(LOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
1805                     
1806                     send_to_srw_client_error(10, 0);
1807                     return;
1808                 }
1809                 query->which = Z_Query_type_1;
1810                 query->u.type_1 =  RPNquery;
1811                 
1812                 yaz_pqf_destroy (pqf_parser);
1813             }
1814             else
1815             {
1816                 send_to_srw_client_error(7, "query");
1817                 return;
1818             }
1819
1820             // present
1821             m_s2z_present_apdu = 0;
1822             int max = 0;
1823             if (srw_req->maximumRecords)
1824                 max = *srw_req->maximumRecords;
1825             int start = 1;
1826             if (srw_req->startRecord)
1827                 start = *srw_req->startRecord;
1828             if (max > 0)
1829             {
1830                 // Some backend, such as Voyager doesn't honor piggyback
1831                 // So we use present always (0 &&).
1832                 if (0 && start <= 1)  // Z39.50 piggyback
1833                 {
1834                     *z_searchRequest->smallSetUpperBound = max;
1835                     *z_searchRequest->mediumSetPresentNumber = max;
1836                     *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
1837
1838                     z_searchRequest->preferredRecordSyntax =
1839                         yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
1840                                                VAL_TEXT_XML);
1841                     if (srw_req->recordSchema)
1842                     {
1843                         z_searchRequest->smallSetElementSetNames =
1844                             z_searchRequest->mediumSetElementSetNames =
1845                             mk_esn_from_schema(m_s2z_odr_search,
1846                                                srw_req->recordSchema);
1847                     }
1848                 }
1849                 else   // Z39.50 present
1850                 {
1851                     m_s2z_present_apdu = zget_APDU(m_s2z_odr_search, 
1852                                                    Z_APDU_presentRequest);
1853                     Z_PresentRequest *z_presentRequest = 
1854                         m_s2z_present_apdu->u.presentRequest;
1855                     *z_presentRequest->resultSetStartPoint = start;
1856                     *z_presentRequest->numberOfRecordsRequested = max;
1857                     z_presentRequest->preferredRecordSyntax =
1858                         yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
1859                                                VAL_TEXT_XML);
1860                     if (srw_req->recordSchema)
1861                     {
1862                         z_presentRequest->recordComposition =
1863                             (Z_RecordComposition *)
1864                             odr_malloc(m_s2z_odr_search,
1865                                        sizeof(Z_RecordComposition));
1866                         z_presentRequest->recordComposition->which = 
1867                             Z_RecordComp_simple;                    
1868                         z_presentRequest->recordComposition->u.simple =
1869                             mk_esn_from_schema(m_s2z_odr_search,
1870                                                srw_req->recordSchema);
1871                     }
1872                 }
1873             }
1874             if (!m_client)
1875             {
1876                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
1877                                             Z_APDU_initRequest);
1878                 
1879                 // prevent m_initRequest_apdu memory from being grabbed
1880                 // in Yaz_Proxy::handle_incoming_Z_PDU
1881                 m_initRequest_apdu = m_s2z_init_apdu;
1882                 handle_incoming_Z_PDU(m_s2z_init_apdu);
1883                 return;
1884             }
1885             else
1886             {
1887                 handle_incoming_Z_PDU(m_s2z_search_apdu);
1888                 return;
1889             }
1890         }
1891         else if (srw_pdu->which == Z_SRW_explain_request)
1892         {
1893             Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
1894
1895             m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
1896
1897             // save stylesheet
1898             if (srw_req->stylesheet)
1899                 m_s2z_stylesheet =
1900                     odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
1901
1902             if (srw_req->recordPacking &&
1903                 !strcmp(srw_req->recordPacking, "xml"))
1904                 m_s2z_packing = Z_SRW_recordPacking_XML;
1905             else
1906                 m_s2z_packing = Z_SRW_recordPacking_string;
1907
1908             if (num_diagnostic)
1909             {
1910                 send_srw_explain_response(diagnostic, num_diagnostic);
1911                 return;
1912             }
1913
1914             if (!m_client)
1915             {
1916                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
1917                                             Z_APDU_initRequest);
1918                 
1919                 // prevent m_initRequest_apdu memory from being grabbed
1920                 // in Yaz_Proxy::handle_incoming_Z_PDU
1921                 m_initRequest_apdu = m_s2z_init_apdu;
1922                 handle_incoming_Z_PDU(m_s2z_init_apdu);
1923             }
1924             else
1925                 send_srw_explain_response(0, 0);
1926             return;
1927         }
1928         else if (srw_pdu->which == Z_SRW_scan_request)
1929         {
1930             m_s2z_database = odr_strdup(m_s2z_odr_init,
1931                                         srw_pdu->u.scan_request->database);
1932
1933             yaz_add_srw_diagnostic(odr_decode(),
1934                                    &diagnostic, &num_diagnostic,
1935                                    4, "scan");
1936             Z_SRW_PDU *srw_pdu =
1937                 yaz_srw_get(odr_encode(),
1938                             Z_SRW_scan_response);
1939             Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
1940             
1941             srw_res->diagnostics = diagnostic;
1942             srw_res->num_diagnostics = num_diagnostic;
1943             send_srw_response(srw_pdu);
1944             return;
1945         }
1946         else
1947         {
1948             m_s2z_database = 0;
1949
1950             send_to_srw_client_error(4, 0);
1951         }
1952     }
1953     int len = 0;
1954     Z_GDU *p = z_get_HTTP_Response(odr_encode(), 400);
1955     timeout(0);
1956     send_GDU(p, &len);
1957 }
1958
1959 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
1960 {
1961     Z_ReferenceId **refid = get_referenceIdP(apdu);
1962     nmem_reset(m_referenceId_mem);
1963     if (refid && *refid)
1964     {
1965         m_referenceId = (Z_ReferenceId *)
1966             nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
1967         m_referenceId->len = m_referenceId->size = (*refid)->len;
1968         m_referenceId->buf = (unsigned char *)
1969             nmem_malloc(m_referenceId_mem, (*refid)->len);
1970         memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
1971     }
1972     else
1973         m_referenceId = 0;
1974
1975     if (!m_client && m_invalid_session)
1976     {
1977         m_apdu_invalid_session = apdu;
1978         m_mem_invalid_session = odr_extract_mem(odr_decode());
1979         apdu = m_initRequest_apdu;
1980     }
1981     
1982     // Determine our client.
1983     Z_OtherInformation **oi;
1984     get_otherInfoAPDU(apdu, &oi);
1985     m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
1986     if (!m_client)
1987     {
1988         delete this;
1989         return;
1990     }
1991     m_client->m_server = this;
1992
1993     if (apdu->which == Z_APDU_initRequest)
1994     {
1995         if (apdu->u.initRequest->implementationId)
1996             yaz_log(LOG_LOG, "%simplementationId: %s",
1997                     m_session_str, apdu->u.initRequest->implementationId);
1998         if (apdu->u.initRequest->implementationName)
1999             yaz_log(LOG_LOG, "%simplementationName: %s",
2000                     m_session_str, apdu->u.initRequest->implementationName);
2001         if (apdu->u.initRequest->implementationVersion)
2002             yaz_log(LOG_LOG, "%simplementationVersion: %s",
2003                     m_session_str, apdu->u.initRequest->implementationVersion);
2004         if (m_initRequest_apdu == 0)
2005         {
2006             if (m_initRequest_mem)
2007                 nmem_destroy(m_initRequest_mem);
2008             m_initRequest_apdu = apdu;
2009             m_initRequest_mem = odr_extract_mem(odr_decode());
2010
2011             m_initRequest_preferredMessageSize = *apdu->u.initRequest->
2012                 preferredMessageSize;
2013             *apdu->u.initRequest->preferredMessageSize = 1024*1024;
2014             m_initRequest_maximumRecordSize = *apdu->u.initRequest->
2015                 maximumRecordSize;
2016             *apdu->u.initRequest->maximumRecordSize = 1024*1024;
2017
2018             // save init options for the response..
2019             m_initRequest_options = apdu->u.initRequest->options;
2020             
2021             apdu->u.initRequest->options = 
2022                 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2023                                            sizeof(Odr_bitmask));
2024             ODR_MASK_ZERO(apdu->u.initRequest->options);
2025             int i;
2026             for (i = 0; i<= 24; i++)
2027                 ODR_MASK_SET(apdu->u.initRequest->options, i);
2028             ODR_MASK_CLEAR(apdu->u.initRequest->options,
2029                            Z_Options_negotiationModel);
2030             ODR_MASK_CLEAR(apdu->u.initRequest->options,
2031                            Z_Options_concurrentOperations);
2032
2033             // make new version
2034             m_initRequest_version = apdu->u.initRequest->protocolVersion;
2035             apdu->u.initRequest->protocolVersion = 
2036                 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2037                                            sizeof(Odr_bitmask));
2038             ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
2039
2040             for (i = 0; i<= 8; i++)
2041                 ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
2042         }
2043         if (m_client->m_init_flag)
2044         {
2045             if (handle_init_response_for_invalid_session(apdu))
2046                 return;
2047             if (m_client->m_initResponse)
2048             {
2049                 Z_APDU *apdu2 = m_client->m_initResponse;
2050                 apdu2->u.initResponse->otherInfo = 0;
2051                 if (m_client->m_cookie && *m_client->m_cookie)
2052                     set_otherInformationString(apdu2, VAL_COOKIE, 1,
2053                                                m_client->m_cookie);
2054                 apdu2->u.initResponse->referenceId =
2055                     apdu->u.initRequest->referenceId;
2056                 apdu2->u.initResponse->options = m_client->m_initResponse_options;
2057                 apdu2->u.initResponse->protocolVersion = 
2058                     m_client->m_initResponse_version;
2059                 
2060                 send_to_client(apdu2);
2061                 return;
2062             }
2063         }
2064         m_client->m_init_flag = 1;
2065     }
2066     handle_max_record_retrieve(apdu);
2067
2068     if (apdu)
2069         apdu = handle_syntax_validation(apdu);
2070
2071     if (apdu)
2072         apdu = handle_query_transformation(apdu);
2073
2074     if (apdu)
2075         apdu = handle_query_validation(apdu);
2076
2077     if (apdu)
2078         apdu = result_set_optimize(apdu);
2079     if (!apdu)
2080     {
2081         m_client->timeout(m_target_idletime);  // mark it active even 
2082         // though we didn't use it
2083         return;
2084     }
2085
2086     // delete other info part from PDU before sending to target
2087     get_otherInfoAPDU(apdu, &oi);
2088     if (oi)
2089         *oi = 0;
2090
2091     if (apdu->which == Z_APDU_presentRequest &&
2092         m_client->m_resultSetStartPoint == 0)
2093     {
2094         Z_PresentRequest *pr = apdu->u.presentRequest;
2095         m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
2096         m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
2097     } else {
2098         m_client->m_resultSetStartPoint = 0;
2099     }
2100     if (m_client->send_to_target(apdu) < 0)
2101     {
2102         delete m_client;
2103         m_client = 0;
2104         delete this;
2105     }
2106     else
2107         m_client->m_waiting = 1;
2108 }
2109
2110 void Yaz_Proxy::connectNotify()
2111 {
2112 }
2113
2114 void Yaz_Proxy::shutdown()
2115 {
2116     m_invalid_session = 0;
2117     // only keep if keep_alive flag is set...
2118     if (m_client && 
2119         m_client->m_pdu_recv < m_keepalive_limit_pdu &&
2120         m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
2121         m_client->m_waiting == 0)
2122     {
2123         yaz_log(LOG_LOG, "%sShutdown (client to proxy) keepalive %s",
2124                  m_session_str,
2125                  m_client->get_hostname());
2126         yaz_log(LOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
2127                 m_session_str, m_client->m_pdu_recv,
2128                 m_client->m_bytes_sent + m_client->m_bytes_recv,
2129                 m_keepalive_limit_bw, m_keepalive_limit_pdu);
2130         assert (m_client->m_waiting != 2);
2131         // Tell client (if any) that no server connection is there..
2132         m_client->m_server = 0;
2133         m_invalid_session = 0;
2134     }
2135     else if (m_client)
2136     {
2137         yaz_log (LOG_LOG, "%sShutdown (client to proxy) close %s",
2138                  m_session_str,
2139                  m_client->get_hostname());
2140         assert (m_client->m_waiting != 2);
2141         delete m_client;
2142     }
2143     else if (!m_parent)
2144     {
2145         yaz_log (LOG_LOG, "%sshutdown (client to proxy) bad state",
2146                  m_session_str);
2147         assert (m_parent);
2148     }
2149     else 
2150     {
2151         yaz_log (LOG_LOG, "%sShutdown (client to proxy)",
2152                  m_session_str);
2153     }
2154     if (m_parent)
2155         m_parent->pre_init();
2156     delete this;
2157 }
2158
2159 const char *Yaz_ProxyClient::get_session_str() 
2160 {
2161     if (!m_server)
2162         return "0 ";
2163     return m_server->get_session_str();
2164 }
2165
2166 void Yaz_ProxyClient::shutdown()
2167 {
2168     yaz_log (LOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
2169              get_hostname());
2170     delete m_server;
2171     delete this;
2172 }
2173
2174 void Yaz_Proxy::failNotify()
2175 {
2176     inc_request_no();
2177     yaz_log (LOG_LOG, "%sConnection closed by client",
2178              get_session_str());
2179     shutdown();
2180 }
2181
2182 void Yaz_ProxyClient::failNotify()
2183 {
2184     if (m_server)
2185         m_server->inc_request_no();
2186     yaz_log (LOG_LOG, "%sConnection closed by target %s", 
2187              get_session_str(), get_hostname());
2188     shutdown();
2189 }
2190
2191 void Yaz_ProxyClient::connectNotify()
2192 {
2193     const char *s = get_session_str();
2194     const char *h = get_hostname();
2195     yaz_log (LOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
2196              m_target_idletime);
2197     timeout(m_target_idletime);
2198     if (!m_server)
2199         pre_init_client();
2200 }
2201
2202 IYaz_PDU_Observer *Yaz_ProxyClient::sessionNotify(IYaz_PDU_Observable
2203                                                   *the_PDU_Observable, int fd)
2204 {
2205     return new Yaz_ProxyClient(the_PDU_Observable, 0);
2206 }
2207
2208 Yaz_ProxyClient::~Yaz_ProxyClient()
2209 {
2210     if (m_prev)
2211         *m_prev = m_next;
2212     if (m_next)
2213         m_next->m_prev = m_prev;
2214     m_waiting = 2;     // for debugging purposes only.
2215     odr_destroy(m_init_odr);
2216     delete m_last_query;
2217     xfree (m_last_resultSetId);
2218     xfree (m_cookie);
2219 }
2220
2221 void Yaz_ProxyClient::pre_init_client()
2222 {
2223     Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
2224     Z_InitRequest *req = apdu->u.initRequest;
2225     
2226     int i;
2227     for (i = 0; i<= 24; i++)
2228         ODR_MASK_SET(req->options, i);
2229     ODR_MASK_CLEAR(apdu->u.initRequest->options,
2230                    Z_Options_negotiationModel);
2231     ODR_MASK_CLEAR(apdu->u.initRequest->options,
2232                    Z_Options_concurrentOperations);
2233     for (i = 0; i<= 10; i++)
2234         ODR_MASK_SET(req->protocolVersion, i);
2235
2236     if (send_to_target(apdu) < 0)
2237     {
2238         delete this;
2239     }
2240     else
2241     {
2242         m_waiting = 1;
2243         m_init_flag = 1;
2244     }
2245 }
2246
2247 void Yaz_Proxy::pre_init()
2248 {
2249     int i;
2250     const char *name = 0;
2251     const char *zurl_in_use[MAX_ZURL_PLEX];
2252     int limit_bw, limit_pdu, limit_req;
2253     int target_idletime, client_idletime;
2254     int max_clients;
2255     int keepalive_limit_bw, keepalive_limit_pdu;
2256     int pre_init;
2257     const char *cql2rpn = 0;
2258
2259     Yaz_ProxyConfig *cfg = check_reconfigure();
2260
2261     zurl_in_use[0] = 0;
2262
2263     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
2264         set_APDU_yazlog(1);
2265     else
2266         set_APDU_yazlog(0);
2267
2268     for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
2269                                           &limit_bw, &limit_pdu, &limit_req,
2270                                           &target_idletime, &client_idletime,
2271                                           &max_clients, 
2272                                           &keepalive_limit_bw,
2273                                           &keepalive_limit_pdu,
2274                                           &pre_init,
2275                                           &cql2rpn) ; i++)
2276     {
2277         if (pre_init)
2278         {
2279             int j;
2280             for (j = 0; zurl_in_use[j]; j++)
2281             {
2282                 Yaz_ProxyClient *c;
2283                 int spare = 0;
2284                 int spare_waiting = 0;
2285                 int in_use = 0;
2286                 int other = 0;
2287                 for (c = m_clientPool; c; c = c->m_next)
2288                 {
2289                     if (!strcmp(zurl_in_use[j], c->get_hostname()))
2290                     {
2291                         if (c->m_cookie == 0)
2292                         {
2293                             if (c->m_server == 0)
2294                                 if (c->m_waiting)
2295                                     spare_waiting;
2296                                 else
2297                                     spare++;
2298                             else
2299                                 in_use++;
2300                         }
2301                         else
2302                             other++;
2303                     }
2304                 }
2305                 yaz_log(LOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
2306                         "sparew=%d preinit=%d",m_session_str,
2307                         name, zurl_in_use[j], in_use, other,
2308                         spare, spare_waiting, pre_init);
2309                 if (spare < pre_init)
2310                 {
2311                     c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
2312                     c->m_next = m_clientPool;
2313                     if (c->m_next)
2314                         c->m_next->m_prev = &c->m_next;
2315                     m_clientPool = c;
2316                     c->m_prev = &m_clientPool;
2317                     
2318                     if (m_log_mask & PROXY_LOG_APDU_SERVER)
2319                         c->set_APDU_yazlog(1);
2320                     else
2321                         c->set_APDU_yazlog(0);
2322
2323                     if (c->client(zurl_in_use[j]))
2324                     {
2325                         timeout(60);
2326                         delete c;
2327                         return;
2328                     }
2329                     c->timeout(30);
2330                     c->m_waiting = 1;
2331                     c->m_target_idletime = target_idletime;
2332                     c->m_seqno = m_seqno++;
2333                 }
2334             }
2335         }
2336     }
2337 }
2338
2339 void Yaz_Proxy::timeoutNotify()
2340 {
2341     if (m_parent)
2342     {
2343         if (m_bw_hold_PDU)
2344         {
2345             timeout(m_client_idletime);
2346             Z_GDU *apdu = m_bw_hold_PDU;
2347             m_bw_hold_PDU = 0;
2348             
2349             if (apdu->which == Z_GDU_Z3950)
2350                 handle_incoming_Z_PDU(apdu->u.z3950);
2351             else if (apdu->which == Z_GDU_HTTP_Request)
2352                 handle_incoming_HTTP(apdu->u.HTTP_Request);
2353         }
2354         else if (m_stylesheet_nprl)
2355             convert_xsl_delay();
2356         else
2357         {
2358             inc_request_no();
2359
2360             yaz_log (LOG_LOG, "%sTimeout (client to proxy)", m_session_str);
2361             shutdown();
2362         }
2363     }
2364     else
2365     {
2366         timeout(600);
2367         pre_init();
2368     }
2369 }
2370
2371 void Yaz_Proxy::markInvalid()
2372 {
2373     m_client = 0;
2374     m_invalid_session = 1;
2375 }
2376
2377 void Yaz_ProxyClient::timeoutNotify()
2378 {
2379     if (m_server)
2380         m_server->inc_request_no();
2381
2382     yaz_log (LOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
2383              get_hostname());
2384     m_waiting = 1;
2385     m_root->pre_init();
2386     if (m_server && m_init_flag)
2387     {
2388         // target timed out in a session that was properly initialized
2389         // server object stay alive but we mark it as invalid so it
2390         // gets initialized again
2391         m_server->markInvalid();
2392         m_server = 0;
2393     }
2394     shutdown();
2395 }
2396
2397 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable,
2398                                  Yaz_Proxy *parent) :
2399     Yaz_Z_Assoc (the_PDU_Observable)
2400 {
2401     m_cookie = 0;
2402     m_next = 0;
2403     m_prev = 0;
2404     m_init_flag = 0;
2405     m_last_query = 0;
2406     m_last_resultSetId = 0;
2407     m_last_resultCount = 0;
2408     m_last_ok = 0;
2409     m_sr_transform = 0;
2410     m_waiting = 0;
2411     m_init_odr = odr_createmem (ODR_DECODE);
2412     m_initResponse = 0;
2413     m_initResponse_options = 0;
2414     m_initResponse_version = 0;
2415     m_initResponse_preferredMessageSize = 0;
2416     m_initResponse_maximumRecordSize = 0;
2417     m_resultSetStartPoint = 0;
2418     m_bytes_sent = m_bytes_recv = 0;
2419     m_pdu_recv = 0;
2420     m_server = 0;
2421     m_seqno = 0;
2422     m_target_idletime = 600;
2423     m_root = parent;
2424 }
2425
2426 const char *Yaz_Proxy::option(const char *name, const char *value)
2427 {
2428     if (!strcmp (name, "optimize")) {
2429         if (value) {
2430             xfree (m_optimize); 
2431             m_optimize = xstrdup (value);
2432         }
2433         return m_optimize;
2434     }
2435     return 0;
2436 }
2437
2438 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
2439 {
2440
2441 }
2442
2443 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
2444 {
2445     if (apdu->which == Z_GDU_Z3950)
2446         recv_Z_PDU(apdu->u.z3950, len);
2447     else if (apdu->which == Z_GDU_HTTP_Response)
2448         recv_HTTP_response(apdu->u.HTTP_Response, len);
2449     else
2450         shutdown();
2451 }
2452
2453 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
2454 {
2455     if (!m_invalid_session)
2456         return 0;
2457     m_invalid_session = 0;
2458     handle_incoming_Z_PDU(m_apdu_invalid_session);
2459     assert (m_mem_invalid_session);
2460     nmem_destroy(m_mem_invalid_session);
2461     m_mem_invalid_session = 0;
2462     return 1;
2463 }
2464
2465 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
2466 {
2467     m_bytes_recv += len;
2468
2469     m_pdu_recv++;
2470     m_waiting = 0;
2471     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
2472         yaz_log (LOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
2473                  apdu_name(apdu), get_hostname(), len);
2474     if (apdu->which == Z_APDU_initResponse)
2475     {
2476         if (!m_server)  // if this is a pre init session , check for more
2477             m_root->pre_init();
2478         NMEM nmem = odr_extract_mem (odr_decode());
2479         odr_reset (m_init_odr);
2480         nmem_transfer (m_init_odr->mem, nmem);
2481         m_initResponse = apdu;
2482         m_initResponse_options = apdu->u.initResponse->options;
2483         m_initResponse_version = apdu->u.initResponse->protocolVersion;
2484         m_initResponse_preferredMessageSize = 
2485             *apdu->u.initResponse->preferredMessageSize;
2486         m_initResponse_maximumRecordSize = 
2487             *apdu->u.initResponse->maximumRecordSize;
2488
2489         Z_InitResponse *ir = apdu->u.initResponse;
2490         char *im0 = ir->implementationName;
2491         
2492         char *im1 = (char*) 
2493             odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
2494         *im1 = '\0';
2495         if (im0)
2496         {
2497             strcat(im1, im0);
2498             strcat(im1, " ");
2499         }
2500         strcat(im1, "(YAZ Proxy)");
2501         ir->implementationName = im1;
2502
2503         nmem_destroy (nmem);
2504
2505         if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
2506             return;
2507     }
2508     if (apdu->which == Z_APDU_searchResponse)
2509     {
2510         Z_SearchResponse *sr = apdu->u.searchResponse;
2511         m_last_resultCount = *sr->resultCount;
2512         int status = *sr->searchStatus;
2513         if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
2514         {
2515             m_last_ok = 1;
2516             
2517             if (sr->records && sr->records->which == Z_Records_DBOSD)
2518             {
2519                 m_cache.add(odr_decode(),
2520                             sr->records->u.databaseOrSurDiagnostics, 1,
2521                             *sr->resultCount);
2522             }
2523         }
2524     }
2525     if (apdu->which == Z_APDU_presentResponse)
2526     {
2527         Z_PresentResponse *pr = apdu->u.presentResponse;
2528         if (m_sr_transform)
2529         {
2530             m_sr_transform = 0;
2531             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2532             Z_SearchResponse *sr = new_apdu->u.searchResponse;
2533             sr->referenceId = pr->referenceId;
2534             *sr->resultCount = m_last_resultCount;
2535             sr->records = pr->records;
2536             sr->nextResultSetPosition = pr->nextResultSetPosition;
2537             sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
2538             apdu = new_apdu;
2539         }
2540         if (pr->records && 
2541             pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
2542         {
2543             m_cache.add(odr_decode(),
2544                         pr->records->u.databaseOrSurDiagnostics,
2545                         m_resultSetStartPoint, -1);
2546             m_resultSetStartPoint = 0;
2547         }
2548     }
2549     if (m_cookie)
2550         set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
2551     if (m_server)
2552     {
2553         m_server->send_to_client(apdu);
2554     }
2555     if (apdu->which == Z_APDU_close)
2556     {
2557         shutdown();
2558     }
2559 }
2560
2561 int Yaz_Proxy::server(const char *addr)
2562 {
2563     int r = Yaz_Z_Assoc::server(addr);
2564     if (!r)
2565     {
2566         yaz_log(LOG_LOG, "%sStarted proxy " VERSION " on %s", m_session_str, addr);
2567         timeout(1);
2568     }
2569     return r;
2570 }
2571