Reconnect on dead sessions to target if client session is active.
[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.89 2004-01-14 12:14:13 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                 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
610
611                 p->records[i]->u.databaseRecord = 
612                     z_ext_record(odr_encode(), VAL_TEXT_XML,
613                                  (char*) out_buf, out_len);
614                 xmlFree(out_buf);
615                 xmlFreeDoc(doc);
616                 xmlFreeDoc(res);
617             }
618         }
619     }
620     xsltFreeStylesheet(xsp);
621 }
622
623 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p)
624 {
625     int i;
626
627     yaz_marc_t mt = yaz_marc_create();
628     yaz_marc_xml(mt, YAZ_MARC_MARCXML);
629     for (i = 0; i < p->num_records; i++)
630     {
631         Z_NamePlusRecord *npr = p->records[i];
632         if (npr->which == Z_NamePlusRecord_databaseRecord)
633         {
634             Z_External *r = npr->u.databaseRecord;
635             if (r->which == Z_External_octet)
636             {
637                 int rlen;
638                 char *result;
639                 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
640                                         r->u.octet_aligned->len,
641                                         &result, &rlen))
642                 {
643                     yaz_iconv_t cd = yaz_iconv_open("UTF-8", "MARC-8");
644                     WRBUF wrbuf = wrbuf_alloc();
645                     
646                     char outbuf[120];
647                     size_t inbytesleft = rlen;
648                     const char *inp = result;
649                     while (cd && inbytesleft)
650                     {
651                         size_t outbytesleft = sizeof(outbuf);
652                         char *outp = outbuf;
653                         size_t r;
654                         
655                         r = yaz_iconv (cd, (char**) &inp,
656                                        &inbytesleft,
657                                        &outp, &outbytesleft);
658                         if (r == (size_t) (-1))
659                         {
660                             int e = yaz_iconv_error(cd);
661                             if (e != YAZ_ICONV_E2BIG)
662                             {
663                                 yaz_log(LOG_WARN, "conversion failure");
664                                 break;
665                             }
666                         }
667                         wrbuf_write(wrbuf, outbuf, outp - outbuf);
668                     }
669                     if (cd)
670                         yaz_iconv_close(cd);
671
672                     npr->u.databaseRecord = z_ext_record(odr_encode(),
673                                                          VAL_TEXT_XML,
674                                                          wrbuf_buf(wrbuf),
675                                                          wrbuf_len(wrbuf));
676                     wrbuf_free(wrbuf, 1);
677                 }
678             }
679         }
680     }
681     yaz_marc_destroy(mt);
682 }
683
684 void Yaz_Proxy::logtime()
685 {
686     if (m_time_tv.tv_sec)
687     {
688         struct timeval tv;
689         gettimeofday(&tv, 0);
690         long diff = (tv.tv_sec - m_time_tv.tv_sec)*1000000 +
691             (tv.tv_usec - m_time_tv.tv_usec);
692         if (diff >= 0)
693             yaz_log(LOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
694                     diff/1000000, (diff/1000)%1000);
695     }
696     m_time_tv.tv_sec = 0;
697     m_time_tv.tv_usec = 0;
698 }
699
700 int Yaz_Proxy::send_http_response(int code)
701 {
702     ODR o = odr_encode();
703     Z_GDU *gdu = z_get_HTTP_Response(o, code);
704     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
705     if (m_http_version)
706         hres->version = odr_strdup(o, m_http_version);
707     m_http_keepalive = 0;
708     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
709     {
710         yaz_log (LOG_LOG, "%sSending %s to client", m_session_str,
711                  gdu_name(gdu));
712     }
713     int len;
714     int r = send_GDU(gdu, &len);
715     logtime();
716     return r;
717 }
718
719 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu)
720 {
721     ODR o = odr_encode();
722     const char *ctype = "text/xml";
723     Z_GDU *gdu = z_get_HTTP_Response(o, 200);
724     Z_HTTP_Response *hres = gdu->u.HTTP_Response;
725     if (m_http_version)
726         hres->version = odr_strdup(o, m_http_version);
727     z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
728     if (m_http_keepalive)
729         z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
730
731     static Z_SOAP_Handler soap_handlers[2] = {
732 #if HAVE_XSLT
733         {"http://www.loc.gov/zing/srw/", 0,
734          (Z_SOAP_fun) yaz_srw_codec},
735 #endif
736         {0, 0, 0}
737     };
738     
739     Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
740     soap_package->which = Z_SOAP_generic;
741     soap_package->u.generic = 
742         (Z_SOAP_Generic *) odr_malloc(o,  sizeof(*soap_package->u.generic));
743     soap_package->u.generic->no = 0;
744     soap_package->u.generic->ns = soap_handlers[0].ns;
745     soap_package->u.generic->p = (void *) srw_pdu;
746     soap_package->ns = m_soap_ns;
747     z_soap_codec_enc_xsl(o, &soap_package,
748                          &hres->content_buf, &hres->content_len,
749                          soap_handlers, 0, m_s2z_stylesheet);
750     if (m_log_mask & PROXY_LOG_REQ_CLIENT)
751     {
752         yaz_log (LOG_LOG, "%sSending %s to client", m_session_str,
753                  gdu_name(gdu));
754     }
755     int len;
756     int r = send_GDU(gdu, &len);
757     logtime();
758     return r;
759 }
760
761 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
762 {
763     ODR o = odr_encode();
764     Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
765     Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
766
767     srw_res->num_diagnostics = 1;
768     srw_res->diagnostics = (Z_SRW_diagnostic *)
769         odr_malloc(o, sizeof(*srw_res->diagnostics));
770     srw_res->diagnostics[0].code =  odr_intdup(o, srw_error);
771     srw_res->diagnostics[0].details = add ? odr_strdup(o, add) : 0;
772     return send_srw_response(srw_pdu);
773 }
774
775 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
776                              Z_DefaultDiagFormat *ddf)
777 {
778     int bib1_code = *ddf->condition;
779     if (bib1_code == 109)
780         return 404;
781     srw_res->num_diagnostics = 1;
782     srw_res->diagnostics = (Z_SRW_diagnostic *)
783         odr_malloc(o, sizeof(*srw_res->diagnostics));
784     srw_res->diagnostics[0].code = 
785         odr_intdup(o, yaz_diag_bib1_to_srw(*ddf->condition));
786     srw_res->diagnostics[0].details = ddf->u.v2Addinfo;
787     return 0;
788 }
789
790 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
791 {
792     ODR o = odr_encode();
793     Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
794     Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
795
796     srw_res->numberOfRecords = odr_intdup (o, hits);
797     if (records && records->which == Z_Records_DBOSD)
798     {
799         srw_res->num_records =
800             records->u.databaseOrSurDiagnostics->num_records;
801         int i;
802         srw_res->records = (Z_SRW_record *)
803             odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
804         for (i = 0; i < srw_res->num_records; i++)
805         {
806             Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
807             if (npr->which != Z_NamePlusRecord_databaseRecord)
808             {
809                 srw_res->records[i].recordSchema = "diagnostic";
810                 srw_res->records[i].recordPacking = m_s2z_packing;
811                 srw_res->records[i].recordData_buf = "67";
812                 srw_res->records[i].recordData_len = 2;
813                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
814                 continue;
815             }
816             Z_External *r = npr->u.databaseRecord;
817             oident *ent = oid_getentbyoid(r->direct_reference);
818             if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
819             {
820                 srw_res->records[i].recordSchema = m_schema;
821                 srw_res->records[i].recordPacking = m_s2z_packing;
822                 srw_res->records[i].recordData_buf = (char*) 
823                     r->u.octet_aligned->buf;
824                 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
825                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
826             }
827             else
828             {
829                 srw_res->records[i].recordSchema = "diagnostic";
830                 srw_res->records[i].recordPacking = m_s2z_packing;
831                 srw_res->records[i].recordData_buf = "67";
832                 srw_res->records[i].recordData_len = 2;
833                 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
834             }
835         }
836     }
837     if (records && records->which == Z_Records_NSD)
838     {
839         int http_code;
840         http_code = z_to_srw_diag(odr_encode(), srw_res,
841                                    records->u.nonSurrogateDiagnostic);
842         if (http_code)
843             return send_http_response(http_code);
844     }
845     return send_srw_response(srw_pdu);
846     
847 }
848
849 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
850                                         int num_diagnostics)
851 {
852     Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
853     Z_SRW_explainResponse *er = res->u.explain_response;
854     
855     Yaz_ProxyConfig *cfg = check_reconfigure();
856     if (cfg)
857     {
858         int len;
859         char *b = cfg->get_explain(odr_encode(), 0 /* target */,
860                                    0 /* db */, &len);
861         if (b)
862         {
863             er->record.recordData_buf = b;
864             er->record.recordData_len = len;
865             er->record.recordPacking = m_s2z_packing;
866         }
867     }
868     er->diagnostics = diagnostics;
869     er->num_diagnostics = num_diagnostics;
870     return send_srw_response(res);
871 }
872
873 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu, int *len)
874 {
875     if (m_http_version)
876     {
877         if (apdu->which == Z_APDU_initResponse)
878         {
879             Z_InitResponse *res = apdu->u.initResponse;
880             if (*res->result == 0)
881             {
882                 send_to_srw_client_error(3, 0);
883             }
884             else if (!m_s2z_search_apdu)
885             {
886                 send_srw_explain_response(0, 0);
887             }
888             else
889             {
890                 handle_incoming_Z_PDU(m_s2z_search_apdu);
891             }
892         }
893         else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
894         {
895             m_s2z_search_apdu = 0;
896             Z_SearchResponse *res = apdu->u.searchResponse;
897             m_s2z_hit_count = *res->resultCount;
898             if (res->records && res->records->which == Z_Records_NSD)
899             {
900                 send_to_srw_client_ok(0, res->records, 1);
901             }
902             else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
903             {
904                 // adjust 
905                 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
906                 
907                 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
908                 {
909                     if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
910                         > m_s2z_hit_count)
911                         *pr->numberOfRecordsRequested =
912                             1 + m_s2z_hit_count - *pr->resultSetStartPoint;
913                 }
914                 handle_incoming_Z_PDU(m_s2z_present_apdu);
915             }
916             else
917             {
918                 m_s2z_present_apdu = 0;
919                 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
920             }
921         }
922         else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
923         {
924             int start = 
925                 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
926
927             m_s2z_present_apdu = 0;
928             Z_PresentResponse *res = apdu->u.presentResponse;
929             send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
930         }
931     }
932     else
933     {
934         if (m_log_mask & PROXY_LOG_REQ_CLIENT)
935             yaz_log (LOG_LOG, "%sSending %s to client", m_session_str,
936                      apdu_name(apdu));
937         int r = send_Z_PDU(apdu, len);
938         logtime();
939         return r;
940     }
941     return 0;
942 }
943
944 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
945 {
946     int len = 0;
947     int kill_session = 0;
948     if (apdu->which == Z_APDU_searchResponse)
949     {
950         Z_SearchResponse *sr = apdu->u.searchResponse;
951         Z_Records *p = sr->records;
952         if (p && p->which == Z_Records_NSD)
953         {
954             Z_DiagRec dr, *dr_p = &dr;
955             dr.which = Z_DiagRec_defaultFormat;
956             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
957
958             *sr->searchStatus = 0;
959             display_diagrecs(&dr_p, 1);
960         }
961         else
962         {
963             if (p && p->which == Z_Records_DBOSD)
964             {
965                 if (m_marcxml_flag)
966                     convert_to_marcxml(p->u.databaseOrSurDiagnostics);
967                 convert_xsl(p->u.databaseOrSurDiagnostics);
968             }
969             if (sr->resultCount)
970             {
971                 yaz_log(LOG_LOG, "%s%d hits", m_session_str,
972                         *sr->resultCount);
973                 if (*sr->resultCount < 0)
974                 {
975                     m_invalid_session = 1;
976                     kill_session = 1;
977
978                     *sr->searchStatus = 0;
979                     sr->records =
980                         create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
981                     *sr->resultCount = 0;
982                 }
983             }
984         }
985     }
986     else if (apdu->which == Z_APDU_presentResponse)
987     {
988         Z_PresentResponse *sr = apdu->u.presentResponse;
989         Z_Records *p = sr->records;
990         if (p && p->which == Z_Records_NSD)
991         {
992             Z_DiagRec dr, *dr_p = &dr;
993             dr.which = Z_DiagRec_defaultFormat;
994             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
995             if (*sr->presentStatus == Z_PresentStatus_success)
996                 *sr->presentStatus = Z_PresentStatus_failure;
997             display_diagrecs(&dr_p, 1);
998         }
999         if (p && p->which == Z_Records_DBOSD)
1000         {
1001             if (m_marcxml_flag)
1002                 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
1003             convert_xsl(p->u.databaseOrSurDiagnostics);
1004         }
1005     }
1006     int r = send_PDU_convert(apdu, &len);
1007     if (r)
1008         return r;
1009     m_bytes_sent += len;
1010     m_bw_stat.add_bytes(len);
1011     if (kill_session)
1012     {
1013         delete m_client;
1014         m_client = 0;
1015         m_parent->pre_init();
1016     }
1017     if (m_http_version)
1018     {
1019         if (!m_http_keepalive)
1020         {
1021 #if 1
1022             timeout(1);
1023 #else
1024             shutdown();
1025             return -1;
1026 #endif
1027         }
1028     }
1029     return r;
1030 }
1031
1032 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1033 {
1034     int len = 0;
1035     const char *apdu_name_tmp = apdu_name(apdu);
1036     int r = send_Z_PDU(apdu, &len);
1037     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1038         yaz_log (LOG_LOG, "%sSending %s to %s %d bytes",
1039                  get_session_str(),
1040                  apdu_name_tmp, get_hostname(), len);
1041     m_bytes_sent += len;
1042     return r;
1043 }
1044
1045 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1046 {
1047     if (apdu->which == Z_APDU_presentRequest)
1048     {
1049         Z_PresentRequest *pr = apdu->u.presentRequest;
1050         int toget = *pr->numberOfRecordsRequested;
1051         int start = *pr->resultSetStartPoint;
1052
1053         yaz_log(LOG_LOG, "%sPresent %s %d+%d", m_session_str,
1054                 pr->resultSetId, start, toget);
1055
1056         if (*m_parent->m_optimize == '0')
1057             return apdu;
1058
1059         if (!m_client->m_last_resultSetId)
1060         {
1061             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1062             new_apdu->u.presentResponse->records =
1063                 create_nonSurrogateDiagnostics(odr_encode(), 30,
1064                                                pr->resultSetId);
1065             send_to_client(new_apdu);
1066             return 0;
1067         }
1068         if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1069         {
1070             if (start+toget-1 > m_client->m_last_resultCount)
1071             {
1072                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1073                 new_apdu->u.presentResponse->records =
1074                     create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
1075                 send_to_client(new_apdu);
1076                 return 0;
1077             }
1078             Z_NamePlusRecordList *npr;
1079             if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1080                                           pr->preferredRecordSyntax,
1081                                           pr->recordComposition))
1082             {
1083                 yaz_log (LOG_LOG, "%sReturned cached records for present request", 
1084                          m_session_str);
1085                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1086                 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1087                 
1088                 new_apdu->u.presentResponse->numberOfRecordsReturned
1089                     = odr_intdup(odr_encode(), toget);
1090                                                                  
1091                 new_apdu->u.presentResponse->records = (Z_Records*)
1092                     odr_malloc(odr_encode(), sizeof(Z_Records));
1093                 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1094                 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1095                 new_apdu->u.presentResponse->nextResultSetPosition =
1096                     odr_intdup(odr_encode(), start+toget);
1097
1098                 send_to_client(new_apdu);
1099                 return 0;
1100             }
1101         }
1102     }
1103
1104     if (apdu->which != Z_APDU_searchRequest)
1105         return apdu;
1106     Z_SearchRequest *sr = apdu->u.searchRequest;
1107     Yaz_Z_Query *this_query = new Yaz_Z_Query;
1108     Yaz_Z_Databases this_databases;
1109
1110     this_databases.set(sr->num_databaseNames, (const char **)
1111                        sr->databaseNames);
1112     
1113     this_query->set_Z_Query(sr->query);
1114
1115     char query_str[120];
1116     this_query->print(query_str, sizeof(query_str)-1);
1117     yaz_log(LOG_LOG, "%sSearch %s", m_session_str, query_str);
1118
1119     if (*m_parent->m_optimize != '0' &&
1120         m_client->m_last_ok && m_client->m_last_query &&
1121         m_client->m_last_query->match(this_query) &&
1122         !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1123         m_client->m_last_databases.match(this_databases))
1124     {
1125         delete this_query;
1126         if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1127             m_client->m_last_resultCount < *sr->largeSetLowerBound)
1128         {
1129             Z_NamePlusRecordList *npr;
1130             int toget = *sr->mediumSetPresentNumber;
1131             Z_RecordComposition *comp = 0;
1132
1133             if (toget > m_client->m_last_resultCount)
1134                 toget = m_client->m_last_resultCount;
1135             
1136             if (sr->mediumSetElementSetNames)
1137             {
1138                 comp = (Z_RecordComposition *)
1139                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1140                 comp->which = Z_RecordComp_simple;
1141                 comp->u.simple = sr->mediumSetElementSetNames;
1142             }
1143  
1144             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1145                                           sr->preferredRecordSyntax, comp))
1146             {
1147                 yaz_log (LOG_LOG, "%sReturned cached records for medium set",
1148                          m_session_str);
1149                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1150                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1151                 new_apdu->u.searchResponse->resultCount =
1152                     &m_client->m_last_resultCount;
1153                 
1154                 new_apdu->u.searchResponse->numberOfRecordsReturned
1155                     = odr_intdup(odr_encode(), toget);
1156                                                         
1157                 new_apdu->u.searchResponse->presentStatus =
1158                     odr_intdup(odr_encode(), Z_PresentStatus_success);
1159                 new_apdu->u.searchResponse->records = (Z_Records*)
1160                     odr_malloc(odr_encode(), sizeof(Z_Records));
1161                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1162                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1163                 new_apdu->u.searchResponse->nextResultSetPosition =
1164                     odr_intdup(odr_encode(), toget+1);
1165                 send_to_client(new_apdu);
1166                 return 0;
1167             }
1168             else
1169             {
1170                 // medium Set
1171                 // send present request (medium size)
1172                 yaz_log (LOG_LOG, "%sOptimizing search for medium set",
1173                          m_session_str);
1174
1175                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1176                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1177                 pr->referenceId = sr->referenceId;
1178                 pr->resultSetId = sr->resultSetName;
1179                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1180                 *pr->numberOfRecordsRequested = toget;
1181                 pr->recordComposition = comp;
1182                 m_client->m_sr_transform = 1;
1183                 return new_apdu;
1184             }
1185         }
1186         else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1187             m_client->m_last_resultCount <= 0)
1188         {
1189             // large set. Return pseudo-search response immediately
1190             yaz_log (LOG_LOG, "%sOptimizing search for large set",
1191                      m_session_str);
1192             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1193             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1194             new_apdu->u.searchResponse->resultCount =
1195                 &m_client->m_last_resultCount;
1196             send_to_client(new_apdu);
1197             return 0;
1198         }
1199         else
1200         {
1201             Z_NamePlusRecordList *npr;
1202             int toget = m_client->m_last_resultCount;
1203             Z_RecordComposition *comp = 0;
1204             // small set
1205             // send a present request (small set)
1206             
1207             if (sr->smallSetElementSetNames)
1208             {
1209                 comp = (Z_RecordComposition *)
1210                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1211                 comp->which = Z_RecordComp_simple;
1212                 comp->u.simple = sr->smallSetElementSetNames;
1213             }
1214
1215             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1216                                           sr->preferredRecordSyntax, comp))
1217             {
1218                 yaz_log (LOG_LOG, "%sReturned cached records for small set",
1219                          m_session_str);
1220                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1221                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1222                 new_apdu->u.searchResponse->resultCount =
1223                     &m_client->m_last_resultCount;
1224                 
1225                 new_apdu->u.searchResponse->numberOfRecordsReturned
1226                     = odr_intdup(odr_encode(), toget);
1227                                                                  
1228                 new_apdu->u.searchResponse->presentStatus =
1229                     odr_intdup(odr_encode(), Z_PresentStatus_success);
1230                 new_apdu->u.searchResponse->records = (Z_Records*)
1231                     odr_malloc(odr_encode(), sizeof(Z_Records));
1232                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1233                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1234                 new_apdu->u.searchResponse->nextResultSetPosition =
1235                     odr_intdup(odr_encode(), toget+1);
1236                 send_to_client(new_apdu);
1237                 return 0;
1238             }
1239             else
1240             {
1241                 yaz_log (LOG_LOG, "%sOptimizing search for small set",
1242                          m_session_str);
1243                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1244                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1245                 pr->referenceId = sr->referenceId;
1246                 pr->resultSetId = sr->resultSetName;
1247                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1248                 *pr->numberOfRecordsRequested = toget;
1249                 pr->recordComposition = comp;
1250                 m_client->m_sr_transform = 1;
1251                 return new_apdu;
1252             }
1253         }
1254     }
1255     else  // query doesn't match
1256     {
1257         delete m_client->m_last_query;
1258         m_client->m_last_query = this_query;
1259         m_client->m_last_ok = 0;
1260         m_client->m_cache.clear();
1261         m_client->m_resultSetStartPoint = 0;
1262
1263         xfree (m_client->m_last_resultSetId);
1264         m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1265
1266         m_client->m_last_databases.set(sr->num_databaseNames,
1267                                        (const char **) sr->databaseNames);
1268     }
1269     return apdu;
1270 }
1271
1272
1273 void Yaz_Proxy::inc_request_no()
1274 {
1275     char *cp = strchr(m_session_str, ' ');
1276     m_request_no++;
1277     if (cp)
1278         sprintf(cp+1, "%d ", m_request_no);
1279 }
1280
1281 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1282 {
1283     inc_request_no();
1284
1285     m_bytes_recv += len;
1286     
1287     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
1288         yaz_log (LOG_DEBUG, "%sReceiving %s from client %d bytes",
1289                  m_session_str, gdu_name(apdu), len);
1290
1291     if (m_bw_hold_PDU)     // double incoming PDU. shutdown now.
1292         shutdown();
1293
1294     m_bw_stat.add_bytes(len);
1295     m_pdu_stat.add_bytes(1);
1296
1297     gettimeofday(&m_time_tv, 0);
1298
1299     int bw_total = m_bw_stat.get_total();
1300     int pdu_total = m_pdu_stat.get_total();
1301
1302     int reduce = 0;
1303     if (m_bw_max)
1304     {
1305         if (bw_total > m_bw_max)
1306         {
1307             reduce = (bw_total/m_bw_max);
1308         }
1309     }
1310     if (m_pdu_max)
1311     {
1312         if (pdu_total > m_pdu_max)
1313         {
1314             int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1315             reduce = (reduce > nreduce) ? reduce : nreduce;
1316         }
1317     }
1318     if (reduce)  
1319     {
1320         yaz_log(LOG_LOG, "%sdelay=%d bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1321                 m_session_str, reduce, bw_total, pdu_total,
1322                 m_bw_max, m_pdu_max);
1323         
1324         m_bw_hold_PDU = apdu;  // save PDU and signal "on hold"
1325         timeout(reduce);       // call us reduce seconds later
1326     }
1327     else if (apdu->which == Z_GDU_Z3950)
1328         handle_incoming_Z_PDU(apdu->u.z3950);
1329     else if (apdu->which == Z_GDU_HTTP_Request)
1330         handle_incoming_HTTP(apdu->u.HTTP_Request);
1331 }
1332
1333 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
1334 {
1335     if (m_max_record_retrieve)
1336     {
1337         if (apdu->which == Z_APDU_presentRequest)
1338         {
1339             Z_PresentRequest *pr = apdu->u.presentRequest;
1340             if (pr->numberOfRecordsRequested && 
1341                 *pr->numberOfRecordsRequested > m_max_record_retrieve)
1342                 *pr->numberOfRecordsRequested = m_max_record_retrieve;
1343         }
1344     }
1345 }
1346
1347 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
1348                                                      int error,
1349                                                      const char *addinfo)
1350 {
1351     Z_Records *rec = (Z_Records *)
1352         odr_malloc (odr, sizeof(*rec));
1353     int *err = (int *)
1354         odr_malloc (odr, sizeof(*err));
1355     Z_DiagRec *drec = (Z_DiagRec *)
1356         odr_malloc (odr, sizeof(*drec));
1357     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1358         odr_malloc (odr, sizeof(*dr));
1359     *err = error;
1360     rec->which = Z_Records_NSD;
1361     rec->u.nonSurrogateDiagnostic = dr;
1362     dr->diagnosticSetId =
1363         yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
1364     dr->condition = err;
1365     dr->which = Z_DefaultDiagFormat_v2Addinfo;
1366     dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1367     return rec;
1368 }
1369
1370 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
1371 {
1372     if (apdu->which == Z_APDU_searchRequest &&
1373         apdu->u.searchRequest->query &&
1374         apdu->u.searchRequest->query->which == Z_Query_type_104 &&
1375         apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
1376     {
1377         Z_RPNQuery *rpnquery = 0;
1378         Z_SearchRequest *sr = apdu->u.searchRequest;
1379         char *addinfo = 0;
1380         
1381         yaz_log(LOG_LOG, "%sCQL: %s", m_session_str,
1382                 sr->query->u.type_104->u.cql);
1383
1384         int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
1385                                           &rpnquery, odr_encode(),
1386                                           &addinfo);
1387         if (r == -3)
1388             yaz_log(LOG_LOG, "%sNo CQL to RPN table", m_session_str);
1389         else if (r)
1390         {
1391             yaz_log(LOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
1392             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1393
1394             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1395             new_apdu->u.searchResponse->records =
1396                 create_nonSurrogateDiagnostics(odr_encode(),
1397                                                yaz_diag_srw_to_bib1(r),
1398                                                addinfo);
1399             *new_apdu->u.searchResponse->searchStatus = 0;
1400
1401             send_to_client(new_apdu);
1402
1403             return 0;
1404         }
1405         else
1406         {
1407             sr->query->which = Z_Query_type_1;
1408             sr->query->u.type_1 = rpnquery;
1409         }
1410         return apdu;
1411     }
1412     return apdu;
1413 }
1414
1415 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
1416 {
1417     if (apdu->which == Z_APDU_searchRequest)
1418     {
1419         Z_SearchRequest *sr = apdu->u.searchRequest;
1420         int err = 0;
1421         char *addinfo = 0;
1422
1423         Yaz_ProxyConfig *cfg = check_reconfigure();
1424         if (cfg)
1425             err = cfg->check_query(odr_encode(), m_default_target,
1426                                    sr->query, &addinfo);
1427         if (err)
1428         {
1429             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1430
1431             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1432             new_apdu->u.searchResponse->records =
1433                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1434             *new_apdu->u.searchResponse->searchStatus = 0;
1435
1436             send_to_client(new_apdu);
1437
1438             return 0;
1439         }
1440     }
1441     return apdu;
1442 }
1443
1444 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
1445 {
1446     m_marcxml_flag = 0;
1447     if (apdu->which == Z_APDU_searchRequest)
1448     {
1449         Z_SearchRequest *sr = apdu->u.searchRequest;
1450         int err = 0;
1451         char *addinfo = 0;
1452         Yaz_ProxyConfig *cfg = check_reconfigure();
1453
1454         Z_RecordComposition rc_temp, *rc = 0;
1455         if (sr->smallSetElementSetNames)
1456         {
1457             rc_temp.which = Z_RecordComp_simple;
1458             rc_temp.u.simple = sr->smallSetElementSetNames;
1459             rc = &rc_temp;
1460         }
1461             
1462         if (cfg)
1463             err = cfg->check_syntax(odr_encode(),
1464                                     m_default_target,
1465                                     sr->preferredRecordSyntax, rc,
1466                                     &addinfo, &m_stylesheet_schema, &m_schema);
1467         if (err == -1)
1468         {
1469             sr->preferredRecordSyntax =
1470                 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN, VAL_USMARC);
1471             m_marcxml_flag = 1;
1472         }
1473         else if (err)
1474         {
1475             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1476             
1477             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1478             new_apdu->u.searchResponse->records =
1479                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1480             *new_apdu->u.searchResponse->searchStatus = 0;
1481             
1482             send_to_client(new_apdu);
1483             
1484             return 0;
1485         }
1486     }
1487     else if (apdu->which == Z_APDU_presentRequest)
1488     {
1489         Z_PresentRequest *pr = apdu->u.presentRequest;
1490         int err = 0;
1491         char *addinfo = 0;
1492         Yaz_ProxyConfig *cfg = check_reconfigure();
1493
1494         if (cfg)
1495             err = cfg->check_syntax(odr_encode(), m_default_target,
1496                                     pr->preferredRecordSyntax,
1497                                     pr->recordComposition,
1498                                     &addinfo, &m_stylesheet_schema, &m_schema);
1499         if (err == -1)
1500         {
1501             pr->preferredRecordSyntax =
1502                 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN, VAL_USMARC);
1503             m_marcxml_flag = 1;
1504         }
1505         else if (err)
1506         {
1507             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1508             
1509             new_apdu->u.presentResponse->referenceId = pr->referenceId;
1510             new_apdu->u.presentResponse->records =
1511                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1512             *new_apdu->u.presentResponse->presentStatus =
1513                 Z_PresentStatus_failure;
1514             
1515             send_to_client(new_apdu);
1516             
1517             return 0;
1518         }
1519     }
1520     return apdu;
1521 }
1522
1523 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
1524 {
1525     if (!schema)
1526         return 0;
1527     Z_ElementSetNames *esn = (Z_ElementSetNames *)
1528         odr_malloc(o, sizeof(Z_ElementSetNames));
1529     esn->which = Z_ElementSetNames_generic;
1530     esn->u.generic = odr_strdup(o, schema);
1531     return esn;
1532 }
1533
1534 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
1535 {
1536
1537     if (m_s2z_odr_init)
1538     {
1539         odr_destroy(m_s2z_odr_init);
1540         m_s2z_odr_init = 0;
1541     }
1542     if (m_s2z_odr_search)
1543     {
1544         odr_destroy(m_s2z_odr_search);
1545         m_s2z_odr_search = 0;
1546     }
1547
1548     m_http_keepalive = 0;
1549     m_http_version = 0;
1550     if (!strcmp(hreq->version, "1.0")) 
1551     {
1552         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1553         if (v && !strcmp(v, "Keep-Alive"))
1554             m_http_keepalive = 1;
1555         else
1556             m_http_keepalive = 0;
1557         m_http_version = "1.0";
1558     }
1559     else
1560     {
1561         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1562         if (v && !strcmp(v, "close"))
1563             m_http_keepalive = 0;
1564         else
1565             m_http_keepalive = 1;
1566         m_http_version = "1.1";
1567     }
1568
1569     Z_SRW_PDU *srw_pdu = 0;
1570     Z_SOAP *soap_package = 0;
1571     char *charset = 0;
1572     Z_SRW_diagnostic *diagnostic = 0;
1573     int num_diagnostic = 0;
1574     if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
1575                        &charset) == 0
1576         || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
1577                           &charset, &diagnostic, &num_diagnostic) == 0)
1578     {
1579         m_s2z_odr_init = odr_createmem(ODR_ENCODE);
1580         m_s2z_odr_search = odr_createmem(ODR_ENCODE);
1581         m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
1582         m_s2z_init_apdu = 0;
1583         m_s2z_search_apdu = 0;
1584         m_s2z_present_apdu = 0;
1585
1586         m_s2z_stylesheet = 0;
1587         
1588         if (srw_pdu->which == Z_SRW_searchRetrieve_request)
1589         {
1590             Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
1591
1592             // recordXPath unsupported.
1593             if (srw_req->recordXPath)
1594             {
1595                 yaz_add_srw_diagnostic(odr_decode(),
1596                                        &diagnostic, &num_diagnostic,
1597                                        72, 0);
1598             }
1599             // must have a query
1600             if (!srw_req->query.cql)
1601             {
1602                 yaz_add_srw_diagnostic(odr_decode(),
1603                                        &diagnostic, &num_diagnostic,
1604                                        7, "query");
1605             }
1606             // sort unsupported
1607             if (srw_req->sort_type != Z_SRW_sort_type_none)
1608             {
1609                 yaz_add_srw_diagnostic(odr_decode(),
1610                                        &diagnostic, &num_diagnostic,
1611                                        80, 0);
1612             }
1613             // save stylesheet
1614             if (srw_req->stylesheet)
1615                 m_s2z_stylesheet =
1616                     odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
1617                                               
1618             // set packing for response records ..
1619             if (srw_req->recordPacking &&
1620                 !strcmp(srw_req->recordPacking, "xml"))
1621                 m_s2z_packing = Z_SRW_recordPacking_XML;
1622             else
1623                 m_s2z_packing = Z_SRW_recordPacking_string;
1624
1625             if (num_diagnostic)
1626             {
1627                 Z_SRW_PDU *srw_pdu =
1628                     yaz_srw_get(odr_encode(),
1629                                 Z_SRW_searchRetrieve_response);
1630                 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1631                 
1632                 srw_res->diagnostics = diagnostic;
1633                 srw_res->num_diagnostics = num_diagnostic;
1634                 send_srw_response(srw_pdu);
1635                 return;
1636             }
1637
1638             // prepare search PDU
1639             m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
1640                                           Z_APDU_searchRequest);
1641             Z_SearchRequest *z_searchRequest =
1642                 m_s2z_search_apdu->u.searchRequest;
1643
1644             z_searchRequest->num_databaseNames = 1;
1645             z_searchRequest->databaseNames = (char**)
1646                 odr_malloc(m_s2z_odr_search, sizeof(char *));
1647             z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
1648                                                            srw_req->database);
1649             
1650             // query transformation
1651             Z_Query *query = (Z_Query *)
1652                 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
1653             z_searchRequest->query = query;
1654             
1655             if (srw_req->query_type == Z_SRW_query_type_cql)
1656             {
1657                 Z_External *ext = (Z_External *) 
1658                     odr_malloc(m_s2z_odr_search, sizeof(*ext));
1659                 ext->direct_reference = 
1660                     odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
1661                 ext->indirect_reference = 0;
1662                 ext->descriptor = 0;
1663                 ext->which = Z_External_CQL;
1664                 ext->u.cql = srw_req->query.cql;
1665                 
1666                 query->which = Z_Query_type_104;
1667                 query->u.type_104 =  ext;
1668             }
1669             else if (srw_req->query_type == Z_SRW_query_type_pqf)
1670             {
1671                 Z_RPNQuery *RPNquery;
1672                 YAZ_PQF_Parser pqf_parser;
1673                 
1674                 pqf_parser = yaz_pqf_create ();
1675                 
1676                 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
1677                                           srw_req->query.pqf);
1678                 if (!RPNquery)
1679                 {
1680                     const char *pqf_msg;
1681                     size_t off;
1682                     int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1683                     yaz_log(LOG_LOG, "%*s^\n", off+4, "");
1684                     yaz_log(LOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
1685                     
1686                     send_to_srw_client_error(10, 0);
1687                     return;
1688                 }
1689                 query->which = Z_Query_type_1;
1690                 query->u.type_1 =  RPNquery;
1691                 
1692                 yaz_pqf_destroy (pqf_parser);
1693             }
1694             else
1695             {
1696                 send_to_srw_client_error(7, "query");
1697                 return;
1698             }
1699
1700             // present
1701             m_s2z_present_apdu = 0;
1702             int max = 0;
1703             if (srw_req->maximumRecords)
1704                 max = *srw_req->maximumRecords;
1705             int start = 1;
1706             if (srw_req->startRecord)
1707                 start = *srw_req->startRecord;
1708             if (max > 0)
1709             {
1710                 // Some backend, such as Voyager doesn't honor piggyback
1711                 // So we use present always (0 &&).
1712                 if (0 && start <= 1)  // Z39.50 piggyback
1713                 {
1714                     *z_searchRequest->smallSetUpperBound = max;
1715                     *z_searchRequest->mediumSetPresentNumber = max;
1716                     *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
1717
1718                     z_searchRequest->preferredRecordSyntax =
1719                         yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
1720                                                VAL_TEXT_XML);
1721                     if (srw_req->recordSchema)
1722                     {
1723                         z_searchRequest->smallSetElementSetNames =
1724                             z_searchRequest->mediumSetElementSetNames =
1725                             mk_esn_from_schema(m_s2z_odr_search,
1726                                                srw_req->recordSchema);
1727                     }
1728                 }
1729                 else   // Z39.50 present
1730                 {
1731                     m_s2z_present_apdu = zget_APDU(m_s2z_odr_search, 
1732                                                    Z_APDU_presentRequest);
1733                     Z_PresentRequest *z_presentRequest = 
1734                         m_s2z_present_apdu->u.presentRequest;
1735                     *z_presentRequest->resultSetStartPoint = start;
1736                     *z_presentRequest->numberOfRecordsRequested = max;
1737                     z_presentRequest->preferredRecordSyntax =
1738                         yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
1739                                                VAL_TEXT_XML);
1740                     z_presentRequest->recordComposition =
1741                         (Z_RecordComposition *)
1742                         odr_malloc(m_s2z_odr_search,
1743                                    sizeof(Z_RecordComposition));
1744                     if (srw_req->recordSchema)
1745                     {
1746                         z_presentRequest->recordComposition->which = 
1747                             Z_RecordComp_simple;                    
1748                         z_presentRequest->recordComposition->u.simple =
1749                             mk_esn_from_schema(m_s2z_odr_search,
1750                                                srw_req->recordSchema);
1751                     }
1752                 }
1753             }
1754             if (!m_client)
1755             {
1756                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
1757                                             Z_APDU_initRequest);
1758                 
1759                 // prevent m_initRequest_apdu memory from being grabbed
1760                 // in Yaz_Proxy::handle_incoming_Z_PDU
1761                 m_initRequest_apdu = m_s2z_init_apdu;
1762                 handle_incoming_Z_PDU(m_s2z_init_apdu);
1763                 return;
1764             }
1765             else
1766             {
1767                 handle_incoming_Z_PDU(m_s2z_search_apdu);
1768                 return;
1769             }
1770         }
1771         else if (srw_pdu->which == Z_SRW_explain_request)
1772         {
1773             Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
1774
1775             // save stylesheet
1776             if (srw_req->stylesheet)
1777                 m_s2z_stylesheet =
1778                     odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
1779
1780             if (srw_req->recordPacking &&
1781                 !strcmp(srw_req->recordPacking, "xml"))
1782                 m_s2z_packing = Z_SRW_recordPacking_XML;
1783             else
1784                 m_s2z_packing = Z_SRW_recordPacking_string;
1785
1786             if (num_diagnostic)
1787             {
1788                 send_srw_explain_response(diagnostic, num_diagnostic);
1789                 return;
1790             }
1791
1792             if (!m_client)
1793             {
1794                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
1795                                             Z_APDU_initRequest);
1796                 
1797                 // prevent m_initRequest_apdu memory from being grabbed
1798                 // in Yaz_Proxy::handle_incoming_Z_PDU
1799                 m_initRequest_apdu = m_s2z_init_apdu;
1800                 handle_incoming_Z_PDU(m_s2z_init_apdu);
1801             }
1802             else
1803                 send_srw_explain_response(0, 0);
1804             return;
1805         }
1806         else if (srw_pdu->which == Z_SRW_scan_request)
1807         {
1808             yaz_add_srw_diagnostic(odr_decode(),
1809                                    &diagnostic, &num_diagnostic,
1810                                    4, "scan");
1811             Z_SRW_PDU *srw_pdu =
1812                 yaz_srw_get(odr_encode(),
1813                             Z_SRW_scan_response);
1814             Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
1815             
1816             srw_res->diagnostics = diagnostic;
1817             srw_res->num_diagnostics = num_diagnostic;
1818             send_srw_response(srw_pdu);
1819             return;
1820         }
1821         else
1822         {
1823             send_to_srw_client_error(4, 0);
1824         }
1825     }
1826     int len = 0;
1827     Z_GDU *p = z_get_HTTP_Response(odr_encode(), 400);
1828     send_GDU(p, &len);
1829     timeout(1);
1830 }
1831
1832 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
1833 {
1834     if (!m_client && m_invalid_session)
1835     {
1836         m_apdu_invalid_session = apdu;
1837         m_mem_invalid_session = odr_extract_mem(odr_decode());
1838         apdu = m_initRequest_apdu;
1839     }
1840
1841     // Determine our client.
1842     Z_OtherInformation **oi;
1843     get_otherInfoAPDU(apdu, &oi);
1844     m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
1845     if (!m_client)
1846     {
1847         delete this;
1848         return;
1849     }
1850     m_client->m_server = this;
1851
1852     if (apdu->which == Z_APDU_initRequest)
1853     {
1854         if (apdu->u.initRequest->implementationId)
1855             yaz_log(LOG_LOG, "%simplementationId: %s",
1856                     m_session_str, apdu->u.initRequest->implementationId);
1857         if (apdu->u.initRequest->implementationName)
1858             yaz_log(LOG_LOG, "%simplementationName: %s",
1859                     m_session_str, apdu->u.initRequest->implementationName);
1860         if (apdu->u.initRequest->implementationVersion)
1861             yaz_log(LOG_LOG, "%simplementationVersion: %s",
1862                     m_session_str, apdu->u.initRequest->implementationVersion);
1863         if (m_initRequest_apdu == 0)
1864         {
1865             if (m_initRequest_mem)
1866                 nmem_destroy(m_initRequest_mem);
1867             m_initRequest_apdu = apdu;
1868             m_initRequest_mem = odr_extract_mem(odr_decode());
1869         }
1870         if (m_client->m_init_flag)
1871         {
1872             if (handle_init_response_for_invalid_session(apdu))
1873                 return;
1874             Z_APDU *apdu2 = m_client->m_initResponse;
1875             apdu2->u.initResponse->otherInfo = 0;
1876             if (m_client->m_cookie && *m_client->m_cookie)
1877                 set_otherInformationString(apdu2, VAL_COOKIE, 1,
1878                                            m_client->m_cookie);
1879             apdu2->u.initResponse->referenceId =
1880                 apdu->u.initRequest->referenceId;
1881             send_to_client(apdu2);
1882             return;
1883         }
1884         m_client->m_init_flag = 1;
1885     }
1886     handle_max_record_retrieve(apdu);
1887
1888     if (apdu)
1889         apdu = handle_syntax_validation(apdu);
1890
1891     if (apdu)
1892         apdu = handle_query_transformation(apdu);
1893
1894     if (apdu)
1895         apdu = handle_query_validation(apdu);
1896
1897     if (apdu)
1898         apdu = result_set_optimize(apdu);
1899     if (!apdu)
1900     {
1901         m_client->timeout(m_target_idletime);  // mark it active even 
1902         // though we didn't use it
1903         return;
1904     }
1905
1906     // delete other info part from PDU before sending to target
1907     get_otherInfoAPDU(apdu, &oi);
1908     if (oi)
1909         *oi = 0;
1910
1911     if (apdu->which == Z_APDU_presentRequest &&
1912         m_client->m_resultSetStartPoint == 0)
1913     {
1914         Z_PresentRequest *pr = apdu->u.presentRequest;
1915         m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
1916         m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
1917     } else {
1918         m_client->m_resultSetStartPoint = 0;
1919     }
1920     if (m_client->send_to_target(apdu) < 0)
1921     {
1922         delete m_client;
1923         m_client = 0;
1924         delete this;
1925     }
1926     else
1927         m_client->m_waiting = 1;
1928 }
1929
1930 void Yaz_Proxy::connectNotify()
1931 {
1932 }
1933
1934 void Yaz_Proxy::shutdown()
1935 {
1936     m_invalid_session = 0;
1937     // only keep if keep_alive flag is set...
1938     if (m_client && 
1939         m_client->m_pdu_recv < m_keepalive_limit_pdu &&
1940         m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
1941         m_client->m_waiting == 0)
1942     {
1943         yaz_log(LOG_LOG, "%sShutdown (client to proxy) keepalive %s",
1944                  m_session_str,
1945                  m_client->get_hostname());
1946         yaz_log(LOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1947                 m_session_str, m_client->m_pdu_recv,
1948                 m_client->m_bytes_sent + m_client->m_bytes_recv,
1949                 m_keepalive_limit_bw, m_keepalive_limit_pdu);
1950         assert (m_client->m_waiting != 2);
1951         // Tell client (if any) that no server connection is there..
1952         m_client->m_server = 0;
1953         m_invalid_session = 0;
1954     }
1955     else if (m_client)
1956     {
1957         yaz_log (LOG_LOG, "%sShutdown (client to proxy) close %s",
1958                  m_session_str,
1959                  m_client->get_hostname());
1960         assert (m_client->m_waiting != 2);
1961         delete m_client;
1962     }
1963     else if (!m_parent)
1964     {
1965         yaz_log (LOG_LOG, "%sshutdown (client to proxy) bad state",
1966                  m_session_str);
1967         assert (m_parent);
1968     }
1969     else 
1970     {
1971         yaz_log (LOG_LOG, "%sShutdown (client to proxy)",
1972                  m_session_str);
1973     }
1974     if (m_parent)
1975         m_parent->pre_init();
1976     delete this;
1977 }
1978
1979 const char *Yaz_ProxyClient::get_session_str() 
1980 {
1981     if (!m_server)
1982         return "0 ";
1983     return m_server->get_session_str();
1984 }
1985
1986 void Yaz_ProxyClient::shutdown()
1987 {
1988     yaz_log (LOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
1989              get_hostname());
1990     delete m_server;
1991     delete this;
1992 }
1993
1994 void Yaz_Proxy::failNotify()
1995 {
1996     inc_request_no();
1997     yaz_log (LOG_LOG, "%sConnection closed by client",
1998              get_session_str());
1999     shutdown();
2000 }
2001
2002 void Yaz_ProxyClient::failNotify()
2003 {
2004     if (m_server)
2005         m_server->inc_request_no();
2006     yaz_log (LOG_LOG, "%sConnection closed by target %s", 
2007              get_session_str(), get_hostname());
2008     shutdown();
2009 }
2010
2011 void Yaz_ProxyClient::connectNotify()
2012 {
2013     const char *s = get_session_str();
2014     const char *h = get_hostname();
2015     yaz_log (LOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
2016              m_target_idletime);
2017     timeout(m_target_idletime);
2018     if (!m_server)
2019         pre_init_client();
2020 }
2021
2022 IYaz_PDU_Observer *Yaz_ProxyClient::sessionNotify(IYaz_PDU_Observable
2023                                                   *the_PDU_Observable, int fd)
2024 {
2025     return new Yaz_ProxyClient(the_PDU_Observable, 0);
2026 }
2027
2028 Yaz_ProxyClient::~Yaz_ProxyClient()
2029 {
2030     if (m_prev)
2031         *m_prev = m_next;
2032     if (m_next)
2033         m_next->m_prev = m_prev;
2034     m_waiting = 2;     // for debugging purposes only.
2035     odr_destroy(m_init_odr);
2036     delete m_last_query;
2037     xfree (m_last_resultSetId);
2038     xfree (m_cookie);
2039 }
2040
2041 void Yaz_ProxyClient::pre_init_client()
2042 {
2043     Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
2044     Z_InitRequest *req = apdu->u.initRequest;
2045     
2046     ODR_MASK_SET(req->options, Z_Options_search);
2047     ODR_MASK_SET(req->options, Z_Options_present);
2048     ODR_MASK_SET(req->options, Z_Options_namedResultSets);
2049     ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
2050     ODR_MASK_SET(req->options, Z_Options_scan);
2051     ODR_MASK_SET(req->options, Z_Options_sort);
2052     ODR_MASK_SET(req->options, Z_Options_extendedServices);
2053     ODR_MASK_SET(req->options, Z_Options_delSet);
2054     
2055     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
2056     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
2057     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
2058     
2059     if (send_to_target(apdu) < 0)
2060     {
2061         delete this;
2062     }
2063     else
2064     {
2065         m_waiting = 1;
2066         m_init_flag = 1;
2067     }
2068 }
2069
2070 void Yaz_Proxy::pre_init()
2071 {
2072     int i;
2073     const char *name = 0;
2074     const char *zurl_in_use[MAX_ZURL_PLEX];
2075     int limit_bw, limit_pdu, limit_req;
2076     int target_idletime, client_idletime;
2077     int max_clients;
2078     int keepalive_limit_bw, keepalive_limit_pdu;
2079     int pre_init;
2080     const char *cql2rpn = 0;
2081
2082     Yaz_ProxyConfig *cfg = check_reconfigure();
2083
2084     zurl_in_use[0] = 0;
2085
2086     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
2087         set_APDU_yazlog(1);
2088     else
2089         set_APDU_yazlog(0);
2090
2091     for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
2092                                           &limit_bw, &limit_pdu, &limit_req,
2093                                           &target_idletime, &client_idletime,
2094                                           &max_clients, 
2095                                           &keepalive_limit_bw,
2096                                           &keepalive_limit_pdu,
2097                                           &pre_init,
2098                                           &cql2rpn) ; i++)
2099     {
2100         if (pre_init)
2101         {
2102             int j;
2103             for (j = 0; zurl_in_use[j]; j++)
2104             {
2105                 Yaz_ProxyClient *c;
2106                 int spare = 0;
2107                 int in_use = 0;
2108                 int other = 0;
2109                 for (c = m_clientPool; c; c = c->m_next)
2110                 {
2111                     if (!strcmp(zurl_in_use[j], c->get_hostname()))
2112                     {
2113                         if (c->m_cookie == 0)
2114                         {
2115                             if (c->m_server == 0)
2116                                 spare++;
2117                             else
2118                                 in_use++;
2119                         }
2120                         else
2121                             other++;
2122                     }
2123                 }
2124                 yaz_log(LOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
2125                         "preinit=%d",m_session_str,
2126                         name, zurl_in_use[j], in_use, other, spare, pre_init);
2127                 if (spare < pre_init)
2128                 {
2129                     c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
2130                     c->m_next = m_clientPool;
2131                     if (c->m_next)
2132                         c->m_next->m_prev = &c->m_next;
2133                     m_clientPool = c;
2134                     c->m_prev = &m_clientPool;
2135                     
2136                     if (m_log_mask & PROXY_LOG_APDU_SERVER)
2137                         c->set_APDU_yazlog(1);
2138                     else
2139                         c->set_APDU_yazlog(0);
2140
2141                     if (c->client(zurl_in_use[j]))
2142                     {
2143                         timeout(60);
2144                         delete c;
2145                         return;
2146                     }
2147                     c->timeout(30);
2148                     c->m_waiting = 1;
2149                     c->m_target_idletime = target_idletime;
2150                     c->m_seqno = m_seqno++;
2151                 }
2152             }
2153         }
2154     }
2155 }
2156
2157 void Yaz_Proxy::timeoutNotify()
2158 {
2159     if (m_parent)
2160     {
2161         if (m_bw_hold_PDU)
2162         {
2163             timeout(m_client_idletime);
2164             Z_GDU *apdu = m_bw_hold_PDU;
2165             m_bw_hold_PDU = 0;
2166             
2167             if (apdu->which == Z_GDU_Z3950)
2168                 handle_incoming_Z_PDU(apdu->u.z3950);
2169             else if (apdu->which == Z_GDU_HTTP_Request)
2170                 handle_incoming_HTTP(apdu->u.HTTP_Request);
2171         }
2172         else
2173         {
2174             inc_request_no();
2175
2176             yaz_log (LOG_LOG, "%sTimeout (client to proxy)", m_session_str);
2177             shutdown();
2178         }
2179     }
2180     else
2181     {
2182         timeout(600);
2183         pre_init();
2184     }
2185 }
2186
2187 void Yaz_Proxy::markInvalid()
2188 {
2189     m_client = 0;
2190     m_invalid_session = 1;
2191 }
2192
2193 void Yaz_ProxyClient::timeoutNotify()
2194 {
2195     if (m_server)
2196         m_server->inc_request_no();
2197
2198     yaz_log (LOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
2199              get_hostname());
2200     m_waiting = 1;
2201     m_root->pre_init();
2202     if (m_server && m_init_flag)
2203     {
2204         // target timed out in a session that was properly initialized
2205         // server object stay alive but we mark it as invalid so it
2206         // gets initialized again
2207         m_server->markInvalid();
2208         m_server = 0;
2209     }
2210     shutdown();
2211 }
2212
2213 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable,
2214                                  Yaz_Proxy *parent) :
2215     Yaz_Z_Assoc (the_PDU_Observable)
2216 {
2217     m_cookie = 0;
2218     m_next = 0;
2219     m_prev = 0;
2220     m_init_flag = 0;
2221     m_last_query = 0;
2222     m_last_resultSetId = 0;
2223     m_last_resultCount = 0;
2224     m_last_ok = 0;
2225     m_sr_transform = 0;
2226     m_waiting = 0;
2227     m_init_odr = odr_createmem (ODR_DECODE);
2228     m_initResponse = 0;
2229     m_resultSetStartPoint = 0;
2230     m_bytes_sent = m_bytes_recv = 0;
2231     m_pdu_recv = 0;
2232     m_server = 0;
2233     m_seqno = 0;
2234     m_target_idletime = 600;
2235     m_root = parent;
2236 }
2237
2238 const char *Yaz_Proxy::option(const char *name, const char *value)
2239 {
2240     if (!strcmp (name, "optimize")) {
2241         if (value) {
2242             xfree (m_optimize); 
2243             m_optimize = xstrdup (value);
2244         }
2245         return m_optimize;
2246     }
2247     return 0;
2248 }
2249
2250 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
2251 {
2252
2253 }
2254
2255 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
2256 {
2257     if (apdu->which == Z_GDU_Z3950)
2258         recv_Z_PDU(apdu->u.z3950, len);
2259     else if (apdu->which == Z_GDU_HTTP_Response)
2260         recv_HTTP_response(apdu->u.HTTP_Response, len);
2261     else
2262         shutdown();
2263 }
2264
2265 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
2266 {
2267     if (!m_invalid_session)
2268         return 0;
2269     m_invalid_session = 0;
2270     handle_incoming_Z_PDU(m_apdu_invalid_session);
2271     assert (m_mem_invalid_session);
2272     nmem_destroy(m_mem_invalid_session);
2273     m_mem_invalid_session = 0;
2274     return 1;
2275 }
2276
2277 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
2278 {
2279     m_bytes_recv += len;
2280     m_pdu_recv++;
2281     m_waiting = 0;
2282     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
2283         yaz_log (LOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
2284                  apdu_name(apdu), get_hostname(), len);
2285     if (apdu->which == Z_APDU_initResponse)
2286     {
2287         if (!m_server)  // if this is a pre init session , check for more
2288             m_root->pre_init();
2289         NMEM nmem = odr_extract_mem (odr_decode());
2290         odr_reset (m_init_odr);
2291         nmem_transfer (m_init_odr->mem, nmem);
2292         m_initResponse = apdu;
2293
2294         Z_InitResponse *ir = apdu->u.initResponse;
2295         char *im0 = ir->implementationName;
2296         
2297         char *im1 = (char*) 
2298             odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
2299         *im1 = '\0';
2300         if (im0)
2301         {
2302             strcat(im1, im0);
2303             strcat(im1, " ");
2304         }
2305         strcat(im1, "(YAZ Proxy)");
2306         ir->implementationName = im1;
2307
2308         nmem_destroy (nmem);
2309
2310         if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
2311             return;
2312     }
2313     if (apdu->which == Z_APDU_searchResponse)
2314     {
2315         Z_SearchResponse *sr = apdu->u.searchResponse;
2316         m_last_resultCount = *sr->resultCount;
2317         int status = *sr->searchStatus;
2318         if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
2319         {
2320             m_last_ok = 1;
2321             
2322             if (sr->records && sr->records->which == Z_Records_DBOSD)
2323             {
2324                 m_cache.add(odr_decode(),
2325                             sr->records->u.databaseOrSurDiagnostics, 1,
2326                             *sr->resultCount);
2327             }
2328         }
2329     }
2330     if (apdu->which == Z_APDU_presentResponse)
2331     {
2332         Z_PresentResponse *pr = apdu->u.presentResponse;
2333         if (m_sr_transform)
2334         {
2335             m_sr_transform = 0;
2336             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2337             Z_SearchResponse *sr = new_apdu->u.searchResponse;
2338             sr->referenceId = pr->referenceId;
2339             *sr->resultCount = m_last_resultCount;
2340             sr->records = pr->records;
2341             sr->nextResultSetPosition = pr->nextResultSetPosition;
2342             sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
2343             apdu = new_apdu;
2344         }
2345         if (pr->records && 
2346             pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
2347         {
2348             m_cache.add(odr_decode(),
2349                         pr->records->u.databaseOrSurDiagnostics,
2350                         m_resultSetStartPoint, -1);
2351             m_resultSetStartPoint = 0;
2352         }
2353     }
2354     if (m_cookie)
2355         set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
2356     if (m_server)
2357     {
2358         m_server->send_to_client(apdu);
2359     }
2360     if (apdu->which == Z_APDU_close)
2361     {
2362         shutdown();
2363     }
2364 }
2365
2366 int Yaz_Proxy::server(const char *addr)
2367 {
2368     int r = Yaz_Z_Assoc::server(addr);
2369     if (!r)
2370     {
2371         yaz_log(LOG_LOG, "%sStarted proxy " VERSION " on %s", m_session_str, addr);
2372         timeout(1);
2373     }
2374     return r;
2375 }
2376