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