2 * Copyright (c) 1998-2003, Index Data.
3 * See the file LICENSE for details.
5 * $Id: yaz-proxy.cpp,v 1.72 2003-12-20 22:44:30 adam Exp $
12 #include <yaz/marcdisp.h>
13 #include <yaz/yaz-iconv.h>
15 #include <yaz/diagbib1.h>
16 #include <yaz++/proxy.h>
17 #include <yaz/pquery.h>
19 static const char *apdu_name(Z_APDU *apdu)
23 case Z_APDU_initRequest:
25 case Z_APDU_initResponse:
26 return "initResponse";
27 case Z_APDU_searchRequest:
28 return "searchRequest";
29 case Z_APDU_searchResponse:
30 return "searchResponse";
31 case Z_APDU_presentRequest:
32 return "presentRequest";
33 case Z_APDU_presentResponse:
34 return "presentResponse";
35 case Z_APDU_deleteResultSetRequest:
36 return "deleteResultSetRequest";
37 case Z_APDU_deleteResultSetResponse:
38 return "deleteResultSetResponse";
39 case Z_APDU_scanRequest:
41 case Z_APDU_scanResponse:
42 return "scanResponse";
43 case Z_APDU_sortRequest:
45 case Z_APDU_sortResponse:
46 return "sortResponse";
47 case Z_APDU_extendedServicesRequest:
48 return "extendedServicesRequest";
49 case Z_APDU_extendedServicesResponse:
50 return "extendedServicesResponse";
57 static const char *gdu_name(Z_GDU *gdu)
62 return apdu_name(gdu->u.z3950);
63 case Z_GDU_HTTP_Request:
64 return "HTTP Request";
65 case Z_GDU_HTTP_Response:
66 return "HTTP Response";
68 return "Unknown request/response";
71 Yaz_Proxy::Yaz_Proxy(IYaz_PDU_Observable *the_PDU_Observable,
73 Yaz_Z_Assoc(the_PDU_Observable), m_bw_stat(60), m_pdu_stat(60)
75 m_PDU_Observable = the_PDU_Observable;
80 m_keepalive_limit_bw = 500000;
81 m_keepalive_limit_pdu = 1000;
84 m_proxy_authentication = 0;
88 m_client_idletime = 600;
89 m_target_idletime = 600;
90 m_optimize = xstrdup ("1");
91 strcpy(m_session_str, "0 ");
93 m_bytes_sent = m_bytes_recv = 0;
97 m_max_record_retrieve = 0;
101 m_invalid_session = 0;
104 m_initRequest_apdu = 0;
105 m_initRequest_mem = 0;
106 m_apdu_invalid_session = 0;
107 m_mem_invalid_session = 0;
109 m_s2z_odr_search = 0;
111 m_s2z_search_apdu = 0;
112 m_s2z_present_apdu = 0;
113 m_http_keepalive = 0;
116 m_s2z_packing = Z_SRW_recordPacking_string;
120 Yaz_Proxy::~Yaz_Proxy()
122 yaz_log(LOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
123 m_bytes_sent, m_bytes_recv);
124 nmem_destroy(m_initRequest_mem);
125 nmem_destroy(m_mem_invalid_session);
126 xfree (m_proxyTarget);
127 xfree (m_default_target);
128 xfree (m_proxy_authentication);
131 odr_destroy(m_s2z_odr_init);
132 if (m_s2z_odr_search)
133 odr_destroy(m_s2z_odr_search);
137 int Yaz_Proxy::set_config(const char *config)
140 m_config = new Yaz_ProxyConfig();
141 xfree(m_config_fname);
142 m_config_fname = xstrdup(config);
143 int r = m_config->read_xml(config);
145 m_config->get_generic_info(&m_log_mask, &m_max_clients);
149 void Yaz_Proxy::set_default_target(const char *target)
151 xfree (m_default_target);
152 m_default_target = 0;
154 m_default_target = (char *) xstrdup (target);
157 void Yaz_Proxy::set_proxy_authentication (const char *auth)
159 xfree (m_proxy_authentication);
160 m_proxy_authentication = 0;
162 m_proxy_authentication = (char *) xstrdup (auth);
165 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
168 return m_parent->check_reconfigure();
170 Yaz_ProxyConfig *cfg = m_config;
173 yaz_log(LOG_LOG, "reconfigure");
175 if (m_config_fname && cfg)
177 yaz_log(LOG_LOG, "reconfigure config %s", m_config_fname);
178 int r = cfg->read_xml(m_config_fname);
180 yaz_log(LOG_WARN, "reconfigure failed");
184 cfg->get_generic_info(&m_log_mask, &m_max_clients);
188 yaz_log(LOG_LOG, "reconfigure");
194 IYaz_PDU_Observer *Yaz_Proxy::sessionNotify(IYaz_PDU_Observable
195 *the_PDU_Observable, int fd)
198 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable, this);
199 new_proxy->m_config = 0;
200 new_proxy->m_config_fname = 0;
201 new_proxy->timeout(m_client_idletime);
202 new_proxy->m_target_idletime = m_target_idletime;
203 new_proxy->set_default_target(m_default_target);
204 new_proxy->m_max_clients = m_max_clients;
205 new_proxy->m_log_mask = m_log_mask;
206 new_proxy->set_APDU_log(get_APDU_log());
207 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
208 new_proxy->set_APDU_yazlog(1);
210 new_proxy->set_APDU_yazlog(0);
211 new_proxy->set_proxy_authentication(m_proxy_authentication);
212 sprintf(new_proxy->m_session_str, "%ld:%d ", (long) time(0), m_session_no);
214 yaz_log (LOG_LOG, "%sNew session %s", new_proxy->m_session_str,
215 the_PDU_Observable->getpeername());
219 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
222 Z_OtherInformationUnit *oi;
224 ent.proto = PROTO_Z3950;
225 ent.oclass = CLASS_USERINFO;
226 ent.value = (oid_value) VAL_COOKIE;
227 assert (oid_ent_to_oid (&ent, oid));
229 if (oid_ent_to_oid (&ent, oid) &&
230 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
231 oi->which == Z_OtherInfo_characterInfo)
232 return oi->information.characterInfo;
236 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
239 Z_OtherInformationUnit *oi;
241 ent.proto = PROTO_Z3950;
242 ent.oclass = CLASS_USERINFO;
243 ent.value = (oid_value) VAL_PROXY;
244 if (oid_ent_to_oid (&ent, oid) &&
245 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
246 oi->which == Z_OtherInfo_characterInfo)
247 return oi->information.characterInfo;
251 const char *Yaz_Proxy::load_balance(const char **url)
253 int zurl_in_use[MAX_ZURL_PLEX];
257 for (i = 0; i<MAX_ZURL_PLEX; i++)
259 for (c = m_parent->m_clientPool; c; c = c->m_next)
261 for (i = 0; url[i]; i++)
262 if (!strcmp(url[i], c->get_hostname()))
267 for (i = 0; url[i]; i++)
269 yaz_log(LOG_DEBUG, "%szurl=%s use=%d",
270 m_session_str, url[i], zurl_in_use[i]);
271 if (min > zurl_in_use[i])
274 min = zurl_in_use[i];
280 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
281 const char *proxy_host)
284 Yaz_Proxy *parent = m_parent;
285 Z_OtherInformation **oi;
286 Yaz_ProxyClient *c = m_client;
290 const char *url[MAX_ZURL_PLEX];
291 Yaz_ProxyConfig *cfg = check_reconfigure();
295 /* only to be enabled for debugging... */
296 if (!strcmp(proxy_host, "stop"))
299 xfree(m_default_target);
300 m_default_target = xstrdup(proxy_host);
301 proxy_host = m_default_target;
303 int client_idletime = -1;
304 const char *cql2rpn_fname = 0;
305 url[0] = m_default_target;
310 cfg->get_target_info(proxy_host, url, &m_bw_max,
311 &m_pdu_max, &m_max_record_retrieve,
312 &m_target_idletime, &client_idletime,
313 &parent->m_max_clients,
314 &m_keepalive_limit_bw,
315 &m_keepalive_limit_pdu,
320 if (client_idletime != -1)
322 m_client_idletime = client_idletime;
323 timeout(m_client_idletime);
326 m_cql2rpn.set_pqf_file(cql2rpn_fname);
329 yaz_log(LOG_LOG, "%sNo default target", m_session_str);
332 // we don't handle multiplexing for cookie session, so we just
333 // pick the first one in this case (anonymous users will be able
334 // to use any backend)
335 if (cookie && *cookie)
336 m_proxyTarget = (char*) xstrdup(url[0]);
338 m_proxyTarget = (char*) xstrdup(load_balance(url));
340 if (cookie && *cookie)
341 { // search in sessions with a cookie
342 for (c = parent->m_clientPool; c; c = c->m_next)
345 assert (*c->m_prev == c);
346 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
347 !strcmp(m_proxyTarget, c->get_hostname()))
350 // The following handles "cancel"
351 // If connection is busy (waiting for PDU) and
352 // we have an initRequest we can safely do re-open
353 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
355 yaz_log (LOG_LOG, "%s REOPEN target=%s", m_session_str,
362 c->m_last_resultCount = 0;
363 c->m_sr_transform = 0;
365 c->m_resultSetStartPoint = 0;
366 c->m_target_idletime = m_target_idletime;
367 if (c->client(m_proxyTarget))
374 c->m_seqno = parent->m_seqno;
375 if (c->m_server && c->m_server != this)
376 c->m_server->m_client = 0;
379 yaz_log (LOG_DEBUG, "get_client 1 %p %p", this, c);
386 // don't have a client session yet. Search in session w/o cookie
387 for (c = parent->m_clientPool; c; c = c->m_next)
390 assert (*c->m_prev == c);
391 if (c->m_server == 0 && c->m_cookie == 0 &&
393 !strcmp(m_proxyTarget, c->get_hostname()))
396 yaz_log (LOG_LOG, "%sREUSE %s",
397 m_session_str, c->get_hostname());
399 c->m_seqno = parent->m_seqno;
400 assert(c->m_server == 0);
403 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
404 c->set_APDU_yazlog(1);
406 c->set_APDU_yazlog(0);
418 if (apdu->which != Z_APDU_initRequest)
420 yaz_log (LOG_LOG, "no first INIT!");
423 Z_InitRequest *initRequest = apdu->u.initRequest;
425 if (!initRequest->idAuthentication)
427 if (m_proxy_authentication)
429 initRequest->idAuthentication =
430 (Z_IdAuthentication *)
431 odr_malloc (odr_encode(),
432 sizeof(*initRequest->idAuthentication));
433 initRequest->idAuthentication->which =
434 Z_IdAuthentication_open;
435 initRequest->idAuthentication->u.open =
436 odr_strdup (odr_encode(), m_proxy_authentication);
440 // go through list of clients - and find the lowest/oldest one.
441 Yaz_ProxyClient *c_min = 0;
443 int no_of_clients = 0;
444 if (parent->m_clientPool)
445 yaz_log (LOG_DEBUG, "Existing sessions");
446 for (c = parent->m_clientPool; c; c = c->m_next)
448 yaz_log (LOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
449 c->m_waiting, c->get_hostname(),
450 c->m_cookie ? c->m_cookie : "");
452 if (min_seq < 0 || c->m_seqno < min_seq)
454 min_seq = c->m_seqno;
458 if (no_of_clients >= parent->m_max_clients)
461 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
463 yaz_log (LOG_LOG, "%sMAXCLIENTS Destroy %d",
464 m_session_str, c->m_seqno);
465 if (c->m_server && c->m_server != this)
471 yaz_log (LOG_LOG, "%sMAXCLIENTS Reuse %d %d %s",
473 c->m_seqno, parent->m_seqno, c->get_hostname());
477 c->m_cookie = xstrdup(cookie);
478 c->m_seqno = parent->m_seqno;
479 if (c->m_server && c->m_server != this)
481 c->m_server->m_client = 0;
485 c->m_target_idletime = m_target_idletime;
486 c->timeout(m_target_idletime);
488 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
489 c->set_APDU_yazlog(1);
491 c->set_APDU_yazlog(0);
498 yaz_log (LOG_LOG, "%sNEW %d %s",
499 m_session_str, parent->m_seqno, m_proxyTarget);
500 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
501 c->m_next = parent->m_clientPool;
503 c->m_next->m_prev = &c->m_next;
504 parent->m_clientPool = c;
505 c->m_prev = &parent->m_clientPool;
511 c->m_cookie = xstrdup(cookie);
513 c->m_seqno = parent->m_seqno;
515 c->m_last_resultCount = 0;
518 c->m_sr_transform = 0;
520 c->m_resultSetStartPoint = 0;
522 if (c->client(m_proxyTarget))
527 c->m_target_idletime = m_target_idletime;
530 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
531 c->set_APDU_yazlog(1);
533 c->set_APDU_yazlog(0);
535 yaz_log (LOG_DEBUG, "get_client 3 %p %p", this, c);
539 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
542 for (i = 0; i<num; i++)
545 Z_DefaultDiagFormat *r;
546 Z_DiagRec *p = pp[i];
547 if (p->which != Z_DiagRec_defaultFormat)
549 yaz_log(LOG_LOG, "%sError no diagnostics", m_session_str);
553 r = p->u.defaultFormat;
554 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
555 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
556 yaz_log(LOG_LOG, "%sError unknown diagnostic set", m_session_str);
559 case Z_DefaultDiagFormat_v2Addinfo:
560 yaz_log(LOG_LOG, "%sError %d %s:%s",
562 *r->condition, diagbib1_str(*r->condition),
565 case Z_DefaultDiagFormat_v3Addinfo:
566 yaz_log(LOG_LOG, "%sError %d %s:%s",
568 *r->condition, diagbib1_str(*r->condition),
575 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p)
579 yaz_marc_t mt = yaz_marc_create();
580 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
581 for (i = 0; i < p->num_records; i++)
583 Z_NamePlusRecord *npr = p->records[i];
584 if (npr->which == Z_NamePlusRecord_databaseRecord)
586 Z_External *r = npr->u.databaseRecord;
587 if (r->which == Z_External_octet)
591 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
592 r->u.octet_aligned->len,
595 yaz_iconv_t cd = yaz_iconv_open("UTF-8", "MARC-8");
596 WRBUF wrbuf = wrbuf_alloc();
599 size_t inbytesleft = rlen;
600 const char *inp = result;
601 while (cd && inbytesleft)
603 size_t outbytesleft = sizeof(outbuf);
607 r = yaz_iconv (cd, (char**) &inp,
609 &outp, &outbytesleft);
610 if (r == (size_t) (-1))
612 int e = yaz_iconv_error(cd);
613 if (e != YAZ_ICONV_E2BIG)
615 yaz_log(LOG_WARN, "conversion failure");
619 wrbuf_write(wrbuf, outbuf, outp - outbuf);
624 npr->u.databaseRecord = z_ext_record(odr_encode(),
628 wrbuf_free(wrbuf, 1);
633 yaz_marc_destroy(mt);
636 int Yaz_Proxy::send_http_response(int code)
638 ODR o = odr_encode();
639 const char *ctype = "text/xml";
640 Z_GDU *gdu = z_get_HTTP_Response(o, code);
641 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
643 hres->version = odr_strdup(o, m_http_version);
644 m_http_keepalive = 0;
646 return send_GDU(gdu, &len);
649 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu)
651 ODR o = odr_encode();
652 const char *ctype = "text/xml";
653 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
654 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
656 hres->version = odr_strdup(o, m_http_version);
657 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
658 if (m_http_keepalive)
659 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
661 static Z_SOAP_Handler soap_handlers[2] = {
663 {"http://www.loc.gov/zing/srw/", 0,
664 (Z_SOAP_fun) yaz_srw_codec},
669 Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
670 soap_package->which = Z_SOAP_generic;
671 soap_package->u.generic =
672 (Z_SOAP_Generic *) odr_malloc(o, sizeof(*soap_package->u.generic));
673 soap_package->u.generic->no = 0;
674 soap_package->u.generic->ns = soap_handlers[0].ns;
675 soap_package->u.generic->p = (void *) srw_pdu;
676 soap_package->ns = m_soap_ns;
677 int ret = z_soap_codec_enc(o, &soap_package,
678 &hres->content_buf, &hres->content_len,
681 return send_GDU(gdu, &len);
684 int Yaz_Proxy::send_to_srw_client_error(int srw_error)
686 ODR o = odr_encode();
687 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
688 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
690 srw_res->num_diagnostics = 1;
691 srw_res->diagnostics = (Z_SRW_diagnostic *)
692 odr_malloc(o, sizeof(*srw_res->diagnostics));
693 srw_res->diagnostics[0].code = odr_intdup(o, srw_error);
694 srw_res->diagnostics[0].details = 0;
695 return send_srw_response(srw_pdu);
698 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
699 Z_DefaultDiagFormat *ddf)
701 int bib1_code = *ddf->condition;
702 if (bib1_code == 109)
704 srw_res->num_diagnostics = 1;
705 srw_res->diagnostics = (Z_SRW_diagnostic *)
706 odr_malloc(o, sizeof(*srw_res->diagnostics));
707 srw_res->diagnostics[0].code =
708 odr_intdup(o, yaz_diag_bib1_to_srw(*ddf->condition));
709 srw_res->diagnostics[0].details = ddf->u.v2Addinfo;
713 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
715 ODR o = odr_encode();
716 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
717 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
719 srw_res->numberOfRecords = odr_intdup (o, hits);
720 if (records && records->which == Z_Records_DBOSD)
722 srw_res->num_records =
723 records->u.databaseOrSurDiagnostics->num_records;
725 srw_res->records = (Z_SRW_record *)
726 odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
727 for (i = 0; i < srw_res->num_records; i++)
729 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
730 if (npr->which != Z_NamePlusRecord_databaseRecord)
732 srw_res->records[i].recordSchema = "diagnostic";
733 srw_res->records[i].recordPacking = m_s2z_packing;
734 srw_res->records[i].recordData_buf = "67";
735 srw_res->records[i].recordData_len = 2;
736 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
739 Z_External *r = npr->u.databaseRecord;
740 oident *ent = oid_getentbyoid(r->direct_reference);
741 if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
743 srw_res->records[i].recordSchema = "http://www.loc.gov/marcxml/";
744 srw_res->records[i].recordPacking = m_s2z_packing;
745 srw_res->records[i].recordData_buf = (char*)
746 r->u.octet_aligned->buf;
747 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
748 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
752 srw_res->records[i].recordSchema = "diagnostic";
753 srw_res->records[i].recordPacking = m_s2z_packing;
754 srw_res->records[i].recordData_buf = "67";
755 srw_res->records[i].recordData_len = 2;
756 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
760 if (records && records->which == Z_Records_NSD)
763 http_code = z_to_srw_diag(odr_encode(), srw_res,
764 records->u.nonSurrogateDiagnostic);
766 return send_http_response(http_code);
768 return send_srw_response(srw_pdu);
772 int Yaz_Proxy::send_srw_explain()
774 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
775 Z_SRW_explainResponse *er = res->u.explain_response;
779 FILE *inf = fopen(m_zeerex_fname, "rb");
782 fseek(inf, 0L, SEEK_END);
783 long sz = ftell(inf);
784 fseek(inf, 0L, SEEK_SET);
787 er->record.recordData_buf =
788 (char*) odr_malloc(odr_encode(), sz);
789 size_t s = fread(er->record.recordData_buf, 1,sz, inf);
791 er->record.recordData_len = s;
794 yaz_log(LOG_WARN|LOG_ERRNO, "zeerex file: ftell");
798 yaz_log(LOG_WARN|LOG_ERRNO, "zeerex file: fopen");
801 yaz_log(LOG_LOG, "zeerex file: not defined");
802 return send_srw_response(res);
805 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu, int *len)
809 if (apdu->which == Z_APDU_initResponse)
811 Z_InitResponse *res = apdu->u.initResponse;
812 if (*res->result == 0)
814 send_to_srw_client_error(3);
816 else if (!m_s2z_search_apdu)
822 handle_incoming_Z_PDU(m_s2z_search_apdu);
825 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
827 m_s2z_search_apdu = 0;
828 Z_SearchResponse *res = apdu->u.searchResponse;
829 m_s2z_hit_count = *res->resultCount;
830 if (res->records && res->records->which == Z_Records_NSD)
832 send_to_srw_client_ok(0, res->records, 1);
834 else if (m_s2z_present_apdu)
836 handle_incoming_Z_PDU(m_s2z_present_apdu);
840 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
843 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
846 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
848 m_s2z_present_apdu = 0;
849 Z_PresentResponse *res = apdu->u.presentResponse;
850 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
854 return send_Z_PDU(apdu, len);
858 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
861 int kill_session = 0;
862 if (apdu->which == Z_APDU_searchResponse)
864 Z_SearchResponse *sr = apdu->u.searchResponse;
865 Z_Records *p = sr->records;
866 if (p && p->which == Z_Records_NSD)
868 Z_DiagRec dr, *dr_p = &dr;
869 dr.which = Z_DiagRec_defaultFormat;
870 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
872 *sr->searchStatus = 0;
873 display_diagrecs(&dr_p, 1);
877 if (m_marcxml_flag && p && p->which == Z_Records_DBOSD)
878 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
881 yaz_log(LOG_LOG, "%s%d hits", m_session_str,
883 if (*sr->resultCount < 0)
885 m_invalid_session = 1;
888 *sr->searchStatus = 0;
890 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
891 *sr->resultCount = 0;
896 else if (apdu->which == Z_APDU_presentResponse)
898 Z_PresentResponse *sr = apdu->u.presentResponse;
899 Z_Records *p = sr->records;
900 if (p && p->which == Z_Records_NSD)
902 Z_DiagRec dr, *dr_p = &dr;
903 dr.which = Z_DiagRec_defaultFormat;
904 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
905 if (*sr->presentStatus == Z_PresentStatus_success)
906 *sr->presentStatus = Z_PresentStatus_failure;
907 display_diagrecs(&dr_p, 1);
909 if (m_marcxml_flag && p && p->which == Z_Records_DBOSD)
910 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
912 int r = send_PDU_convert(apdu, &len);
915 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
916 yaz_log (LOG_DEBUG, "%sSending %s to client %d bytes", m_session_str,
917 apdu_name(apdu), len);
919 m_bw_stat.add_bytes(len);
924 m_parent->pre_init();
928 if (!m_http_keepalive)
941 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
944 int r = send_Z_PDU(apdu, &len);
945 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
946 yaz_log (LOG_LOG, "%sSending %s to %s %d bytes",
948 apdu_name(apdu), get_hostname(), len);
953 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
955 if (apdu->which == Z_APDU_presentRequest)
957 Z_PresentRequest *pr = apdu->u.presentRequest;
958 int toget = *pr->numberOfRecordsRequested;
959 int start = *pr->resultSetStartPoint;
961 yaz_log(LOG_LOG, "%sPresent %s %d+%d", m_session_str,
962 pr->resultSetId, start, toget);
964 if (*m_parent->m_optimize == '0')
967 if (!m_client->m_last_resultSetId)
969 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
970 new_apdu->u.presentResponse->records =
971 create_nonSurrogateDiagnostics(odr_encode(), 30,
973 send_to_client(new_apdu);
976 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
978 if (start+toget-1 > m_client->m_last_resultCount)
980 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
981 new_apdu->u.presentResponse->records =
982 create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
983 send_to_client(new_apdu);
986 Z_NamePlusRecordList *npr;
987 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
988 pr->preferredRecordSyntax,
989 pr->recordComposition))
991 yaz_log (LOG_LOG, "%sReturned cached records for present request",
993 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
994 new_apdu->u.presentResponse->referenceId = pr->referenceId;
996 new_apdu->u.presentResponse->numberOfRecordsReturned
997 = odr_intdup(odr_encode(), toget);
999 new_apdu->u.presentResponse->records = (Z_Records*)
1000 odr_malloc(odr_encode(), sizeof(Z_Records));
1001 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1002 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1003 new_apdu->u.presentResponse->nextResultSetPosition =
1004 odr_intdup(odr_encode(), start+toget);
1006 send_to_client(new_apdu);
1012 if (apdu->which != Z_APDU_searchRequest)
1014 Z_SearchRequest *sr = apdu->u.searchRequest;
1015 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1016 Yaz_Z_Databases this_databases;
1018 this_databases.set(sr->num_databaseNames, (const char **)
1021 this_query->set_Z_Query(sr->query);
1023 char query_str[120];
1024 this_query->print(query_str, sizeof(query_str)-1);
1025 yaz_log(LOG_LOG, "%sSearch %s", m_session_str, query_str);
1027 if (*m_parent->m_optimize != '0' &&
1028 m_client->m_last_ok && m_client->m_last_query &&
1029 m_client->m_last_query->match(this_query) &&
1030 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1031 m_client->m_last_databases.match(this_databases))
1034 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1035 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1037 Z_NamePlusRecordList *npr;
1038 int toget = *sr->mediumSetPresentNumber;
1039 Z_RecordComposition *comp = 0;
1041 if (toget > m_client->m_last_resultCount)
1042 toget = m_client->m_last_resultCount;
1044 if (sr->mediumSetElementSetNames)
1046 comp = (Z_RecordComposition *)
1047 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1048 comp->which = Z_RecordComp_simple;
1049 comp->u.simple = sr->mediumSetElementSetNames;
1052 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1053 sr->preferredRecordSyntax, comp))
1055 yaz_log (LOG_LOG, "%sReturned cached records for medium set",
1057 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1058 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1059 new_apdu->u.searchResponse->resultCount =
1060 &m_client->m_last_resultCount;
1062 new_apdu->u.searchResponse->numberOfRecordsReturned
1063 = odr_intdup(odr_encode(), toget);
1065 new_apdu->u.searchResponse->presentStatus =
1066 odr_intdup(odr_encode(), Z_PresentStatus_success);
1067 new_apdu->u.searchResponse->records = (Z_Records*)
1068 odr_malloc(odr_encode(), sizeof(Z_Records));
1069 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1070 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1071 new_apdu->u.searchResponse->nextResultSetPosition =
1072 odr_intdup(odr_encode(), toget+1);
1073 send_to_client(new_apdu);
1079 // send present request (medium size)
1080 yaz_log (LOG_LOG, "%sOptimizing search for medium set",
1083 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1084 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1085 pr->referenceId = sr->referenceId;
1086 pr->resultSetId = sr->resultSetName;
1087 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1088 *pr->numberOfRecordsRequested = toget;
1089 pr->recordComposition = comp;
1090 m_client->m_sr_transform = 1;
1094 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1095 m_client->m_last_resultCount <= 0)
1097 // large set. Return pseudo-search response immediately
1098 yaz_log (LOG_LOG, "%sOptimizing search for large set",
1100 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1101 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1102 new_apdu->u.searchResponse->resultCount =
1103 &m_client->m_last_resultCount;
1104 send_to_client(new_apdu);
1109 Z_NamePlusRecordList *npr;
1110 int toget = m_client->m_last_resultCount;
1111 Z_RecordComposition *comp = 0;
1113 // send a present request (small set)
1115 if (sr->smallSetElementSetNames)
1117 comp = (Z_RecordComposition *)
1118 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1119 comp->which = Z_RecordComp_simple;
1120 comp->u.simple = sr->smallSetElementSetNames;
1123 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1124 sr->preferredRecordSyntax, comp))
1126 yaz_log (LOG_LOG, "%sReturned cached records for small set",
1128 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1129 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1130 new_apdu->u.searchResponse->resultCount =
1131 &m_client->m_last_resultCount;
1133 new_apdu->u.searchResponse->numberOfRecordsReturned
1134 = odr_intdup(odr_encode(), toget);
1136 new_apdu->u.searchResponse->presentStatus =
1137 odr_intdup(odr_encode(), Z_PresentStatus_success);
1138 new_apdu->u.searchResponse->records = (Z_Records*)
1139 odr_malloc(odr_encode(), sizeof(Z_Records));
1140 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1141 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1142 new_apdu->u.searchResponse->nextResultSetPosition =
1143 odr_intdup(odr_encode(), toget+1);
1144 send_to_client(new_apdu);
1149 yaz_log (LOG_LOG, "%sOptimizing search for small set",
1151 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1152 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1153 pr->referenceId = sr->referenceId;
1154 pr->resultSetId = sr->resultSetName;
1155 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1156 *pr->numberOfRecordsRequested = toget;
1157 pr->recordComposition = comp;
1158 m_client->m_sr_transform = 1;
1163 else // query doesn't match
1165 delete m_client->m_last_query;
1166 m_client->m_last_query = this_query;
1167 m_client->m_last_ok = 0;
1168 m_client->m_cache.clear();
1169 m_client->m_resultSetStartPoint = 0;
1171 xfree (m_client->m_last_resultSetId);
1172 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1174 m_client->m_last_databases.set(sr->num_databaseNames,
1175 (const char **) sr->databaseNames);
1181 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1183 char *cp = strchr(m_session_str, ' ');
1186 sprintf(cp+1, "%d ", m_request_no);
1188 m_bytes_recv += len;
1190 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
1191 yaz_log (LOG_DEBUG, "%sReceiving %s from client %d bytes",
1192 m_session_str, gdu_name(apdu), len);
1194 if (m_bw_hold_PDU) // double incoming PDU. shutdown now.
1197 m_bw_stat.add_bytes(len);
1198 m_pdu_stat.add_bytes(1);
1200 int bw_total = m_bw_stat.get_total();
1201 int pdu_total = m_pdu_stat.get_total();
1206 if (bw_total > m_bw_max)
1208 reduce = (bw_total/m_bw_max);
1213 if (pdu_total > m_pdu_max)
1215 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1216 reduce = (reduce > nreduce) ? reduce : nreduce;
1221 yaz_log(LOG_LOG, "%sdelay=%d bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1222 m_session_str, reduce, bw_total, pdu_total,
1223 m_bw_max, m_pdu_max);
1225 m_bw_hold_PDU = apdu; // save PDU and signal "on hold"
1226 timeout(reduce); // call us reduce seconds later
1228 else if (apdu->which == Z_GDU_Z3950)
1229 handle_incoming_Z_PDU(apdu->u.z3950);
1230 else if (apdu->which == Z_GDU_HTTP_Request)
1231 handle_incoming_HTTP(apdu->u.HTTP_Request);
1234 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
1236 if (m_max_record_retrieve)
1238 if (apdu->which == Z_APDU_presentRequest)
1240 Z_PresentRequest *pr = apdu->u.presentRequest;
1241 if (pr->numberOfRecordsRequested &&
1242 *pr->numberOfRecordsRequested > m_max_record_retrieve)
1243 *pr->numberOfRecordsRequested = m_max_record_retrieve;
1248 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
1250 const char *addinfo)
1252 Z_Records *rec = (Z_Records *)
1253 odr_malloc (odr, sizeof(*rec));
1255 odr_malloc (odr, sizeof(*err));
1256 Z_DiagRec *drec = (Z_DiagRec *)
1257 odr_malloc (odr, sizeof(*drec));
1258 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1259 odr_malloc (odr, sizeof(*dr));
1261 rec->which = Z_Records_NSD;
1262 rec->u.nonSurrogateDiagnostic = dr;
1263 dr->diagnosticSetId =
1264 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
1265 dr->condition = err;
1266 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1267 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1271 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
1273 if (apdu->which == Z_APDU_searchRequest &&
1274 apdu->u.searchRequest->query &&
1275 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
1276 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
1278 Z_RPNQuery *rpnquery = 0;
1279 Z_SearchRequest *sr = apdu->u.searchRequest;
1281 yaz_log(LOG_LOG, "%sCQL: %s", m_session_str,
1282 sr->query->u.type_104->u.cql);
1284 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
1285 &rpnquery, odr_encode());
1287 yaz_log(LOG_LOG, "%sNo CQL to RPN table", m_session_str);
1289 yaz_log(LOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
1292 sr->query->which = Z_Query_type_1;
1293 sr->query->u.type_1 = rpnquery;
1300 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
1302 if (apdu->which == Z_APDU_searchRequest)
1304 Z_SearchRequest *sr = apdu->u.searchRequest;
1308 Yaz_ProxyConfig *cfg = check_reconfigure();
1310 err = cfg->check_query(odr_encode(), m_default_target,
1311 sr->query, &addinfo);
1314 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1316 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1317 new_apdu->u.searchResponse->records =
1318 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1319 *new_apdu->u.searchResponse->searchStatus = 0;
1321 send_to_client(new_apdu);
1329 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
1332 if (apdu->which == Z_APDU_searchRequest)
1334 Z_SearchRequest *sr = apdu->u.searchRequest;
1337 Yaz_ProxyConfig *cfg = check_reconfigure();
1340 err = cfg->check_syntax(odr_encode(),
1342 sr->preferredRecordSyntax,
1346 sr->preferredRecordSyntax =
1347 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN,
1353 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1355 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1356 new_apdu->u.searchResponse->records =
1357 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1358 *new_apdu->u.searchResponse->searchStatus = 0;
1360 send_to_client(new_apdu);
1365 else if (apdu->which == Z_APDU_presentRequest)
1367 Z_PresentRequest *pr = apdu->u.presentRequest;
1370 Yaz_ProxyConfig *cfg = check_reconfigure();
1373 err = cfg->check_syntax(odr_encode(), m_default_target,
1374 pr->preferredRecordSyntax,
1378 pr->preferredRecordSyntax =
1379 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN,
1385 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1387 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1388 new_apdu->u.presentResponse->records =
1389 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1390 *new_apdu->u.presentResponse->presentStatus =
1391 Z_PresentStatus_failure;
1393 send_to_client(new_apdu);
1401 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
1403 Z_SRW_PDU *srw_pdu = 0;
1407 odr_destroy(m_s2z_odr_init);
1410 if (m_s2z_odr_search)
1412 odr_destroy(m_s2z_odr_search);
1413 m_s2z_odr_search = 0;
1416 m_http_keepalive = 0;
1418 if (!strcmp(hreq->version, "1.0"))
1420 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1421 if (v && !strcmp(v, "Keep-Alive"))
1422 m_http_keepalive = 1;
1424 m_http_keepalive = 0;
1425 m_http_version = "1.0";
1429 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1430 if (v && !strcmp(v, "close"))
1431 m_http_keepalive = 0;
1433 m_http_keepalive = 1;
1434 m_http_version = "1.1";
1437 if (yaz_check_for_srw(hreq, &srw_pdu, &soap_ns, odr_decode()) == 0
1438 || yaz_check_for_sru(hreq, &srw_pdu, &soap_ns, odr_decode()) == 0)
1440 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
1441 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
1442 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_ns);
1443 m_s2z_init_apdu = 0;
1444 m_s2z_search_apdu = 0;
1445 m_s2z_present_apdu = 0;
1446 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
1448 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
1450 // set packing for response records ..
1451 if (srw_req->recordPacking &&
1452 !strcmp(srw_req->recordPacking, "xml"))
1453 m_s2z_packing = Z_SRW_recordPacking_XML;
1455 m_s2z_packing = Z_SRW_recordPacking_string;
1457 // prepare search PDU
1458 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
1459 Z_APDU_searchRequest);
1460 Z_SearchRequest *z_searchRequest =
1461 m_s2z_search_apdu->u.searchRequest;
1463 z_searchRequest->num_databaseNames = 1;
1464 z_searchRequest->databaseNames = (char**)
1465 odr_malloc(m_s2z_odr_search, sizeof(char *));
1466 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
1469 // query transformation
1470 Z_Query *query = (Z_Query *)
1471 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
1472 z_searchRequest->query = query;
1474 if (srw_req->query_type == Z_SRW_query_type_cql)
1476 Z_External *ext = (Z_External *)
1477 odr_malloc(m_s2z_odr_search, sizeof(*ext));
1478 ext->direct_reference =
1479 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
1480 ext->indirect_reference = 0;
1481 ext->descriptor = 0;
1482 ext->which = Z_External_CQL;
1483 ext->u.cql = srw_req->query.cql;
1485 query->which = Z_Query_type_104;
1486 query->u.type_104 = ext;
1488 else if (srw_req->query_type == Z_SRW_query_type_pqf)
1490 Z_RPNQuery *RPNquery;
1491 YAZ_PQF_Parser pqf_parser;
1493 pqf_parser = yaz_pqf_create ();
1495 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
1496 srw_req->query.pqf);
1499 const char *pqf_msg;
1501 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1502 yaz_log(LOG_LOG, "%*s^\n", off+4, "");
1503 yaz_log(LOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
1505 send_to_srw_client_error(10);
1508 query->which = Z_Query_type_1;
1509 query->u.type_1 = RPNquery;
1511 yaz_pqf_destroy (pqf_parser);
1515 send_to_srw_client_error(11);
1520 m_s2z_present_apdu = 0;
1522 if (srw_req->maximumRecords)
1523 max = *srw_req->maximumRecords;
1525 if (srw_req->startRecord)
1526 start = *srw_req->startRecord;
1529 if (start <= 1) // Z39.50 piggyback
1531 *z_searchRequest->smallSetUpperBound = max;
1532 *z_searchRequest->mediumSetPresentNumber = max;
1533 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
1534 z_searchRequest->preferredRecordSyntax =
1535 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
1538 else // Z39.50 present
1540 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
1541 Z_APDU_presentRequest);
1542 Z_PresentRequest *z_presentRequest =
1543 m_s2z_present_apdu->u.presentRequest;
1544 *z_presentRequest->resultSetStartPoint = start;
1545 *z_presentRequest->numberOfRecordsRequested = max;
1546 z_presentRequest->preferredRecordSyntax =
1547 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
1553 yaz_log(LOG_LOG, "handle_incoming: initRequest");
1554 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
1555 Z_APDU_initRequest);
1557 // prevent m_initRequest_apdu memory from being grabbed
1558 // in Yaz_Proxy::handle_incoming_Z_PDU
1559 m_initRequest_apdu = m_s2z_init_apdu;
1560 handle_incoming_Z_PDU(m_s2z_init_apdu);
1565 handle_incoming_Z_PDU(m_s2z_search_apdu);
1569 else if (srw_pdu->which == Z_SRW_explain_request)
1573 yaz_log(LOG_LOG, "handle_incoming: initRequest");
1574 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
1575 Z_APDU_initRequest);
1577 // prevent m_initRequest_apdu memory from being grabbed
1578 // in Yaz_Proxy::handle_incoming_Z_PDU
1579 m_initRequest_apdu = m_s2z_init_apdu;
1580 handle_incoming_Z_PDU(m_s2z_init_apdu);
1588 Z_GDU *p = z_get_HTTP_Response(odr_encode(), 400);
1593 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
1595 if (!m_client && m_invalid_session)
1597 m_apdu_invalid_session = apdu;
1598 m_mem_invalid_session = odr_extract_mem(odr_decode());
1599 apdu = m_initRequest_apdu;
1602 // Determine our client.
1603 Z_OtherInformation **oi;
1604 get_otherInfoAPDU(apdu, &oi);
1605 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
1611 m_client->m_server = this;
1613 if (apdu->which == Z_APDU_initRequest)
1615 if (apdu->u.initRequest->implementationId)
1616 yaz_log(LOG_LOG, "%simplementationId: %s",
1617 m_session_str, apdu->u.initRequest->implementationId);
1618 if (apdu->u.initRequest->implementationName)
1619 yaz_log(LOG_LOG, "%simplementationName: %s",
1620 m_session_str, apdu->u.initRequest->implementationName);
1621 if (apdu->u.initRequest->implementationVersion)
1622 yaz_log(LOG_LOG, "%simplementationVersion: %s",
1623 m_session_str, apdu->u.initRequest->implementationVersion);
1624 if (m_initRequest_apdu == 0)
1626 if (m_initRequest_mem)
1627 nmem_destroy(m_initRequest_mem);
1628 m_initRequest_apdu = apdu;
1629 m_initRequest_mem = odr_extract_mem(odr_decode());
1631 if (m_client->m_init_flag)
1633 if (handle_init_response_for_invalid_session(apdu))
1635 Z_APDU *apdu2 = m_client->m_initResponse;
1636 apdu2->u.initResponse->otherInfo = 0;
1637 if (m_client->m_cookie && *m_client->m_cookie)
1638 set_otherInformationString(apdu2, VAL_COOKIE, 1,
1639 m_client->m_cookie);
1640 apdu2->u.initResponse->referenceId =
1641 apdu->u.initRequest->referenceId;
1642 send_to_client(apdu2);
1645 m_client->m_init_flag = 1;
1647 handle_max_record_retrieve(apdu);
1650 apdu = handle_syntax_validation(apdu);
1653 apdu = handle_query_transformation(apdu);
1656 apdu = handle_query_validation(apdu);
1659 apdu = result_set_optimize(apdu);
1662 m_client->timeout(m_target_idletime); // mark it active even
1663 // though we didn't use it
1667 // delete other info part from PDU before sending to target
1668 get_otherInfoAPDU(apdu, &oi);
1672 if (apdu->which == Z_APDU_presentRequest &&
1673 m_client->m_resultSetStartPoint == 0)
1675 Z_PresentRequest *pr = apdu->u.presentRequest;
1676 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
1677 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
1679 m_client->m_resultSetStartPoint = 0;
1681 if (m_client->send_to_target(apdu) < 0)
1688 m_client->m_waiting = 1;
1691 void Yaz_Proxy::connectNotify()
1695 void Yaz_Proxy::shutdown()
1697 m_invalid_session = 0;
1698 // only keep if keep_alive flag is set...
1700 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
1701 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
1702 m_client->m_waiting == 0)
1704 yaz_log(LOG_LOG, "%sShutdown (client to proxy) keepalive %s",
1706 m_client->get_hostname());
1707 yaz_log(LOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1708 m_session_str, m_client->m_pdu_recv,
1709 m_client->m_bytes_sent + m_client->m_bytes_recv,
1710 m_keepalive_limit_bw, m_keepalive_limit_pdu);
1711 assert (m_client->m_waiting != 2);
1712 // Tell client (if any) that no server connection is there..
1713 m_client->m_server = 0;
1714 m_invalid_session = 0;
1718 yaz_log (LOG_LOG, "%sShutdown (client to proxy) close %s",
1720 m_client->get_hostname());
1721 assert (m_client->m_waiting != 2);
1726 yaz_log (LOG_LOG, "%sshutdown (client to proxy) bad state",
1732 yaz_log (LOG_LOG, "%sShutdown (client to proxy)",
1736 m_parent->pre_init();
1740 const char *Yaz_ProxyClient::get_session_str()
1744 return m_server->get_session_str();
1747 void Yaz_ProxyClient::shutdown()
1749 yaz_log (LOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
1755 void Yaz_Proxy::failNotify()
1757 yaz_log (LOG_LOG, "%sConnection closed by client",
1762 void Yaz_ProxyClient::failNotify()
1764 yaz_log (LOG_LOG, "%sConnection closed by target %s",
1765 get_session_str(), get_hostname());
1769 void Yaz_ProxyClient::connectNotify()
1771 const char *s = get_session_str();
1772 const char *h = get_hostname();
1773 yaz_log (LOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
1775 timeout(m_target_idletime);
1780 IYaz_PDU_Observer *Yaz_ProxyClient::sessionNotify(IYaz_PDU_Observable
1781 *the_PDU_Observable, int fd)
1783 return new Yaz_ProxyClient(the_PDU_Observable, 0);
1786 Yaz_ProxyClient::~Yaz_ProxyClient()
1791 m_next->m_prev = m_prev;
1792 m_waiting = 2; // for debugging purposes only.
1793 odr_destroy(m_init_odr);
1794 delete m_last_query;
1795 xfree (m_last_resultSetId);
1799 void Yaz_ProxyClient::pre_init_client()
1801 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
1802 Z_InitRequest *req = apdu->u.initRequest;
1804 ODR_MASK_SET(req->options, Z_Options_search);
1805 ODR_MASK_SET(req->options, Z_Options_present);
1806 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
1807 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
1808 ODR_MASK_SET(req->options, Z_Options_scan);
1809 ODR_MASK_SET(req->options, Z_Options_sort);
1810 ODR_MASK_SET(req->options, Z_Options_extendedServices);
1811 ODR_MASK_SET(req->options, Z_Options_delSet);
1813 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
1814 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
1815 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
1817 if (send_to_target(apdu) < 0)
1828 void Yaz_Proxy::pre_init()
1831 const char *name = 0;
1832 const char *zurl_in_use[MAX_ZURL_PLEX];
1833 int limit_bw, limit_pdu, limit_req;
1834 int target_idletime, client_idletime;
1836 int keepalive_limit_bw, keepalive_limit_pdu;
1838 const char *cql2rpn = 0;
1839 const char *zeerex = 0;
1841 Yaz_ProxyConfig *cfg = check_reconfigure();
1845 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
1850 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
1851 &limit_bw, &limit_pdu, &limit_req,
1852 &target_idletime, &client_idletime,
1854 &keepalive_limit_bw,
1855 &keepalive_limit_pdu,
1863 for (j = 0; zurl_in_use[j]; j++)
1869 for (c = m_clientPool; c; c = c->m_next)
1871 if (!strcmp(zurl_in_use[j], c->get_hostname()))
1873 if (c->m_cookie == 0)
1875 if (c->m_server == 0)
1884 yaz_log(LOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
1885 "preinit=%d",m_session_str,
1886 name, zurl_in_use[j], in_use, other, spare, pre_init);
1887 if (spare < pre_init)
1889 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
1890 c->m_next = m_clientPool;
1892 c->m_next->m_prev = &c->m_next;
1894 c->m_prev = &m_clientPool;
1896 if (m_log_mask & PROXY_LOG_APDU_SERVER)
1897 c->set_APDU_yazlog(1);
1899 c->set_APDU_yazlog(0);
1901 if (c->client(zurl_in_use[j]))
1909 c->m_target_idletime = target_idletime;
1910 c->m_seqno = m_seqno++;
1917 void Yaz_Proxy::timeoutNotify()
1923 timeout(m_client_idletime);
1924 Z_GDU *apdu = m_bw_hold_PDU;
1927 if (apdu->which == Z_GDU_Z3950)
1928 handle_incoming_Z_PDU(apdu->u.z3950);
1929 else if (apdu->which == Z_GDU_HTTP_Request)
1930 handle_incoming_HTTP(apdu->u.HTTP_Request);
1934 yaz_log (LOG_LOG, "%sTimeout (client to proxy)", m_session_str);
1945 void Yaz_ProxyClient::timeoutNotify()
1947 yaz_log (LOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
1954 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable,
1955 Yaz_Proxy *parent) :
1956 Yaz_Z_Assoc (the_PDU_Observable)
1963 m_last_resultSetId = 0;
1964 m_last_resultCount = 0;
1968 m_init_odr = odr_createmem (ODR_DECODE);
1970 m_resultSetStartPoint = 0;
1971 m_bytes_sent = m_bytes_recv = 0;
1975 m_target_idletime = 600;
1979 const char *Yaz_Proxy::option(const char *name, const char *value)
1981 if (!strcmp (name, "optimize")) {
1984 m_optimize = xstrdup (value);
1991 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
1996 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
1998 if (apdu->which == Z_GDU_Z3950)
1999 recv_Z_PDU(apdu->u.z3950, len);
2000 else if (apdu->which == Z_GDU_HTTP_Response)
2001 recv_HTTP_response(apdu->u.HTTP_Response, len);
2006 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
2008 if (!m_invalid_session)
2010 m_invalid_session = 0;
2011 handle_incoming_Z_PDU(m_apdu_invalid_session);
2012 assert (m_mem_invalid_session);
2013 nmem_destroy(m_mem_invalid_session);
2014 m_mem_invalid_session = 0;
2018 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
2020 m_bytes_recv += len;
2023 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
2024 yaz_log (LOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
2025 apdu_name(apdu), get_hostname(), len);
2026 if (apdu->which == Z_APDU_initResponse)
2028 if (!m_server) // if this is a pre init session , check for more
2030 NMEM nmem = odr_extract_mem (odr_decode());
2031 odr_reset (m_init_odr);
2032 nmem_transfer (m_init_odr->mem, nmem);
2033 m_initResponse = apdu;
2035 Z_InitResponse *ir = apdu->u.initResponse;
2036 char *im0 = ir->implementationName;
2039 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
2046 strcat(im1, "(YAZ Proxy)");
2047 ir->implementationName = im1;
2049 nmem_destroy (nmem);
2051 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
2054 if (apdu->which == Z_APDU_searchResponse)
2056 Z_SearchResponse *sr = apdu->u.searchResponse;
2057 m_last_resultCount = *sr->resultCount;
2058 int status = *sr->searchStatus;
2059 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
2063 if (sr->records && sr->records->which == Z_Records_DBOSD)
2065 m_cache.add(odr_decode(),
2066 sr->records->u.databaseOrSurDiagnostics, 1,
2071 if (apdu->which == Z_APDU_presentResponse)
2073 Z_PresentResponse *pr = apdu->u.presentResponse;
2077 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2078 Z_SearchResponse *sr = new_apdu->u.searchResponse;
2079 sr->referenceId = pr->referenceId;
2080 *sr->resultCount = m_last_resultCount;
2081 sr->records = pr->records;
2082 sr->nextResultSetPosition = pr->nextResultSetPosition;
2083 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
2087 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
2089 m_cache.add(odr_decode(),
2090 pr->records->u.databaseOrSurDiagnostics,
2091 m_resultSetStartPoint, -1);
2092 m_resultSetStartPoint = 0;
2096 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
2099 m_server->send_to_client(apdu);
2101 if (apdu->which == Z_APDU_close)
2107 int Yaz_Proxy::server(const char *addr)
2109 int r = Yaz_Z_Assoc::server(addr);
2112 yaz_log(LOG_LOG, "%sStarted listener on %s", m_session_str, addr);