Get rid of a few warnings
[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.79 2004-01-07 11:37:45 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 = 0;
110     m_schema = 0;
111     m_initRequest_apdu = 0;
112     m_initRequest_mem = 0;
113     m_apdu_invalid_session = 0;
114     m_mem_invalid_session = 0;
115     m_s2z_odr_init = 0;
116     m_s2z_odr_search = 0;
117     m_s2z_init_apdu = 0;
118     m_s2z_search_apdu = 0;
119     m_s2z_present_apdu = 0;
120     m_http_keepalive = 0;
121     m_http_version = 0;
122     m_soap_ns = 0;
123     m_s2z_packing = Z_SRW_recordPacking_string;
124     m_time_tv.tv_sec = 0;
125     m_time_tv.tv_usec = 0;
126 }
127
128 Yaz_Proxy::~Yaz_Proxy()
129 {
130     yaz_log(LOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
131             m_bytes_sent, m_bytes_recv);
132     nmem_destroy(m_initRequest_mem);
133     nmem_destroy(m_mem_invalid_session);
134     xfree (m_proxyTarget);
135     xfree (m_default_target);
136     xfree (m_proxy_authentication);
137     xfree (m_optimize);
138     xfree (m_stylesheet);
139     xfree (m_schema);
140     if (m_s2z_odr_init)
141         odr_destroy(m_s2z_odr_init);
142     if (m_s2z_odr_search)
143         odr_destroy(m_s2z_odr_search);
144     delete m_config;
145 }
146
147 int Yaz_Proxy::set_config(const char *config)
148 {
149     delete m_config;
150     m_config = new Yaz_ProxyConfig();
151     xfree(m_config_fname);
152     m_config_fname = xstrdup(config);
153     int r = m_config->read_xml(config);
154     if (!r)
155         m_config->get_generic_info(&m_log_mask, &m_max_clients);
156     return r;
157 }
158
159 void Yaz_Proxy::set_default_target(const char *target)
160 {
161     xfree (m_default_target);
162     m_default_target = 0;
163     if (target)
164         m_default_target = (char *) xstrdup (target);
165 }
166
167 void Yaz_Proxy::set_proxy_authentication (const char *auth)
168 {
169     xfree (m_proxy_authentication);
170     m_proxy_authentication = 0;
171     if (auth)
172         m_proxy_authentication = (char *) xstrdup (auth);
173 }
174
175 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
176 {
177     if (m_parent)
178         return m_parent->check_reconfigure();
179
180     Yaz_ProxyConfig *cfg = m_config;
181     if (m_reconfig_flag)
182     {
183         yaz_log(LOG_LOG, "reconfigure");
184         yaz_log_reopen();
185         if (m_config_fname && cfg)
186         {
187             yaz_log(LOG_LOG, "reconfigure config %s", m_config_fname);
188             int r = cfg->read_xml(m_config_fname);
189             if (r)
190                 yaz_log(LOG_WARN, "reconfigure failed");
191             else
192             {
193                 m_log_mask = 0;
194                 cfg->get_generic_info(&m_log_mask, &m_max_clients);
195             }
196         }
197         else
198             yaz_log(LOG_LOG, "reconfigure");
199         m_reconfig_flag = 0;
200     }
201     return cfg;
202 }
203
204 IYaz_PDU_Observer *Yaz_Proxy::sessionNotify(IYaz_PDU_Observable
205                                             *the_PDU_Observable, int fd)
206 {
207     check_reconfigure();
208     Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable, this);
209     new_proxy->m_config = 0;
210     new_proxy->m_config_fname = 0;
211     new_proxy->timeout(m_client_idletime);
212     new_proxy->m_target_idletime = m_target_idletime;
213     new_proxy->set_default_target(m_default_target);
214     new_proxy->m_max_clients = m_max_clients;
215     new_proxy->m_log_mask = m_log_mask;
216     new_proxy->set_APDU_log(get_APDU_log());
217     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
218         new_proxy->set_APDU_yazlog(1);
219     else
220         new_proxy->set_APDU_yazlog(0);
221     new_proxy->set_proxy_authentication(m_proxy_authentication);
222     sprintf(new_proxy->m_session_str, "%ld:%d ", (long) time(0), m_session_no);
223     m_session_no++;
224     yaz_log (LOG_LOG, "%sNew session %s", new_proxy->m_session_str,
225              the_PDU_Observable->getpeername());
226     return new_proxy;
227 }
228
229 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
230 {
231     int oid[OID_SIZE];
232     Z_OtherInformationUnit *oi;
233     struct oident ent;
234     ent.proto = PROTO_Z3950;
235     ent.oclass = CLASS_USERINFO;
236     ent.value = (oid_value) VAL_COOKIE;
237     assert (oid_ent_to_oid (&ent, oid));
238
239     if (oid_ent_to_oid (&ent, oid) && 
240         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
241         oi->which == Z_OtherInfo_characterInfo)
242         return oi->information.characterInfo;
243     return 0;
244 }
245
246 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
247 {
248     int oid[OID_SIZE];
249     Z_OtherInformationUnit *oi;
250     struct oident ent;
251     ent.proto = PROTO_Z3950;
252     ent.oclass = CLASS_USERINFO;
253     ent.value = (oid_value) VAL_PROXY;
254     if (oid_ent_to_oid (&ent, oid) &&
255         (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
256         oi->which == Z_OtherInfo_characterInfo)
257         return oi->information.characterInfo;
258     return 0;
259 }
260
261 const char *Yaz_Proxy::load_balance(const char **url)
262 {
263     int zurl_in_use[MAX_ZURL_PLEX];
264     Yaz_ProxyClient *c;
265     int i;
266
267     for (i = 0; i<MAX_ZURL_PLEX; i++)
268         zurl_in_use[i] = 0;
269     for (c = m_parent->m_clientPool; c; c = c->m_next)
270     {
271         for (i = 0; url[i]; i++)
272             if (!strcmp(url[i], c->get_hostname()))
273                 zurl_in_use[i]++;
274     }
275     int min = 100000;
276     const char *ret = 0;
277     for (i = 0; url[i]; i++)
278     {
279         yaz_log(LOG_DEBUG, "%szurl=%s use=%d",
280                 m_session_str, url[i], zurl_in_use[i]);
281         if (min > zurl_in_use[i])
282         {
283             ret = url[i];
284             min = zurl_in_use[i];
285         }
286     }
287     return ret;
288 }
289
290 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
291                                        const char *proxy_host)
292 {
293     assert (m_parent);
294     Yaz_Proxy *parent = m_parent;
295     Z_OtherInformation **oi;
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)
587         return;
588     xmlDocPtr xslt_doc = xmlParseFile(m_stylesheet);
589     xsltStylesheetPtr xsp;
590
591     xsp = xsltParseStylesheetDoc(xslt_doc);
592
593     int i;
594     for (i = 0; i < p->num_records; i++)
595     {
596         Z_NamePlusRecord *npr = p->records[i];
597         if (npr->which == Z_NamePlusRecord_databaseRecord)
598         {
599             Z_External *r = npr->u.databaseRecord;
600             if (r->which == Z_External_octet)
601             {
602                 xmlDocPtr res, doc = xmlParseMemory(
603                     (char*) r->u.octet_aligned->buf,
604                     r->u.octet_aligned->len);
605                 
606                 res = xsltApplyStylesheet(xsp, doc, 0);
607                 
608                 xmlChar *out_buf;
609                 int out_len;
610                 xmlDocDumpMemory (res, &out_buf, &out_len);
611                 p->records[i]->u.databaseRecord = 
612                     z_ext_record(odr_encode(), VAL_TEXT_XML,
613                                  (char*) out_buf, out_len);
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     const char *ctype = "text/xml";
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     int ret = z_soap_codec_enc(o, &soap_package,
748                                &hres->content_buf, &hres->content_len,
749                                soap_handlers, 0);
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)
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 = 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()
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         assert (m_proxyTarget);
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     return send_srw_response(res);
869 }
870
871 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu, int *len)
872 {
873     if (m_http_version)
874     {
875         if (apdu->which == Z_APDU_initResponse)
876         {
877             Z_InitResponse *res = apdu->u.initResponse;
878             if (*res->result == 0)
879             {
880                 send_to_srw_client_error(3);
881             }
882             else if (!m_s2z_search_apdu)
883             {
884                 send_srw_explain();
885             }
886             else
887             {
888                 handle_incoming_Z_PDU(m_s2z_search_apdu);
889             }
890         }
891         else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
892         {
893             m_s2z_search_apdu = 0;
894             Z_SearchResponse *res = apdu->u.searchResponse;
895             m_s2z_hit_count = *res->resultCount;
896             if (res->records && res->records->which == Z_Records_NSD)
897             {
898                 send_to_srw_client_ok(0, res->records, 1);
899             }
900             else if (m_s2z_present_apdu)
901             {
902                 handle_incoming_Z_PDU(m_s2z_present_apdu);
903             }
904             else
905             {
906                 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
907             }
908         }
909         else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
910         {
911             int start = 
912                 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
913
914             m_s2z_present_apdu = 0;
915             Z_PresentResponse *res = apdu->u.presentResponse;
916             send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
917         }
918     }
919     else
920     {
921         if (m_log_mask & PROXY_LOG_REQ_CLIENT)
922             yaz_log (LOG_LOG, "%sSending %s to client", m_session_str,
923                      apdu_name(apdu));
924         int r = send_Z_PDU(apdu, len);
925         logtime();
926         return r;
927     }
928     return 0;
929 }
930
931 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
932 {
933     int len = 0;
934     int kill_session = 0;
935     if (apdu->which == Z_APDU_searchResponse)
936     {
937         Z_SearchResponse *sr = apdu->u.searchResponse;
938         Z_Records *p = sr->records;
939         if (p && p->which == Z_Records_NSD)
940         {
941             Z_DiagRec dr, *dr_p = &dr;
942             dr.which = Z_DiagRec_defaultFormat;
943             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
944
945             *sr->searchStatus = 0;
946             display_diagrecs(&dr_p, 1);
947         }
948         else
949         {
950             if (p && p->which == Z_Records_DBOSD)
951             {
952                 if (m_marcxml_flag)
953                     convert_to_marcxml(p->u.databaseOrSurDiagnostics);
954                 convert_xsl(p->u.databaseOrSurDiagnostics);
955             }
956             if (sr->resultCount)
957             {
958                 yaz_log(LOG_LOG, "%s%d hits", m_session_str,
959                         *sr->resultCount);
960                 if (*sr->resultCount < 0)
961                 {
962                     m_invalid_session = 1;
963                     kill_session = 1;
964
965                     *sr->searchStatus = 0;
966                     sr->records =
967                         create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
968                     *sr->resultCount = 0;
969                 }
970             }
971         }
972     }
973     else if (apdu->which == Z_APDU_presentResponse)
974     {
975         Z_PresentResponse *sr = apdu->u.presentResponse;
976         Z_Records *p = sr->records;
977         if (p && p->which == Z_Records_NSD)
978         {
979             Z_DiagRec dr, *dr_p = &dr;
980             dr.which = Z_DiagRec_defaultFormat;
981             dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
982             if (*sr->presentStatus == Z_PresentStatus_success)
983                 *sr->presentStatus = Z_PresentStatus_failure;
984             display_diagrecs(&dr_p, 1);
985         }
986         if (p && p->which == Z_Records_DBOSD)
987         {
988             if (m_marcxml_flag)
989                 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
990             convert_xsl(p->u.databaseOrSurDiagnostics);
991         }
992     }
993     int r = send_PDU_convert(apdu, &len);
994     if (r)
995         return r;
996     m_bytes_sent += len;
997     m_bw_stat.add_bytes(len);
998     if (kill_session)
999     {
1000         delete m_client;
1001         m_client = 0;
1002         m_parent->pre_init();
1003     }
1004     if (m_http_version)
1005     {
1006         if (!m_http_keepalive)
1007         {
1008 #if 1
1009             timeout(1);
1010 #else
1011             shutdown();
1012             return -1;
1013 #endif
1014         }
1015     }
1016     return r;
1017 }
1018
1019 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1020 {
1021     int len = 0;
1022     const char *apdu_name_tmp = apdu_name(apdu);
1023     int r = send_Z_PDU(apdu, &len);
1024     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1025         yaz_log (LOG_LOG, "%sSending %s to %s %d bytes",
1026                  get_session_str(),
1027                  apdu_name_tmp, get_hostname(), len);
1028     m_bytes_sent += len;
1029     return r;
1030 }
1031
1032 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1033 {
1034     if (apdu->which == Z_APDU_presentRequest)
1035     {
1036         Z_PresentRequest *pr = apdu->u.presentRequest;
1037         int toget = *pr->numberOfRecordsRequested;
1038         int start = *pr->resultSetStartPoint;
1039
1040         yaz_log(LOG_LOG, "%sPresent %s %d+%d", m_session_str,
1041                 pr->resultSetId, start, toget);
1042
1043         if (*m_parent->m_optimize == '0')
1044             return apdu;
1045
1046         if (!m_client->m_last_resultSetId)
1047         {
1048             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1049             new_apdu->u.presentResponse->records =
1050                 create_nonSurrogateDiagnostics(odr_encode(), 30,
1051                                                pr->resultSetId);
1052             send_to_client(new_apdu);
1053             return 0;
1054         }
1055         if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1056         {
1057             if (start+toget-1 > m_client->m_last_resultCount)
1058             {
1059                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1060                 new_apdu->u.presentResponse->records =
1061                     create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
1062                 send_to_client(new_apdu);
1063                 return 0;
1064             }
1065             Z_NamePlusRecordList *npr;
1066             if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1067                                           pr->preferredRecordSyntax,
1068                                           pr->recordComposition))
1069             {
1070                 yaz_log (LOG_LOG, "%sReturned cached records for present request", 
1071                          m_session_str);
1072                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1073                 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1074                 
1075                 new_apdu->u.presentResponse->numberOfRecordsReturned
1076                     = odr_intdup(odr_encode(), toget);
1077                                                                  
1078                 new_apdu->u.presentResponse->records = (Z_Records*)
1079                     odr_malloc(odr_encode(), sizeof(Z_Records));
1080                 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1081                 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1082                 new_apdu->u.presentResponse->nextResultSetPosition =
1083                     odr_intdup(odr_encode(), start+toget);
1084
1085                 send_to_client(new_apdu);
1086                 return 0;
1087             }
1088         }
1089     }
1090
1091     if (apdu->which != Z_APDU_searchRequest)
1092         return apdu;
1093     Z_SearchRequest *sr = apdu->u.searchRequest;
1094     Yaz_Z_Query *this_query = new Yaz_Z_Query;
1095     Yaz_Z_Databases this_databases;
1096
1097     this_databases.set(sr->num_databaseNames, (const char **)
1098                        sr->databaseNames);
1099     
1100     this_query->set_Z_Query(sr->query);
1101
1102     char query_str[120];
1103     this_query->print(query_str, sizeof(query_str)-1);
1104     yaz_log(LOG_LOG, "%sSearch %s", m_session_str, query_str);
1105
1106     if (*m_parent->m_optimize != '0' &&
1107         m_client->m_last_ok && m_client->m_last_query &&
1108         m_client->m_last_query->match(this_query) &&
1109         !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1110         m_client->m_last_databases.match(this_databases))
1111     {
1112         delete this_query;
1113         if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1114             m_client->m_last_resultCount < *sr->largeSetLowerBound)
1115         {
1116             Z_NamePlusRecordList *npr;
1117             int toget = *sr->mediumSetPresentNumber;
1118             Z_RecordComposition *comp = 0;
1119
1120             if (toget > m_client->m_last_resultCount)
1121                 toget = m_client->m_last_resultCount;
1122             
1123             if (sr->mediumSetElementSetNames)
1124             {
1125                 comp = (Z_RecordComposition *)
1126                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1127                 comp->which = Z_RecordComp_simple;
1128                 comp->u.simple = sr->mediumSetElementSetNames;
1129             }
1130  
1131             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1132                                           sr->preferredRecordSyntax, comp))
1133             {
1134                 yaz_log (LOG_LOG, "%sReturned cached records for medium set",
1135                          m_session_str);
1136                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1137                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1138                 new_apdu->u.searchResponse->resultCount =
1139                     &m_client->m_last_resultCount;
1140                 
1141                 new_apdu->u.searchResponse->numberOfRecordsReturned
1142                     = odr_intdup(odr_encode(), toget);
1143                                                         
1144                 new_apdu->u.searchResponse->presentStatus =
1145                     odr_intdup(odr_encode(), Z_PresentStatus_success);
1146                 new_apdu->u.searchResponse->records = (Z_Records*)
1147                     odr_malloc(odr_encode(), sizeof(Z_Records));
1148                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1149                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1150                 new_apdu->u.searchResponse->nextResultSetPosition =
1151                     odr_intdup(odr_encode(), toget+1);
1152                 send_to_client(new_apdu);
1153                 return 0;
1154             }
1155             else
1156             {
1157                 // medium Set
1158                 // send present request (medium size)
1159                 yaz_log (LOG_LOG, "%sOptimizing search for medium set",
1160                          m_session_str);
1161
1162                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1163                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1164                 pr->referenceId = sr->referenceId;
1165                 pr->resultSetId = sr->resultSetName;
1166                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1167                 *pr->numberOfRecordsRequested = toget;
1168                 pr->recordComposition = comp;
1169                 m_client->m_sr_transform = 1;
1170                 return new_apdu;
1171             }
1172         }
1173         else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1174             m_client->m_last_resultCount <= 0)
1175         {
1176             // large set. Return pseudo-search response immediately
1177             yaz_log (LOG_LOG, "%sOptimizing search for large set",
1178                      m_session_str);
1179             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1180             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1181             new_apdu->u.searchResponse->resultCount =
1182                 &m_client->m_last_resultCount;
1183             send_to_client(new_apdu);
1184             return 0;
1185         }
1186         else
1187         {
1188             Z_NamePlusRecordList *npr;
1189             int toget = m_client->m_last_resultCount;
1190             Z_RecordComposition *comp = 0;
1191             // small set
1192             // send a present request (small set)
1193             
1194             if (sr->smallSetElementSetNames)
1195             {
1196                 comp = (Z_RecordComposition *)
1197                     odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1198                 comp->which = Z_RecordComp_simple;
1199                 comp->u.simple = sr->smallSetElementSetNames;
1200             }
1201
1202             if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1203                                           sr->preferredRecordSyntax, comp))
1204             {
1205                 yaz_log (LOG_LOG, "%sReturned cached records for small set",
1206                          m_session_str);
1207                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1208                 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1209                 new_apdu->u.searchResponse->resultCount =
1210                     &m_client->m_last_resultCount;
1211                 
1212                 new_apdu->u.searchResponse->numberOfRecordsReturned
1213                     = odr_intdup(odr_encode(), toget);
1214                                                                  
1215                 new_apdu->u.searchResponse->presentStatus =
1216                     odr_intdup(odr_encode(), Z_PresentStatus_success);
1217                 new_apdu->u.searchResponse->records = (Z_Records*)
1218                     odr_malloc(odr_encode(), sizeof(Z_Records));
1219                 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1220                 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1221                 new_apdu->u.searchResponse->nextResultSetPosition =
1222                     odr_intdup(odr_encode(), toget+1);
1223                 send_to_client(new_apdu);
1224                 return 0;
1225             }
1226             else
1227             {
1228                 yaz_log (LOG_LOG, "%sOptimizing search for small set",
1229                          m_session_str);
1230                 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1231                 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1232                 pr->referenceId = sr->referenceId;
1233                 pr->resultSetId = sr->resultSetName;
1234                 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1235                 *pr->numberOfRecordsRequested = toget;
1236                 pr->recordComposition = comp;
1237                 m_client->m_sr_transform = 1;
1238                 return new_apdu;
1239             }
1240         }
1241     }
1242     else  // query doesn't match
1243     {
1244         delete m_client->m_last_query;
1245         m_client->m_last_query = this_query;
1246         m_client->m_last_ok = 0;
1247         m_client->m_cache.clear();
1248         m_client->m_resultSetStartPoint = 0;
1249
1250         xfree (m_client->m_last_resultSetId);
1251         m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1252
1253         m_client->m_last_databases.set(sr->num_databaseNames,
1254                                        (const char **) sr->databaseNames);
1255     }
1256     return apdu;
1257 }
1258
1259
1260 void Yaz_Proxy::inc_request_no()
1261 {
1262     char *cp = strchr(m_session_str, ' ');
1263     m_request_no++;
1264     if (cp)
1265         sprintf(cp+1, "%d ", m_request_no);
1266 }
1267
1268 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1269 {
1270     inc_request_no();
1271
1272     m_bytes_recv += len;
1273     
1274     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
1275         yaz_log (LOG_DEBUG, "%sReceiving %s from client %d bytes",
1276                  m_session_str, gdu_name(apdu), len);
1277
1278     if (m_bw_hold_PDU)     // double incoming PDU. shutdown now.
1279         shutdown();
1280
1281     m_bw_stat.add_bytes(len);
1282     m_pdu_stat.add_bytes(1);
1283
1284     gettimeofday(&m_time_tv, 0);
1285
1286     int bw_total = m_bw_stat.get_total();
1287     int pdu_total = m_pdu_stat.get_total();
1288
1289     int reduce = 0;
1290     if (m_bw_max)
1291     {
1292         if (bw_total > m_bw_max)
1293         {
1294             reduce = (bw_total/m_bw_max);
1295         }
1296     }
1297     if (m_pdu_max)
1298     {
1299         if (pdu_total > m_pdu_max)
1300         {
1301             int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1302             reduce = (reduce > nreduce) ? reduce : nreduce;
1303         }
1304     }
1305     if (reduce)  
1306     {
1307         yaz_log(LOG_LOG, "%sdelay=%d bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1308                 m_session_str, reduce, bw_total, pdu_total,
1309                 m_bw_max, m_pdu_max);
1310         
1311         m_bw_hold_PDU = apdu;  // save PDU and signal "on hold"
1312         timeout(reduce);       // call us reduce seconds later
1313     }
1314     else if (apdu->which == Z_GDU_Z3950)
1315         handle_incoming_Z_PDU(apdu->u.z3950);
1316     else if (apdu->which == Z_GDU_HTTP_Request)
1317         handle_incoming_HTTP(apdu->u.HTTP_Request);
1318 }
1319
1320 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
1321 {
1322     if (m_max_record_retrieve)
1323     {
1324         if (apdu->which == Z_APDU_presentRequest)
1325         {
1326             Z_PresentRequest *pr = apdu->u.presentRequest;
1327             if (pr->numberOfRecordsRequested && 
1328                 *pr->numberOfRecordsRequested > m_max_record_retrieve)
1329                 *pr->numberOfRecordsRequested = m_max_record_retrieve;
1330         }
1331     }
1332 }
1333
1334 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
1335                                                      int error,
1336                                                      const char *addinfo)
1337 {
1338     Z_Records *rec = (Z_Records *)
1339         odr_malloc (odr, sizeof(*rec));
1340     int *err = (int *)
1341         odr_malloc (odr, sizeof(*err));
1342     Z_DiagRec *drec = (Z_DiagRec *)
1343         odr_malloc (odr, sizeof(*drec));
1344     Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1345         odr_malloc (odr, sizeof(*dr));
1346     *err = error;
1347     rec->which = Z_Records_NSD;
1348     rec->u.nonSurrogateDiagnostic = dr;
1349     dr->diagnosticSetId =
1350         yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
1351     dr->condition = err;
1352     dr->which = Z_DefaultDiagFormat_v2Addinfo;
1353     dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1354     return rec;
1355 }
1356
1357 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
1358 {
1359     if (apdu->which == Z_APDU_searchRequest &&
1360         apdu->u.searchRequest->query &&
1361         apdu->u.searchRequest->query->which == Z_Query_type_104 &&
1362         apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
1363     {
1364         Z_RPNQuery *rpnquery = 0;
1365         Z_SearchRequest *sr = apdu->u.searchRequest;
1366         char *addinfo = 0;
1367         
1368         yaz_log(LOG_LOG, "%sCQL: %s", m_session_str,
1369                 sr->query->u.type_104->u.cql);
1370
1371         int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
1372                                           &rpnquery, odr_encode(),
1373                                           &addinfo);
1374         if (r == -3)
1375             yaz_log(LOG_LOG, "%sNo CQL to RPN table", m_session_str);
1376         else if (r)
1377         {
1378             yaz_log(LOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
1379             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1380
1381             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1382             new_apdu->u.searchResponse->records =
1383                 create_nonSurrogateDiagnostics(odr_encode(),
1384                                                yaz_diag_srw_to_bib1(r),
1385                                                addinfo);
1386             *new_apdu->u.searchResponse->searchStatus = 0;
1387
1388             send_to_client(new_apdu);
1389
1390             return 0;
1391         }
1392         else
1393         {
1394             sr->query->which = Z_Query_type_1;
1395             sr->query->u.type_1 = rpnquery;
1396         }
1397         return apdu;
1398     }
1399     return apdu;
1400 }
1401
1402 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
1403 {
1404     if (apdu->which == Z_APDU_searchRequest)
1405     {
1406         Z_SearchRequest *sr = apdu->u.searchRequest;
1407         int err = 0;
1408         char *addinfo = 0;
1409
1410         Yaz_ProxyConfig *cfg = check_reconfigure();
1411         if (cfg)
1412             err = cfg->check_query(odr_encode(), m_default_target,
1413                                    sr->query, &addinfo);
1414         if (err)
1415         {
1416             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1417
1418             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1419             new_apdu->u.searchResponse->records =
1420                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1421             *new_apdu->u.searchResponse->searchStatus = 0;
1422
1423             send_to_client(new_apdu);
1424
1425             return 0;
1426         }
1427     }
1428     return apdu;
1429 }
1430
1431 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
1432 {
1433     m_marcxml_flag = 0;
1434     if (apdu->which == Z_APDU_searchRequest)
1435     {
1436         Z_SearchRequest *sr = apdu->u.searchRequest;
1437         int err = 0;
1438         char *addinfo = 0;
1439         Yaz_ProxyConfig *cfg = check_reconfigure();
1440
1441         Z_RecordComposition rc_temp, *rc = 0;
1442         if (sr->smallSetElementSetNames)
1443         {
1444             rc_temp.which = Z_RecordComp_simple;
1445             rc_temp.u.simple = sr->smallSetElementSetNames;
1446             rc = &rc_temp;
1447         }
1448             
1449         if (cfg)
1450             err = cfg->check_syntax(odr_encode(),
1451                                     m_default_target,
1452                                     sr->preferredRecordSyntax, rc,
1453                                     &addinfo, &m_stylesheet, &m_schema);
1454         if (err == -1)
1455         {
1456             sr->preferredRecordSyntax =
1457                 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN, VAL_USMARC);
1458             m_marcxml_flag = 1;
1459         }
1460         else if (err)
1461         {
1462             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1463             
1464             new_apdu->u.searchResponse->referenceId = sr->referenceId;
1465             new_apdu->u.searchResponse->records =
1466                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1467             *new_apdu->u.searchResponse->searchStatus = 0;
1468             
1469             send_to_client(new_apdu);
1470             
1471             return 0;
1472         }
1473     }
1474     else if (apdu->which == Z_APDU_presentRequest)
1475     {
1476         Z_PresentRequest *pr = apdu->u.presentRequest;
1477         int err = 0;
1478         char *addinfo = 0;
1479         Yaz_ProxyConfig *cfg = check_reconfigure();
1480
1481         if (cfg)
1482             err = cfg->check_syntax(odr_encode(), m_default_target,
1483                                     pr->preferredRecordSyntax,
1484                                     pr->recordComposition,
1485                                     &addinfo, &m_stylesheet, &m_schema);
1486         if (err == -1)
1487         {
1488             pr->preferredRecordSyntax =
1489                 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN, VAL_USMARC);
1490             m_marcxml_flag = 1;
1491         }
1492         else if (err)
1493         {
1494             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1495             
1496             new_apdu->u.presentResponse->referenceId = pr->referenceId;
1497             new_apdu->u.presentResponse->records =
1498                 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1499             *new_apdu->u.presentResponse->presentStatus =
1500                 Z_PresentStatus_failure;
1501             
1502             send_to_client(new_apdu);
1503             
1504             return 0;
1505         }
1506     }
1507     return apdu;
1508 }
1509
1510 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
1511 {
1512     if (!schema)
1513         return 0;
1514     Z_ElementSetNames *esn = (Z_ElementSetNames *)
1515         odr_malloc(o, sizeof(Z_ElementSetNames));
1516     esn->which = Z_ElementSetNames_generic;
1517     esn->u.generic = odr_strdup(o, schema);
1518     return esn;
1519 }
1520
1521 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
1522 {
1523
1524     if (m_s2z_odr_init)
1525     {
1526         odr_destroy(m_s2z_odr_init);
1527         m_s2z_odr_init = 0;
1528     }
1529     if (m_s2z_odr_search)
1530     {
1531         odr_destroy(m_s2z_odr_search);
1532         m_s2z_odr_search = 0;
1533     }
1534
1535     m_http_keepalive = 0;
1536     m_http_version = 0;
1537     if (!strcmp(hreq->version, "1.0")) 
1538     {
1539         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1540         if (v && !strcmp(v, "Keep-Alive"))
1541             m_http_keepalive = 1;
1542         else
1543             m_http_keepalive = 0;
1544         m_http_version = "1.0";
1545     }
1546     else
1547     {
1548         const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1549         if (v && !strcmp(v, "close"))
1550             m_http_keepalive = 0;
1551         else
1552             m_http_keepalive = 1;
1553         m_http_version = "1.1";
1554     }
1555
1556     Z_SRW_PDU *srw_pdu = 0;
1557     Z_SOAP *soap_package = 0;
1558     char *charset = 0;
1559     if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
1560                        &charset) == 0
1561         || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
1562                           &charset) == 0)
1563     {
1564         m_s2z_odr_init = odr_createmem(ODR_ENCODE);
1565         m_s2z_odr_search = odr_createmem(ODR_ENCODE);
1566         m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
1567         m_s2z_init_apdu = 0;
1568         m_s2z_search_apdu = 0;
1569         m_s2z_present_apdu = 0;
1570         if (srw_pdu->which == Z_SRW_searchRetrieve_request)
1571         {
1572             Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
1573
1574             // set packing for response records ..
1575             if (srw_req->recordPacking &&
1576                 !strcmp(srw_req->recordPacking, "xml"))
1577                 m_s2z_packing = Z_SRW_recordPacking_XML;
1578             else
1579                 m_s2z_packing = Z_SRW_recordPacking_string;
1580
1581             // prepare search PDU
1582             m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
1583                                           Z_APDU_searchRequest);
1584             Z_SearchRequest *z_searchRequest =
1585                 m_s2z_search_apdu->u.searchRequest;
1586
1587             z_searchRequest->num_databaseNames = 1;
1588             z_searchRequest->databaseNames = (char**)
1589                 odr_malloc(m_s2z_odr_search, sizeof(char *));
1590             z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
1591                                                            srw_req->database);
1592             
1593             // query transformation
1594             Z_Query *query = (Z_Query *)
1595                 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
1596             z_searchRequest->query = query;
1597             
1598             if (srw_req->query_type == Z_SRW_query_type_cql)
1599             {
1600                 Z_External *ext = (Z_External *) 
1601                     odr_malloc(m_s2z_odr_search, sizeof(*ext));
1602                 ext->direct_reference = 
1603                     odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
1604                 ext->indirect_reference = 0;
1605                 ext->descriptor = 0;
1606                 ext->which = Z_External_CQL;
1607                 ext->u.cql = srw_req->query.cql;
1608                 
1609                 query->which = Z_Query_type_104;
1610                 query->u.type_104 =  ext;
1611             }
1612             else if (srw_req->query_type == Z_SRW_query_type_pqf)
1613             {
1614                 Z_RPNQuery *RPNquery;
1615                 YAZ_PQF_Parser pqf_parser;
1616                 
1617                 pqf_parser = yaz_pqf_create ();
1618                 
1619                 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
1620                                           srw_req->query.pqf);
1621                 if (!RPNquery)
1622                 {
1623                     const char *pqf_msg;
1624                     size_t off;
1625                     int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1626                     yaz_log(LOG_LOG, "%*s^\n", off+4, "");
1627                     yaz_log(LOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
1628                     
1629                     send_to_srw_client_error(10);
1630                     return;
1631                 }
1632                 query->which = Z_Query_type_1;
1633                 query->u.type_1 =  RPNquery;
1634                 
1635                 yaz_pqf_destroy (pqf_parser);
1636             }
1637             else
1638             {
1639                 send_to_srw_client_error(11);
1640                 return;
1641             }
1642
1643             // present
1644             m_s2z_present_apdu = 0;
1645             int max = 0;
1646             if (srw_req->maximumRecords)
1647                 max = *srw_req->maximumRecords;
1648             int start = 1;
1649             if (srw_req->startRecord)
1650                 start = *srw_req->startRecord;
1651             if (max > 0)
1652             {
1653                 // Some backend, such as Voyager doesn't honor piggyback
1654                 // So we use present always (0 &&).
1655                 if (0 && start <= 1)  // Z39.50 piggyback
1656                 {
1657                     *z_searchRequest->smallSetUpperBound = max;
1658                     *z_searchRequest->mediumSetPresentNumber = max;
1659                     *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
1660
1661                     z_searchRequest->preferredRecordSyntax =
1662                         yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
1663                                                VAL_TEXT_XML);
1664                     if (srw_req->recordSchema)
1665                     {
1666                         z_searchRequest->smallSetElementSetNames =
1667                             z_searchRequest->mediumSetElementSetNames =
1668                             mk_esn_from_schema(m_s2z_odr_search,
1669                                                srw_req->recordSchema);
1670                     }
1671                 }
1672                 else   // Z39.50 present
1673                 {
1674                     m_s2z_present_apdu = zget_APDU(m_s2z_odr_search, 
1675                                                    Z_APDU_presentRequest);
1676                     Z_PresentRequest *z_presentRequest = 
1677                         m_s2z_present_apdu->u.presentRequest;
1678                     *z_presentRequest->resultSetStartPoint = start;
1679                     *z_presentRequest->numberOfRecordsRequested = max;
1680                     z_presentRequest->preferredRecordSyntax =
1681                         yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
1682                                                VAL_TEXT_XML);
1683                     z_presentRequest->recordComposition =
1684                         (Z_RecordComposition *)
1685                         odr_malloc(m_s2z_odr_search,
1686                                    sizeof(Z_RecordComposition));
1687                     if (srw_req->recordSchema)
1688                     {
1689                         z_presentRequest->recordComposition->which = 
1690                             Z_RecordComp_simple;                    
1691                         z_presentRequest->recordComposition->u.simple =
1692                             mk_esn_from_schema(m_s2z_odr_search,
1693                                                srw_req->recordSchema);
1694                     }
1695                 }
1696             }
1697             if (!m_client)
1698             {
1699                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
1700                                             Z_APDU_initRequest);
1701                 
1702                 // prevent m_initRequest_apdu memory from being grabbed
1703                 // in Yaz_Proxy::handle_incoming_Z_PDU
1704                 m_initRequest_apdu = m_s2z_init_apdu;
1705                 handle_incoming_Z_PDU(m_s2z_init_apdu);
1706                 return;
1707             }
1708             else
1709             {
1710                 handle_incoming_Z_PDU(m_s2z_search_apdu);
1711                 return;
1712             }
1713         }
1714         else if (srw_pdu->which == Z_SRW_explain_request)
1715         {
1716             Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
1717             
1718             if (srw_req->recordPacking &&
1719                 !strcmp(srw_req->recordPacking, "xml"))
1720                 m_s2z_packing = Z_SRW_recordPacking_XML;
1721             else
1722                 m_s2z_packing = Z_SRW_recordPacking_string;
1723
1724             if (!m_client)
1725             {
1726                 yaz_log(LOG_LOG, "handle_incoming: initRequest");
1727                 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
1728                                             Z_APDU_initRequest);
1729                 
1730                 // prevent m_initRequest_apdu memory from being grabbed
1731                 // in Yaz_Proxy::handle_incoming_Z_PDU
1732                 m_initRequest_apdu = m_s2z_init_apdu;
1733                 handle_incoming_Z_PDU(m_s2z_init_apdu);
1734             }
1735             else
1736                 send_srw_explain();
1737             return;
1738         }
1739     }
1740     int len = 0;
1741     Z_GDU *p = z_get_HTTP_Response(odr_encode(), 400);
1742     send_GDU(p, &len);
1743     timeout(1);
1744 }
1745
1746 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
1747 {
1748     if (!m_client && m_invalid_session)
1749     {
1750         m_apdu_invalid_session = apdu;
1751         m_mem_invalid_session = odr_extract_mem(odr_decode());
1752         apdu = m_initRequest_apdu;
1753     }
1754
1755     // Determine our client.
1756     Z_OtherInformation **oi;
1757     get_otherInfoAPDU(apdu, &oi);
1758     m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
1759     if (!m_client)
1760     {
1761         delete this;
1762         return;
1763     }
1764     m_client->m_server = this;
1765
1766     if (apdu->which == Z_APDU_initRequest)
1767     {
1768         if (apdu->u.initRequest->implementationId)
1769             yaz_log(LOG_LOG, "%simplementationId: %s",
1770                     m_session_str, apdu->u.initRequest->implementationId);
1771         if (apdu->u.initRequest->implementationName)
1772             yaz_log(LOG_LOG, "%simplementationName: %s",
1773                     m_session_str, apdu->u.initRequest->implementationName);
1774         if (apdu->u.initRequest->implementationVersion)
1775             yaz_log(LOG_LOG, "%simplementationVersion: %s",
1776                     m_session_str, apdu->u.initRequest->implementationVersion);
1777         if (m_initRequest_apdu == 0)
1778         {
1779             if (m_initRequest_mem)
1780                 nmem_destroy(m_initRequest_mem);
1781             m_initRequest_apdu = apdu;
1782             m_initRequest_mem = odr_extract_mem(odr_decode());
1783         }
1784         if (m_client->m_init_flag)
1785         {
1786             if (handle_init_response_for_invalid_session(apdu))
1787                 return;
1788             Z_APDU *apdu2 = m_client->m_initResponse;
1789             apdu2->u.initResponse->otherInfo = 0;
1790             if (m_client->m_cookie && *m_client->m_cookie)
1791                 set_otherInformationString(apdu2, VAL_COOKIE, 1,
1792                                            m_client->m_cookie);
1793             apdu2->u.initResponse->referenceId =
1794                 apdu->u.initRequest->referenceId;
1795             send_to_client(apdu2);
1796             return;
1797         }
1798         m_client->m_init_flag = 1;
1799     }
1800     handle_max_record_retrieve(apdu);
1801
1802     if (apdu)
1803         apdu = handle_syntax_validation(apdu);
1804
1805     if (apdu)
1806         apdu = handle_query_transformation(apdu);
1807
1808     if (apdu)
1809         apdu = handle_query_validation(apdu);
1810
1811     if (apdu)
1812         apdu = result_set_optimize(apdu);
1813     if (!apdu)
1814     {
1815         m_client->timeout(m_target_idletime);  // mark it active even 
1816         // though we didn't use it
1817         return;
1818     }
1819
1820     // delete other info part from PDU before sending to target
1821     get_otherInfoAPDU(apdu, &oi);
1822     if (oi)
1823         *oi = 0;
1824
1825     if (apdu->which == Z_APDU_presentRequest &&
1826         m_client->m_resultSetStartPoint == 0)
1827     {
1828         Z_PresentRequest *pr = apdu->u.presentRequest;
1829         m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
1830         m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
1831     } else {
1832         m_client->m_resultSetStartPoint = 0;
1833     }
1834     if (m_client->send_to_target(apdu) < 0)
1835     {
1836         delete m_client;
1837         m_client = 0;
1838         delete this;
1839     }
1840     else
1841         m_client->m_waiting = 1;
1842 }
1843
1844 void Yaz_Proxy::connectNotify()
1845 {
1846 }
1847
1848 void Yaz_Proxy::shutdown()
1849 {
1850     m_invalid_session = 0;
1851     // only keep if keep_alive flag is set...
1852     if (m_client && 
1853         m_client->m_pdu_recv < m_keepalive_limit_pdu &&
1854         m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
1855         m_client->m_waiting == 0)
1856     {
1857         yaz_log(LOG_LOG, "%sShutdown (client to proxy) keepalive %s",
1858                  m_session_str,
1859                  m_client->get_hostname());
1860         yaz_log(LOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1861                 m_session_str, m_client->m_pdu_recv,
1862                 m_client->m_bytes_sent + m_client->m_bytes_recv,
1863                 m_keepalive_limit_bw, m_keepalive_limit_pdu);
1864         assert (m_client->m_waiting != 2);
1865         // Tell client (if any) that no server connection is there..
1866         m_client->m_server = 0;
1867         m_invalid_session = 0;
1868     }
1869     else if (m_client)
1870     {
1871         yaz_log (LOG_LOG, "%sShutdown (client to proxy) close %s",
1872                  m_session_str,
1873                  m_client->get_hostname());
1874         assert (m_client->m_waiting != 2);
1875         delete m_client;
1876     }
1877     else if (!m_parent)
1878     {
1879         yaz_log (LOG_LOG, "%sshutdown (client to proxy) bad state",
1880                  m_session_str);
1881         assert (m_parent);
1882     }
1883     else 
1884     {
1885         yaz_log (LOG_LOG, "%sShutdown (client to proxy)",
1886                  m_session_str);
1887     }
1888     if (m_parent)
1889         m_parent->pre_init();
1890     delete this;
1891 }
1892
1893 const char *Yaz_ProxyClient::get_session_str() 
1894 {
1895     if (!m_server)
1896         return "0 ";
1897     return m_server->get_session_str();
1898 }
1899
1900 void Yaz_ProxyClient::shutdown()
1901 {
1902     yaz_log (LOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
1903              get_hostname());
1904     delete m_server;
1905     delete this;
1906 }
1907
1908 void Yaz_Proxy::failNotify()
1909 {
1910     inc_request_no();
1911     yaz_log (LOG_LOG, "%sConnection closed by client",
1912              get_session_str());
1913     shutdown();
1914 }
1915
1916 void Yaz_ProxyClient::failNotify()
1917 {
1918     if (m_server)
1919         m_server->inc_request_no();
1920     yaz_log (LOG_LOG, "%sConnection closed by target %s", 
1921              get_session_str(), get_hostname());
1922     shutdown();
1923 }
1924
1925 void Yaz_ProxyClient::connectNotify()
1926 {
1927     const char *s = get_session_str();
1928     const char *h = get_hostname();
1929     yaz_log (LOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
1930              m_target_idletime);
1931     timeout(m_target_idletime);
1932     if (!m_server)
1933         pre_init_client();
1934 }
1935
1936 IYaz_PDU_Observer *Yaz_ProxyClient::sessionNotify(IYaz_PDU_Observable
1937                                                   *the_PDU_Observable, int fd)
1938 {
1939     return new Yaz_ProxyClient(the_PDU_Observable, 0);
1940 }
1941
1942 Yaz_ProxyClient::~Yaz_ProxyClient()
1943 {
1944     if (m_prev)
1945         *m_prev = m_next;
1946     if (m_next)
1947         m_next->m_prev = m_prev;
1948     m_waiting = 2;     // for debugging purposes only.
1949     odr_destroy(m_init_odr);
1950     delete m_last_query;
1951     xfree (m_last_resultSetId);
1952     xfree (m_cookie);
1953 }
1954
1955 void Yaz_ProxyClient::pre_init_client()
1956 {
1957     Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
1958     Z_InitRequest *req = apdu->u.initRequest;
1959     
1960     ODR_MASK_SET(req->options, Z_Options_search);
1961     ODR_MASK_SET(req->options, Z_Options_present);
1962     ODR_MASK_SET(req->options, Z_Options_namedResultSets);
1963     ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
1964     ODR_MASK_SET(req->options, Z_Options_scan);
1965     ODR_MASK_SET(req->options, Z_Options_sort);
1966     ODR_MASK_SET(req->options, Z_Options_extendedServices);
1967     ODR_MASK_SET(req->options, Z_Options_delSet);
1968     
1969     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
1970     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
1971     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
1972     
1973     if (send_to_target(apdu) < 0)
1974     {
1975         delete this;
1976     }
1977     else
1978     {
1979         m_waiting = 1;
1980         m_init_flag = 1;
1981     }
1982 }
1983
1984 void Yaz_Proxy::pre_init()
1985 {
1986     int i;
1987     const char *name = 0;
1988     const char *zurl_in_use[MAX_ZURL_PLEX];
1989     int limit_bw, limit_pdu, limit_req;
1990     int target_idletime, client_idletime;
1991     int max_clients;
1992     int keepalive_limit_bw, keepalive_limit_pdu;
1993     int pre_init;
1994     const char *cql2rpn = 0;
1995     const char *zeerex = 0;
1996
1997     Yaz_ProxyConfig *cfg = check_reconfigure();
1998
1999     zurl_in_use[0] = 0;
2000
2001     if (m_log_mask & PROXY_LOG_APDU_CLIENT)
2002         set_APDU_yazlog(1);
2003     else
2004         set_APDU_yazlog(0);
2005
2006     for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
2007                                           &limit_bw, &limit_pdu, &limit_req,
2008                                           &target_idletime, &client_idletime,
2009                                           &max_clients, 
2010                                           &keepalive_limit_bw,
2011                                           &keepalive_limit_pdu,
2012                                           &pre_init,
2013                                           &cql2rpn) ; i++)
2014     {
2015         if (pre_init)
2016         {
2017             int j;
2018             for (j = 0; zurl_in_use[j]; j++)
2019             {
2020                 Yaz_ProxyClient *c;
2021                 int spare = 0;
2022                 int in_use = 0;
2023                 int other = 0;
2024                 for (c = m_clientPool; c; c = c->m_next)
2025                 {
2026                     if (!strcmp(zurl_in_use[j], c->get_hostname()))
2027                     {
2028                         if (c->m_cookie == 0)
2029                         {
2030                             if (c->m_server == 0)
2031                                 spare++;
2032                             else
2033                                 in_use++;
2034                         }
2035                         else
2036                             other++;
2037                     }
2038                 }
2039                 yaz_log(LOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
2040                         "preinit=%d",m_session_str,
2041                         name, zurl_in_use[j], in_use, other, spare, pre_init);
2042                 if (spare < pre_init)
2043                 {
2044                     c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
2045                     c->m_next = m_clientPool;
2046                     if (c->m_next)
2047                         c->m_next->m_prev = &c->m_next;
2048                     m_clientPool = c;
2049                     c->m_prev = &m_clientPool;
2050                     
2051                     if (m_log_mask & PROXY_LOG_APDU_SERVER)
2052                         c->set_APDU_yazlog(1);
2053                     else
2054                         c->set_APDU_yazlog(0);
2055
2056                     if (c->client(zurl_in_use[j]))
2057                     {
2058                         timeout(60);
2059                         delete c;
2060                         return;
2061                     }
2062                     c->timeout(30);
2063                     c->m_waiting = 1;
2064                     c->m_target_idletime = target_idletime;
2065                     c->m_seqno = m_seqno++;
2066                 }
2067             }
2068         }
2069     }
2070 }
2071
2072 void Yaz_Proxy::timeoutNotify()
2073 {
2074     if (m_parent)
2075     {
2076         if (m_bw_hold_PDU)
2077         {
2078             timeout(m_client_idletime);
2079             Z_GDU *apdu = m_bw_hold_PDU;
2080             m_bw_hold_PDU = 0;
2081             
2082             if (apdu->which == Z_GDU_Z3950)
2083                 handle_incoming_Z_PDU(apdu->u.z3950);
2084             else if (apdu->which == Z_GDU_HTTP_Request)
2085                 handle_incoming_HTTP(apdu->u.HTTP_Request);
2086         }
2087         else
2088         {
2089             inc_request_no();
2090
2091             yaz_log (LOG_LOG, "%sTimeout (client to proxy)", m_session_str);
2092             shutdown();
2093         }
2094     }
2095     else
2096     {
2097         timeout(600);
2098         pre_init();
2099     }
2100 }
2101
2102 void Yaz_ProxyClient::timeoutNotify()
2103 {
2104     if (m_server)
2105         m_server->inc_request_no();
2106
2107     yaz_log (LOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
2108              get_hostname());
2109     m_waiting = 1;
2110     m_root->pre_init();
2111     shutdown();
2112 }
2113
2114 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable,
2115                                  Yaz_Proxy *parent) :
2116     Yaz_Z_Assoc (the_PDU_Observable)
2117 {
2118     m_cookie = 0;
2119     m_next = 0;
2120     m_prev = 0;
2121     m_init_flag = 0;
2122     m_last_query = 0;
2123     m_last_resultSetId = 0;
2124     m_last_resultCount = 0;
2125     m_last_ok = 0;
2126     m_sr_transform = 0;
2127     m_waiting = 0;
2128     m_init_odr = odr_createmem (ODR_DECODE);
2129     m_initResponse = 0;
2130     m_resultSetStartPoint = 0;
2131     m_bytes_sent = m_bytes_recv = 0;
2132     m_pdu_recv = 0;
2133     m_server = 0;
2134     m_seqno = 0;
2135     m_target_idletime = 600;
2136     m_root = parent;
2137 }
2138
2139 const char *Yaz_Proxy::option(const char *name, const char *value)
2140 {
2141     if (!strcmp (name, "optimize")) {
2142         if (value) {
2143             xfree (m_optimize); 
2144             m_optimize = xstrdup (value);
2145         }
2146         return m_optimize;
2147     }
2148     return 0;
2149 }
2150
2151 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
2152 {
2153
2154 }
2155
2156 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
2157 {
2158     if (apdu->which == Z_GDU_Z3950)
2159         recv_Z_PDU(apdu->u.z3950, len);
2160     else if (apdu->which == Z_GDU_HTTP_Response)
2161         recv_HTTP_response(apdu->u.HTTP_Response, len);
2162     else
2163         shutdown();
2164 }
2165
2166 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
2167 {
2168     if (!m_invalid_session)
2169         return 0;
2170     m_invalid_session = 0;
2171     handle_incoming_Z_PDU(m_apdu_invalid_session);
2172     assert (m_mem_invalid_session);
2173     nmem_destroy(m_mem_invalid_session);
2174     m_mem_invalid_session = 0;
2175     return 1;
2176 }
2177
2178 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
2179 {
2180     m_bytes_recv += len;
2181     m_pdu_recv++;
2182     m_waiting = 0;
2183     if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
2184         yaz_log (LOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
2185                  apdu_name(apdu), get_hostname(), len);
2186     if (apdu->which == Z_APDU_initResponse)
2187     {
2188         if (!m_server)  // if this is a pre init session , check for more
2189             m_root->pre_init();
2190         NMEM nmem = odr_extract_mem (odr_decode());
2191         odr_reset (m_init_odr);
2192         nmem_transfer (m_init_odr->mem, nmem);
2193         m_initResponse = apdu;
2194
2195         Z_InitResponse *ir = apdu->u.initResponse;
2196         char *im0 = ir->implementationName;
2197         
2198         char *im1 = (char*) 
2199             odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
2200         *im1 = '\0';
2201         if (im0)
2202         {
2203             strcat(im1, im0);
2204             strcat(im1, " ");
2205         }
2206         strcat(im1, "(YAZ Proxy)");
2207         ir->implementationName = im1;
2208
2209         nmem_destroy (nmem);
2210
2211         if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
2212             return;
2213     }
2214     if (apdu->which == Z_APDU_searchResponse)
2215     {
2216         Z_SearchResponse *sr = apdu->u.searchResponse;
2217         m_last_resultCount = *sr->resultCount;
2218         int status = *sr->searchStatus;
2219         if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
2220         {
2221             m_last_ok = 1;
2222             
2223             if (sr->records && sr->records->which == Z_Records_DBOSD)
2224             {
2225                 m_cache.add(odr_decode(),
2226                             sr->records->u.databaseOrSurDiagnostics, 1,
2227                             *sr->resultCount);
2228             }
2229         }
2230     }
2231     if (apdu->which == Z_APDU_presentResponse)
2232     {
2233         Z_PresentResponse *pr = apdu->u.presentResponse;
2234         if (m_sr_transform)
2235         {
2236             m_sr_transform = 0;
2237             Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2238             Z_SearchResponse *sr = new_apdu->u.searchResponse;
2239             sr->referenceId = pr->referenceId;
2240             *sr->resultCount = m_last_resultCount;
2241             sr->records = pr->records;
2242             sr->nextResultSetPosition = pr->nextResultSetPosition;
2243             sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
2244             apdu = new_apdu;
2245         }
2246         if (pr->records && 
2247             pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
2248         {
2249             m_cache.add(odr_decode(),
2250                         pr->records->u.databaseOrSurDiagnostics,
2251                         m_resultSetStartPoint, -1);
2252             m_resultSetStartPoint = 0;
2253         }
2254     }
2255     if (m_cookie)
2256         set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
2257     if (m_server)
2258     {
2259         m_server->send_to_client(apdu);
2260     }
2261     if (apdu->which == Z_APDU_close)
2262     {
2263         shutdown();
2264     }
2265 }
2266
2267 int Yaz_Proxy::server(const char *addr)
2268 {
2269     int r = Yaz_Z_Assoc::server(addr);
2270     if (!r)
2271     {
2272         yaz_log(LOG_LOG, "%sStarted proxy " VERSION " on %s", m_session_str, addr);
2273         timeout(1);
2274     }
2275     return r;
2276 }
2277