1 /* $Id: yaz-proxy.cpp,v 1.16 2005-01-11 20:50:29 adam Exp $
2 Copyright (c) 1998-2005, Index Data.
4 This file is part of the yaz-proxy.
6 YAZ proxy is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
11 YAZ proxy is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with YAZ proxy; see the file LICENSE. If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
29 #include <sys/types.h>
40 #include <yaz/marcdisp.h>
41 #include <yaz/yaz-iconv.h>
43 #include <yaz/diagbib1.h>
45 #include <yaz/pquery.h>
46 #include <yaz/otherinfo.h>
48 static const char *apdu_name(Z_APDU *apdu)
52 case Z_APDU_initRequest:
54 case Z_APDU_initResponse:
55 return "initResponse";
56 case Z_APDU_searchRequest:
57 return "searchRequest";
58 case Z_APDU_searchResponse:
59 return "searchResponse";
60 case Z_APDU_presentRequest:
61 return "presentRequest";
62 case Z_APDU_presentResponse:
63 return "presentResponse";
64 case Z_APDU_deleteResultSetRequest:
65 return "deleteResultSetRequest";
66 case Z_APDU_deleteResultSetResponse:
67 return "deleteResultSetResponse";
68 case Z_APDU_scanRequest:
70 case Z_APDU_scanResponse:
71 return "scanResponse";
72 case Z_APDU_sortRequest:
74 case Z_APDU_sortResponse:
75 return "sortResponse";
76 case Z_APDU_extendedServicesRequest:
77 return "extendedServicesRequest";
78 case Z_APDU_extendedServicesResponse:
79 return "extendedServicesResponse";
86 static const char *gdu_name(Z_GDU *gdu)
91 return apdu_name(gdu->u.z3950);
92 case Z_GDU_HTTP_Request:
93 return "HTTP Request";
94 case Z_GDU_HTTP_Response:
95 return "HTTP Response";
97 return "Unknown request/response";
100 Yaz_Proxy::Yaz_Proxy(IYaz_PDU_Observable *the_PDU_Observable,
102 Yaz_Z_Assoc(the_PDU_Observable), m_bw_stat(60), m_pdu_stat(60)
104 m_PDU_Observable = the_PDU_Observable;
109 m_keepalive_limit_bw = 500000;
110 m_keepalive_limit_pdu = 1000;
112 m_default_target = 0;
113 m_proxy_authentication = 0;
117 m_client_idletime = 600;
118 m_target_idletime = 600;
119 m_optimize = xstrdup ("1");
120 strcpy(m_session_str, "0 ");
127 m_max_record_retrieve = 0;
131 m_invalid_session = 0;
133 m_referenceId_mem = nmem_create();
136 m_stylesheet_xsp = 0;
137 m_stylesheet_nprl = 0;
138 m_s2z_stylesheet = 0;
142 m_backend_charset = 0;
144 m_initRequest_apdu = 0;
145 m_initRequest_mem = 0;
146 m_initRequest_preferredMessageSize = 0;
147 m_initRequest_maximumRecordSize = 0;
148 m_initRequest_options = 0;
149 m_initRequest_version = 0;
150 m_apdu_invalid_session = 0;
151 m_mem_invalid_session = 0;
153 m_s2z_odr_search = 0;
155 m_s2z_search_apdu = 0;
156 m_s2z_present_apdu = 0;
157 m_http_keepalive = 0;
160 m_s2z_packing = Z_SRW_recordPacking_string;
161 #if HAVE_GETTIMEOFDAY
162 m_time_tv = xmalloc(sizeof(struct timeval));
163 struct timeval *tv = (struct timeval *) m_time_tv;
169 m_usemarcon_ini_stage1 = 0;
170 m_usemarcon_ini_stage2 = 0;
171 m_usemarcon = new Yaz_usemarcon();
176 Yaz_Proxy::~Yaz_Proxy()
178 yaz_log(YLOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
179 m_bytes_sent, m_bytes_recv);
180 nmem_destroy(m_initRequest_mem);
181 nmem_destroy(m_mem_invalid_session);
182 nmem_destroy(m_referenceId_mem);
184 xfree(m_proxyTarget);
185 xfree(m_default_target);
186 xfree(m_proxy_authentication);
190 if (m_stylesheet_xsp)
191 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
196 xfree (m_backend_type);
197 xfree (m_backend_charset);
198 xfree (m_usemarcon_ini_stage1);
199 xfree (m_usemarcon_ini_stage2);
202 odr_destroy(m_s2z_odr_init);
203 if (m_s2z_odr_search)
204 odr_destroy(m_s2z_odr_search);
210 int Yaz_Proxy::set_config(const char *config)
213 m_config = new Yaz_ProxyConfig();
214 xfree(m_config_fname);
215 m_config_fname = xstrdup(config);
216 int r = m_config->read_xml(config);
218 m_config->get_generic_info(&m_log_mask, &m_max_clients);
222 void Yaz_Proxy::set_default_target(const char *target)
224 xfree (m_default_target);
225 m_default_target = 0;
227 m_default_target = (char *) xstrdup (target);
230 void Yaz_Proxy::set_proxy_authentication (const char *auth)
232 xfree (m_proxy_authentication);
233 m_proxy_authentication = 0;
235 m_proxy_authentication = (char *) xstrdup (auth);
238 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
241 return m_parent->check_reconfigure();
243 Yaz_ProxyConfig *cfg = m_config;
246 yaz_log(YLOG_LOG, "reconfigure");
248 if (m_config_fname && cfg)
250 yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
251 int r = cfg->read_xml(m_config_fname);
253 yaz_log(YLOG_WARN, "reconfigure failed");
257 cfg->get_generic_info(&m_log_mask, &m_max_clients);
261 yaz_log(YLOG_LOG, "reconfigure");
267 IYaz_PDU_Observer *Yaz_Proxy::sessionNotify(IYaz_PDU_Observable
268 *the_PDU_Observable, int fd)
271 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable, this);
272 new_proxy->m_config = 0;
273 new_proxy->m_config_fname = 0;
274 new_proxy->timeout(m_client_idletime);
275 new_proxy->m_target_idletime = m_target_idletime;
276 new_proxy->set_default_target(m_default_target);
277 new_proxy->m_max_clients = m_max_clients;
278 new_proxy->m_log_mask = m_log_mask;
279 new_proxy->set_APDU_log(get_APDU_log());
280 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
281 new_proxy->set_APDU_yazlog(1);
283 new_proxy->set_APDU_yazlog(0);
284 new_proxy->set_proxy_authentication(m_proxy_authentication);
285 sprintf(new_proxy->m_session_str, "%ld:%d ", (long) time(0), m_session_no);
287 yaz_log (YLOG_LOG, "%sNew session %s", new_proxy->m_session_str,
288 the_PDU_Observable->getpeername());
292 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
295 Z_OtherInformationUnit *oi;
297 ent.proto = PROTO_Z3950;
298 ent.oclass = CLASS_USERINFO;
299 ent.value = (oid_value) VAL_COOKIE;
300 assert (oid_ent_to_oid (&ent, oid));
302 if (oid_ent_to_oid (&ent, oid) &&
303 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
304 oi->which == Z_OtherInfo_characterInfo)
305 return oi->information.characterInfo;
309 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
312 Z_OtherInformationUnit *oi;
314 ent.proto = PROTO_Z3950;
315 ent.oclass = CLASS_USERINFO;
316 ent.value = (oid_value) VAL_PROXY;
317 if (oid_ent_to_oid (&ent, oid) &&
318 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
319 oi->which == Z_OtherInfo_characterInfo)
320 return oi->information.characterInfo;
324 const char *Yaz_Proxy::load_balance(const char **url)
326 int zurl_in_use[MAX_ZURL_PLEX];
327 int zurl_in_spare[MAX_ZURL_PLEX];
331 for (i = 0; i<MAX_ZURL_PLEX; i++)
334 zurl_in_spare[i] = 0;
336 for (c = m_parent->m_clientPool; c; c = c->m_next)
338 for (i = 0; url[i]; i++)
339 if (!strcmp(url[i], c->get_hostname()))
342 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
346 int min_use = 100000;
347 int spare_for_min = 0;
349 const char *ret_min = 0;
350 const char *ret_spare = 0;
351 for (i = 0; url[i]; i++)
353 yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
354 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
355 if (min_use > zurl_in_use[i])
358 min_use = zurl_in_use[i];
359 spare_for_min = zurl_in_spare[i];
361 if (max_spare < zurl_in_spare[i])
364 max_spare = zurl_in_spare[i];
367 // use the one with minimum connections if spare is > 3
368 if (spare_for_min > 3)
370 // use one with most spares (if any)
376 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
377 const char *proxy_host)
380 Yaz_Proxy *parent = m_parent;
381 Yaz_ProxyClient *c = m_client;
385 const char *url[MAX_ZURL_PLEX];
386 Yaz_ProxyConfig *cfg = check_reconfigure();
390 /* only to be enabled for debugging... */
391 if (!strcmp(proxy_host, "stop"))
394 xfree(m_default_target);
395 m_default_target = xstrdup(proxy_host);
397 proxy_host = m_default_target;
398 int client_idletime = -1;
399 const char *cql2rpn_fname = 0;
400 const char *authentication = 0;
401 url[0] = m_default_target;
406 cfg->get_target_info(proxy_host, url, &m_bw_max,
407 &m_pdu_max, &m_max_record_retrieve,
408 &m_target_idletime, &client_idletime,
409 &parent->m_max_clients,
410 &m_keepalive_limit_bw,
411 &m_keepalive_limit_pdu,
416 if (client_idletime != -1)
418 m_client_idletime = client_idletime;
419 timeout(m_client_idletime);
422 m_cql2rpn.set_pqf_file(cql2rpn_fname);
424 set_proxy_authentication(authentication);
427 yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
430 // we don't handle multiplexing for cookie session, so we just
431 // pick the first one in this case (anonymous users will be able
432 // to use any backend)
433 if (cookie && *cookie)
434 m_proxyTarget = (char*) xstrdup(url[0]);
436 m_proxyTarget = (char*) xstrdup(load_balance(url));
438 if (cookie && *cookie)
439 { // search in sessions with a cookie
440 for (c = parent->m_clientPool; c; c = c->m_next)
443 assert (*c->m_prev == c);
444 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
445 !strcmp(m_proxyTarget, c->get_hostname()))
448 // The following handles "cancel"
449 // If connection is busy (waiting for PDU) and
450 // we have an initRequest we can safely do re-open
451 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
453 yaz_log (YLOG_LOG, "%s REOPEN target=%s", m_session_str,
460 c->m_last_resultCount = 0;
461 c->m_sr_transform = 0;
463 c->m_resultSetStartPoint = 0;
464 c->m_target_idletime = m_target_idletime;
465 if (c->client(m_proxyTarget))
472 c->m_seqno = parent->m_seqno;
473 if (c->m_server && c->m_server != this)
474 c->m_server->m_client = 0;
477 yaz_log (YLOG_DEBUG, "get_client 1 %p %p", this, c);
482 else if (!c && apdu->which == Z_APDU_initRequest
483 && apdu->u.initRequest->idAuthentication == 0)
485 // anonymous sessions without cookie.
486 // if authentication is set it is NOT anonymous se we can't share them.
487 for (c = parent->m_clientPool; c; c = c->m_next)
490 assert(*c->m_prev == c);
491 if (c->m_server == 0 && c->m_cookie == 0 &&
493 !strcmp(m_proxyTarget, c->get_hostname()))
496 yaz_log (YLOG_LOG, "%sREUSE %d %s",
497 m_session_str, parent->m_seqno, c->get_hostname());
499 c->m_seqno = parent->m_seqno;
500 assert(c->m_server == 0);
503 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
504 c->set_APDU_yazlog(1);
506 c->set_APDU_yazlog(0);
518 if (apdu->which != Z_APDU_initRequest)
520 yaz_log (YLOG_LOG, "%sno init request as first PDU", m_session_str);
523 Z_InitRequest *initRequest = apdu->u.initRequest;
525 if (!initRequest->idAuthentication)
527 if (m_proxy_authentication)
529 initRequest->idAuthentication =
530 (Z_IdAuthentication *)
531 odr_malloc (odr_encode(),
532 sizeof(*initRequest->idAuthentication));
533 initRequest->idAuthentication->which =
534 Z_IdAuthentication_open;
535 initRequest->idAuthentication->u.open =
536 odr_strdup (odr_encode(), m_proxy_authentication);
541 // the client use authentication. We set the keepalive PDU
542 // to 0 so we don't cache it in releaseClient
543 m_keepalive_limit_pdu = 0;
545 // go through list of clients - and find the lowest/oldest one.
546 Yaz_ProxyClient *c_min = 0;
548 int no_of_clients = 0;
549 if (parent->m_clientPool)
550 yaz_log (YLOG_DEBUG, "Existing sessions");
551 for (c = parent->m_clientPool; c; c = c->m_next)
553 yaz_log (YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
554 c->m_waiting, c->get_hostname(),
555 c->m_cookie ? c->m_cookie : "");
557 if (min_seq < 0 || c->m_seqno < min_seq)
559 min_seq = c->m_seqno;
563 if (no_of_clients >= parent->m_max_clients)
566 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
568 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
569 m_session_str, parent->m_max_clients, c->m_seqno);
570 if (c->m_server && c->m_server != this)
576 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
577 m_session_str, parent->m_max_clients,
578 c->m_seqno, parent->m_seqno, c->get_hostname());
582 c->m_cookie = xstrdup(cookie);
583 c->m_seqno = parent->m_seqno;
584 if (c->m_server && c->m_server != this)
586 c->m_server->m_client = 0;
590 c->m_target_idletime = m_target_idletime;
591 c->timeout(m_target_idletime);
593 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
594 c->set_APDU_yazlog(1);
596 c->set_APDU_yazlog(0);
603 yaz_log (YLOG_LOG, "%sNEW %d %s",
604 m_session_str, parent->m_seqno, m_proxyTarget);
605 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
606 c->m_next = parent->m_clientPool;
608 c->m_next->m_prev = &c->m_next;
609 parent->m_clientPool = c;
610 c->m_prev = &parent->m_clientPool;
616 c->m_cookie = xstrdup(cookie);
618 c->m_seqno = parent->m_seqno;
620 c->m_last_resultCount = 0;
623 c->m_sr_transform = 0;
625 c->m_resultSetStartPoint = 0;
627 if (c->client(m_proxyTarget))
632 c->m_target_idletime = m_target_idletime;
635 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
636 c->set_APDU_yazlog(1);
638 c->set_APDU_yazlog(0);
640 yaz_log (YLOG_DEBUG, "get_client 3 %p %p", this, c);
644 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
647 for (i = 0; i<num; i++)
650 Z_DefaultDiagFormat *r;
651 Z_DiagRec *p = pp[i];
652 if (p->which != Z_DiagRec_defaultFormat)
654 yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
658 r = p->u.defaultFormat;
659 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
660 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
661 yaz_log(YLOG_LOG, "%sError unknown diagnostic set", m_session_str);
664 case Z_DefaultDiagFormat_v2Addinfo:
665 yaz_log(YLOG_LOG, "%sError %d %s:%s",
667 *r->condition, diagbib1_str(*r->condition),
670 case Z_DefaultDiagFormat_v3Addinfo:
671 yaz_log(YLOG_LOG, "%sError %d %s:%s",
673 *r->condition, diagbib1_str(*r->condition),
680 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
682 if (!m_stylesheet_xsp || p->num_records <= 0)
683 return 0; /* no XSLT to be done ... */
685 m_stylesheet_offset = 0;
686 m_stylesheet_nprl = p;
687 m_stylesheet_apdu = apdu;
692 void Yaz_Proxy::convert_xsl_delay()
694 Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
696 if (npr->which == Z_NamePlusRecord_databaseRecord)
698 Z_External *r = npr->u.databaseRecord;
699 if (r->which == Z_External_octet)
702 fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
704 xmlDocPtr res, doc = xmlParseMemory(
705 (char*) r->u.octet_aligned->buf,
706 r->u.octet_aligned->len);
709 yaz_log(YLOG_LOG, "%sXSLT convert %d",
710 m_session_str, m_stylesheet_offset);
711 res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
718 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
720 m_stylesheet_nprl->records[m_stylesheet_offset]->
722 z_ext_record(odr_encode(), VAL_TEXT_XML,
723 (char*) out_buf, out_len);
732 m_stylesheet_offset++;
733 if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
735 m_stylesheet_nprl = 0;
737 if (m_stylesheet_xsp)
738 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
740 m_stylesheet_xsp = 0;
741 timeout(m_client_idletime);
742 send_PDU_convert(m_stylesheet_apdu);
748 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
750 if (m_frontend_type != VAL_NONE)
753 for (i = 0; i < p->num_records; i++)
755 Z_NamePlusRecord *npr = p->records[i];
756 if (npr->which == Z_NamePlusRecord_databaseRecord)
758 Z_External *r = npr->u.databaseRecord;
759 if (r->which == Z_External_octet)
762 if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
764 if (!m_usemarcon->m_stage1)
766 m_usemarcon->m_stage1 = new CDetails();
768 m_usemarcon->m_stage1->SetIniFileName(m_usemarcon_ini_stage1);
769 m_usemarcon->m_stage1->SetMarcRecord((char*) r->u.octet_aligned->buf, r->u.octet_aligned->len);
770 int res = m_usemarcon->m_stage1->Start();
775 m_usemarcon->m_stage1->GetMarcRecord(converted, convlen);
776 if (m_usemarcon_ini_stage2 && *m_usemarcon_ini_stage2)
778 if (!m_usemarcon->m_stage2)
780 m_usemarcon->m_stage2 = new CDetails();
782 m_usemarcon->m_stage2->SetIniFileName(m_usemarcon_ini_stage2);
783 m_usemarcon->m_stage2->SetMarcRecord(converted, convlen);
784 res = m_usemarcon->m_stage2->Start();
788 m_usemarcon->m_stage2->GetMarcRecord(converted, convlen);
792 yaz_log(YLOG_LOG, "%sUSEMARCON stage 2 error %d", m_session_str, res);
795 npr->u.databaseRecord =
796 z_ext_record(odr_encode(),
804 yaz_log(YLOG_LOG, "%sUSEMARCON stage 1 error %d", m_session_str, res);
809 npr->u.databaseRecord =
810 z_ext_record(odr_encode(),
812 (char*) r->u.octet_aligned->buf,
813 r->u.octet_aligned->len);
820 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
821 const char *backend_charset)
825 if (!backend_charset)
826 backend_charset = "MARC-8";
827 yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
828 yaz_marc_t mt = yaz_marc_create();
829 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
830 yaz_marc_iconv(mt, cd);
831 for (i = 0; i < p->num_records; i++)
833 Z_NamePlusRecord *npr = p->records[i];
834 if (npr->which == Z_NamePlusRecord_databaseRecord)
836 Z_External *r = npr->u.databaseRecord;
837 if (r->which == Z_External_octet)
841 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
842 r->u.octet_aligned->len,
845 npr->u.databaseRecord = z_ext_record(odr_encode(),
854 yaz_marc_destroy(mt);
857 void Yaz_Proxy::logtime()
859 #if HAVE_GETTIMEOFDAY
860 struct timeval *tv = (struct timeval*) m_time_tv;
864 gettimeofday(&tv1, 0);
865 long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
866 (tv1.tv_usec - tv->tv_usec);
868 yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
869 diff/1000000, (diff/1000)%1000);
876 int Yaz_Proxy::send_http_response(int code)
878 ODR o = odr_encode();
879 Z_GDU *gdu = z_get_HTTP_Response(o, code);
880 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
882 hres->version = odr_strdup(o, m_http_version);
883 if (m_http_keepalive)
884 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
888 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
890 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
894 int r = send_GDU(gdu, &len);
896 m_bw_stat.add_bytes(len);
901 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu)
903 ODR o = odr_encode();
904 const char *ctype = "text/xml";
905 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
906 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
908 hres->version = odr_strdup(o, m_http_version);
909 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
910 if (m_http_keepalive)
911 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
915 static Z_SOAP_Handler soap_handlers[2] = {
917 {"http://www.loc.gov/zing/srw/", 0,
918 (Z_SOAP_fun) yaz_srw_codec},
923 Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
924 soap_package->which = Z_SOAP_generic;
925 soap_package->u.generic =
926 (Z_SOAP_Generic *) odr_malloc(o, sizeof(*soap_package->u.generic));
927 soap_package->u.generic->no = 0;
928 soap_package->u.generic->ns = soap_handlers[0].ns;
929 soap_package->u.generic->p = (void *) srw_pdu;
930 soap_package->ns = m_soap_ns;
931 z_soap_codec_enc_xsl(o, &soap_package,
932 &hres->content_buf, &hres->content_len,
933 soap_handlers, 0, m_s2z_stylesheet);
934 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
936 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
940 int r = send_GDU(gdu, &len);
942 m_bw_stat.add_bytes(len);
947 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
949 ODR o = odr_encode();
950 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
951 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
953 srw_res->num_diagnostics = 1;
954 srw_res->diagnostics = (Z_SRW_diagnostic *)
955 odr_malloc(o, sizeof(*srw_res->diagnostics));
956 yaz_mk_std_diagnostic(o, srw_res->diagnostics, srw_error, add);
957 return send_srw_response(srw_pdu);
960 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
961 Z_DefaultDiagFormat *ddf)
963 int bib1_code = *ddf->condition;
964 if (bib1_code == 109)
966 srw_res->num_diagnostics = 1;
967 srw_res->diagnostics = (Z_SRW_diagnostic *)
968 odr_malloc(o, sizeof(*srw_res->diagnostics));
969 yaz_mk_std_diagnostic(o, srw_res->diagnostics,
970 yaz_diag_bib1_to_srw(*ddf->condition),
975 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
977 ODR o = odr_encode();
978 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
979 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
981 srw_res->numberOfRecords = odr_intdup (o, hits);
982 if (records && records->which == Z_Records_DBOSD)
984 srw_res->num_records =
985 records->u.databaseOrSurDiagnostics->num_records;
987 srw_res->records = (Z_SRW_record *)
988 odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
989 for (i = 0; i < srw_res->num_records; i++)
991 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
992 if (npr->which != Z_NamePlusRecord_databaseRecord)
994 srw_res->records[i].recordSchema = "diagnostic";
995 srw_res->records[i].recordPacking = m_s2z_packing;
996 srw_res->records[i].recordData_buf = "67";
997 srw_res->records[i].recordData_len = 2;
998 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1001 Z_External *r = npr->u.databaseRecord;
1002 oident *ent = oid_getentbyoid(r->direct_reference);
1003 if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
1005 srw_res->records[i].recordSchema = m_schema;
1006 srw_res->records[i].recordPacking = m_s2z_packing;
1007 srw_res->records[i].recordData_buf = (char*)
1008 r->u.octet_aligned->buf;
1009 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1010 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1014 srw_res->records[i].recordSchema = "diagnostic";
1015 srw_res->records[i].recordPacking = m_s2z_packing;
1016 srw_res->records[i].recordData_buf = "67";
1017 srw_res->records[i].recordData_len = 2;
1018 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1022 if (records && records->which == Z_Records_NSD)
1025 http_code = z_to_srw_diag(odr_encode(), srw_res,
1026 records->u.nonSurrogateDiagnostic);
1028 return send_http_response(http_code);
1030 return send_srw_response(srw_pdu);
1034 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1035 int num_diagnostics)
1037 Yaz_ProxyConfig *cfg = check_reconfigure();
1041 char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1042 m_s2z_database, &len);
1045 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1046 Z_SRW_explainResponse *er = res->u.explain_response;
1048 er->record.recordData_buf = b;
1049 er->record.recordData_len = len;
1050 er->record.recordPacking = m_s2z_packing;
1051 er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
1053 er->diagnostics = diagnostics;
1054 er->num_diagnostics = num_diagnostics;
1055 return send_srw_response(res);
1058 return send_http_response(404);
1061 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1065 if (apdu->which == Z_APDU_initResponse)
1067 Z_InitResponse *res = apdu->u.initResponse;
1068 if (*res->result == 0)
1070 send_to_srw_client_error(3, 0);
1072 else if (!m_s2z_search_apdu)
1074 send_srw_explain_response(0, 0);
1078 handle_incoming_Z_PDU(m_s2z_search_apdu);
1081 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1083 m_s2z_search_apdu = 0;
1084 Z_SearchResponse *res = apdu->u.searchResponse;
1085 m_s2z_hit_count = *res->resultCount;
1086 if (res->records && res->records->which == Z_Records_NSD)
1088 send_to_srw_client_ok(0, res->records, 1);
1090 else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1093 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1095 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1097 if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1099 *pr->numberOfRecordsRequested =
1100 1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1102 handle_incoming_Z_PDU(m_s2z_present_apdu);
1106 m_s2z_present_apdu = 0;
1107 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1110 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1113 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1115 m_s2z_present_apdu = 0;
1116 Z_PresentResponse *res = apdu->u.presentResponse;
1117 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1123 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1124 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1126 int r = send_Z_PDU(apdu, &len);
1127 m_bytes_sent += len;
1128 m_bw_stat.add_bytes(len);
1135 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1137 int kill_session = 0;
1138 Z_ReferenceId **new_id = get_referenceIdP(apdu);
1141 *new_id = m_referenceId;
1143 if (apdu->which == Z_APDU_searchResponse)
1145 Z_SearchResponse *sr = apdu->u.searchResponse;
1146 Z_Records *p = sr->records;
1147 if (p && p->which == Z_Records_NSD)
1149 Z_DiagRec dr, *dr_p = &dr;
1150 dr.which = Z_DiagRec_defaultFormat;
1151 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1153 *sr->searchStatus = 0;
1154 display_diagrecs(&dr_p, 1);
1158 if (p && p->which == Z_Records_DBOSD)
1162 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1165 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1167 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1169 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1173 if (sr->resultCount)
1175 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1177 if (*sr->resultCount < 0)
1179 m_invalid_session = 1;
1182 *sr->searchStatus = 0;
1184 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1185 *sr->resultCount = 0;
1190 else if (apdu->which == Z_APDU_presentResponse)
1192 Z_PresentResponse *sr = apdu->u.presentResponse;
1193 Z_Records *p = sr->records;
1194 if (p && p->which == Z_Records_NSD)
1196 Z_DiagRec dr, *dr_p = &dr;
1197 dr.which = Z_DiagRec_defaultFormat;
1198 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1199 if (*sr->presentStatus == Z_PresentStatus_success)
1200 *sr->presentStatus = Z_PresentStatus_failure;
1201 display_diagrecs(&dr_p, 1);
1203 if (p && p->which == Z_Records_DBOSD)
1207 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1210 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1212 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1214 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1218 else if (apdu->which == Z_APDU_initResponse)
1220 if (m_initRequest_options)
1223 (Odr_bitmask *)odr_malloc(odr_encode(),
1224 sizeof(Odr_bitmask));
1225 ODR_MASK_ZERO(nopt);
1228 for (i = 0; i<24; i++)
1229 if (ODR_MASK_GET(m_initRequest_options, i) &&
1230 ODR_MASK_GET(apdu->u.initResponse->options, i))
1231 ODR_MASK_SET(nopt, i);
1232 apdu->u.initResponse->options = nopt;
1234 if (m_initRequest_version)
1236 Z_ProtocolVersion *nopt =
1237 (Odr_bitmask *)odr_malloc(odr_encode(),
1238 sizeof(Odr_bitmask));
1239 ODR_MASK_ZERO(nopt);
1242 for (i = 0; i<8; i++)
1243 if (ODR_MASK_GET(m_initRequest_version, i) &&
1244 ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1245 ODR_MASK_SET(nopt, i);
1246 apdu->u.initResponse->protocolVersion = nopt;
1248 apdu->u.initResponse->preferredMessageSize =
1249 odr_intdup(odr_encode(),
1250 m_client->m_initResponse_preferredMessageSize >
1251 m_initRequest_preferredMessageSize ?
1252 m_initRequest_preferredMessageSize :
1253 m_client->m_initResponse_preferredMessageSize);
1254 apdu->u.initResponse->maximumRecordSize =
1255 odr_intdup(odr_encode(),
1256 m_client->m_initResponse_maximumRecordSize >
1257 m_initRequest_maximumRecordSize ?
1258 m_initRequest_maximumRecordSize :
1259 m_client->m_initResponse_maximumRecordSize);
1261 int r = send_PDU_convert(apdu);
1268 m_parent->pre_init();
1273 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1276 const char *apdu_name_tmp = apdu_name(apdu);
1277 int r = send_Z_PDU(apdu, &len);
1278 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1279 yaz_log (YLOG_LOG, "%sSending %s to %s %d bytes",
1281 apdu_name_tmp, get_hostname(), len);
1282 m_bytes_sent += len;
1286 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1288 if (apdu->which == Z_APDU_presentRequest)
1290 Z_PresentRequest *pr = apdu->u.presentRequest;
1291 int toget = *pr->numberOfRecordsRequested;
1292 int start = *pr->resultSetStartPoint;
1294 yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1295 pr->resultSetId, start, toget);
1297 if (*m_parent->m_optimize == '0')
1300 if (!m_client->m_last_resultSetId)
1302 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1303 new_apdu->u.presentResponse->records =
1304 create_nonSurrogateDiagnostics(odr_encode(), 30,
1306 send_to_client(new_apdu);
1309 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1311 if (start+toget-1 > m_client->m_last_resultCount)
1313 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1314 new_apdu->u.presentResponse->records =
1315 create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
1316 send_to_client(new_apdu);
1319 Z_NamePlusRecordList *npr;
1321 yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1322 m_session_str, start, toget, yaz_z3950oid_to_str(
1323 pr->preferredRecordSyntax, &oclass));
1325 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1326 pr->preferredRecordSyntax,
1327 pr->recordComposition))
1329 yaz_log (YLOG_LOG, "%sReturned cached records for present request",
1331 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1332 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1334 new_apdu->u.presentResponse->numberOfRecordsReturned
1335 = odr_intdup(odr_encode(), toget);
1337 new_apdu->u.presentResponse->records = (Z_Records*)
1338 odr_malloc(odr_encode(), sizeof(Z_Records));
1339 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1340 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1341 new_apdu->u.presentResponse->nextResultSetPosition =
1342 odr_intdup(odr_encode(), start+toget);
1344 send_to_client(new_apdu);
1350 if (apdu->which != Z_APDU_searchRequest)
1352 Z_SearchRequest *sr = apdu->u.searchRequest;
1353 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1354 Yaz_Z_Databases this_databases;
1356 this_databases.set(sr->num_databaseNames, (const char **)
1359 this_query->set_Z_Query(sr->query);
1361 char query_str[120];
1362 this_query->print(query_str, sizeof(query_str)-1);
1363 yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1365 if (*m_parent->m_optimize != '0' &&
1366 m_client->m_last_ok && m_client->m_last_query &&
1367 m_client->m_last_query->match(this_query) &&
1368 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1369 m_client->m_last_databases.match(this_databases))
1372 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1373 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1375 Z_NamePlusRecordList *npr;
1376 int toget = *sr->mediumSetPresentNumber;
1377 Z_RecordComposition *comp = 0;
1379 if (toget > m_client->m_last_resultCount)
1380 toget = m_client->m_last_resultCount;
1382 if (sr->mediumSetElementSetNames)
1384 comp = (Z_RecordComposition *)
1385 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1386 comp->which = Z_RecordComp_simple;
1387 comp->u.simple = sr->mediumSetElementSetNames;
1390 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1391 sr->preferredRecordSyntax, comp))
1393 yaz_log (YLOG_LOG, "%sReturned cached records for medium set",
1395 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1396 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1397 new_apdu->u.searchResponse->resultCount =
1398 &m_client->m_last_resultCount;
1400 new_apdu->u.searchResponse->numberOfRecordsReturned
1401 = odr_intdup(odr_encode(), toget);
1403 new_apdu->u.searchResponse->presentStatus =
1404 odr_intdup(odr_encode(), Z_PresentStatus_success);
1405 new_apdu->u.searchResponse->records = (Z_Records*)
1406 odr_malloc(odr_encode(), sizeof(Z_Records));
1407 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1408 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1409 new_apdu->u.searchResponse->nextResultSetPosition =
1410 odr_intdup(odr_encode(), toget+1);
1411 send_to_client(new_apdu);
1417 // send present request (medium size)
1418 yaz_log (YLOG_LOG, "%sOptimizing search for medium set",
1421 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1422 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1423 pr->referenceId = sr->referenceId;
1424 pr->resultSetId = sr->resultSetName;
1425 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1426 *pr->numberOfRecordsRequested = toget;
1427 pr->recordComposition = comp;
1428 m_client->m_sr_transform = 1;
1432 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1433 m_client->m_last_resultCount <= 0)
1435 // large set. Return pseudo-search response immediately
1436 yaz_log (YLOG_LOG, "%sOptimizing search for large set",
1438 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1439 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1440 new_apdu->u.searchResponse->resultCount =
1441 &m_client->m_last_resultCount;
1442 send_to_client(new_apdu);
1447 Z_NamePlusRecordList *npr;
1448 int toget = m_client->m_last_resultCount;
1449 Z_RecordComposition *comp = 0;
1451 // send a present request (small set)
1453 if (sr->smallSetElementSetNames)
1455 comp = (Z_RecordComposition *)
1456 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1457 comp->which = Z_RecordComp_simple;
1458 comp->u.simple = sr->smallSetElementSetNames;
1461 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1462 sr->preferredRecordSyntax, comp))
1464 yaz_log (YLOG_LOG, "%sReturned cached records for small set",
1466 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1467 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1468 new_apdu->u.searchResponse->resultCount =
1469 &m_client->m_last_resultCount;
1471 new_apdu->u.searchResponse->numberOfRecordsReturned
1472 = odr_intdup(odr_encode(), toget);
1474 new_apdu->u.searchResponse->presentStatus =
1475 odr_intdup(odr_encode(), Z_PresentStatus_success);
1476 new_apdu->u.searchResponse->records = (Z_Records*)
1477 odr_malloc(odr_encode(), sizeof(Z_Records));
1478 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1479 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1480 new_apdu->u.searchResponse->nextResultSetPosition =
1481 odr_intdup(odr_encode(), toget+1);
1482 send_to_client(new_apdu);
1487 yaz_log (YLOG_LOG, "%sOptimizing search for small set",
1489 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1490 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1491 pr->referenceId = sr->referenceId;
1492 pr->resultSetId = sr->resultSetName;
1493 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1494 *pr->numberOfRecordsRequested = toget;
1495 pr->recordComposition = comp;
1496 m_client->m_sr_transform = 1;
1501 else // query doesn't match
1503 delete m_client->m_last_query;
1504 m_client->m_last_query = this_query;
1505 m_client->m_last_ok = 0;
1506 m_client->m_cache.clear();
1507 m_client->m_resultSetStartPoint = 0;
1509 xfree (m_client->m_last_resultSetId);
1510 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1512 m_client->m_last_databases.set(sr->num_databaseNames,
1513 (const char **) sr->databaseNames);
1519 void Yaz_Proxy::inc_request_no()
1521 char *cp = strchr(m_session_str, ' ');
1524 sprintf(cp+1, "%d ", m_request_no);
1527 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1531 m_bytes_recv += len;
1533 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1534 yaz_log (YLOG_LOG, "%sReceiving %s from client %d bytes",
1535 m_session_str, gdu_name(apdu), len);
1537 if (m_bw_hold_PDU) // double incoming PDU. shutdown now.
1540 m_bw_stat.add_bytes(len);
1541 m_pdu_stat.add_bytes(1);
1543 #if HAVE_GETTIMEOFDAY
1544 gettimeofday((struct timeval *) m_time_tv, 0);
1547 int bw_total = m_bw_stat.get_total();
1548 int pdu_total = m_pdu_stat.get_total();
1553 if (bw_total > m_bw_max)
1555 reduce = (bw_total/m_bw_max);
1560 if (pdu_total > m_pdu_max)
1562 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1563 reduce = (reduce > nreduce) ? reduce : nreduce;
1569 yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1570 m_session_str, reduce, bw_total, pdu_total,
1571 m_bw_max, m_pdu_max);
1573 m_bw_hold_PDU = apdu; // save PDU and signal "on hold"
1574 timeout(reduce); // call us reduce seconds later
1576 else if (apdu->which == Z_GDU_Z3950)
1577 handle_incoming_Z_PDU(apdu->u.z3950);
1578 else if (apdu->which == Z_GDU_HTTP_Request)
1579 handle_incoming_HTTP(apdu->u.HTTP_Request);
1582 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
1584 if (m_max_record_retrieve)
1586 if (apdu->which == Z_APDU_presentRequest)
1588 Z_PresentRequest *pr = apdu->u.presentRequest;
1589 if (pr->numberOfRecordsRequested &&
1590 *pr->numberOfRecordsRequested > m_max_record_retrieve)
1591 *pr->numberOfRecordsRequested = m_max_record_retrieve;
1596 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
1598 const char *addinfo)
1600 Z_Records *rec = (Z_Records *)
1601 odr_malloc (odr, sizeof(*rec));
1603 odr_malloc (odr, sizeof(*err));
1604 Z_DiagRec *drec = (Z_DiagRec *)
1605 odr_malloc (odr, sizeof(*drec));
1606 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1607 odr_malloc (odr, sizeof(*dr));
1609 rec->which = Z_Records_NSD;
1610 rec->u.nonSurrogateDiagnostic = dr;
1611 dr->diagnosticSetId =
1612 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
1613 dr->condition = err;
1614 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1615 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1619 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
1621 if (apdu->which == Z_APDU_searchRequest &&
1622 apdu->u.searchRequest->query &&
1623 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
1624 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
1626 Z_RPNQuery *rpnquery = 0;
1627 Z_SearchRequest *sr = apdu->u.searchRequest;
1630 yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
1631 sr->query->u.type_104->u.cql);
1633 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
1634 &rpnquery, odr_encode(),
1637 yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
1640 yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
1641 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1643 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1644 new_apdu->u.searchResponse->records =
1645 create_nonSurrogateDiagnostics(odr_encode(),
1646 yaz_diag_srw_to_bib1(r),
1648 *new_apdu->u.searchResponse->searchStatus = 0;
1650 send_to_client(new_apdu);
1656 sr->query->which = Z_Query_type_1;
1657 sr->query->u.type_1 = rpnquery;
1664 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
1666 if (apdu->which == Z_APDU_searchRequest)
1668 Z_SearchRequest *sr = apdu->u.searchRequest;
1672 Yaz_ProxyConfig *cfg = check_reconfigure();
1674 err = cfg->check_query(odr_encode(), m_default_target,
1675 sr->query, &addinfo);
1678 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1680 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1681 new_apdu->u.searchResponse->records =
1682 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1683 *new_apdu->u.searchResponse->searchStatus = 0;
1685 send_to_client(new_apdu);
1693 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
1696 if (apdu->which == Z_APDU_searchRequest)
1698 Z_SearchRequest *sr = apdu->u.searchRequest;
1701 Yaz_ProxyConfig *cfg = check_reconfigure();
1703 Z_RecordComposition rc_temp, *rc = 0;
1704 if (sr->smallSetElementSetNames)
1706 rc_temp.which = Z_RecordComp_simple;
1707 rc_temp.u.simple = sr->smallSetElementSetNames;
1711 if (sr->preferredRecordSyntax)
1714 ent = oid_getentbyoid(sr->preferredRecordSyntax);
1715 m_frontend_type = ent->value;
1718 m_frontend_type = VAL_NONE;
1720 char *stylesheet_name = 0;
1722 err = cfg->check_syntax(odr_encode(),
1724 sr->preferredRecordSyntax, rc,
1725 &addinfo, &stylesheet_name, &m_schema,
1726 &m_backend_type, &m_backend_charset,
1727 &m_usemarcon_ini_stage1,
1728 &m_usemarcon_ini_stage2);
1729 if (stylesheet_name)
1731 m_parent->low_socket_close();
1734 if (m_stylesheet_xsp)
1735 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
1736 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
1739 m_stylesheet_offset = 0;
1740 xfree(stylesheet_name);
1742 m_parent->low_socket_open();
1746 sr->smallSetElementSetNames = 0;
1747 sr->mediumSetElementSetNames = 0;
1751 sr->preferredRecordSyntax =
1752 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
1756 sr->preferredRecordSyntax =
1757 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
1763 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1765 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1766 new_apdu->u.searchResponse->records =
1767 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1768 *new_apdu->u.searchResponse->searchStatus = 0;
1770 send_to_client(new_apdu);
1774 else if (m_backend_type)
1776 sr->preferredRecordSyntax =
1777 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
1780 else if (apdu->which == Z_APDU_presentRequest)
1782 Z_PresentRequest *pr = apdu->u.presentRequest;
1785 Yaz_ProxyConfig *cfg = check_reconfigure();
1787 if (pr->preferredRecordSyntax)
1790 ent = oid_getentbyoid(pr->preferredRecordSyntax);
1791 m_frontend_type = ent->value;
1794 m_frontend_type = VAL_NONE;
1796 char *stylesheet_name = 0;
1798 err = cfg->check_syntax(odr_encode(), m_default_target,
1799 pr->preferredRecordSyntax,
1800 pr->recordComposition,
1801 &addinfo, &stylesheet_name, &m_schema,
1802 &m_backend_type, &m_backend_charset,
1803 &m_usemarcon_ini_stage1,
1804 &m_usemarcon_ini_stage2
1806 if (stylesheet_name)
1808 m_parent->low_socket_close();
1811 if (m_stylesheet_xsp)
1812 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
1813 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
1816 m_stylesheet_offset = 0;
1817 xfree(stylesheet_name);
1819 m_parent->low_socket_open();
1823 pr->recordComposition = 0;
1827 pr->preferredRecordSyntax =
1828 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
1832 pr->preferredRecordSyntax =
1833 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
1839 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1841 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1842 new_apdu->u.presentResponse->records =
1843 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1844 *new_apdu->u.presentResponse->presentStatus =
1845 Z_PresentStatus_failure;
1847 send_to_client(new_apdu);
1851 else if (m_backend_type)
1853 pr->preferredRecordSyntax =
1854 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
1860 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
1864 Z_ElementSetNames *esn = (Z_ElementSetNames *)
1865 odr_malloc(o, sizeof(Z_ElementSetNames));
1866 esn->which = Z_ElementSetNames_generic;
1867 esn->u.generic = odr_strdup(o, schema);
1871 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
1874 Yaz_ProxyConfig *cfg = check_reconfigure();
1876 t = cfg->get_explain_name(db, backend_db);
1878 if (m_client && m_default_target && t && strcmp(m_default_target, t))
1885 xfree(m_default_target);
1886 m_default_target = xstrdup(t);
1890 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
1892 yaz_log(YLOG_LOG, "file_access");
1893 if (strcmp(hreq->method, "GET"))
1896 if (hreq->path[0] != '/')
1898 yaz_log(YLOG_WARN, "Path != /");
1901 const char *cp = hreq->path;
1904 if (*cp == '/' && strchr("/.", cp[1]))
1908 const char *fname = hreq->path+1;
1909 if (stat(fname, &sbuf))
1911 yaz_log(YLOG_WARN, "stat %s failed", fname);
1914 if ((sbuf.st_mode & S_IFMT) != S_IFREG)
1916 if (sbuf.st_size > (off_t) 1000000)
1919 ODR o = odr_encode();
1920 Yaz_ProxyConfig *cfg = check_reconfigure();
1921 const char *ctype = cfg->check_mime_type(fname);
1922 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
1923 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1925 hres->version = odr_strdup(o, m_http_version);
1926 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1927 if (m_http_keepalive)
1928 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1932 hres->content_len = sbuf.st_size;
1933 hres->content_buf = (char*) odr_malloc(o, hres->content_len);
1934 FILE *f = fopen(fname, "rb");
1937 fread(hres->content_buf, 1, hres->content_len, f);
1944 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1946 yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
1950 send_GDU(gdu, &len);
1954 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
1958 odr_destroy(m_s2z_odr_init);
1961 if (m_s2z_odr_search)
1963 odr_destroy(m_s2z_odr_search);
1964 m_s2z_odr_search = 0;
1967 m_http_keepalive = 0;
1969 if (!strcmp(hreq->version, "1.0"))
1971 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1972 if (v && !strcmp(v, "Keep-Alive"))
1973 m_http_keepalive = 1;
1975 m_http_keepalive = 0;
1976 m_http_version = "1.0";
1980 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1981 if (v && !strcmp(v, "close"))
1982 m_http_keepalive = 0;
1984 m_http_keepalive = 1;
1985 m_http_version = "1.1";
1988 Z_SRW_PDU *srw_pdu = 0;
1989 Z_SOAP *soap_package = 0;
1991 Z_SRW_diagnostic *diagnostic = 0;
1992 int num_diagnostic = 0;
1994 if (file_access(hreq))
1998 else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2000 || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2001 &charset, &diagnostic, &num_diagnostic) == 0)
2003 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2004 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2005 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2006 m_s2z_init_apdu = 0;
2007 m_s2z_search_apdu = 0;
2008 m_s2z_present_apdu = 0;
2010 m_s2z_stylesheet = 0;
2012 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2014 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2016 const char *backend_db = srw_req->database;
2017 srw_get_client(srw_req->database, &backend_db);
2019 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2020 // recordXPath unsupported.
2021 if (srw_req->recordXPath)
2023 yaz_add_srw_diagnostic(odr_decode(),
2024 &diagnostic, &num_diagnostic,
2028 if (srw_req->sort_type != Z_SRW_sort_type_none)
2030 yaz_add_srw_diagnostic(odr_decode(),
2031 &diagnostic, &num_diagnostic,
2035 if (srw_req->stylesheet)
2037 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2039 // set packing for response records ..
2040 if (srw_req->recordPacking &&
2041 !strcmp(srw_req->recordPacking, "xml"))
2042 m_s2z_packing = Z_SRW_recordPacking_XML;
2044 m_s2z_packing = Z_SRW_recordPacking_string;
2048 Z_SRW_PDU *srw_pdu =
2049 yaz_srw_get(odr_encode(),
2050 Z_SRW_searchRetrieve_response);
2051 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2053 srw_res->diagnostics = diagnostic;
2054 srw_res->num_diagnostics = num_diagnostic;
2055 send_srw_response(srw_pdu);
2059 // prepare search PDU
2060 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2061 Z_APDU_searchRequest);
2062 Z_SearchRequest *z_searchRequest =
2063 m_s2z_search_apdu->u.searchRequest;
2065 z_searchRequest->num_databaseNames = 1;
2066 z_searchRequest->databaseNames = (char**)
2067 odr_malloc(m_s2z_odr_search, sizeof(char *));
2068 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2071 // query transformation
2072 Z_Query *query = (Z_Query *)
2073 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2074 z_searchRequest->query = query;
2076 if (srw_req->query_type == Z_SRW_query_type_cql)
2078 Z_External *ext = (Z_External *)
2079 odr_malloc(m_s2z_odr_search, sizeof(*ext));
2080 ext->direct_reference =
2081 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2082 ext->indirect_reference = 0;
2083 ext->descriptor = 0;
2084 ext->which = Z_External_CQL;
2085 ext->u.cql = srw_req->query.cql;
2087 query->which = Z_Query_type_104;
2088 query->u.type_104 = ext;
2090 else if (srw_req->query_type == Z_SRW_query_type_pqf)
2092 Z_RPNQuery *RPNquery;
2093 YAZ_PQF_Parser pqf_parser;
2095 pqf_parser = yaz_pqf_create ();
2097 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2098 srw_req->query.pqf);
2101 const char *pqf_msg;
2103 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2104 yaz_log(YLOG_LOG, "%*s^\n", off+4, "");
2105 yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2107 send_to_srw_client_error(10, 0);
2110 query->which = Z_Query_type_1;
2111 query->u.type_1 = RPNquery;
2113 yaz_pqf_destroy (pqf_parser);
2117 send_to_srw_client_error(7, "query");
2122 m_s2z_present_apdu = 0;
2124 if (srw_req->maximumRecords)
2125 max = *srw_req->maximumRecords;
2127 if (srw_req->startRecord)
2128 start = *srw_req->startRecord;
2131 // Some backend, such as Voyager doesn't honor piggyback
2132 // So we use present always (0 &&).
2133 if (0 && start <= 1) // Z39.50 piggyback
2135 *z_searchRequest->smallSetUpperBound = max;
2136 *z_searchRequest->mediumSetPresentNumber = max;
2137 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2139 z_searchRequest->preferredRecordSyntax =
2140 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2142 if (srw_req->recordSchema)
2144 z_searchRequest->smallSetElementSetNames =
2145 z_searchRequest->mediumSetElementSetNames =
2146 mk_esn_from_schema(m_s2z_odr_search,
2147 srw_req->recordSchema);
2150 else // Z39.50 present
2152 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2153 Z_APDU_presentRequest);
2154 Z_PresentRequest *z_presentRequest =
2155 m_s2z_present_apdu->u.presentRequest;
2156 *z_presentRequest->resultSetStartPoint = start;
2157 *z_presentRequest->numberOfRecordsRequested = max;
2158 z_presentRequest->preferredRecordSyntax =
2159 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2161 if (srw_req->recordSchema)
2163 z_presentRequest->recordComposition =
2164 (Z_RecordComposition *)
2165 odr_malloc(m_s2z_odr_search,
2166 sizeof(Z_RecordComposition));
2167 z_presentRequest->recordComposition->which =
2168 Z_RecordComp_simple;
2169 z_presentRequest->recordComposition->u.simple =
2170 mk_esn_from_schema(m_s2z_odr_search,
2171 srw_req->recordSchema);
2177 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2178 Z_APDU_initRequest);
2180 // prevent m_initRequest_apdu memory from being grabbed
2181 // in Yaz_Proxy::handle_incoming_Z_PDU
2182 m_initRequest_apdu = m_s2z_init_apdu;
2183 handle_incoming_Z_PDU(m_s2z_init_apdu);
2188 handle_incoming_Z_PDU(m_s2z_search_apdu);
2192 else if (srw_pdu->which == Z_SRW_explain_request)
2194 Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
2196 const char *backend_db = srw_req->database;
2197 srw_get_client(srw_req->database, &backend_db);
2199 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2202 if (srw_req->stylesheet)
2204 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2206 if (srw_req->recordPacking &&
2207 !strcmp(srw_req->recordPacking, "xml"))
2208 m_s2z_packing = Z_SRW_recordPacking_XML;
2210 m_s2z_packing = Z_SRW_recordPacking_string;
2214 send_srw_explain_response(diagnostic, num_diagnostic);
2220 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2221 Z_APDU_initRequest);
2223 // prevent m_initRequest_apdu memory from being grabbed
2224 // in Yaz_Proxy::handle_incoming_Z_PDU
2225 m_initRequest_apdu = m_s2z_init_apdu;
2226 handle_incoming_Z_PDU(m_s2z_init_apdu);
2229 send_srw_explain_response(0, 0);
2232 else if (srw_pdu->which == Z_SRW_scan_request)
2234 m_s2z_database = odr_strdup(m_s2z_odr_init,
2235 srw_pdu->u.scan_request->database);
2237 yaz_add_srw_diagnostic(odr_decode(),
2238 &diagnostic, &num_diagnostic,
2240 Z_SRW_PDU *srw_pdu =
2241 yaz_srw_get(odr_encode(),
2242 Z_SRW_scan_response);
2243 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
2245 srw_res->diagnostics = diagnostic;
2246 srw_res->num_diagnostics = num_diagnostic;
2247 send_srw_response(srw_pdu);
2254 send_to_srw_client_error(4, 0);
2257 send_http_response(400);
2260 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
2262 Z_ReferenceId **refid = get_referenceIdP(apdu);
2263 nmem_reset(m_referenceId_mem);
2264 if (refid && *refid)
2266 m_referenceId = (Z_ReferenceId *)
2267 nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
2268 m_referenceId->len = m_referenceId->size = (*refid)->len;
2269 m_referenceId->buf = (unsigned char *)
2270 nmem_malloc(m_referenceId_mem, (*refid)->len);
2271 memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
2276 if (!m_client && m_invalid_session)
2278 m_apdu_invalid_session = apdu;
2279 m_mem_invalid_session = odr_extract_mem(odr_decode());
2280 apdu = m_initRequest_apdu;
2283 // Determine our client.
2284 Z_OtherInformation **oi;
2285 get_otherInfoAPDU(apdu, &oi);
2286 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
2291 send_http_response(404);
2300 m_client->m_server = this;
2302 if (apdu->which == Z_APDU_initRequest)
2304 if (apdu->u.initRequest->implementationId)
2305 yaz_log(YLOG_LOG, "%simplementationId: %s",
2306 m_session_str, apdu->u.initRequest->implementationId);
2307 if (apdu->u.initRequest->implementationName)
2308 yaz_log(YLOG_LOG, "%simplementationName: %s",
2309 m_session_str, apdu->u.initRequest->implementationName);
2310 if (apdu->u.initRequest->implementationVersion)
2311 yaz_log(YLOG_LOG, "%simplementationVersion: %s",
2312 m_session_str, apdu->u.initRequest->implementationVersion);
2313 if (m_initRequest_apdu == 0)
2315 if (m_initRequest_mem)
2316 nmem_destroy(m_initRequest_mem);
2317 m_initRequest_apdu = apdu;
2318 m_initRequest_mem = odr_extract_mem(odr_decode());
2320 m_initRequest_preferredMessageSize = *apdu->u.initRequest->
2321 preferredMessageSize;
2322 *apdu->u.initRequest->preferredMessageSize = 1024*1024;
2323 m_initRequest_maximumRecordSize = *apdu->u.initRequest->
2325 *apdu->u.initRequest->maximumRecordSize = 1024*1024;
2327 // save init options for the response..
2328 m_initRequest_options = apdu->u.initRequest->options;
2330 apdu->u.initRequest->options =
2331 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2332 sizeof(Odr_bitmask));
2333 ODR_MASK_ZERO(apdu->u.initRequest->options);
2335 for (i = 0; i<= 24; i++)
2336 ODR_MASK_SET(apdu->u.initRequest->options, i);
2337 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2338 Z_Options_negotiationModel);
2339 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2340 Z_Options_concurrentOperations);
2343 m_initRequest_version = apdu->u.initRequest->protocolVersion;
2344 apdu->u.initRequest->protocolVersion =
2345 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2346 sizeof(Odr_bitmask));
2347 ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
2349 for (i = 0; i<= 8; i++)
2350 ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
2352 if (m_client->m_init_flag)
2354 if (handle_init_response_for_invalid_session(apdu))
2356 if (m_client->m_initResponse)
2358 Z_APDU *apdu2 = m_client->m_initResponse;
2359 apdu2->u.initResponse->otherInfo = 0;
2360 if (m_client->m_cookie && *m_client->m_cookie)
2361 set_otherInformationString(apdu2, VAL_COOKIE, 1,
2362 m_client->m_cookie);
2363 apdu2->u.initResponse->referenceId =
2364 apdu->u.initRequest->referenceId;
2365 apdu2->u.initResponse->options = m_client->m_initResponse_options;
2366 apdu2->u.initResponse->protocolVersion =
2367 m_client->m_initResponse_version;
2369 send_to_client(apdu2);
2373 m_client->m_init_flag = 1;
2375 handle_max_record_retrieve(apdu);
2378 apdu = handle_syntax_validation(apdu);
2381 apdu = handle_query_transformation(apdu);
2384 apdu = handle_query_validation(apdu);
2387 apdu = result_set_optimize(apdu);
2390 m_client->timeout(m_target_idletime); // mark it active even
2391 // though we didn't use it
2395 // delete other info construct completely if 0 elements
2396 get_otherInfoAPDU(apdu, &oi);
2397 if (oi && *oi && (*oi)->num_elements == 0)
2400 if (apdu->which == Z_APDU_presentRequest &&
2401 m_client->m_resultSetStartPoint == 0)
2403 Z_PresentRequest *pr = apdu->u.presentRequest;
2404 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
2405 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
2407 m_client->m_resultSetStartPoint = 0;
2409 if (m_client->send_to_target(apdu) < 0)
2416 m_client->m_waiting = 1;
2419 void Yaz_Proxy::connectNotify()
2423 void Yaz_Proxy::releaseClient()
2425 xfree(m_proxyTarget);
2427 m_invalid_session = 0;
2428 // only keep if keep_alive flag is set...
2430 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
2431 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
2432 m_client->m_waiting == 0)
2434 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
2436 m_client->get_hostname());
2437 yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
2438 m_session_str, m_client->m_pdu_recv,
2439 m_client->m_bytes_sent + m_client->m_bytes_recv,
2440 m_keepalive_limit_bw, m_keepalive_limit_pdu);
2441 assert (m_client->m_waiting != 2);
2442 // Tell client (if any) that no server connection is there..
2443 m_client->m_server = 0;
2448 yaz_log (YLOG_LOG, "%sShutdown (client to proxy) close %s",
2450 m_client->get_hostname());
2451 assert (m_client->m_waiting != 2);
2457 yaz_log (YLOG_LOG, "%sshutdown (client to proxy) bad state",
2463 yaz_log (YLOG_LOG, "%sShutdown (client to proxy)",
2467 m_parent->pre_init();
2470 void Yaz_Proxy::shutdown()
2476 const char *Yaz_ProxyClient::get_session_str()
2480 return m_server->get_session_str();
2483 void Yaz_ProxyClient::shutdown()
2485 yaz_log (YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
2491 void Yaz_Proxy::failNotify()
2494 yaz_log (YLOG_LOG, "%sConnection closed by client",
2499 void Yaz_ProxyClient::failNotify()
2502 m_server->inc_request_no();
2503 yaz_log (YLOG_LOG, "%sConnection closed by target %s",
2504 get_session_str(), get_hostname());
2508 void Yaz_ProxyClient::connectNotify()
2510 const char *s = get_session_str();
2511 const char *h = get_hostname();
2512 yaz_log (YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
2514 timeout(m_target_idletime);
2519 IYaz_PDU_Observer *Yaz_ProxyClient::sessionNotify(IYaz_PDU_Observable
2520 *the_PDU_Observable, int fd)
2522 return new Yaz_ProxyClient(the_PDU_Observable, 0);
2525 Yaz_ProxyClient::~Yaz_ProxyClient()
2530 m_next->m_prev = m_prev;
2531 m_waiting = 2; // for debugging purposes only.
2532 odr_destroy(m_init_odr);
2533 delete m_last_query;
2534 xfree (m_last_resultSetId);
2538 void Yaz_ProxyClient::pre_init_client()
2540 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
2541 Z_InitRequest *req = apdu->u.initRequest;
2544 for (i = 0; i<= 24; i++)
2545 ODR_MASK_SET(req->options, i);
2546 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2547 Z_Options_negotiationModel);
2548 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2549 Z_Options_concurrentOperations);
2550 for (i = 0; i<= 10; i++)
2551 ODR_MASK_SET(req->protocolVersion, i);
2553 if (send_to_target(apdu) < 0)
2564 void Yaz_Proxy::pre_init()
2567 const char *name = 0;
2568 const char *zurl_in_use[MAX_ZURL_PLEX];
2569 int limit_bw, limit_pdu, limit_req;
2570 int target_idletime, client_idletime;
2572 int keepalive_limit_bw, keepalive_limit_pdu;
2574 const char *cql2rpn = 0;
2575 const char *authentication = 0;
2577 Yaz_ProxyConfig *cfg = check_reconfigure();
2581 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
2586 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
2587 &limit_bw, &limit_pdu, &limit_req,
2588 &target_idletime, &client_idletime,
2590 &keepalive_limit_bw,
2591 &keepalive_limit_pdu,
2594 &authentication) ; i++)
2599 for (j = 0; zurl_in_use[j]; j++)
2603 int spare_waiting = 0;
2606 for (c = m_clientPool; c; c = c->m_next)
2608 if (!strcmp(zurl_in_use[j], c->get_hostname()))
2610 if (c->m_cookie == 0)
2612 if (c->m_server == 0)
2624 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
2625 "sparew=%d preinit=%d",m_session_str,
2626 name, zurl_in_use[j], in_use, other,
2627 spare, spare_waiting, pre_init);
2628 if (spare + spare_waiting < pre_init)
2630 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
2631 c->m_next = m_clientPool;
2633 c->m_next->m_prev = &c->m_next;
2635 c->m_prev = &m_clientPool;
2637 if (m_log_mask & PROXY_LOG_APDU_SERVER)
2638 c->set_APDU_yazlog(1);
2640 c->set_APDU_yazlog(0);
2642 if (c->client(zurl_in_use[j]))
2650 c->m_target_idletime = target_idletime;
2651 c->m_seqno = m_seqno++;
2658 void Yaz_Proxy::timeoutNotify()
2664 timeout(m_client_idletime);
2665 Z_GDU *apdu = m_bw_hold_PDU;
2668 if (apdu->which == Z_GDU_Z3950)
2669 handle_incoming_Z_PDU(apdu->u.z3950);
2670 else if (apdu->which == Z_GDU_HTTP_Request)
2671 handle_incoming_HTTP(apdu->u.HTTP_Request);
2673 else if (m_stylesheet_nprl)
2674 convert_xsl_delay();
2679 yaz_log (YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
2690 void Yaz_Proxy::markInvalid()
2693 m_invalid_session = 1;
2696 void Yaz_ProxyClient::timeoutNotify()
2699 m_server->inc_request_no();
2701 yaz_log (YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
2705 if (m_server && m_init_flag)
2707 // target timed out in a session that was properly initialized
2708 // server object stay alive but we mark it as invalid so it
2709 // gets initialized again
2710 m_server->markInvalid();
2716 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable,
2717 Yaz_Proxy *parent) :
2718 Yaz_Z_Assoc (the_PDU_Observable)
2725 m_last_resultSetId = 0;
2726 m_last_resultCount = 0;
2730 m_init_odr = odr_createmem (ODR_DECODE);
2732 m_initResponse_options = 0;
2733 m_initResponse_version = 0;
2734 m_initResponse_preferredMessageSize = 0;
2735 m_initResponse_maximumRecordSize = 0;
2736 m_resultSetStartPoint = 0;
2737 m_bytes_sent = m_bytes_recv = 0;
2741 m_target_idletime = 600;
2745 const char *Yaz_Proxy::option(const char *name, const char *value)
2747 if (!strcmp (name, "optimize")) {
2750 m_optimize = xstrdup (value);
2757 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
2762 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
2764 if (apdu->which == Z_GDU_Z3950)
2765 recv_Z_PDU(apdu->u.z3950, len);
2766 else if (apdu->which == Z_GDU_HTTP_Response)
2767 recv_HTTP_response(apdu->u.HTTP_Response, len);
2772 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
2774 if (!m_invalid_session)
2776 m_invalid_session = 0;
2777 handle_incoming_Z_PDU(m_apdu_invalid_session);
2778 assert (m_mem_invalid_session);
2779 nmem_destroy(m_mem_invalid_session);
2780 m_mem_invalid_session = 0;
2784 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
2786 m_bytes_recv += len;
2790 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
2791 yaz_log (YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
2792 apdu_name(apdu), get_hostname(), len);
2793 if (apdu->which == Z_APDU_initResponse)
2795 if (!m_server) // if this is a pre init session , check for more
2797 NMEM nmem = odr_extract_mem (odr_decode());
2798 odr_reset (m_init_odr);
2799 nmem_transfer (m_init_odr->mem, nmem);
2800 m_initResponse = apdu;
2801 m_initResponse_options = apdu->u.initResponse->options;
2802 m_initResponse_version = apdu->u.initResponse->protocolVersion;
2803 m_initResponse_preferredMessageSize =
2804 *apdu->u.initResponse->preferredMessageSize;
2805 m_initResponse_maximumRecordSize =
2806 *apdu->u.initResponse->maximumRecordSize;
2808 Z_InitResponse *ir = apdu->u.initResponse;
2809 char *im0 = ir->implementationName;
2812 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
2819 strcat(im1, "(YAZ Proxy)");
2820 ir->implementationName = im1;
2822 nmem_destroy (nmem);
2824 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
2827 if (apdu->which == Z_APDU_searchResponse)
2829 Z_SearchResponse *sr = apdu->u.searchResponse;
2830 m_last_resultCount = *sr->resultCount;
2831 int status = *sr->searchStatus;
2832 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
2836 if (sr->records && sr->records->which == Z_Records_DBOSD)
2838 m_cache.add(odr_decode(),
2839 sr->records->u.databaseOrSurDiagnostics, 1,
2844 if (apdu->which == Z_APDU_presentResponse)
2846 Z_PresentResponse *pr = apdu->u.presentResponse;
2850 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2851 Z_SearchResponse *sr = new_apdu->u.searchResponse;
2852 sr->referenceId = pr->referenceId;
2853 *sr->resultCount = m_last_resultCount;
2854 sr->records = pr->records;
2855 sr->nextResultSetPosition = pr->nextResultSetPosition;
2856 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
2860 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
2862 m_cache.add(odr_decode(),
2863 pr->records->u.databaseOrSurDiagnostics,
2864 m_resultSetStartPoint, -1);
2865 m_resultSetStartPoint = 0;
2869 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
2872 m_server->send_to_client(apdu);
2874 if (apdu->which == Z_APDU_close)
2880 void Yaz_Proxy::low_socket_close()
2885 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
2886 if (m_lo_fd[i] >= 0)
2887 ::close(m_lo_fd[i]);
2891 void Yaz_Proxy::low_socket_open()
2896 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
2897 m_lo_fd[i] = open("/dev/null", O_RDONLY);
2901 int Yaz_Proxy::server(const char *addr)
2903 int r = Yaz_Z_Assoc::server(addr);
2906 yaz_log(YLOG_LOG, "%sStarted proxy "
2910 " on %s", m_session_str, addr);