2 * Copyright (c) 1998-2004, Index Data.
3 * See the file LICENSE for details.
5 * $Id: yaz-proxy.cpp,v 1.88 2004-01-12 22:35:59 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>
20 #include <libxslt/xsltutils.h>
21 #include <libxslt/transform.h>
24 static const char *apdu_name(Z_APDU *apdu)
28 case Z_APDU_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:
46 case Z_APDU_scanResponse:
47 return "scanResponse";
48 case Z_APDU_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";
62 static const char *gdu_name(Z_GDU *gdu)
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";
73 return "Unknown request/response";
76 Yaz_Proxy::Yaz_Proxy(IYaz_PDU_Observable *the_PDU_Observable,
78 Yaz_Z_Assoc(the_PDU_Observable), m_bw_stat(60), m_pdu_stat(60)
80 m_PDU_Observable = the_PDU_Observable;
85 m_keepalive_limit_bw = 500000;
86 m_keepalive_limit_pdu = 1000;
89 m_proxy_authentication = 0;
93 m_client_idletime = 600;
94 m_target_idletime = 600;
95 m_optimize = xstrdup ("1");
96 strcpy(m_session_str, "0 ");
98 m_bytes_sent = m_bytes_recv = 0;
102 m_max_record_retrieve = 0;
106 m_invalid_session = 0;
109 m_stylesheet_schema = 0;
110 m_s2z_stylesheet = 0;
112 m_initRequest_apdu = 0;
113 m_initRequest_mem = 0;
114 m_apdu_invalid_session = 0;
115 m_mem_invalid_session = 0;
117 m_s2z_odr_search = 0;
119 m_s2z_search_apdu = 0;
120 m_s2z_present_apdu = 0;
121 m_http_keepalive = 0;
124 m_s2z_packing = Z_SRW_recordPacking_string;
125 m_time_tv.tv_sec = 0;
126 m_time_tv.tv_usec = 0;
129 Yaz_Proxy::~Yaz_Proxy()
131 yaz_log(LOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
132 m_bytes_sent, m_bytes_recv);
133 nmem_destroy(m_initRequest_mem);
134 nmem_destroy(m_mem_invalid_session);
135 xfree (m_proxyTarget);
136 xfree (m_default_target);
137 xfree (m_proxy_authentication);
139 xfree (m_stylesheet_schema);
142 odr_destroy(m_s2z_odr_init);
143 if (m_s2z_odr_search)
144 odr_destroy(m_s2z_odr_search);
148 int Yaz_Proxy::set_config(const char *config)
151 m_config = new Yaz_ProxyConfig();
152 xfree(m_config_fname);
153 m_config_fname = xstrdup(config);
154 int r = m_config->read_xml(config);
156 m_config->get_generic_info(&m_log_mask, &m_max_clients);
160 void Yaz_Proxy::set_default_target(const char *target)
162 xfree (m_default_target);
163 m_default_target = 0;
165 m_default_target = (char *) xstrdup (target);
168 void Yaz_Proxy::set_proxy_authentication (const char *auth)
170 xfree (m_proxy_authentication);
171 m_proxy_authentication = 0;
173 m_proxy_authentication = (char *) xstrdup (auth);
176 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
179 return m_parent->check_reconfigure();
181 Yaz_ProxyConfig *cfg = m_config;
184 yaz_log(LOG_LOG, "reconfigure");
186 if (m_config_fname && cfg)
188 yaz_log(LOG_LOG, "reconfigure config %s", m_config_fname);
189 int r = cfg->read_xml(m_config_fname);
191 yaz_log(LOG_WARN, "reconfigure failed");
195 cfg->get_generic_info(&m_log_mask, &m_max_clients);
199 yaz_log(LOG_LOG, "reconfigure");
205 IYaz_PDU_Observer *Yaz_Proxy::sessionNotify(IYaz_PDU_Observable
206 *the_PDU_Observable, int fd)
209 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable, this);
210 new_proxy->m_config = 0;
211 new_proxy->m_config_fname = 0;
212 new_proxy->timeout(m_client_idletime);
213 new_proxy->m_target_idletime = m_target_idletime;
214 new_proxy->set_default_target(m_default_target);
215 new_proxy->m_max_clients = m_max_clients;
216 new_proxy->m_log_mask = m_log_mask;
217 new_proxy->set_APDU_log(get_APDU_log());
218 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
219 new_proxy->set_APDU_yazlog(1);
221 new_proxy->set_APDU_yazlog(0);
222 new_proxy->set_proxy_authentication(m_proxy_authentication);
223 sprintf(new_proxy->m_session_str, "%ld:%d ", (long) time(0), m_session_no);
225 yaz_log (LOG_LOG, "%sNew session %s", new_proxy->m_session_str,
226 the_PDU_Observable->getpeername());
230 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
233 Z_OtherInformationUnit *oi;
235 ent.proto = PROTO_Z3950;
236 ent.oclass = CLASS_USERINFO;
237 ent.value = (oid_value) VAL_COOKIE;
238 assert (oid_ent_to_oid (&ent, oid));
240 if (oid_ent_to_oid (&ent, oid) &&
241 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
242 oi->which == Z_OtherInfo_characterInfo)
243 return oi->information.characterInfo;
247 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
250 Z_OtherInformationUnit *oi;
252 ent.proto = PROTO_Z3950;
253 ent.oclass = CLASS_USERINFO;
254 ent.value = (oid_value) VAL_PROXY;
255 if (oid_ent_to_oid (&ent, oid) &&
256 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
257 oi->which == Z_OtherInfo_characterInfo)
258 return oi->information.characterInfo;
262 const char *Yaz_Proxy::load_balance(const char **url)
264 int zurl_in_use[MAX_ZURL_PLEX];
268 for (i = 0; i<MAX_ZURL_PLEX; i++)
270 for (c = m_parent->m_clientPool; c; c = c->m_next)
272 for (i = 0; url[i]; i++)
273 if (!strcmp(url[i], c->get_hostname()))
278 for (i = 0; url[i]; i++)
280 yaz_log(LOG_DEBUG, "%szurl=%s use=%d",
281 m_session_str, url[i], zurl_in_use[i]);
282 if (min > zurl_in_use[i])
285 min = zurl_in_use[i];
291 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
292 const char *proxy_host)
295 Yaz_Proxy *parent = m_parent;
296 Yaz_ProxyClient *c = m_client;
300 const char *url[MAX_ZURL_PLEX];
301 Yaz_ProxyConfig *cfg = check_reconfigure();
305 /* only to be enabled for debugging... */
306 if (!strcmp(proxy_host, "stop"))
309 xfree(m_default_target);
310 m_default_target = xstrdup(proxy_host);
311 proxy_host = m_default_target;
313 int client_idletime = -1;
314 const char *cql2rpn_fname = 0;
315 url[0] = m_default_target;
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,
329 if (client_idletime != -1)
331 m_client_idletime = client_idletime;
332 timeout(m_client_idletime);
335 m_cql2rpn.set_pqf_file(cql2rpn_fname);
338 yaz_log(LOG_LOG, "%sNo default target", m_session_str);
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]);
347 m_proxyTarget = (char*) xstrdup(load_balance(url));
349 if (cookie && *cookie)
350 { // search in sessions with a cookie
351 for (c = parent->m_clientPool; c; c = c->m_next)
354 assert (*c->m_prev == c);
355 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
356 !strcmp(m_proxyTarget, c->get_hostname()))
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)
364 yaz_log (LOG_LOG, "%s REOPEN target=%s", m_session_str,
371 c->m_last_resultCount = 0;
372 c->m_sr_transform = 0;
374 c->m_resultSetStartPoint = 0;
375 c->m_target_idletime = m_target_idletime;
376 if (c->client(m_proxyTarget))
383 c->m_seqno = parent->m_seqno;
384 if (c->m_server && c->m_server != this)
385 c->m_server->m_client = 0;
388 yaz_log (LOG_DEBUG, "get_client 1 %p %p", this, c);
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)
399 assert (*c->m_prev == c);
400 if (c->m_server == 0 && c->m_cookie == 0 &&
402 !strcmp(m_proxyTarget, c->get_hostname()))
405 yaz_log (LOG_LOG, "%sREUSE %s",
406 m_session_str, c->get_hostname());
408 c->m_seqno = parent->m_seqno;
409 assert(c->m_server == 0);
412 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
413 c->set_APDU_yazlog(1);
415 c->set_APDU_yazlog(0);
427 if (apdu->which != Z_APDU_initRequest)
429 yaz_log (LOG_LOG, "no first INIT!");
432 Z_InitRequest *initRequest = apdu->u.initRequest;
434 if (!initRequest->idAuthentication)
436 if (m_proxy_authentication)
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);
449 // go through list of clients - and find the lowest/oldest one.
450 Yaz_ProxyClient *c_min = 0;
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)
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 : "");
461 if (min_seq < 0 || c->m_seqno < min_seq)
463 min_seq = c->m_seqno;
467 if (no_of_clients >= parent->m_max_clients)
470 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
472 yaz_log (LOG_LOG, "%sMAXCLIENTS Destroy %d",
473 m_session_str, c->m_seqno);
474 if (c->m_server && c->m_server != this)
480 yaz_log (LOG_LOG, "%sMAXCLIENTS Reuse %d %d %s",
482 c->m_seqno, parent->m_seqno, c->get_hostname());
486 c->m_cookie = xstrdup(cookie);
487 c->m_seqno = parent->m_seqno;
488 if (c->m_server && c->m_server != this)
490 c->m_server->m_client = 0;
494 c->m_target_idletime = m_target_idletime;
495 c->timeout(m_target_idletime);
497 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
498 c->set_APDU_yazlog(1);
500 c->set_APDU_yazlog(0);
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;
512 c->m_next->m_prev = &c->m_next;
513 parent->m_clientPool = c;
514 c->m_prev = &parent->m_clientPool;
520 c->m_cookie = xstrdup(cookie);
522 c->m_seqno = parent->m_seqno;
524 c->m_last_resultCount = 0;
527 c->m_sr_transform = 0;
529 c->m_resultSetStartPoint = 0;
531 if (c->client(m_proxyTarget))
536 c->m_target_idletime = m_target_idletime;
539 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
540 c->set_APDU_yazlog(1);
542 c->set_APDU_yazlog(0);
544 yaz_log (LOG_DEBUG, "get_client 3 %p %p", this, c);
548 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
551 for (i = 0; i<num; i++)
554 Z_DefaultDiagFormat *r;
555 Z_DiagRec *p = pp[i];
556 if (p->which != Z_DiagRec_defaultFormat)
558 yaz_log(LOG_LOG, "%sError no diagnostics", m_session_str);
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);
568 case Z_DefaultDiagFormat_v2Addinfo:
569 yaz_log(LOG_LOG, "%sError %d %s:%s",
571 *r->condition, diagbib1_str(*r->condition),
574 case Z_DefaultDiagFormat_v3Addinfo:
575 yaz_log(LOG_LOG, "%sError %d %s:%s",
577 *r->condition, diagbib1_str(*r->condition),
584 void Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p)
586 if (!m_stylesheet_schema)
588 xsltStylesheetPtr xsp;
590 xsp = xsltParseStylesheetFile((const xmlChar *) m_stylesheet_schema);
593 for (i = 0; i < p->num_records; i++)
595 Z_NamePlusRecord *npr = p->records[i];
596 if (npr->which == Z_NamePlusRecord_databaseRecord)
598 Z_External *r = npr->u.databaseRecord;
599 if (r->which == Z_External_octet)
601 xmlDocPtr res, doc = xmlParseMemory(
602 (char*) r->u.octet_aligned->buf,
603 r->u.octet_aligned->len);
605 res = xsltApplyStylesheet(xsp, doc, 0);
609 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
611 p->records[i]->u.databaseRecord =
612 z_ext_record(odr_encode(), VAL_TEXT_XML,
613 (char*) out_buf, out_len);
620 xsltFreeStylesheet(xsp);
623 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p)
627 yaz_marc_t mt = yaz_marc_create();
628 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
629 for (i = 0; i < p->num_records; i++)
631 Z_NamePlusRecord *npr = p->records[i];
632 if (npr->which == Z_NamePlusRecord_databaseRecord)
634 Z_External *r = npr->u.databaseRecord;
635 if (r->which == Z_External_octet)
639 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
640 r->u.octet_aligned->len,
643 yaz_iconv_t cd = yaz_iconv_open("UTF-8", "MARC-8");
644 WRBUF wrbuf = wrbuf_alloc();
647 size_t inbytesleft = rlen;
648 const char *inp = result;
649 while (cd && inbytesleft)
651 size_t outbytesleft = sizeof(outbuf);
655 r = yaz_iconv (cd, (char**) &inp,
657 &outp, &outbytesleft);
658 if (r == (size_t) (-1))
660 int e = yaz_iconv_error(cd);
661 if (e != YAZ_ICONV_E2BIG)
663 yaz_log(LOG_WARN, "conversion failure");
667 wrbuf_write(wrbuf, outbuf, outp - outbuf);
672 npr->u.databaseRecord = z_ext_record(odr_encode(),
676 wrbuf_free(wrbuf, 1);
681 yaz_marc_destroy(mt);
684 void Yaz_Proxy::logtime()
686 if (m_time_tv.tv_sec)
689 gettimeofday(&tv, 0);
690 long diff = (tv.tv_sec - m_time_tv.tv_sec)*1000000 +
691 (tv.tv_usec - m_time_tv.tv_usec);
693 yaz_log(LOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
694 diff/1000000, (diff/1000)%1000);
696 m_time_tv.tv_sec = 0;
697 m_time_tv.tv_usec = 0;
700 int Yaz_Proxy::send_http_response(int code)
702 ODR o = odr_encode();
703 Z_GDU *gdu = z_get_HTTP_Response(o, code);
704 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
706 hres->version = odr_strdup(o, m_http_version);
707 m_http_keepalive = 0;
708 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
710 yaz_log (LOG_LOG, "%sSending %s to client", m_session_str,
714 int r = send_GDU(gdu, &len);
719 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu)
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;
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");
731 static Z_SOAP_Handler soap_handlers[2] = {
733 {"http://www.loc.gov/zing/srw/", 0,
734 (Z_SOAP_fun) yaz_srw_codec},
739 Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
740 soap_package->which = Z_SOAP_generic;
741 soap_package->u.generic =
742 (Z_SOAP_Generic *) odr_malloc(o, sizeof(*soap_package->u.generic));
743 soap_package->u.generic->no = 0;
744 soap_package->u.generic->ns = soap_handlers[0].ns;
745 soap_package->u.generic->p = (void *) srw_pdu;
746 soap_package->ns = m_soap_ns;
747 z_soap_codec_enc_xsl(o, &soap_package,
748 &hres->content_buf, &hres->content_len,
749 soap_handlers, 0, m_s2z_stylesheet);
750 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
752 yaz_log (LOG_LOG, "%sSending %s to client", m_session_str,
756 int r = send_GDU(gdu, &len);
761 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
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;
767 srw_res->num_diagnostics = 1;
768 srw_res->diagnostics = (Z_SRW_diagnostic *)
769 odr_malloc(o, sizeof(*srw_res->diagnostics));
770 srw_res->diagnostics[0].code = odr_intdup(o, srw_error);
771 srw_res->diagnostics[0].details = add ? odr_strdup(o, add) : 0;
772 return send_srw_response(srw_pdu);
775 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
776 Z_DefaultDiagFormat *ddf)
778 int bib1_code = *ddf->condition;
779 if (bib1_code == 109)
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;
790 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
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;
796 srw_res->numberOfRecords = odr_intdup (o, hits);
797 if (records && records->which == Z_Records_DBOSD)
799 srw_res->num_records =
800 records->u.databaseOrSurDiagnostics->num_records;
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++)
806 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
807 if (npr->which != Z_NamePlusRecord_databaseRecord)
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);
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)
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);
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);
837 if (records && records->which == Z_Records_NSD)
840 http_code = z_to_srw_diag(odr_encode(), srw_res,
841 records->u.nonSurrogateDiagnostic);
843 return send_http_response(http_code);
845 return send_srw_response(srw_pdu);
849 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
852 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
853 Z_SRW_explainResponse *er = res->u.explain_response;
855 Yaz_ProxyConfig *cfg = check_reconfigure();
859 char *b = cfg->get_explain(odr_encode(), 0 /* target */,
863 er->record.recordData_buf = b;
864 er->record.recordData_len = len;
865 er->record.recordPacking = m_s2z_packing;
868 er->diagnostics = diagnostics;
869 er->num_diagnostics = num_diagnostics;
870 return send_srw_response(res);
873 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu, int *len)
877 if (apdu->which == Z_APDU_initResponse)
879 Z_InitResponse *res = apdu->u.initResponse;
880 if (*res->result == 0)
882 send_to_srw_client_error(3, 0);
884 else if (!m_s2z_search_apdu)
886 send_srw_explain_response(0, 0);
890 handle_incoming_Z_PDU(m_s2z_search_apdu);
893 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
895 m_s2z_search_apdu = 0;
896 Z_SearchResponse *res = apdu->u.searchResponse;
897 m_s2z_hit_count = *res->resultCount;
898 if (res->records && res->records->which == Z_Records_NSD)
900 send_to_srw_client_ok(0, res->records, 1);
902 else if (m_s2z_present_apdu)
905 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
907 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
909 if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
911 *pr->numberOfRecordsRequested =
912 1 + m_s2z_hit_count - *pr->resultSetStartPoint;
914 handle_incoming_Z_PDU(m_s2z_present_apdu);
918 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
921 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
924 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
926 m_s2z_present_apdu = 0;
927 Z_PresentResponse *res = apdu->u.presentResponse;
928 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
933 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
934 yaz_log (LOG_LOG, "%sSending %s to client", m_session_str,
936 int r = send_Z_PDU(apdu, len);
943 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
946 int kill_session = 0;
947 if (apdu->which == Z_APDU_searchResponse)
949 Z_SearchResponse *sr = apdu->u.searchResponse;
950 Z_Records *p = sr->records;
951 if (p && p->which == Z_Records_NSD)
953 Z_DiagRec dr, *dr_p = &dr;
954 dr.which = Z_DiagRec_defaultFormat;
955 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
957 *sr->searchStatus = 0;
958 display_diagrecs(&dr_p, 1);
962 if (p && p->which == Z_Records_DBOSD)
965 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
966 convert_xsl(p->u.databaseOrSurDiagnostics);
970 yaz_log(LOG_LOG, "%s%d hits", m_session_str,
972 if (*sr->resultCount < 0)
974 m_invalid_session = 1;
977 *sr->searchStatus = 0;
979 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
980 *sr->resultCount = 0;
985 else if (apdu->which == Z_APDU_presentResponse)
987 Z_PresentResponse *sr = apdu->u.presentResponse;
988 Z_Records *p = sr->records;
989 if (p && p->which == Z_Records_NSD)
991 Z_DiagRec dr, *dr_p = &dr;
992 dr.which = Z_DiagRec_defaultFormat;
993 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
994 if (*sr->presentStatus == Z_PresentStatus_success)
995 *sr->presentStatus = Z_PresentStatus_failure;
996 display_diagrecs(&dr_p, 1);
998 if (p && p->which == Z_Records_DBOSD)
1001 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
1002 convert_xsl(p->u.databaseOrSurDiagnostics);
1005 int r = send_PDU_convert(apdu, &len);
1008 m_bytes_sent += len;
1009 m_bw_stat.add_bytes(len);
1014 m_parent->pre_init();
1018 if (!m_http_keepalive)
1031 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1034 const char *apdu_name_tmp = apdu_name(apdu);
1035 int r = send_Z_PDU(apdu, &len);
1036 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1037 yaz_log (LOG_LOG, "%sSending %s to %s %d bytes",
1039 apdu_name_tmp, get_hostname(), len);
1040 m_bytes_sent += len;
1044 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1046 if (apdu->which == Z_APDU_presentRequest)
1048 Z_PresentRequest *pr = apdu->u.presentRequest;
1049 int toget = *pr->numberOfRecordsRequested;
1050 int start = *pr->resultSetStartPoint;
1052 yaz_log(LOG_LOG, "%sPresent %s %d+%d", m_session_str,
1053 pr->resultSetId, start, toget);
1055 if (*m_parent->m_optimize == '0')
1058 if (!m_client->m_last_resultSetId)
1060 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1061 new_apdu->u.presentResponse->records =
1062 create_nonSurrogateDiagnostics(odr_encode(), 30,
1064 send_to_client(new_apdu);
1067 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1069 if (start+toget-1 > m_client->m_last_resultCount)
1071 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1072 new_apdu->u.presentResponse->records =
1073 create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
1074 send_to_client(new_apdu);
1077 Z_NamePlusRecordList *npr;
1078 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1079 pr->preferredRecordSyntax,
1080 pr->recordComposition))
1082 yaz_log (LOG_LOG, "%sReturned cached records for present request",
1084 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1085 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1087 new_apdu->u.presentResponse->numberOfRecordsReturned
1088 = odr_intdup(odr_encode(), toget);
1090 new_apdu->u.presentResponse->records = (Z_Records*)
1091 odr_malloc(odr_encode(), sizeof(Z_Records));
1092 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1093 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1094 new_apdu->u.presentResponse->nextResultSetPosition =
1095 odr_intdup(odr_encode(), start+toget);
1097 send_to_client(new_apdu);
1103 if (apdu->which != Z_APDU_searchRequest)
1105 Z_SearchRequest *sr = apdu->u.searchRequest;
1106 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1107 Yaz_Z_Databases this_databases;
1109 this_databases.set(sr->num_databaseNames, (const char **)
1112 this_query->set_Z_Query(sr->query);
1114 char query_str[120];
1115 this_query->print(query_str, sizeof(query_str)-1);
1116 yaz_log(LOG_LOG, "%sSearch %s", m_session_str, query_str);
1118 if (*m_parent->m_optimize != '0' &&
1119 m_client->m_last_ok && m_client->m_last_query &&
1120 m_client->m_last_query->match(this_query) &&
1121 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1122 m_client->m_last_databases.match(this_databases))
1125 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1126 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1128 Z_NamePlusRecordList *npr;
1129 int toget = *sr->mediumSetPresentNumber;
1130 Z_RecordComposition *comp = 0;
1132 if (toget > m_client->m_last_resultCount)
1133 toget = m_client->m_last_resultCount;
1135 if (sr->mediumSetElementSetNames)
1137 comp = (Z_RecordComposition *)
1138 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1139 comp->which = Z_RecordComp_simple;
1140 comp->u.simple = sr->mediumSetElementSetNames;
1143 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1144 sr->preferredRecordSyntax, comp))
1146 yaz_log (LOG_LOG, "%sReturned cached records for medium set",
1148 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1149 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1150 new_apdu->u.searchResponse->resultCount =
1151 &m_client->m_last_resultCount;
1153 new_apdu->u.searchResponse->numberOfRecordsReturned
1154 = odr_intdup(odr_encode(), toget);
1156 new_apdu->u.searchResponse->presentStatus =
1157 odr_intdup(odr_encode(), Z_PresentStatus_success);
1158 new_apdu->u.searchResponse->records = (Z_Records*)
1159 odr_malloc(odr_encode(), sizeof(Z_Records));
1160 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1161 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1162 new_apdu->u.searchResponse->nextResultSetPosition =
1163 odr_intdup(odr_encode(), toget+1);
1164 send_to_client(new_apdu);
1170 // send present request (medium size)
1171 yaz_log (LOG_LOG, "%sOptimizing search for medium set",
1174 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1175 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1176 pr->referenceId = sr->referenceId;
1177 pr->resultSetId = sr->resultSetName;
1178 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1179 *pr->numberOfRecordsRequested = toget;
1180 pr->recordComposition = comp;
1181 m_client->m_sr_transform = 1;
1185 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1186 m_client->m_last_resultCount <= 0)
1188 // large set. Return pseudo-search response immediately
1189 yaz_log (LOG_LOG, "%sOptimizing search for large set",
1191 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1192 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1193 new_apdu->u.searchResponse->resultCount =
1194 &m_client->m_last_resultCount;
1195 send_to_client(new_apdu);
1200 Z_NamePlusRecordList *npr;
1201 int toget = m_client->m_last_resultCount;
1202 Z_RecordComposition *comp = 0;
1204 // send a present request (small set)
1206 if (sr->smallSetElementSetNames)
1208 comp = (Z_RecordComposition *)
1209 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1210 comp->which = Z_RecordComp_simple;
1211 comp->u.simple = sr->smallSetElementSetNames;
1214 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1215 sr->preferredRecordSyntax, comp))
1217 yaz_log (LOG_LOG, "%sReturned cached records for small set",
1219 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1220 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1221 new_apdu->u.searchResponse->resultCount =
1222 &m_client->m_last_resultCount;
1224 new_apdu->u.searchResponse->numberOfRecordsReturned
1225 = odr_intdup(odr_encode(), toget);
1227 new_apdu->u.searchResponse->presentStatus =
1228 odr_intdup(odr_encode(), Z_PresentStatus_success);
1229 new_apdu->u.searchResponse->records = (Z_Records*)
1230 odr_malloc(odr_encode(), sizeof(Z_Records));
1231 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1232 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1233 new_apdu->u.searchResponse->nextResultSetPosition =
1234 odr_intdup(odr_encode(), toget+1);
1235 send_to_client(new_apdu);
1240 yaz_log (LOG_LOG, "%sOptimizing search for small set",
1242 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1243 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1244 pr->referenceId = sr->referenceId;
1245 pr->resultSetId = sr->resultSetName;
1246 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1247 *pr->numberOfRecordsRequested = toget;
1248 pr->recordComposition = comp;
1249 m_client->m_sr_transform = 1;
1254 else // query doesn't match
1256 delete m_client->m_last_query;
1257 m_client->m_last_query = this_query;
1258 m_client->m_last_ok = 0;
1259 m_client->m_cache.clear();
1260 m_client->m_resultSetStartPoint = 0;
1262 xfree (m_client->m_last_resultSetId);
1263 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1265 m_client->m_last_databases.set(sr->num_databaseNames,
1266 (const char **) sr->databaseNames);
1272 void Yaz_Proxy::inc_request_no()
1274 char *cp = strchr(m_session_str, ' ');
1277 sprintf(cp+1, "%d ", m_request_no);
1280 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1284 m_bytes_recv += len;
1286 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
1287 yaz_log (LOG_DEBUG, "%sReceiving %s from client %d bytes",
1288 m_session_str, gdu_name(apdu), len);
1290 if (m_bw_hold_PDU) // double incoming PDU. shutdown now.
1293 m_bw_stat.add_bytes(len);
1294 m_pdu_stat.add_bytes(1);
1296 gettimeofday(&m_time_tv, 0);
1298 int bw_total = m_bw_stat.get_total();
1299 int pdu_total = m_pdu_stat.get_total();
1304 if (bw_total > m_bw_max)
1306 reduce = (bw_total/m_bw_max);
1311 if (pdu_total > m_pdu_max)
1313 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1314 reduce = (reduce > nreduce) ? reduce : nreduce;
1319 yaz_log(LOG_LOG, "%sdelay=%d bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1320 m_session_str, reduce, bw_total, pdu_total,
1321 m_bw_max, m_pdu_max);
1323 m_bw_hold_PDU = apdu; // save PDU and signal "on hold"
1324 timeout(reduce); // call us reduce seconds later
1326 else if (apdu->which == Z_GDU_Z3950)
1327 handle_incoming_Z_PDU(apdu->u.z3950);
1328 else if (apdu->which == Z_GDU_HTTP_Request)
1329 handle_incoming_HTTP(apdu->u.HTTP_Request);
1332 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
1334 if (m_max_record_retrieve)
1336 if (apdu->which == Z_APDU_presentRequest)
1338 Z_PresentRequest *pr = apdu->u.presentRequest;
1339 if (pr->numberOfRecordsRequested &&
1340 *pr->numberOfRecordsRequested > m_max_record_retrieve)
1341 *pr->numberOfRecordsRequested = m_max_record_retrieve;
1346 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
1348 const char *addinfo)
1350 Z_Records *rec = (Z_Records *)
1351 odr_malloc (odr, sizeof(*rec));
1353 odr_malloc (odr, sizeof(*err));
1354 Z_DiagRec *drec = (Z_DiagRec *)
1355 odr_malloc (odr, sizeof(*drec));
1356 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1357 odr_malloc (odr, sizeof(*dr));
1359 rec->which = Z_Records_NSD;
1360 rec->u.nonSurrogateDiagnostic = dr;
1361 dr->diagnosticSetId =
1362 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
1363 dr->condition = err;
1364 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1365 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1369 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
1371 if (apdu->which == Z_APDU_searchRequest &&
1372 apdu->u.searchRequest->query &&
1373 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
1374 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
1376 Z_RPNQuery *rpnquery = 0;
1377 Z_SearchRequest *sr = apdu->u.searchRequest;
1380 yaz_log(LOG_LOG, "%sCQL: %s", m_session_str,
1381 sr->query->u.type_104->u.cql);
1383 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
1384 &rpnquery, odr_encode(),
1387 yaz_log(LOG_LOG, "%sNo CQL to RPN table", m_session_str);
1390 yaz_log(LOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
1391 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1393 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1394 new_apdu->u.searchResponse->records =
1395 create_nonSurrogateDiagnostics(odr_encode(),
1396 yaz_diag_srw_to_bib1(r),
1398 *new_apdu->u.searchResponse->searchStatus = 0;
1400 send_to_client(new_apdu);
1406 sr->query->which = Z_Query_type_1;
1407 sr->query->u.type_1 = rpnquery;
1414 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
1416 if (apdu->which == Z_APDU_searchRequest)
1418 Z_SearchRequest *sr = apdu->u.searchRequest;
1422 Yaz_ProxyConfig *cfg = check_reconfigure();
1424 err = cfg->check_query(odr_encode(), m_default_target,
1425 sr->query, &addinfo);
1428 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1430 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1431 new_apdu->u.searchResponse->records =
1432 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1433 *new_apdu->u.searchResponse->searchStatus = 0;
1435 send_to_client(new_apdu);
1443 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
1446 if (apdu->which == Z_APDU_searchRequest)
1448 Z_SearchRequest *sr = apdu->u.searchRequest;
1451 Yaz_ProxyConfig *cfg = check_reconfigure();
1453 Z_RecordComposition rc_temp, *rc = 0;
1454 if (sr->smallSetElementSetNames)
1456 rc_temp.which = Z_RecordComp_simple;
1457 rc_temp.u.simple = sr->smallSetElementSetNames;
1462 err = cfg->check_syntax(odr_encode(),
1464 sr->preferredRecordSyntax, rc,
1465 &addinfo, &m_stylesheet_schema, &m_schema);
1468 sr->preferredRecordSyntax =
1469 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN, VAL_USMARC);
1474 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1476 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1477 new_apdu->u.searchResponse->records =
1478 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1479 *new_apdu->u.searchResponse->searchStatus = 0;
1481 send_to_client(new_apdu);
1486 else if (apdu->which == Z_APDU_presentRequest)
1488 Z_PresentRequest *pr = apdu->u.presentRequest;
1491 Yaz_ProxyConfig *cfg = check_reconfigure();
1494 err = cfg->check_syntax(odr_encode(), m_default_target,
1495 pr->preferredRecordSyntax,
1496 pr->recordComposition,
1497 &addinfo, &m_stylesheet_schema, &m_schema);
1500 pr->preferredRecordSyntax =
1501 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN, VAL_USMARC);
1506 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1508 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1509 new_apdu->u.presentResponse->records =
1510 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1511 *new_apdu->u.presentResponse->presentStatus =
1512 Z_PresentStatus_failure;
1514 send_to_client(new_apdu);
1522 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
1526 Z_ElementSetNames *esn = (Z_ElementSetNames *)
1527 odr_malloc(o, sizeof(Z_ElementSetNames));
1528 esn->which = Z_ElementSetNames_generic;
1529 esn->u.generic = odr_strdup(o, schema);
1533 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
1538 odr_destroy(m_s2z_odr_init);
1541 if (m_s2z_odr_search)
1543 odr_destroy(m_s2z_odr_search);
1544 m_s2z_odr_search = 0;
1547 m_http_keepalive = 0;
1549 if (!strcmp(hreq->version, "1.0"))
1551 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1552 if (v && !strcmp(v, "Keep-Alive"))
1553 m_http_keepalive = 1;
1555 m_http_keepalive = 0;
1556 m_http_version = "1.0";
1560 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1561 if (v && !strcmp(v, "close"))
1562 m_http_keepalive = 0;
1564 m_http_keepalive = 1;
1565 m_http_version = "1.1";
1568 Z_SRW_PDU *srw_pdu = 0;
1569 Z_SOAP *soap_package = 0;
1571 Z_SRW_diagnostic *diagnostic = 0;
1572 int num_diagnostic = 0;
1573 if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
1575 || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
1576 &charset, &diagnostic, &num_diagnostic) == 0)
1578 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
1579 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
1580 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
1581 m_s2z_init_apdu = 0;
1582 m_s2z_search_apdu = 0;
1583 m_s2z_present_apdu = 0;
1585 m_s2z_stylesheet = 0;
1587 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
1589 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
1591 // recordXPath unsupported.
1592 if (srw_req->recordXPath)
1594 yaz_add_srw_diagnostic(odr_decode(),
1595 &diagnostic, &num_diagnostic,
1598 // must have a query
1599 if (!srw_req->query.cql)
1601 yaz_add_srw_diagnostic(odr_decode(),
1602 &diagnostic, &num_diagnostic,
1606 if (srw_req->sort_type != Z_SRW_sort_type_none)
1608 yaz_add_srw_diagnostic(odr_decode(),
1609 &diagnostic, &num_diagnostic,
1613 if (srw_req->stylesheet)
1615 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
1617 // set packing for response records ..
1618 if (srw_req->recordPacking &&
1619 !strcmp(srw_req->recordPacking, "xml"))
1620 m_s2z_packing = Z_SRW_recordPacking_XML;
1622 m_s2z_packing = Z_SRW_recordPacking_string;
1626 Z_SRW_PDU *srw_pdu =
1627 yaz_srw_get(odr_encode(),
1628 Z_SRW_searchRetrieve_response);
1629 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1631 srw_res->diagnostics = diagnostic;
1632 srw_res->num_diagnostics = num_diagnostic;
1633 send_srw_response(srw_pdu);
1637 // prepare search PDU
1638 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
1639 Z_APDU_searchRequest);
1640 Z_SearchRequest *z_searchRequest =
1641 m_s2z_search_apdu->u.searchRequest;
1643 z_searchRequest->num_databaseNames = 1;
1644 z_searchRequest->databaseNames = (char**)
1645 odr_malloc(m_s2z_odr_search, sizeof(char *));
1646 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
1649 // query transformation
1650 Z_Query *query = (Z_Query *)
1651 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
1652 z_searchRequest->query = query;
1654 if (srw_req->query_type == Z_SRW_query_type_cql)
1656 Z_External *ext = (Z_External *)
1657 odr_malloc(m_s2z_odr_search, sizeof(*ext));
1658 ext->direct_reference =
1659 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
1660 ext->indirect_reference = 0;
1661 ext->descriptor = 0;
1662 ext->which = Z_External_CQL;
1663 ext->u.cql = srw_req->query.cql;
1665 query->which = Z_Query_type_104;
1666 query->u.type_104 = ext;
1668 else if (srw_req->query_type == Z_SRW_query_type_pqf)
1670 Z_RPNQuery *RPNquery;
1671 YAZ_PQF_Parser pqf_parser;
1673 pqf_parser = yaz_pqf_create ();
1675 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
1676 srw_req->query.pqf);
1679 const char *pqf_msg;
1681 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1682 yaz_log(LOG_LOG, "%*s^\n", off+4, "");
1683 yaz_log(LOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
1685 send_to_srw_client_error(10, 0);
1688 query->which = Z_Query_type_1;
1689 query->u.type_1 = RPNquery;
1691 yaz_pqf_destroy (pqf_parser);
1695 send_to_srw_client_error(7, "query");
1700 m_s2z_present_apdu = 0;
1702 if (srw_req->maximumRecords)
1703 max = *srw_req->maximumRecords;
1705 if (srw_req->startRecord)
1706 start = *srw_req->startRecord;
1709 // Some backend, such as Voyager doesn't honor piggyback
1710 // So we use present always (0 &&).
1711 if (0 && start <= 1) // Z39.50 piggyback
1713 *z_searchRequest->smallSetUpperBound = max;
1714 *z_searchRequest->mediumSetPresentNumber = max;
1715 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
1717 z_searchRequest->preferredRecordSyntax =
1718 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
1720 if (srw_req->recordSchema)
1722 z_searchRequest->smallSetElementSetNames =
1723 z_searchRequest->mediumSetElementSetNames =
1724 mk_esn_from_schema(m_s2z_odr_search,
1725 srw_req->recordSchema);
1728 else // Z39.50 present
1730 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
1731 Z_APDU_presentRequest);
1732 Z_PresentRequest *z_presentRequest =
1733 m_s2z_present_apdu->u.presentRequest;
1734 *z_presentRequest->resultSetStartPoint = start;
1735 *z_presentRequest->numberOfRecordsRequested = max;
1736 z_presentRequest->preferredRecordSyntax =
1737 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
1739 z_presentRequest->recordComposition =
1740 (Z_RecordComposition *)
1741 odr_malloc(m_s2z_odr_search,
1742 sizeof(Z_RecordComposition));
1743 if (srw_req->recordSchema)
1745 z_presentRequest->recordComposition->which =
1746 Z_RecordComp_simple;
1747 z_presentRequest->recordComposition->u.simple =
1748 mk_esn_from_schema(m_s2z_odr_search,
1749 srw_req->recordSchema);
1755 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
1756 Z_APDU_initRequest);
1758 // prevent m_initRequest_apdu memory from being grabbed
1759 // in Yaz_Proxy::handle_incoming_Z_PDU
1760 m_initRequest_apdu = m_s2z_init_apdu;
1761 handle_incoming_Z_PDU(m_s2z_init_apdu);
1766 handle_incoming_Z_PDU(m_s2z_search_apdu);
1770 else if (srw_pdu->which == Z_SRW_explain_request)
1772 Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
1775 if (srw_req->stylesheet)
1777 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
1779 if (srw_req->recordPacking &&
1780 !strcmp(srw_req->recordPacking, "xml"))
1781 m_s2z_packing = Z_SRW_recordPacking_XML;
1783 m_s2z_packing = Z_SRW_recordPacking_string;
1787 send_srw_explain_response(diagnostic, num_diagnostic);
1793 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
1794 Z_APDU_initRequest);
1796 // prevent m_initRequest_apdu memory from being grabbed
1797 // in Yaz_Proxy::handle_incoming_Z_PDU
1798 m_initRequest_apdu = m_s2z_init_apdu;
1799 handle_incoming_Z_PDU(m_s2z_init_apdu);
1802 send_srw_explain_response(0, 0);
1805 else if (srw_pdu->which == Z_SRW_scan_request)
1807 yaz_add_srw_diagnostic(odr_decode(),
1808 &diagnostic, &num_diagnostic,
1810 Z_SRW_PDU *srw_pdu =
1811 yaz_srw_get(odr_encode(),
1812 Z_SRW_scan_response);
1813 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
1815 srw_res->diagnostics = diagnostic;
1816 srw_res->num_diagnostics = num_diagnostic;
1817 send_srw_response(srw_pdu);
1822 send_to_srw_client_error(4, 0);
1826 Z_GDU *p = z_get_HTTP_Response(odr_encode(), 400);
1831 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
1833 if (!m_client && m_invalid_session)
1835 m_apdu_invalid_session = apdu;
1836 m_mem_invalid_session = odr_extract_mem(odr_decode());
1837 apdu = m_initRequest_apdu;
1840 // Determine our client.
1841 Z_OtherInformation **oi;
1842 get_otherInfoAPDU(apdu, &oi);
1843 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
1849 m_client->m_server = this;
1851 if (apdu->which == Z_APDU_initRequest)
1853 if (apdu->u.initRequest->implementationId)
1854 yaz_log(LOG_LOG, "%simplementationId: %s",
1855 m_session_str, apdu->u.initRequest->implementationId);
1856 if (apdu->u.initRequest->implementationName)
1857 yaz_log(LOG_LOG, "%simplementationName: %s",
1858 m_session_str, apdu->u.initRequest->implementationName);
1859 if (apdu->u.initRequest->implementationVersion)
1860 yaz_log(LOG_LOG, "%simplementationVersion: %s",
1861 m_session_str, apdu->u.initRequest->implementationVersion);
1862 if (m_initRequest_apdu == 0)
1864 if (m_initRequest_mem)
1865 nmem_destroy(m_initRequest_mem);
1866 m_initRequest_apdu = apdu;
1867 m_initRequest_mem = odr_extract_mem(odr_decode());
1869 if (m_client->m_init_flag)
1871 if (handle_init_response_for_invalid_session(apdu))
1873 Z_APDU *apdu2 = m_client->m_initResponse;
1874 apdu2->u.initResponse->otherInfo = 0;
1875 if (m_client->m_cookie && *m_client->m_cookie)
1876 set_otherInformationString(apdu2, VAL_COOKIE, 1,
1877 m_client->m_cookie);
1878 apdu2->u.initResponse->referenceId =
1879 apdu->u.initRequest->referenceId;
1880 send_to_client(apdu2);
1883 m_client->m_init_flag = 1;
1885 handle_max_record_retrieve(apdu);
1888 apdu = handle_syntax_validation(apdu);
1891 apdu = handle_query_transformation(apdu);
1894 apdu = handle_query_validation(apdu);
1897 apdu = result_set_optimize(apdu);
1900 m_client->timeout(m_target_idletime); // mark it active even
1901 // though we didn't use it
1905 // delete other info part from PDU before sending to target
1906 get_otherInfoAPDU(apdu, &oi);
1910 if (apdu->which == Z_APDU_presentRequest &&
1911 m_client->m_resultSetStartPoint == 0)
1913 Z_PresentRequest *pr = apdu->u.presentRequest;
1914 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
1915 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
1917 m_client->m_resultSetStartPoint = 0;
1919 if (m_client->send_to_target(apdu) < 0)
1926 m_client->m_waiting = 1;
1929 void Yaz_Proxy::connectNotify()
1933 void Yaz_Proxy::shutdown()
1935 m_invalid_session = 0;
1936 // only keep if keep_alive flag is set...
1938 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
1939 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
1940 m_client->m_waiting == 0)
1942 yaz_log(LOG_LOG, "%sShutdown (client to proxy) keepalive %s",
1944 m_client->get_hostname());
1945 yaz_log(LOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1946 m_session_str, m_client->m_pdu_recv,
1947 m_client->m_bytes_sent + m_client->m_bytes_recv,
1948 m_keepalive_limit_bw, m_keepalive_limit_pdu);
1949 assert (m_client->m_waiting != 2);
1950 // Tell client (if any) that no server connection is there..
1951 m_client->m_server = 0;
1952 m_invalid_session = 0;
1956 yaz_log (LOG_LOG, "%sShutdown (client to proxy) close %s",
1958 m_client->get_hostname());
1959 assert (m_client->m_waiting != 2);
1964 yaz_log (LOG_LOG, "%sshutdown (client to proxy) bad state",
1970 yaz_log (LOG_LOG, "%sShutdown (client to proxy)",
1974 m_parent->pre_init();
1978 const char *Yaz_ProxyClient::get_session_str()
1982 return m_server->get_session_str();
1985 void Yaz_ProxyClient::shutdown()
1987 yaz_log (LOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
1993 void Yaz_Proxy::failNotify()
1996 yaz_log (LOG_LOG, "%sConnection closed by client",
2001 void Yaz_ProxyClient::failNotify()
2004 m_server->inc_request_no();
2005 yaz_log (LOG_LOG, "%sConnection closed by target %s",
2006 get_session_str(), get_hostname());
2010 void Yaz_ProxyClient::connectNotify()
2012 const char *s = get_session_str();
2013 const char *h = get_hostname();
2014 yaz_log (LOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
2016 timeout(m_target_idletime);
2021 IYaz_PDU_Observer *Yaz_ProxyClient::sessionNotify(IYaz_PDU_Observable
2022 *the_PDU_Observable, int fd)
2024 return new Yaz_ProxyClient(the_PDU_Observable, 0);
2027 Yaz_ProxyClient::~Yaz_ProxyClient()
2032 m_next->m_prev = m_prev;
2033 m_waiting = 2; // for debugging purposes only.
2034 odr_destroy(m_init_odr);
2035 delete m_last_query;
2036 xfree (m_last_resultSetId);
2040 void Yaz_ProxyClient::pre_init_client()
2042 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
2043 Z_InitRequest *req = apdu->u.initRequest;
2045 ODR_MASK_SET(req->options, Z_Options_search);
2046 ODR_MASK_SET(req->options, Z_Options_present);
2047 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
2048 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
2049 ODR_MASK_SET(req->options, Z_Options_scan);
2050 ODR_MASK_SET(req->options, Z_Options_sort);
2051 ODR_MASK_SET(req->options, Z_Options_extendedServices);
2052 ODR_MASK_SET(req->options, Z_Options_delSet);
2054 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
2055 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
2056 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
2058 if (send_to_target(apdu) < 0)
2069 void Yaz_Proxy::pre_init()
2072 const char *name = 0;
2073 const char *zurl_in_use[MAX_ZURL_PLEX];
2074 int limit_bw, limit_pdu, limit_req;
2075 int target_idletime, client_idletime;
2077 int keepalive_limit_bw, keepalive_limit_pdu;
2079 const char *cql2rpn = 0;
2081 Yaz_ProxyConfig *cfg = check_reconfigure();
2085 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
2090 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
2091 &limit_bw, &limit_pdu, &limit_req,
2092 &target_idletime, &client_idletime,
2094 &keepalive_limit_bw,
2095 &keepalive_limit_pdu,
2102 for (j = 0; zurl_in_use[j]; j++)
2108 for (c = m_clientPool; c; c = c->m_next)
2110 if (!strcmp(zurl_in_use[j], c->get_hostname()))
2112 if (c->m_cookie == 0)
2114 if (c->m_server == 0)
2123 yaz_log(LOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
2124 "preinit=%d",m_session_str,
2125 name, zurl_in_use[j], in_use, other, spare, pre_init);
2126 if (spare < pre_init)
2128 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
2129 c->m_next = m_clientPool;
2131 c->m_next->m_prev = &c->m_next;
2133 c->m_prev = &m_clientPool;
2135 if (m_log_mask & PROXY_LOG_APDU_SERVER)
2136 c->set_APDU_yazlog(1);
2138 c->set_APDU_yazlog(0);
2140 if (c->client(zurl_in_use[j]))
2148 c->m_target_idletime = target_idletime;
2149 c->m_seqno = m_seqno++;
2156 void Yaz_Proxy::timeoutNotify()
2162 timeout(m_client_idletime);
2163 Z_GDU *apdu = m_bw_hold_PDU;
2166 if (apdu->which == Z_GDU_Z3950)
2167 handle_incoming_Z_PDU(apdu->u.z3950);
2168 else if (apdu->which == Z_GDU_HTTP_Request)
2169 handle_incoming_HTTP(apdu->u.HTTP_Request);
2175 yaz_log (LOG_LOG, "%sTimeout (client to proxy)", m_session_str);
2186 void Yaz_ProxyClient::timeoutNotify()
2189 m_server->inc_request_no();
2191 yaz_log (LOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
2198 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable,
2199 Yaz_Proxy *parent) :
2200 Yaz_Z_Assoc (the_PDU_Observable)
2207 m_last_resultSetId = 0;
2208 m_last_resultCount = 0;
2212 m_init_odr = odr_createmem (ODR_DECODE);
2214 m_resultSetStartPoint = 0;
2215 m_bytes_sent = m_bytes_recv = 0;
2219 m_target_idletime = 600;
2223 const char *Yaz_Proxy::option(const char *name, const char *value)
2225 if (!strcmp (name, "optimize")) {
2228 m_optimize = xstrdup (value);
2235 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
2240 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
2242 if (apdu->which == Z_GDU_Z3950)
2243 recv_Z_PDU(apdu->u.z3950, len);
2244 else if (apdu->which == Z_GDU_HTTP_Response)
2245 recv_HTTP_response(apdu->u.HTTP_Response, len);
2250 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
2252 if (!m_invalid_session)
2254 m_invalid_session = 0;
2255 handle_incoming_Z_PDU(m_apdu_invalid_session);
2256 assert (m_mem_invalid_session);
2257 nmem_destroy(m_mem_invalid_session);
2258 m_mem_invalid_session = 0;
2262 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
2264 m_bytes_recv += len;
2267 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
2268 yaz_log (LOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
2269 apdu_name(apdu), get_hostname(), len);
2270 if (apdu->which == Z_APDU_initResponse)
2272 if (!m_server) // if this is a pre init session , check for more
2274 NMEM nmem = odr_extract_mem (odr_decode());
2275 odr_reset (m_init_odr);
2276 nmem_transfer (m_init_odr->mem, nmem);
2277 m_initResponse = apdu;
2279 Z_InitResponse *ir = apdu->u.initResponse;
2280 char *im0 = ir->implementationName;
2283 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
2290 strcat(im1, "(YAZ Proxy)");
2291 ir->implementationName = im1;
2293 nmem_destroy (nmem);
2295 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
2298 if (apdu->which == Z_APDU_searchResponse)
2300 Z_SearchResponse *sr = apdu->u.searchResponse;
2301 m_last_resultCount = *sr->resultCount;
2302 int status = *sr->searchStatus;
2303 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
2307 if (sr->records && sr->records->which == Z_Records_DBOSD)
2309 m_cache.add(odr_decode(),
2310 sr->records->u.databaseOrSurDiagnostics, 1,
2315 if (apdu->which == Z_APDU_presentResponse)
2317 Z_PresentResponse *pr = apdu->u.presentResponse;
2321 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2322 Z_SearchResponse *sr = new_apdu->u.searchResponse;
2323 sr->referenceId = pr->referenceId;
2324 *sr->resultCount = m_last_resultCount;
2325 sr->records = pr->records;
2326 sr->nextResultSetPosition = pr->nextResultSetPosition;
2327 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
2331 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
2333 m_cache.add(odr_decode(),
2334 pr->records->u.databaseOrSurDiagnostics,
2335 m_resultSetStartPoint, -1);
2336 m_resultSetStartPoint = 0;
2340 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
2343 m_server->send_to_client(apdu);
2345 if (apdu->which == Z_APDU_close)
2351 int Yaz_Proxy::server(const char *addr)
2353 int r = Yaz_Z_Assoc::server(addr);
2356 yaz_log(LOG_LOG, "%sStarted proxy " VERSION " on %s", m_session_str, addr);