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