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