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