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