1 /* $Id: yaz-proxy.cpp,v 1.51 2006-04-06 16:25:21 adam Exp $
2 Copyright (c) 1998-2006, Index Data.
4 This file is part of the yazproxy.
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
23 #define HAVE_SYS_STAT_H 1
24 #define HAVE_SYS_TYPES_H 1
34 #include <sys/types.h>
46 #include <yaz/marcdisp.h>
47 #include <yaz/yaz-iconv.h>
49 #include <yaz/diagbib1.h>
51 #include <yaz/pquery.h>
52 #include <yaz/otherinfo.h>
53 #include <yaz/charneg.h>
54 #include "msg-thread.h"
56 using namespace yazpp_1;
59 #define strncasecmp _strnicmp
62 #define USE_AUTH_MSG 1
65 class YAZ_EXPORT Auth_Msg : public IMsg_Thread {
68 IMsg_Thread *handle();
80 m_nmem = nmem_create();
88 IMsg_Thread *Auth_Msg::handle()
90 ODR decode = odr_createmem(ODR_DECODE);
93 odr_setbuf(decode, m_apdu_buf, m_apdu_len, 0);
94 int r = z_APDU(decode, &apdu, 0, 0);
97 yaz_log(YLOG_WARN, "decode failed in Auth_Msg::handle");
101 m_ret = m_proxy->handle_authentication(apdu);
107 void Auth_Msg::result()
109 if (m_proxy->dec_ref(false))
111 yaz_log(YLOG_LOG, "Auth_Msg::proxy deleted meanwhile");
115 odr_setbuf(m_proxy->odr_decode(), m_apdu_buf, m_apdu_len, 0);
117 int r = z_APDU(m_proxy->odr_decode(), &apdu, 0, 0);
119 yaz_log(YLOG_LOG, "Auth_Msg::result z_APDU failed");
120 m_proxy->result_authentication(apdu, m_ret);
127 void Yaz_Proxy::result_authentication(Z_APDU *apdu, int ret)
129 if (apdu == 0 || ret == 0)
131 Z_APDU *apdu_reject = zget_APDU(odr_encode(), Z_APDU_initResponse);
132 *apdu_reject->u.initResponse->result = 0;
133 send_to_client(apdu_reject);
138 if (apdu->which == Z_APDU_initRequest)
140 Yaz_ProxyConfig *cfg = check_reconfigure();
142 cfg->target_authentication(m_default_target, odr_encode(),
143 apdu->u.initRequest);
145 handle_incoming_Z_PDU_2(apdu);
149 static const char *apdu_name(Z_APDU *apdu)
153 case Z_APDU_initRequest:
154 return "initRequest";
155 case Z_APDU_initResponse:
156 return "initResponse";
157 case Z_APDU_searchRequest:
158 return "searchRequest";
159 case Z_APDU_searchResponse:
160 return "searchResponse";
161 case Z_APDU_presentRequest:
162 return "presentRequest";
163 case Z_APDU_presentResponse:
164 return "presentResponse";
165 case Z_APDU_deleteResultSetRequest:
166 return "deleteResultSetRequest";
167 case Z_APDU_deleteResultSetResponse:
168 return "deleteResultSetResponse";
169 case Z_APDU_scanRequest:
170 return "scanRequest";
171 case Z_APDU_scanResponse:
172 return "scanResponse";
173 case Z_APDU_sortRequest:
174 return "sortRequest";
175 case Z_APDU_sortResponse:
176 return "sortResponse";
177 case Z_APDU_extendedServicesRequest:
178 return "extendedServicesRequest";
179 case Z_APDU_extendedServicesResponse:
180 return "extendedServicesResponse";
187 static const char *gdu_name(Z_GDU *gdu)
192 return apdu_name(gdu->u.z3950);
193 case Z_GDU_HTTP_Request:
194 return "HTTP Request";
195 case Z_GDU_HTTP_Response:
196 return "HTTP Response";
198 return "Unknown request/response";
201 Yaz_Proxy::Yaz_Proxy(IPDU_Observable *the_PDU_Observable,
202 ISocketObservable *the_socket_observable,
205 Z_Assoc(the_PDU_Observable),
206 m_bw_stat(60), m_pdu_stat(60), m_search_stat(60)
208 m_PDU_Observable = the_PDU_Observable;
209 m_socket_observable = the_socket_observable;
214 m_keepalive_limit_bw = 500000;
215 m_keepalive_limit_pdu = 1000;
217 m_default_target = 0;
218 m_proxy_negotiation_charset = 0;
219 m_proxy_negotiation_lang = 0;
220 m_proxy_negotiation_default_charset = 0;
221 m_charset_converter = new Yaz_CharsetConverter;
225 m_client_idletime = 600;
226 m_target_idletime = 600;
227 m_optimize = xstrdup ("1");
228 strcpy(m_session_str, "0 ");
236 m_max_connect_period = 0;
238 m_limit_connect_period = 0;
239 m_timeout_mode = timeout_normal;
241 m_max_record_retrieve = 0;
245 m_flag_invalid_session = 0;
247 m_referenceId_mem = nmem_create();
249 m_marcxml_mode = none;
250 m_stylesheet_xsp = 0;
251 m_stylesheet_nprl = 0;
252 m_stylesheet_apdu = 0;
253 m_s2z_stylesheet = 0;
257 m_backend_charset = 0;
259 m_initRequest_apdu = 0;
260 m_initRequest_mem = 0;
261 m_initRequest_preferredMessageSize = 0;
262 m_initRequest_maximumRecordSize = 0;
263 m_initRequest_options = 0;
264 m_initRequest_version = 0;
265 m_initRequest_oi_negotiation_charsets = 0;
266 m_initRequest_oi_negotiation_num_charsets = 0;
267 m_initRequest_oi_negotiation_langs = 0;
268 m_initRequest_oi_negotiation_num_langs = 0;
269 m_initRequest_oi_negotiation_selected = 0;
270 m_apdu_invalid_session = 0;
271 m_mem_invalid_session = 0;
273 m_s2z_odr_search = 0;
275 m_s2z_search_apdu = 0;
276 m_s2z_present_apdu = 0;
277 m_http_keepalive = 0;
280 m_s2z_packing = Z_SRW_recordPacking_string;
281 #if HAVE_GETTIMEOFDAY
282 m_time_tv = xmalloc(sizeof(struct timeval));
283 struct timeval *tv = (struct timeval *) m_time_tv;
289 m_usemarcon_ini_stage1 = 0;
290 m_usemarcon_ini_stage2 = 0;
291 m_usemarcon = new Yaz_usemarcon();
296 m_main_ptr_dec = false;
298 m_initial_reduce = 0;
301 void Yaz_Proxy::inc_ref()
306 Yaz_Proxy::~Yaz_Proxy()
308 yaz_log(YLOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
309 m_bytes_sent, m_bytes_recv);
310 nmem_destroy(m_initRequest_mem);
311 nmem_destroy(m_mem_invalid_session);
312 nmem_destroy(m_referenceId_mem);
314 xfree(m_proxyTarget);
315 xfree(m_default_target);
316 xfree(m_proxy_negotiation_charset);
317 xfree(m_proxy_negotiation_lang);
318 xfree(m_proxy_negotiation_default_charset);
319 delete m_charset_converter;
323 if (m_stylesheet_xsp)
324 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
330 xfree (m_backend_type);
331 xfree (m_backend_charset);
332 xfree (m_usemarcon_ini_stage1);
333 xfree (m_usemarcon_ini_stage2);
336 odr_destroy(m_s2z_odr_init);
337 if (m_s2z_odr_search)
338 odr_destroy(m_s2z_odr_search);
346 void Yaz_Proxy::set_debug_mode(int mode)
351 int Yaz_Proxy::set_config(const char *config)
354 m_config = new Yaz_ProxyConfig();
355 xfree(m_config_fname);
356 m_config_fname = xstrdup(config);
357 int r = m_config->read_xml(config);
361 m_config->get_generic_info(&m_log_mask, &m_max_clients,
362 &m_max_connect, &m_limit_connect, &period);
363 m_connect.set_period(period);
368 void Yaz_Proxy::set_default_target(const char *target)
370 xfree (m_default_target);
371 m_default_target = 0;
373 m_default_target = (char *) xstrdup (target);
376 void Yaz_Proxy::set_proxy_negotiation (const char *charset, const char *lang,
377 const char *default_charset)
379 yaz_log(YLOG_LOG, "%sSet the proxy negotiation: charset to '%s', "
380 "default charset to '%s', language to '%s'", m_session_str,
381 charset?charset:"none",
382 default_charset?default_charset:"none",
384 xfree (m_proxy_negotiation_charset);
385 xfree (m_proxy_negotiation_lang);
386 m_proxy_negotiation_charset = m_proxy_negotiation_lang = 0;
388 m_proxy_negotiation_charset = (char *) xstrdup (charset);
390 m_proxy_negotiation_lang = (char *) xstrdup (lang);
392 m_proxy_negotiation_default_charset =
393 (char *) xstrdup (default_charset);
396 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
399 return m_parent->check_reconfigure();
401 Yaz_ProxyConfig *cfg = m_config;
404 yaz_log(YLOG_LOG, "reconfigure");
406 if (m_config_fname && cfg)
408 yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
409 int r = cfg->read_xml(m_config_fname);
411 yaz_log(YLOG_WARN, "reconfigure failed");
416 cfg->get_generic_info(&m_log_mask, &m_max_clients,
417 &m_max_connect, &m_limit_connect,
419 m_connect.set_period(period);
423 yaz_log(YLOG_LOG, "reconfigure");
429 IPDU_Observer *Yaz_Proxy::sessionNotify(IPDU_Observable
430 *the_PDU_Observable, int fd)
434 char session_str[200];
435 const char *peername = the_PDU_Observable->getpeername();
436 if (m_log_mask & PROXY_LOG_IP_CLIENT)
437 sprintf(session_str, "%ld:%d %s 0 ",
438 (long) time(0), m_session_no, peername);
440 sprintf(session_str, "%ld:%d 0 ",
441 (long) time(0), m_session_no);
444 yaz_log (YLOG_LOG, "%sNew session %s", session_str, peername);
446 m_connect.cleanup(false);
447 m_connect.add_connect(peername);
449 int connect_total = m_connect.get_total(peername);
450 int connect_max = m_max_connect;
451 if (connect_max && connect_total > connect_max)
453 yaz_log(YLOG_LOG, "%sconnect not accepted total=%d max=%d",
454 session_str, connect_total, connect_max);
457 yaz_log(YLOG_LOG, "%sconnect accepted total=%d", session_str,
460 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable,
461 m_socket_observable, this);
464 new_proxy->m_initial_reduce = connect_total / m_limit_connect;
466 new_proxy->m_config = 0;
467 new_proxy->m_config_fname = 0;
468 new_proxy->timeout(m_client_idletime);
469 new_proxy->m_target_idletime = m_target_idletime;
470 new_proxy->set_default_target(m_default_target);
471 new_proxy->m_max_clients = m_max_clients;
472 new_proxy->m_log_mask = m_log_mask;
473 new_proxy->set_APDU_log(get_APDU_log());
474 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
475 new_proxy->set_APDU_yazlog(1);
477 new_proxy->set_APDU_yazlog(0);
478 strcpy(new_proxy->m_session_str, session_str);
479 new_proxy->m_peername = xstrdup(peername);
480 new_proxy->set_proxy_negotiation(m_proxy_negotiation_charset,
481 m_proxy_negotiation_lang, m_proxy_negotiation_default_charset);
482 // create thread object the first time we get an incoming connection
484 m_my_thread = new Msg_Thread(m_socket_observable, 1);
485 new_proxy->m_my_thread = m_my_thread;
489 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
492 Z_OtherInformationUnit *oi;
494 ent.proto = PROTO_Z3950;
495 ent.oclass = CLASS_USERINFO;
496 ent.value = (oid_value) VAL_COOKIE;
497 assert (oid_ent_to_oid (&ent, oid));
499 if (oid_ent_to_oid (&ent, oid) &&
500 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
501 oi->which == Z_OtherInfo_characterInfo)
502 return oi->information.characterInfo;
505 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
508 Z_OtherInformationUnit *oi;
510 ent.proto = PROTO_Z3950;
511 ent.oclass = CLASS_USERINFO;
512 ent.value = (oid_value) VAL_PROXY;
513 if (oid_ent_to_oid (&ent, oid) &&
514 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
515 oi->which == Z_OtherInfo_characterInfo)
516 return oi->information.characterInfo;
519 const char *Yaz_Proxy::load_balance(const char **url)
521 int zurl_in_use[MAX_ZURL_PLEX];
522 int zurl_in_spare[MAX_ZURL_PLEX];
526 for (i = 0; i<MAX_ZURL_PLEX; i++)
529 zurl_in_spare[i] = 0;
531 for (c = m_parent->m_clientPool; c; c = c->m_next)
533 for (i = 0; url[i]; i++)
534 if (!strcmp(url[i], c->get_hostname()))
537 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
541 int min_use = 100000;
542 int spare_for_min = 0;
544 const char *ret_min = 0;
545 const char *ret_spare = 0;
546 for (i = 0; url[i]; i++)
548 yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
549 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
550 if (min_use > zurl_in_use[i])
553 min_use = zurl_in_use[i];
554 spare_for_min = zurl_in_spare[i];
556 if (max_spare < zurl_in_spare[i])
559 max_spare = zurl_in_spare[i];
565 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
566 const char *proxy_host)
569 Yaz_Proxy *parent = m_parent;
570 Yaz_ProxyClient *c = m_client;
574 const char *url[MAX_ZURL_PLEX];
575 Yaz_ProxyConfig *cfg = check_reconfigure();
578 if (parent && parent->m_debug_mode)
580 // only to be enabled for debugging...
581 if (!strcmp(proxy_host, "stop"))
584 xfree(m_default_target);
585 m_default_target = xstrdup(proxy_host);
587 proxy_host = m_default_target;
588 int client_idletime = -1;
589 const char *cql2rpn_fname = 0;
590 const char *negotiation_charset = 0;
591 const char *negotiation_lang = 0;
592 const char *query_charset = 0;
593 const char *default_client_query_charset = 0;
594 url[0] = m_default_target;
599 cfg->get_target_info(proxy_host, url, &m_bw_max,
600 &m_pdu_max, &m_max_record_retrieve,
602 &m_target_idletime, &client_idletime,
603 &parent->m_max_clients,
604 &m_keepalive_limit_bw,
605 &m_keepalive_limit_pdu,
608 &negotiation_charset,
611 &default_client_query_charset);
613 if (client_idletime != -1)
615 m_client_idletime = client_idletime;
616 timeout(m_client_idletime);
619 m_cql2rpn.set_pqf_file(cql2rpn_fname);
620 if (negotiation_charset || negotiation_lang || default_client_query_charset)
622 set_proxy_negotiation(negotiation_charset,
623 negotiation_lang, default_client_query_charset);
625 m_charset_converter->set_target_query_charset(query_charset);
628 yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
631 // we don't handle multiplexing for cookie session, so we just
632 // pick the first one in this case (anonymous users will be able
633 // to use any backend)
634 if (cookie && *cookie)
635 m_proxyTarget = (char*) xstrdup(url[0]);
637 m_proxyTarget = (char*) xstrdup(load_balance(url));
639 if (cookie && *cookie)
640 { // search in sessions with a cookie
641 for (c = parent->m_clientPool; c; c = c->m_next)
644 assert (*c->m_prev == c);
645 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
646 !strcmp(m_proxyTarget, c->get_hostname()))
649 // The following handles "cancel"
650 // If connection is busy (waiting for PDU) and
651 // we have an initRequest we can safely do re-open
652 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
654 yaz_log (YLOG_LOG, "%s REOPEN target=%s", m_session_str,
661 c->m_last_resultCount = 0;
662 c->m_sr_transform = 0;
664 c->m_resultSetStartPoint = 0;
665 c->m_target_idletime = m_target_idletime;
666 if (c->client(m_proxyTarget))
673 c->m_seqno = parent->m_seqno;
674 if (c->m_server && c->m_server != this)
675 c->m_server->m_client = 0;
678 yaz_log (YLOG_DEBUG, "get_client 1 %p %p", this, c);
683 else if (!c && apdu->which == Z_APDU_initRequest )
685 // anonymous sessions without cookie.
686 // if authentication is set it is NOT anonymous se we can't share them.
687 // If charset and lang negotiation is use it is NOT anonymous session too.
688 for (c = parent->m_clientPool; c; c = c->m_next)
691 assert(*c->m_prev == c);
692 if (c->m_server == 0 && c->m_cookie == 0 && c->m_waiting == 0
693 && c->compare_idAuthentication(apdu)
694 && c->compare_charset(apdu)
695 && !strcmp(m_proxyTarget, c->get_hostname()))
698 yaz_log (YLOG_LOG, "%sREUSE %d %s",
699 m_session_str, parent->m_seqno, c->get_hostname());
701 c->m_seqno = parent->m_seqno;
702 assert(c->m_server == 0);
705 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
706 c->set_APDU_yazlog(1);
708 c->set_APDU_yazlog(0);
720 if (apdu->which != Z_APDU_initRequest)
722 yaz_log (YLOG_LOG, "%sno init request as first PDU", m_session_str);
725 // go through list of clients - and find the lowest/oldest one.
726 Yaz_ProxyClient *c_min = 0;
728 int no_of_clients = 0;
729 if (parent->m_clientPool)
730 yaz_log (YLOG_DEBUG, "Existing sessions");
731 for (c = parent->m_clientPool; c; c = c->m_next)
733 yaz_log (YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
734 c->m_waiting, c->get_hostname(),
735 c->m_cookie ? c->m_cookie : "");
737 if (min_seq < 0 || c->m_seqno < min_seq)
739 min_seq = c->m_seqno;
743 if (no_of_clients >= parent->m_max_clients)
746 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
748 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
749 m_session_str, parent->m_max_clients, c->m_seqno);
750 if (c->m_server && c->m_server != this)
751 delete c->m_server; // PROBLEM: m_ref_count!
756 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
757 m_session_str, parent->m_max_clients,
758 c->m_seqno, parent->m_seqno, c->get_hostname());
762 c->m_cookie = xstrdup(cookie);
763 c->m_seqno = parent->m_seqno;
764 if (c->m_server && c->m_server != this)
766 c->m_server->m_client = 0;
767 delete c->m_server; // PROBLEM: m_ref_count!
770 c->m_target_idletime = m_target_idletime;
771 c->timeout(m_target_idletime);
773 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
774 c->set_APDU_yazlog(1);
776 c->set_APDU_yazlog(0);
783 yaz_log (YLOG_LOG, "%sNEW %d %s",
784 m_session_str, parent->m_seqno, m_proxyTarget);
785 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
786 c->m_next = parent->m_clientPool;
788 c->m_next->m_prev = &c->m_next;
789 parent->m_clientPool = c;
790 c->m_prev = &parent->m_clientPool;
796 c->m_cookie = xstrdup(cookie);
798 c->m_seqno = parent->m_seqno;
800 c->m_last_resultCount = 0;
803 c->m_sr_transform = 0;
805 c->m_resultSetStartPoint = 0;
807 if (c->client(m_proxyTarget))
812 c->m_target_idletime = m_target_idletime;
815 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
816 c->set_APDU_yazlog(1);
818 c->set_APDU_yazlog(0);
820 c->set_idAuthentication(apdu);
822 yaz_log (YLOG_DEBUG, "get_client 3 %p %p", this, c);
826 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
829 for (i = 0; i<num; i++)
832 Z_DefaultDiagFormat *r;
833 Z_DiagRec *p = pp[i];
834 if (p->which != Z_DiagRec_defaultFormat)
836 yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
840 r = p->u.defaultFormat;
841 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
842 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
843 yaz_log(YLOG_LOG, "%sError unknown diagnostic set", m_session_str);
846 case Z_DefaultDiagFormat_v2Addinfo:
847 yaz_log(YLOG_LOG, "%sError %d %s:%s",
849 *r->condition, diagbib1_str(*r->condition),
852 case Z_DefaultDiagFormat_v3Addinfo:
853 yaz_log(YLOG_LOG, "%sError %d %s:%s",
855 *r->condition, diagbib1_str(*r->condition),
862 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
864 if (!m_stylesheet_xsp || p->num_records <= 0)
866 return 0; /* no XSLT to be done ... */
869 m_stylesheet_offset = 0;
870 m_stylesheet_nprl = p;
871 m_stylesheet_apdu = apdu;
872 m_timeout_mode = timeout_xsl;
878 void Yaz_Proxy::convert_xsl_delay()
881 Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
882 if (npr->which == Z_NamePlusRecord_databaseRecord)
884 Z_External *r = npr->u.databaseRecord;
885 if (r->which == Z_External_octet)
888 fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
890 xmlDocPtr res, doc = xmlParseMemory(
891 (char*) r->u.octet_aligned->buf,
892 r->u.octet_aligned->len);
895 yaz_log(YLOG_LOG, "%sXSLT convert %d",
896 m_session_str, m_stylesheet_offset);
897 res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
904 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
906 m_stylesheet_nprl->records[m_stylesheet_offset]->
908 z_ext_record(odr_encode(), VAL_TEXT_XML,
909 (char*) out_buf, out_len);
918 m_stylesheet_offset++;
919 if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
921 m_timeout_mode = timeout_normal;
922 m_stylesheet_nprl = 0;
924 if (m_stylesheet_xsp)
925 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
927 m_stylesheet_xsp = 0;
928 timeout(m_client_idletime);
929 send_PDU_convert(m_stylesheet_apdu);
935 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
937 if (m_frontend_type != VAL_NONE)
940 for (i = 0; i < p->num_records; i++)
942 Z_NamePlusRecord *npr = p->records[i];
943 if (npr->which == Z_NamePlusRecord_databaseRecord)
945 Z_External *r = npr->u.databaseRecord;
946 if (r->which == Z_External_octet)
949 if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
951 if (!m_usemarcon->m_stage1)
953 m_usemarcon->m_stage1 = new CDetails();
955 m_usemarcon->m_stage1->SetIniFileName(m_usemarcon_ini_stage1);
956 m_usemarcon->m_stage1->SetMarcRecord((char*) r->u.octet_aligned->buf, r->u.octet_aligned->len);
957 int res = m_usemarcon->m_stage1->Start();
962 m_usemarcon->m_stage1->GetMarcRecord(converted, convlen);
963 if (m_usemarcon_ini_stage2 && *m_usemarcon_ini_stage2)
965 if (!m_usemarcon->m_stage2)
967 m_usemarcon->m_stage2 = new CDetails();
969 m_usemarcon->m_stage2->SetIniFileName(m_usemarcon_ini_stage2);
970 m_usemarcon->m_stage2->SetMarcRecord(converted, convlen);
971 res = m_usemarcon->m_stage2->Start();
975 m_usemarcon->m_stage2->GetMarcRecord(converted, convlen);
979 yaz_log(YLOG_LOG, "%sUSEMARCON stage 2 error %d", m_session_str, res);
982 npr->u.databaseRecord =
983 z_ext_record(odr_encode(),
991 yaz_log(YLOG_LOG, "%sUSEMARCON stage 1 error %d", m_session_str, res);
997 npr->u.databaseRecord =
998 z_ext_record(odr_encode(),
1000 (char*) r->u.octet_aligned->buf,
1001 r->u.octet_aligned->len);
1008 void Yaz_Proxy::convert_records_charset(Z_NamePlusRecordList *p,
1009 const char *backend_charset)
1011 int sel = m_charset_converter->get_client_charset_selected();
1012 const char *client_record_charset =
1013 m_charset_converter->get_client_query_charset();
1014 if (sel && backend_charset && client_record_charset &&
1015 strcmp(backend_charset, client_record_charset))
1018 yaz_iconv_t cd = yaz_iconv_open(client_record_charset,
1020 yaz_marc_t mt = yaz_marc_create();
1021 yaz_marc_xml(mt, YAZ_MARC_ISO2709);
1022 yaz_marc_iconv(mt, cd);
1023 for (i = 0; i < p->num_records; i++)
1025 Z_NamePlusRecord *npr = p->records[i];
1026 if (npr->which == Z_NamePlusRecord_databaseRecord)
1028 Z_External *r = npr->u.databaseRecord;
1029 oident *ent = oid_getentbyoid(r->direct_reference);
1030 if (!ent || ent->value == VAL_NONE)
1033 if (ent->value == VAL_SUTRS)
1035 WRBUF w = wrbuf_alloc();
1037 wrbuf_iconv_write(w, cd, (char*) r->u.octet_aligned->buf,
1038 r->u.octet_aligned->len);
1039 npr->u.databaseRecord =
1040 z_ext_record(odr_encode(), ent->value, wrbuf_buf(w),
1044 else if (ent->value == VAL_TEXT_XML)
1048 else if (r->which == Z_External_octet)
1052 if (yaz_marc_decode_buf(mt,
1053 (char*) r->u.octet_aligned->buf,
1054 r->u.octet_aligned->len,
1057 npr->u.databaseRecord =
1058 z_ext_record(odr_encode(), ent->value, result, rlen);
1059 yaz_log(YLOG_LOG, "%sRecoding MARC record",
1066 yaz_iconv_close(cd);
1067 yaz_marc_destroy(mt);
1071 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
1072 const char *backend_charset)
1075 if (!backend_charset)
1076 backend_charset = "MARC-8";
1077 yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
1078 yaz_marc_t mt = yaz_marc_create();
1079 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1080 yaz_marc_iconv(mt, cd);
1081 for (i = 0; i < p->num_records; i++)
1083 Z_NamePlusRecord *npr = p->records[i];
1084 if (npr->which == Z_NamePlusRecord_databaseRecord)
1086 Z_External *r = npr->u.databaseRecord;
1087 if (r->which == Z_External_OPAC)
1089 WRBUF w = wrbuf_alloc();
1091 yaz_opac_decode_wrbuf(mt, r->u.opac, w);
1092 npr->u.databaseRecord = z_ext_record(
1093 odr_encode(), VAL_TEXT_XML,
1094 wrbuf_buf(w), wrbuf_len(w)
1098 else if (r->which == Z_External_octet)
1102 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
1103 r->u.octet_aligned->len,
1106 npr->u.databaseRecord =
1107 z_ext_record(odr_encode(), VAL_TEXT_XML, result, rlen);
1113 yaz_iconv_close(cd);
1114 yaz_marc_destroy(mt);
1117 void Yaz_Proxy::logtime()
1119 #if HAVE_GETTIMEOFDAY
1120 struct timeval *tv = (struct timeval*) m_time_tv;
1124 gettimeofday(&tv1, 0);
1125 long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
1126 (tv1.tv_usec - tv->tv_usec);
1128 yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
1129 diff/1000000, (diff/1000)%1000);
1136 int Yaz_Proxy::send_http_response(int code)
1138 ODR o = odr_encode();
1139 Z_GDU *gdu = z_get_HTTP_Response(o, code);
1140 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1142 hres->version = odr_strdup(o, m_http_version);
1143 if (m_http_keepalive)
1144 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1148 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1150 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1154 int r = send_GDU(gdu, &len);
1155 m_bytes_sent += len;
1156 m_bw_stat.add_bytes(len);
1159 recv_GDU_more(true);
1164 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu, int http_code /* = 200 */)
1166 ODR o = odr_encode();
1167 const char *ctype = "text/xml";
1168 Z_GDU *gdu = z_get_HTTP_Response(o, http_code);
1169 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1171 hres->version = odr_strdup(o, m_http_version);
1172 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1173 if (m_http_keepalive)
1174 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1177 if (http_code == 401)
1178 z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate", "Basic realm=\"YAZ Proxy\"");
1180 static Z_SOAP_Handler soap_handlers[2] = {
1182 {"http://www.loc.gov/zing/srw/", 0,
1183 (Z_SOAP_fun) yaz_srw_codec},
1188 Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
1189 soap_package->which = Z_SOAP_generic;
1190 soap_package->u.generic =
1191 (Z_SOAP_Generic *) odr_malloc(o, sizeof(*soap_package->u.generic));
1192 soap_package->u.generic->no = 0;
1193 soap_package->u.generic->ns = soap_handlers[0].ns;
1194 soap_package->u.generic->p = (void *) srw_pdu;
1195 soap_package->ns = m_soap_ns;
1196 z_soap_codec_enc_xsl(o, &soap_package,
1197 &hres->content_buf, &hres->content_len,
1198 soap_handlers, 0, m_s2z_stylesheet);
1199 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1201 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1205 int r = send_GDU(gdu, &len);
1206 m_bytes_sent += len;
1207 m_bw_stat.add_bytes(len);
1210 recv_GDU_more(true);
1215 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
1217 ODR o = odr_encode();
1218 Z_SRW_diagnostic *diagnostic = (Z_SRW_diagnostic *)
1219 odr_malloc(o, sizeof(*diagnostic));
1220 int num_diagnostic = 1;
1221 yaz_mk_std_diagnostic(o, diagnostic, srw_error, add);
1222 return send_srw_search_response(diagnostic, num_diagnostic, srw_error == 3 ? 401 : 200);
1225 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
1226 Z_DefaultDiagFormat *ddf)
1228 int bib1_code = *ddf->condition;
1229 if (bib1_code == 109)
1231 srw_res->num_diagnostics = 1;
1232 srw_res->diagnostics = (Z_SRW_diagnostic *)
1233 odr_malloc(o, sizeof(*srw_res->diagnostics));
1234 yaz_mk_std_diagnostic(o, srw_res->diagnostics,
1235 yaz_diag_bib1_to_srw(*ddf->condition),
1240 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
1242 ODR o = odr_encode();
1243 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1244 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1246 srw_res->numberOfRecords = odr_intdup (o, hits);
1247 if (records && records->which == Z_Records_DBOSD)
1249 srw_res->num_records =
1250 records->u.databaseOrSurDiagnostics->num_records;
1252 srw_res->records = (Z_SRW_record *)
1253 odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
1254 for (i = 0; i < srw_res->num_records; i++)
1256 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
1257 if (npr->which != Z_NamePlusRecord_databaseRecord)
1259 srw_res->records[i].recordSchema = "diagnostic";
1260 srw_res->records[i].recordPacking = m_s2z_packing;
1261 srw_res->records[i].recordData_buf = "67";
1262 srw_res->records[i].recordData_len = 2;
1263 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1266 Z_External *r = npr->u.databaseRecord;
1267 oident *ent = oid_getentbyoid(r->direct_reference);
1268 if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
1270 srw_res->records[i].recordSchema = m_schema;
1271 srw_res->records[i].recordPacking = m_s2z_packing;
1272 srw_res->records[i].recordData_buf = (char*)
1273 r->u.octet_aligned->buf;
1274 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1275 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1279 srw_res->records[i].recordSchema = "diagnostic";
1280 srw_res->records[i].recordPacking = m_s2z_packing;
1281 srw_res->records[i].recordData_buf = "67";
1282 srw_res->records[i].recordData_len = 2;
1283 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1287 if (records && records->which == Z_Records_NSD)
1290 http_code = z_to_srw_diag(odr_encode(), srw_res,
1291 records->u.nonSurrogateDiagnostic);
1293 return send_http_response(http_code);
1295 return send_srw_response(srw_pdu);
1299 int Yaz_Proxy::send_srw_search_response(Z_SRW_diagnostic *diagnostics,
1300 int num_diagnostics, int http_code /* = 200 */)
1302 ODR o = odr_encode();
1303 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1304 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1306 srw_res->num_diagnostics = num_diagnostics;
1307 srw_res->diagnostics = diagnostics;
1308 return send_srw_response(srw_pdu, http_code);
1311 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1312 int num_diagnostics)
1314 Yaz_ProxyConfig *cfg = check_reconfigure();
1318 char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1319 m_s2z_database, &len);
1322 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1323 Z_SRW_explainResponse *er = res->u.explain_response;
1325 er->record.recordData_buf = b;
1326 er->record.recordData_len = len;
1327 er->record.recordPacking = m_s2z_packing;
1328 er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
1330 er->diagnostics = diagnostics;
1331 er->num_diagnostics = num_diagnostics;
1332 return send_srw_response(res);
1335 return send_http_response(404);
1338 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1342 if (apdu->which == Z_APDU_initResponse)
1344 Z_InitResponse *res = apdu->u.initResponse;
1345 if (*res->result == 0)
1347 send_to_srw_client_error(3, 0);
1349 else if (!m_s2z_search_apdu)
1351 send_srw_explain_response(0, 0);
1355 handle_incoming_Z_PDU(m_s2z_search_apdu);
1358 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1360 m_s2z_search_apdu = 0;
1361 Z_SearchResponse *res = apdu->u.searchResponse;
1362 m_s2z_hit_count = *res->resultCount;
1363 if (res->records && res->records->which == Z_Records_NSD)
1365 send_to_srw_client_ok(0, res->records, 1);
1367 else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1370 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1372 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1374 if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1376 *pr->numberOfRecordsRequested =
1377 1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1379 handle_incoming_Z_PDU(m_s2z_present_apdu);
1383 m_s2z_present_apdu = 0;
1384 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1387 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1390 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1392 m_s2z_present_apdu = 0;
1393 Z_PresentResponse *res = apdu->u.presentResponse;
1394 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1400 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1401 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1403 int r = send_Z_PDU(apdu, &len);
1404 m_bytes_sent += len;
1405 m_bw_stat.add_bytes(len);
1412 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1414 int kill_session = 0;
1415 Z_ReferenceId **new_id = get_referenceIdP(apdu);
1418 *new_id = m_referenceId;
1420 if (apdu->which == Z_APDU_searchResponse)
1422 Z_SearchResponse *sr = apdu->u.searchResponse;
1423 Z_Records *p = sr->records;
1424 if (p && p->which == Z_Records_NSD)
1426 Z_DiagRec dr, *dr_p = &dr;
1427 dr.which = Z_DiagRec_defaultFormat;
1428 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1430 *sr->searchStatus = 0;
1431 display_diagrecs(&dr_p, 1);
1435 if (p && p->which == Z_Records_DBOSD)
1439 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1442 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1443 if (m_marcxml_mode == marcxml)
1444 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1447 convert_records_charset(p->u.databaseOrSurDiagnostics,
1449 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1453 if (sr->resultCount)
1455 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1457 if (*sr->resultCount < 0)
1459 m_flag_invalid_session = 1;
1462 *sr->searchStatus = 0;
1464 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1465 *sr->resultCount = 0;
1470 else if (apdu->which == Z_APDU_presentResponse)
1472 Z_PresentResponse *sr = apdu->u.presentResponse;
1473 Z_Records *p = sr->records;
1474 if (p && p->which == Z_Records_NSD)
1476 Z_DiagRec dr, *dr_p = &dr;
1477 dr.which = Z_DiagRec_defaultFormat;
1478 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1479 if (*sr->presentStatus == Z_PresentStatus_success)
1480 *sr->presentStatus = Z_PresentStatus_failure;
1481 display_diagrecs(&dr_p, 1);
1483 if (p && p->which == Z_Records_DBOSD)
1487 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1490 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1491 if (m_marcxml_mode == marcxml)
1492 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1495 convert_records_charset(p->u.databaseOrSurDiagnostics,
1497 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1501 else if (apdu->which == Z_APDU_initResponse)
1503 //Get and check negotiation record
1504 //from init response.
1505 handle_charset_lang_negotiation(apdu);
1507 if (m_initRequest_options)
1510 (Odr_bitmask *)odr_malloc(odr_encode(),
1511 sizeof(Odr_bitmask));
1512 ODR_MASK_ZERO(nopt);
1515 for (i = 0; i<24; i++)
1516 if (ODR_MASK_GET(m_initRequest_options, i) &&
1517 ODR_MASK_GET(apdu->u.initResponse->options, i))
1518 ODR_MASK_SET(nopt, i);
1519 apdu->u.initResponse->options = nopt;
1521 if (m_initRequest_version)
1523 Z_ProtocolVersion *nopt =
1524 (Odr_bitmask *)odr_malloc(odr_encode(),
1525 sizeof(Odr_bitmask));
1526 ODR_MASK_ZERO(nopt);
1529 for (i = 0; i<8; i++)
1530 if (ODR_MASK_GET(m_initRequest_version, i) &&
1531 ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1532 ODR_MASK_SET(nopt, i);
1533 apdu->u.initResponse->protocolVersion = nopt;
1535 apdu->u.initResponse->preferredMessageSize =
1536 odr_intdup(odr_encode(),
1537 m_client->m_initResponse_preferredMessageSize >
1538 m_initRequest_preferredMessageSize ?
1539 m_initRequest_preferredMessageSize :
1540 m_client->m_initResponse_preferredMessageSize);
1541 apdu->u.initResponse->maximumRecordSize =
1542 odr_intdup(odr_encode(),
1543 m_client->m_initResponse_maximumRecordSize >
1544 m_initRequest_maximumRecordSize ?
1545 m_initRequest_maximumRecordSize :
1546 m_client->m_initResponse_maximumRecordSize);
1549 int r = send_PDU_convert(apdu);
1556 m_parent->pre_init();
1561 void Yaz_ProxyClient::set_idAuthentication(Z_APDU *apdu)
1563 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1565 odr_reset(m_idAuthentication_odr);
1566 z_IdAuthentication(m_idAuthentication_odr, &t, 1, 0);
1567 m_idAuthentication_ber_buf =
1568 odr_getbuf(m_idAuthentication_odr,
1569 &m_idAuthentication_ber_size, 0);
1572 bool Yaz_ProxyClient::compare_charset(Z_APDU *apdu)
1577 bool Yaz_ProxyClient::compare_idAuthentication(Z_APDU *apdu)
1579 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1580 ODR odr = odr_createmem(ODR_ENCODE);
1582 z_IdAuthentication(odr, &t, 1, 0);
1584 char *buf = odr_getbuf(odr, &sz, 0);
1585 if (buf && m_idAuthentication_ber_buf
1586 && sz == m_idAuthentication_ber_size
1587 && !memcmp(m_idAuthentication_ber_buf, buf, sz))
1593 if (!buf && !m_idAuthentication_ber_buf)
1598 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1601 const char *apdu_name_tmp = apdu_name(apdu);
1602 int r = send_Z_PDU(apdu, &len);
1603 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1604 yaz_log (YLOG_LOG, "%sSending %s to %s %d bytes",
1606 apdu_name_tmp, get_hostname(), len);
1607 m_bytes_sent += len;
1611 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1613 if (apdu->which == Z_APDU_presentRequest)
1615 Z_PresentRequest *pr = apdu->u.presentRequest;
1616 int toget = *pr->numberOfRecordsRequested;
1617 int start = *pr->resultSetStartPoint;
1619 yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1620 pr->resultSetId, start, toget);
1622 if (*m_parent->m_optimize == '0')
1625 if (!m_client->m_last_resultSetId)
1627 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1628 new_apdu->u.presentResponse->records =
1629 create_nonSurrogateDiagnostics(odr_encode(), 30,
1631 send_to_client(new_apdu);
1634 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1636 if (start+toget-1 > m_client->m_last_resultCount)
1638 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1639 new_apdu->u.presentResponse->records =
1640 create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
1641 send_to_client(new_apdu);
1644 Z_NamePlusRecordList *npr;
1646 yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1647 m_session_str, start, toget, yaz_z3950oid_to_str(
1648 pr->preferredRecordSyntax, &oclass));
1650 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1651 pr->preferredRecordSyntax,
1652 pr->recordComposition))
1654 yaz_log (YLOG_LOG, "%sReturned cached records for present request",
1656 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1657 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1659 new_apdu->u.presentResponse->numberOfRecordsReturned
1660 = odr_intdup(odr_encode(), toget);
1662 new_apdu->u.presentResponse->records = (Z_Records*)
1663 odr_malloc(odr_encode(), sizeof(Z_Records));
1664 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1665 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1666 new_apdu->u.presentResponse->nextResultSetPosition =
1667 odr_intdup(odr_encode(), start+toget);
1669 send_to_client(new_apdu);
1675 if (apdu->which != Z_APDU_searchRequest)
1677 Z_SearchRequest *sr = apdu->u.searchRequest;
1678 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1679 Yaz_Z_Databases this_databases;
1681 this_databases.set(sr->num_databaseNames, (const char **)
1684 this_query->set_Z_Query(sr->query);
1686 char query_str[120];
1687 this_query->print(query_str, sizeof(query_str)-1);
1688 yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1690 if (*m_parent->m_optimize != '0' &&
1691 m_client->m_last_ok && m_client->m_last_query &&
1692 m_client->m_last_query->match(this_query) &&
1693 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1694 m_client->m_last_databases.match(this_databases))
1697 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1698 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1700 Z_NamePlusRecordList *npr;
1701 int toget = *sr->mediumSetPresentNumber;
1702 Z_RecordComposition *comp = 0;
1704 if (toget > m_client->m_last_resultCount)
1705 toget = m_client->m_last_resultCount;
1707 if (sr->mediumSetElementSetNames)
1709 comp = (Z_RecordComposition *)
1710 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1711 comp->which = Z_RecordComp_simple;
1712 comp->u.simple = sr->mediumSetElementSetNames;
1715 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1716 sr->preferredRecordSyntax, comp))
1718 yaz_log (YLOG_LOG, "%sReturned cached records for medium set",
1720 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1721 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1722 new_apdu->u.searchResponse->resultCount =
1723 &m_client->m_last_resultCount;
1725 new_apdu->u.searchResponse->numberOfRecordsReturned
1726 = odr_intdup(odr_encode(), toget);
1728 new_apdu->u.searchResponse->presentStatus =
1729 odr_intdup(odr_encode(), Z_PresentStatus_success);
1730 new_apdu->u.searchResponse->records = (Z_Records*)
1731 odr_malloc(odr_encode(), sizeof(Z_Records));
1732 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1733 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1734 new_apdu->u.searchResponse->nextResultSetPosition =
1735 odr_intdup(odr_encode(), toget+1);
1736 send_to_client(new_apdu);
1742 // send present request (medium size)
1743 yaz_log (YLOG_LOG, "%sOptimizing search for medium set",
1746 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1747 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1748 pr->referenceId = sr->referenceId;
1749 pr->resultSetId = sr->resultSetName;
1750 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1751 *pr->numberOfRecordsRequested = toget;
1752 pr->recordComposition = comp;
1753 m_client->m_sr_transform = 1;
1757 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1758 m_client->m_last_resultCount <= 0)
1760 // large set. Return pseudo-search response immediately
1761 yaz_log (YLOG_LOG, "%sOptimizing search for large set",
1763 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1764 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1765 new_apdu->u.searchResponse->resultCount =
1766 &m_client->m_last_resultCount;
1767 send_to_client(new_apdu);
1772 Z_NamePlusRecordList *npr;
1773 int toget = m_client->m_last_resultCount;
1774 Z_RecordComposition *comp = 0;
1776 // send a present request (small set)
1778 if (sr->smallSetElementSetNames)
1780 comp = (Z_RecordComposition *)
1781 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1782 comp->which = Z_RecordComp_simple;
1783 comp->u.simple = sr->smallSetElementSetNames;
1786 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1787 sr->preferredRecordSyntax, comp))
1789 yaz_log (YLOG_LOG, "%sReturned cached records for small set",
1791 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1792 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1793 new_apdu->u.searchResponse->resultCount =
1794 &m_client->m_last_resultCount;
1796 new_apdu->u.searchResponse->numberOfRecordsReturned
1797 = odr_intdup(odr_encode(), toget);
1799 new_apdu->u.searchResponse->presentStatus =
1800 odr_intdup(odr_encode(), Z_PresentStatus_success);
1801 new_apdu->u.searchResponse->records = (Z_Records*)
1802 odr_malloc(odr_encode(), sizeof(Z_Records));
1803 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1804 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1805 new_apdu->u.searchResponse->nextResultSetPosition =
1806 odr_intdup(odr_encode(), toget+1);
1807 send_to_client(new_apdu);
1812 yaz_log (YLOG_LOG, "%sOptimizing search for small set",
1814 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1815 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1816 pr->referenceId = sr->referenceId;
1817 pr->resultSetId = sr->resultSetName;
1818 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1819 *pr->numberOfRecordsRequested = toget;
1820 pr->recordComposition = comp;
1821 m_client->m_sr_transform = 1;
1826 else // query doesn't match
1828 delete m_client->m_last_query;
1829 m_client->m_last_query = this_query;
1830 m_client->m_last_ok = 0;
1831 m_client->m_cache.clear();
1832 m_client->m_resultSetStartPoint = 0;
1834 xfree (m_client->m_last_resultSetId);
1835 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1837 m_client->m_last_databases.set(sr->num_databaseNames,
1838 (const char **) sr->databaseNames);
1844 void Yaz_Proxy::inc_request_no()
1846 char *cp = m_session_str + strlen(m_session_str)-1;
1849 while (*cp && *cp != ' ')
1852 sprintf(cp+1, "%d ", m_request_no);
1855 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1859 m_bytes_recv += len;
1861 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1862 yaz_log (YLOG_LOG, "%sReceiving %s from client %d bytes",
1863 m_session_str, gdu_name(apdu), len);
1865 #if HAVE_GETTIMEOFDAY
1866 gettimeofday((struct timeval *) m_time_tv, 0);
1868 m_bw_stat.add_bytes(len);
1869 m_pdu_stat.add_bytes(1);
1871 GDU *gdu = new GDU(apdu);
1872 m_in_queue.enqueue(gdu);
1874 recv_GDU_more(false);
1877 void Yaz_Proxy::recv_GDU_reduce(GDU *gdu)
1879 int reduce = m_initial_reduce; // initial reduce from connect phase..
1880 m_initial_reduce = 0; // reset it..
1882 int bw_total = m_bw_stat.get_total();
1883 int pdu_total = m_pdu_stat.get_total();
1884 int search_total = m_search_stat.get_total();
1886 assert(m_timeout_mode == timeout_busy);
1887 assert(m_timeout_gdu == 0);
1890 reduce += search_total / m_search_max;
1892 reduce += (bw_total/m_bw_max);
1895 if (pdu_total > m_pdu_max)
1897 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1898 reduce = (reduce > nreduce) ? reduce : nreduce;
1904 /* uncomment to force a big reduce */
1905 m_timeout_mode = timeout_reduce;
1906 m_timeout_gdu = gdu;
1907 timeout(3); // call us reduce seconds later
1912 yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d search=%d limit-bw=%d limit-pdu=%d limit-search=%d",
1913 m_session_str, reduce, bw_total, pdu_total, search_total,
1914 m_bw_max, m_pdu_max, m_search_max);
1916 m_timeout_mode = timeout_reduce;
1917 m_timeout_gdu = gdu;
1918 timeout(reduce); // call us reduce seconds later
1921 recv_GDU_normal(gdu);
1924 void Yaz_Proxy::recv_GDU_more(bool normal)
1927 if (normal && m_timeout_mode == timeout_busy)
1928 m_timeout_mode = timeout_normal;
1929 while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
1931 m_timeout_mode = timeout_busy;
1936 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
1939 gdu->move_away_gdu(odr_decode(), &apdu);
1942 if (apdu->which == Z_GDU_Z3950)
1943 handle_incoming_Z_PDU(apdu->u.z3950);
1944 else if (apdu->which == Z_GDU_HTTP_Request)
1945 handle_incoming_HTTP(apdu->u.HTTP_Request);
1948 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
1950 if (m_max_record_retrieve)
1952 if (apdu->which == Z_APDU_presentRequest)
1954 Z_PresentRequest *pr = apdu->u.presentRequest;
1955 if (pr->numberOfRecordsRequested &&
1956 *pr->numberOfRecordsRequested > m_max_record_retrieve)
1957 *pr->numberOfRecordsRequested = m_max_record_retrieve;
1962 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
1964 if (apdu->which == Z_APDU_initRequest)
1966 if (m_initRequest_options &&
1967 !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
1968 (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
1970 // There is no negotiation proposal from
1971 // client's side. OK. The proxy negotiation
1973 Z_InitRequest *initRequest = apdu->u.initRequest;
1974 Z_OtherInformation **otherInfo;
1975 Z_OtherInformationUnit *oi;
1976 get_otherInfoAPDU(apdu, &otherInfo);
1977 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
1980 ODR_MASK_SET(initRequest->options,
1981 Z_Options_negotiationModel);
1982 oi->which = Z_OtherInfo_externallyDefinedInfo;
1983 oi->information.externallyDefinedInfo =
1984 yaz_set_proposal_charneg(odr_encode(),
1985 (const char**)&m_proxy_negotiation_charset,
1986 m_proxy_negotiation_charset ? 1:0,
1987 (const char**)&m_proxy_negotiation_lang,
1988 m_proxy_negotiation_lang ? 1:0,
1992 else if (m_initRequest_options &&
1993 ODR_MASK_GET(m_initRequest_options,
1994 Z_Options_negotiationModel) &&
1995 m_charset_converter->get_target_query_charset())
1997 yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
1999 m_charset_converter->get_target_query_charset());
2000 Z_InitRequest *initRequest = apdu->u.initRequest;
2001 Z_CharSetandLanguageNegotiation *negotiation =
2002 yaz_get_charneg_record (initRequest->otherInfo);
2004 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2006 NMEM nmem = nmem_create();
2007 char **charsets = 0;
2008 int num_charsets = 0;
2012 yaz_get_proposal_charneg (nmem, negotiation,
2013 &charsets, &num_charsets,
2014 &langs, &num_langs, &selected);
2016 for (i = 0; i<num_charsets; i++)
2017 yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
2019 for (i = 0; i<num_langs; i++)
2020 yaz_log(YLOG_LOG, "%slang %s", m_session_str,
2023 const char *t_charset =
2024 m_charset_converter->get_target_query_charset();
2025 // sweep through charsets and pick the first supported
2027 for (i = 0; i<num_charsets; i++)
2029 const char *c_charset = charsets[i];
2030 if (!odr_set_charset(odr_decode(), t_charset, c_charset))
2033 if (i != num_charsets)
2035 // got one .. set up ODR for reverse direction
2036 const char *c_charset = charsets[i];
2037 odr_set_charset(odr_encode(), c_charset, t_charset);
2038 m_charset_converter->set_client_query_charset(c_charset);
2039 m_charset_converter->set_client_charset_selected(selected);
2042 ODR_MASK_CLEAR(m_initRequest_options,
2043 Z_Options_negotiationModel);
2044 yaz_del_charneg_record(&initRequest->otherInfo);
2048 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
2052 else if (m_charset_converter->get_target_query_charset() &&
2053 m_proxy_negotiation_default_charset)
2055 m_charset_converter->
2056 set_client_query_charset(m_proxy_negotiation_default_charset);
2059 else if (apdu->which == Z_APDU_initResponse)
2061 Z_InitResponse *initResponse = apdu->u.initResponse;
2062 Z_OtherInformation **otherInfo;
2063 get_otherInfoAPDU(apdu, &otherInfo);
2065 Z_CharSetandLanguageNegotiation *charneg = 0;
2067 if (otherInfo && *otherInfo &&
2068 ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel)
2069 && (charneg = yaz_get_charneg_record(*otherInfo)))
2075 yaz_get_response_charneg(m_referenceId_mem, charneg,
2076 &charset, &lang, &selected);
2078 yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
2079 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
2081 if (m_initRequest_options &&
2082 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
2084 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2087 else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2089 // negotiation-charset, negotiation-lang
2090 // elements of config file in use.
2092 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2095 // clear negotiation option.
2096 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2098 // Delete negotiation (charneg-3) entry.
2099 yaz_del_charneg_record(otherInfo);
2104 if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2106 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2109 else if (m_charset_converter->get_client_query_charset())
2111 Z_OtherInformation **otherInfo;
2112 Z_OtherInformationUnit *oi;
2113 get_otherInfoAPDU(apdu, &otherInfo);
2114 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2117 ODR_MASK_SET(initResponse->options,
2118 Z_Options_negotiationModel);
2119 if (m_initRequest_options)
2120 ODR_MASK_SET(m_initRequest_options,
2121 Z_Options_negotiationModel);
2123 oi->which = Z_OtherInfo_externallyDefinedInfo;
2124 oi->information.externallyDefinedInfo =
2125 yaz_set_response_charneg(
2127 m_charset_converter->get_client_query_charset(),
2129 m_charset_converter->get_client_charset_selected());
2136 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2138 const char *addinfo)
2140 Z_Records *rec = (Z_Records *)
2141 odr_malloc (odr, sizeof(*rec));
2143 odr_malloc (odr, sizeof(*err));
2144 Z_DiagRec *drec = (Z_DiagRec *)
2145 odr_malloc (odr, sizeof(*drec));
2146 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2147 odr_malloc (odr, sizeof(*dr));
2149 rec->which = Z_Records_NSD;
2150 rec->u.nonSurrogateDiagnostic = dr;
2151 dr->diagnosticSetId =
2152 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
2153 dr->condition = err;
2154 dr->which = Z_DefaultDiagFormat_v2Addinfo;
2155 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2159 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2161 if (apdu->which == Z_APDU_searchRequest &&
2162 apdu->u.searchRequest->query &&
2163 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2164 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2166 Z_RPNQuery *rpnquery = 0;
2167 Z_SearchRequest *sr = apdu->u.searchRequest;
2170 yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2171 sr->query->u.type_104->u.cql);
2173 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2174 &rpnquery, odr_encode(),
2177 yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2180 yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2181 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2183 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2184 new_apdu->u.searchResponse->records =
2185 create_nonSurrogateDiagnostics(odr_encode(),
2186 yaz_diag_srw_to_bib1(r),
2188 *new_apdu->u.searchResponse->searchStatus = 0;
2190 send_to_client(new_apdu);
2196 sr->query->which = Z_Query_type_1;
2197 sr->query->u.type_1 = rpnquery;
2204 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2206 if (apdu->which == Z_APDU_searchRequest &&
2207 apdu->u.searchRequest->query)
2209 if (apdu->u.searchRequest->query->which == Z_Query_type_1
2210 || apdu->u.searchRequest->query->which == Z_Query_type_101)
2213 m_charset_converter->set_client_query_charset("UTF-8");
2214 Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2215 m_charset_converter->convert_type_1(rpnquery, odr_encode());
2222 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2224 if (apdu->which == Z_APDU_searchRequest)
2226 Z_SearchRequest *sr = apdu->u.searchRequest;
2230 Yaz_ProxyConfig *cfg = check_reconfigure();
2232 err = cfg->check_query(odr_encode(), m_default_target,
2233 sr->query, &addinfo);
2236 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2238 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2239 new_apdu->u.searchResponse->records =
2240 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2241 *new_apdu->u.searchResponse->searchStatus = 0;
2243 send_to_client(new_apdu);
2251 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2253 if (apdu->which != Z_APDU_initRequest)
2254 return 1; // pass if no init request
2255 Z_InitRequest *req = apdu->u.initRequest;
2257 Yaz_ProxyConfig *cfg = check_reconfigure();
2259 return 1; // pass if no config
2262 if (req->idAuthentication == 0)
2264 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2267 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2269 ret = cfg->client_authentication(
2271 req->idAuthentication->u.idPass->userId,
2272 req->idAuthentication->u.idPass->groupId,
2273 req->idAuthentication->u.idPass->password,
2276 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2278 char user[64], pass[64];
2281 sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2282 ret = cfg->client_authentication(m_default_target, user, 0, pass,
2286 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2291 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2293 m_marcxml_mode = none;
2294 if (apdu->which == Z_APDU_searchRequest)
2296 Z_SearchRequest *sr = apdu->u.searchRequest;
2299 Yaz_ProxyConfig *cfg = check_reconfigure();
2301 Z_RecordComposition rc_temp, *rc = 0;
2302 if (sr->smallSetElementSetNames)
2304 rc_temp.which = Z_RecordComp_simple;
2305 rc_temp.u.simple = sr->smallSetElementSetNames;
2309 if (sr->preferredRecordSyntax)
2312 ent = oid_getentbyoid(sr->preferredRecordSyntax);
2313 m_frontend_type = ent->value;
2316 m_frontend_type = VAL_NONE;
2318 char *stylesheet_name = 0;
2320 err = cfg->check_syntax(odr_encode(),
2322 sr->preferredRecordSyntax, rc,
2323 &addinfo, &stylesheet_name, &m_schema,
2324 &m_backend_type, &m_backend_charset,
2325 &m_usemarcon_ini_stage1,
2326 &m_usemarcon_ini_stage2);
2327 if (stylesheet_name)
2329 m_parent->low_socket_close();
2332 if (m_stylesheet_xsp)
2333 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2334 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2337 m_stylesheet_offset = 0;
2338 xfree(stylesheet_name);
2340 m_parent->low_socket_open();
2344 sr->smallSetElementSetNames = 0;
2345 sr->mediumSetElementSetNames = 0;
2346 m_marcxml_mode = marcxml;
2350 sr->preferredRecordSyntax =
2351 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2355 sr->preferredRecordSyntax =
2356 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2361 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2363 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2364 new_apdu->u.searchResponse->records =
2365 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2366 *new_apdu->u.searchResponse->searchStatus = 0;
2368 send_to_client(new_apdu);
2372 else if (m_backend_type)
2374 sr->preferredRecordSyntax =
2375 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2378 else if (apdu->which == Z_APDU_presentRequest)
2380 Z_PresentRequest *pr = apdu->u.presentRequest;
2383 Yaz_ProxyConfig *cfg = check_reconfigure();
2385 if (pr->preferredRecordSyntax)
2388 ent = oid_getentbyoid(pr->preferredRecordSyntax);
2389 m_frontend_type = ent->value;
2392 m_frontend_type = VAL_NONE;
2394 char *stylesheet_name = 0;
2396 err = cfg->check_syntax(odr_encode(), m_default_target,
2397 pr->preferredRecordSyntax,
2398 pr->recordComposition,
2399 &addinfo, &stylesheet_name, &m_schema,
2400 &m_backend_type, &m_backend_charset,
2401 &m_usemarcon_ini_stage1,
2402 &m_usemarcon_ini_stage2
2404 if (stylesheet_name)
2406 m_parent->low_socket_close();
2409 if (m_stylesheet_xsp)
2410 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2411 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2414 m_stylesheet_offset = 0;
2415 xfree(stylesheet_name);
2417 m_parent->low_socket_open();
2421 pr->recordComposition = 0;
2422 m_marcxml_mode = marcxml;
2426 pr->preferredRecordSyntax =
2427 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2431 pr->preferredRecordSyntax =
2432 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2437 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2439 new_apdu->u.presentResponse->referenceId = pr->referenceId;
2440 new_apdu->u.presentResponse->records =
2441 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2442 *new_apdu->u.presentResponse->presentStatus =
2443 Z_PresentStatus_failure;
2445 send_to_client(new_apdu);
2449 else if (m_backend_type)
2451 pr->preferredRecordSyntax =
2452 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2458 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2462 Z_ElementSetNames *esn = (Z_ElementSetNames *)
2463 odr_malloc(o, sizeof(Z_ElementSetNames));
2464 esn->which = Z_ElementSetNames_generic;
2465 esn->u.generic = odr_strdup(o, schema);
2469 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2472 Yaz_ProxyConfig *cfg = check_reconfigure();
2474 t = cfg->get_explain_name(db, backend_db);
2476 if (m_client && m_default_target && t && strcmp(m_default_target, t))
2483 xfree(m_default_target);
2484 m_default_target = xstrdup(t);
2488 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2491 if (strcmp(hreq->method, "GET"))
2493 if (hreq->path[0] != '/')
2495 const char *cp = hreq->path;
2498 if (*cp == '/' && strchr("/.", cp[1]))
2500 yaz_log(YLOG_LOG, "%sRejecting path %s", m_session_str,
2507 Yaz_ProxyConfig *cfg = check_reconfigure();
2509 if (!cfg->get_file_access_info(hreq->path+1))
2512 const char *fname = hreq->path+1;
2513 if (stat(fname, &sbuf))
2515 yaz_log(YLOG_LOG|YLOG_ERRNO, "%sstat failed for %s", m_session_str,
2519 if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2521 yaz_log(YLOG_LOG, "%sNot a regular file %s", m_session_str, fname);
2524 if (sbuf.st_size > (off_t) 1000000)
2526 yaz_log(YLOG_WARN, "%sFile %s too large for transfer", m_session_str,
2531 ODR o = odr_encode();
2533 const char *ctype = cfg->check_mime_type(fname);
2534 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2535 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2537 hres->version = odr_strdup(o, m_http_version);
2538 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2539 if (m_http_keepalive)
2540 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2544 hres->content_len = sbuf.st_size;
2545 hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2546 FILE *f = fopen(fname, "rb");
2549 fread(hres->content_buf, 1, hres->content_len, f);
2556 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2558 yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
2562 send_GDU(gdu, &len);
2563 recv_GDU_more(true);
2567 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2571 odr_destroy(m_s2z_odr_init);
2574 if (m_s2z_odr_search)
2576 odr_destroy(m_s2z_odr_search);
2577 m_s2z_odr_search = 0;
2580 m_http_keepalive = 0;
2582 if (!strcmp(hreq->version, "1.0"))
2584 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2585 if (v && !strcmp(v, "Keep-Alive"))
2586 m_http_keepalive = 1;
2588 m_http_keepalive = 0;
2589 m_http_version = "1.0";
2593 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2594 if (v && !strcmp(v, "close"))
2595 m_http_keepalive = 0;
2597 m_http_keepalive = 1;
2598 m_http_version = "1.1";
2601 const char *a = z_HTTP_header_lookup(hreq->headers, "Authorization");
2602 char authorization_str[255];
2603 *authorization_str = '\0';
2604 if (a && strncasecmp(a, "Basic ", 6) == 0)
2605 base64_decode(a + 6, authorization_str, 254);
2607 Z_SRW_PDU *srw_pdu = 0;
2608 Z_SOAP *soap_package = 0;
2610 Z_SRW_diagnostic *diagnostic = 0;
2611 int num_diagnostic = 0;
2613 if (file_access(hreq))
2617 else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2619 || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2620 &charset, &diagnostic, &num_diagnostic) == 0)
2622 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2623 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2624 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2625 m_s2z_init_apdu = 0;
2626 m_s2z_search_apdu = 0;
2627 m_s2z_present_apdu = 0;
2629 m_s2z_stylesheet = 0;
2631 Z_IdAuthentication *auth = NULL;
2632 if (*authorization_str)
2634 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2635 auth->which = Z_IdAuthentication_idPass;
2636 auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2637 auth->u.idPass->groupId = NULL;
2638 char *p = strchr(authorization_str, ':');
2643 auth->u.idPass->password = odr_strdup(m_s2z_odr_init, p);
2645 auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, authorization_str);
2648 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2651 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2653 const char *backend_db = srw_req->database;
2654 srw_get_client(srw_req->database, &backend_db);
2656 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2657 // recordXPath unsupported.
2658 if (srw_req->recordXPath)
2660 yaz_add_srw_diagnostic(odr_decode(),
2661 &diagnostic, &num_diagnostic,
2665 if (srw_req->sort_type != Z_SRW_sort_type_none)
2667 yaz_add_srw_diagnostic(odr_decode(),
2668 &diagnostic, &num_diagnostic,
2672 if (srw_req->stylesheet)
2674 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2676 // set packing for response records ..
2677 if (srw_req->recordPacking &&
2678 !strcmp(srw_req->recordPacking, "xml"))
2679 m_s2z_packing = Z_SRW_recordPacking_XML;
2681 m_s2z_packing = Z_SRW_recordPacking_string;
2685 Z_SRW_PDU *srw_pdu =
2686 yaz_srw_get(odr_encode(),
2687 Z_SRW_searchRetrieve_response);
2688 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2690 srw_res->diagnostics = diagnostic;
2691 srw_res->num_diagnostics = num_diagnostic;
2692 send_srw_response(srw_pdu);
2696 // prepare search PDU
2697 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2698 Z_APDU_searchRequest);
2699 Z_SearchRequest *z_searchRequest =
2700 m_s2z_search_apdu->u.searchRequest;
2702 z_searchRequest->num_databaseNames = 1;
2703 z_searchRequest->databaseNames = (char**)
2704 odr_malloc(m_s2z_odr_search, sizeof(char *));
2705 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2708 // query transformation
2709 Z_Query *query = (Z_Query *)
2710 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2711 z_searchRequest->query = query;
2713 if (srw_req->query_type == Z_SRW_query_type_cql)
2715 Z_External *ext = (Z_External *)
2716 odr_malloc(m_s2z_odr_search, sizeof(*ext));
2717 ext->direct_reference =
2718 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2719 ext->indirect_reference = 0;
2720 ext->descriptor = 0;
2721 ext->which = Z_External_CQL;
2722 ext->u.cql = srw_req->query.cql;
2724 query->which = Z_Query_type_104;
2725 query->u.type_104 = ext;
2727 else if (srw_req->query_type == Z_SRW_query_type_pqf)
2729 Z_RPNQuery *RPNquery;
2730 YAZ_PQF_Parser pqf_parser;
2732 pqf_parser = yaz_pqf_create ();
2734 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2735 srw_req->query.pqf);
2738 const char *pqf_msg;
2740 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2742 yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
2743 yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2745 send_to_srw_client_error(10, 0);
2748 query->which = Z_Query_type_1;
2749 query->u.type_1 = RPNquery;
2751 yaz_pqf_destroy (pqf_parser);
2755 send_to_srw_client_error(7, "query");
2760 m_s2z_present_apdu = 0;
2762 if (srw_req->maximumRecords)
2763 max = *srw_req->maximumRecords;
2765 if (srw_req->startRecord)
2766 start = *srw_req->startRecord;
2769 // Some backend, such as Voyager doesn't honor piggyback
2770 // So we use present always (0 &&).
2771 if (0 && start <= 1) // Z39.50 piggyback
2773 *z_searchRequest->smallSetUpperBound = max;
2774 *z_searchRequest->mediumSetPresentNumber = max;
2775 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2777 z_searchRequest->preferredRecordSyntax =
2778 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2780 if (srw_req->recordSchema)
2782 z_searchRequest->smallSetElementSetNames =
2783 z_searchRequest->mediumSetElementSetNames =
2784 mk_esn_from_schema(m_s2z_odr_search,
2785 srw_req->recordSchema);
2788 else // Z39.50 present
2790 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2791 Z_APDU_presentRequest);
2792 Z_PresentRequest *z_presentRequest =
2793 m_s2z_present_apdu->u.presentRequest;
2794 *z_presentRequest->resultSetStartPoint = start;
2795 *z_presentRequest->numberOfRecordsRequested = max;
2796 z_presentRequest->preferredRecordSyntax =
2797 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2799 if (srw_req->recordSchema)
2801 z_presentRequest->recordComposition =
2802 (Z_RecordComposition *)
2803 odr_malloc(m_s2z_odr_search,
2804 sizeof(Z_RecordComposition));
2805 z_presentRequest->recordComposition->which =
2806 Z_RecordComp_simple;
2807 z_presentRequest->recordComposition->u.simple =
2808 mk_esn_from_schema(m_s2z_odr_search,
2809 srw_req->recordSchema);
2815 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2816 Z_APDU_initRequest);
2818 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2820 // prevent m_initRequest_apdu memory from being grabbed
2821 // in Yaz_Proxy::handle_incoming_Z_PDU
2822 m_initRequest_apdu = m_s2z_init_apdu;
2823 handle_incoming_Z_PDU(m_s2z_init_apdu);
2828 handle_incoming_Z_PDU(m_s2z_search_apdu);
2832 else if (srw_pdu->which == Z_SRW_explain_request)
2834 Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
2836 const char *backend_db = srw_req->database;
2837 srw_get_client(srw_req->database, &backend_db);
2839 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2842 if (srw_req->stylesheet)
2844 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2846 if (srw_req->recordPacking &&
2847 !strcmp(srw_req->recordPacking, "xml"))
2848 m_s2z_packing = Z_SRW_recordPacking_XML;
2850 m_s2z_packing = Z_SRW_recordPacking_string;
2854 send_srw_explain_response(diagnostic, num_diagnostic);
2860 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2861 Z_APDU_initRequest);
2863 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2865 // prevent m_initRequest_apdu memory from being grabbed
2866 // in Yaz_Proxy::handle_incoming_Z_PDU
2867 m_initRequest_apdu = m_s2z_init_apdu;
2868 handle_incoming_Z_PDU(m_s2z_init_apdu);
2871 send_srw_explain_response(0, 0);
2874 else if (srw_pdu->which == Z_SRW_scan_request)
2876 m_s2z_database = odr_strdup(m_s2z_odr_init,
2877 srw_pdu->u.scan_request->database);
2879 yaz_add_srw_diagnostic(odr_decode(),
2880 &diagnostic, &num_diagnostic,
2882 Z_SRW_PDU *srw_pdu =
2883 yaz_srw_get(odr_encode(),
2884 Z_SRW_scan_response);
2885 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
2887 srw_res->diagnostics = diagnostic;
2888 srw_res->num_diagnostics = num_diagnostic;
2889 send_srw_response(srw_pdu);
2896 send_to_srw_client_error(4, 0);
2899 send_http_response(400);
2902 void Yaz_Proxy::handle_init(Z_APDU *apdu)
2905 Z_OtherInformation **oi;
2906 get_otherInfoAPDU(apdu, &oi);
2908 if (apdu->u.initRequest->implementationId)
2909 yaz_log(YLOG_LOG, "%simplementationId: %s",
2910 m_session_str, apdu->u.initRequest->implementationId);
2911 if (apdu->u.initRequest->implementationName)
2912 yaz_log(YLOG_LOG, "%simplementationName: %s",
2913 m_session_str, apdu->u.initRequest->implementationName);
2914 if (apdu->u.initRequest->implementationVersion)
2915 yaz_log(YLOG_LOG, "%simplementationVersion: %s",
2916 m_session_str, apdu->u.initRequest->implementationVersion);
2917 if (m_initRequest_apdu == 0)
2919 if (m_initRequest_mem)
2920 nmem_destroy(m_initRequest_mem);
2922 m_initRequest_apdu = apdu;
2923 m_initRequest_mem = odr_extract_mem(odr_decode());
2925 m_initRequest_preferredMessageSize = *apdu->u.initRequest->
2926 preferredMessageSize;
2927 *apdu->u.initRequest->preferredMessageSize = 1024*1024;
2928 m_initRequest_maximumRecordSize = *apdu->u.initRequest->
2930 *apdu->u.initRequest->maximumRecordSize = 1024*1024;
2932 Z_CharSetandLanguageNegotiation *charSetandLangRecord =
2933 yaz_get_charneg_record(*oi);
2935 // Save proposal charsets and langs.
2936 if (ODR_MASK_GET(apdu->u.initRequest->options,
2937 Z_Options_negotiationModel)
2938 && charSetandLangRecord)
2941 yaz_get_proposal_charneg(m_referenceId_mem,
2942 charSetandLangRecord,
2943 &m_initRequest_oi_negotiation_charsets,
2944 &m_initRequest_oi_negotiation_num_charsets,
2945 &m_initRequest_oi_negotiation_langs,
2946 &m_initRequest_oi_negotiation_num_langs,
2947 &m_initRequest_oi_negotiation_selected);
2949 for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
2951 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
2952 m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
2953 m_initRequest_oi_negotiation_charsets[i]:"none");
2955 for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
2957 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
2958 m_session_str, (m_initRequest_oi_negotiation_langs[i])?
2959 m_initRequest_oi_negotiation_langs[i]:"none");
2961 yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
2962 m_session_str, m_initRequest_oi_negotiation_selected);
2964 // save init options for the response..
2965 m_initRequest_options = apdu->u.initRequest->options;
2967 apdu->u.initRequest->options =
2968 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2969 sizeof(Odr_bitmask));
2970 ODR_MASK_ZERO(apdu->u.initRequest->options);
2972 for (i = 0; i<= 24; i++)
2973 ODR_MASK_SET(apdu->u.initRequest->options, i);
2974 // check negotiation option
2975 if (!ODR_MASK_GET(m_initRequest_options,
2976 Z_Options_negotiationModel))
2978 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2979 Z_Options_negotiationModel);
2981 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2982 Z_Options_concurrentOperations);
2984 m_initRequest_version = apdu->u.initRequest->protocolVersion;
2985 apdu->u.initRequest->protocolVersion =
2986 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2987 sizeof(Odr_bitmask));
2988 ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
2990 for (i = 0; i<= 8; i++)
2991 ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
2993 handle_charset_lang_negotiation(apdu);
2994 if (m_client->m_init_flag)
2996 if (handle_init_response_for_invalid_session(apdu))
2998 if (m_client->m_initResponse)
3000 Z_APDU *apdu2 = m_client->m_initResponse;
3001 apdu2->u.initResponse->otherInfo = 0;
3002 if (m_client->m_cookie && *m_client->m_cookie)
3003 set_otherInformationString(apdu2, VAL_COOKIE, 1,
3004 m_client->m_cookie);
3005 apdu2->u.initResponse->referenceId =
3006 apdu->u.initRequest->referenceId;
3007 apdu2->u.initResponse->options = m_client->m_initResponse_options;
3008 apdu2->u.initResponse->protocolVersion =
3009 m_client->m_initResponse_version;
3011 handle_charset_lang_negotiation(apdu2);
3013 send_to_client(apdu2);
3014 m_timeout_mode = timeout_normal;
3018 m_client->m_init_flag = 1;
3021 Auth_Msg *m = new Auth_Msg;
3023 z_APDU(odr_encode(), &apdu, 0, "encode");
3024 char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
3025 m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
3026 memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
3027 odr_reset(odr_encode());
3030 m_my_thread->put(m);
3032 int ret = handle_authentication(apdu);
3033 result_authentication(apdu, ret);
3037 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
3039 Z_ReferenceId **refid = get_referenceIdP(apdu);
3040 nmem_reset(m_referenceId_mem);
3041 if (refid && *refid)
3043 m_referenceId = (Z_ReferenceId *)
3044 nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
3045 m_referenceId->len = m_referenceId->size = (*refid)->len;
3046 m_referenceId->buf = (unsigned char *)
3047 nmem_malloc(m_referenceId_mem, (*refid)->len);
3048 memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
3053 if (!m_client && m_flag_invalid_session)
3055 // Got request for a session that is invalid..
3056 m_apdu_invalid_session = apdu; // save package
3057 m_mem_invalid_session = odr_extract_mem(odr_decode());
3058 apdu = m_initRequest_apdu; // but throw an init to the target
3061 if (apdu->which == Z_APDU_searchRequest)
3062 m_search_stat.add_bytes(1);
3064 // Determine our client.
3065 Z_OtherInformation **oi;
3066 get_otherInfoAPDU(apdu, &oi);
3067 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
3071 { // HTTP. Send not found
3072 send_http_response(404);
3077 // Z39.50 just shutdown
3083 m_client->m_server = this;
3085 if (apdu->which == Z_APDU_initRequest)
3088 handle_incoming_Z_PDU_2(apdu);
3091 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
3093 handle_max_record_retrieve(apdu);
3096 apdu = handle_syntax_validation(apdu);
3099 apdu = handle_query_transformation(apdu);
3102 apdu = handle_target_charset_conversion(apdu);
3105 apdu = handle_query_validation(apdu);
3108 apdu = result_set_optimize(apdu);
3112 m_client->timeout(m_target_idletime); // mark it active even
3113 recv_GDU_more(true);
3114 // though we didn't use it
3118 // delete other info construct completely if 0 elements
3119 Z_OtherInformation **oi;
3120 get_otherInfoAPDU(apdu, &oi);
3121 if (oi && *oi && (*oi)->num_elements == 0)
3124 if (apdu->which == Z_APDU_presentRequest &&
3125 m_client->m_resultSetStartPoint == 0)
3127 Z_PresentRequest *pr = apdu->u.presentRequest;
3128 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3129 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3131 m_client->m_resultSetStartPoint = 0;
3133 if (m_client->send_to_target(apdu) < 0)
3135 m_client->shutdown();
3138 m_client->m_waiting = 1;
3141 void Yaz_Proxy::connectNotify()
3145 void Yaz_Proxy::releaseClient()
3147 xfree(m_proxyTarget);
3149 m_flag_invalid_session = 0;
3150 // only keep if keep_alive flag is set...
3152 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3153 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3154 m_client->m_waiting == 0)
3156 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3158 m_client->get_hostname());
3159 yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3160 m_session_str, m_client->m_pdu_recv,
3161 m_client->m_bytes_sent + m_client->m_bytes_recv,
3162 m_keepalive_limit_bw, m_keepalive_limit_pdu);
3163 assert (m_client->m_waiting != 2);
3164 // Tell client (if any) that no server connection is there..
3165 m_client->m_server = 0;
3170 yaz_log (YLOG_LOG, "%sShutdown (client to proxy) close %s",
3172 m_client->get_hostname());
3173 assert (m_client->m_waiting != 2);
3179 yaz_log (YLOG_LOG, "%sshutdown (client to proxy) bad state",
3185 yaz_log (YLOG_LOG, "%sShutdown (client to proxy)",
3189 m_parent->pre_init();
3192 bool Yaz_Proxy::dec_ref(bool main_ptr)
3194 assert(m_ref_count > 0);
3199 m_main_ptr_dec = true;
3202 m_http_keepalive = 0;
3205 if (m_ref_count > 0)
3214 const char *Yaz_ProxyClient::get_session_str()
3218 return m_server->get_session_str();
3221 void Yaz_ProxyClient::shutdown()
3223 yaz_log (YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
3228 m_waiting = 1; // ensure it's released from Proxy in releaseClient
3229 m_server->dec_ref(true);
3235 void Yaz_Proxy::failNotify()
3238 yaz_log (YLOG_LOG, "%sConnection closed by client",
3243 void Yaz_Proxy::send_response_fail_client(const char *addr)
3247 Z_SRW_diagnostic *diagnostic = 0;
3248 int num_diagnostic = 0;
3250 yaz_add_srw_diagnostic(odr_encode(),
3251 &diagnostic, &num_diagnostic,
3252 YAZ_SRW_SYSTEM_TEMPORARILY_UNAVAILABLE, addr);
3253 if (m_s2z_search_apdu)
3254 send_srw_search_response(diagnostic, num_diagnostic);
3256 send_srw_explain_response(diagnostic, num_diagnostic);
3259 void Yaz_ProxyClient::failNotify()
3262 m_server->inc_request_no();
3263 yaz_log (YLOG_LOG, "%sConnection closed by target %s",
3264 get_session_str(), get_hostname());
3267 m_server->send_response_fail_client(get_hostname());
3271 void Yaz_ProxyClient::connectNotify()
3273 const char *s = get_session_str();
3274 const char *h = get_hostname();
3275 yaz_log (YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
3277 timeout(m_target_idletime);
3282 IPDU_Observer *Yaz_ProxyClient::sessionNotify(IPDU_Observable
3283 *the_PDU_Observable, int fd)
3285 return new Yaz_ProxyClient(the_PDU_Observable, 0);
3288 Yaz_ProxyClient::~Yaz_ProxyClient()
3293 m_next->m_prev = m_prev;
3294 m_waiting = 2; // for debugging purposes only.
3295 odr_destroy(m_init_odr);
3296 odr_destroy(m_idAuthentication_odr);
3297 delete m_last_query;
3298 xfree (m_last_resultSetId);
3302 void Yaz_ProxyClient::pre_init_client()
3304 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
3305 Z_InitRequest *req = apdu->u.initRequest;
3308 for (i = 0; i<= 24; i++)
3309 ODR_MASK_SET(req->options, i);
3310 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3311 Z_Options_negotiationModel);
3312 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3313 Z_Options_concurrentOperations);
3314 for (i = 0; i<= 10; i++)
3315 ODR_MASK_SET(req->protocolVersion, i);
3317 if (send_to_target(apdu) < 0)
3328 void Yaz_Proxy::pre_init()
3331 const char *name = 0;
3332 const char *zurl_in_use[MAX_ZURL_PLEX];
3333 int limit_bw, limit_pdu, limit_req, limit_search;
3334 int target_idletime, client_idletime;
3336 int keepalive_limit_bw, keepalive_limit_pdu;
3338 const char *cql2rpn = 0;
3339 const char *authentication = 0;
3340 const char *negotiation_charset = 0;
3341 const char *negotiation_lang = 0;
3343 Yaz_ProxyConfig *cfg = check_reconfigure();
3347 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
3352 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
3353 &limit_bw, &limit_pdu, &limit_req,
3355 &target_idletime, &client_idletime,
3357 &keepalive_limit_bw,
3358 &keepalive_limit_pdu,
3362 &negotiation_charset,
3370 for (j = 0; zurl_in_use[j]; j++)
3374 int spare_waiting = 0;
3377 for (c = m_clientPool; c; c = c->m_next)
3379 if (!strcmp(zurl_in_use[j], c->get_hostname()))
3381 if (c->m_cookie == 0)
3383 if (c->m_server == 0)
3395 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
3396 "sparew=%d preinit=%d",m_session_str,
3397 name, zurl_in_use[j], in_use, other,
3398 spare, spare_waiting, pre_init);
3399 if (spare + spare_waiting < pre_init)
3401 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
3402 c->m_next = m_clientPool;
3404 c->m_next->m_prev = &c->m_next;
3406 c->m_prev = &m_clientPool;
3408 if (m_log_mask & PROXY_LOG_APDU_SERVER)
3409 c->set_APDU_yazlog(1);
3411 c->set_APDU_yazlog(0);
3413 if (c->client(zurl_in_use[j]))
3421 c->m_target_idletime = target_idletime;
3422 c->m_seqno = m_seqno++;
3429 void Yaz_Proxy::timeoutNotify()
3434 switch(m_timeout_mode)
3436 case timeout_normal:
3440 yaz_log (YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
3443 case timeout_reduce:
3444 timeout(m_client_idletime);
3445 m_timeout_mode = timeout_busy;
3446 gdu = m_timeout_gdu;
3448 recv_GDU_normal(gdu);
3451 assert(m_stylesheet_nprl);
3452 convert_xsl_delay();
3453 recv_GDU_more(true);
3463 void Yaz_Proxy::markInvalid()
3466 m_flag_invalid_session = 1;
3469 void Yaz_ProxyClient::timeoutNotify()
3472 m_server->inc_request_no();
3474 yaz_log (YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
3478 m_server->send_response_fail_client(get_hostname());
3484 Yaz_ProxyClient::Yaz_ProxyClient(IPDU_Observable *the_PDU_Observable,
3485 Yaz_Proxy *parent) :
3486 Z_Assoc (the_PDU_Observable)
3493 m_last_resultSetId = 0;
3494 m_last_resultCount = 0;
3498 m_init_odr = odr_createmem (ODR_DECODE);
3500 m_initResponse_options = 0;
3501 m_initResponse_version = 0;
3502 m_initResponse_preferredMessageSize = 0;
3503 m_initResponse_maximumRecordSize = 0;
3504 m_resultSetStartPoint = 0;
3505 m_bytes_sent = m_bytes_recv = 0;
3509 m_target_idletime = 600;
3511 m_idAuthentication_odr = odr_createmem(ODR_ENCODE);
3512 m_idAuthentication_ber_buf = 0;
3513 m_idAuthentication_ber_size = 0;
3516 const char *Yaz_Proxy::option(const char *name, const char *value)
3518 if (!strcmp (name, "optimize")) {
3521 m_optimize = xstrdup (value);
3528 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
3533 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
3535 if (apdu->which == Z_GDU_Z3950)
3536 recv_Z_PDU(apdu->u.z3950, len);
3537 else if (apdu->which == Z_GDU_HTTP_Response)
3538 recv_HTTP_response(apdu->u.HTTP_Response, len);
3543 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
3545 if (!m_flag_invalid_session)
3547 m_flag_invalid_session = 0;
3548 handle_incoming_Z_PDU(m_apdu_invalid_session);
3549 assert (m_mem_invalid_session);
3550 nmem_destroy(m_mem_invalid_session);
3551 m_mem_invalid_session = 0;
3555 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
3557 m_bytes_recv += len;
3561 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
3562 yaz_log (YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
3563 apdu_name(apdu), get_hostname(), len);
3564 if (apdu->which == Z_APDU_initResponse)
3566 if (!m_server) // if this is a pre init session , check for more
3568 NMEM nmem = odr_extract_mem (odr_decode());
3569 odr_reset (m_init_odr);
3570 nmem_transfer (m_init_odr->mem, nmem);
3571 m_initResponse = apdu;
3572 m_initResponse_options = apdu->u.initResponse->options;
3573 m_initResponse_version = apdu->u.initResponse->protocolVersion;
3574 m_initResponse_preferredMessageSize =
3575 *apdu->u.initResponse->preferredMessageSize;
3576 m_initResponse_maximumRecordSize =
3577 *apdu->u.initResponse->maximumRecordSize;
3579 Z_InitResponse *ir = apdu->u.initResponse;
3580 char *im0 = ir->implementationName;
3583 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
3590 strcat(im1, "(YAZ Proxy)");
3591 ir->implementationName = im1;
3593 nmem_destroy (nmem);
3595 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
3598 if (apdu->which == Z_APDU_searchResponse)
3600 Z_SearchResponse *sr = apdu->u.searchResponse;
3601 m_last_resultCount = *sr->resultCount;
3602 int status = *sr->searchStatus;
3603 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
3607 if (sr->records && sr->records->which == Z_Records_DBOSD)
3609 m_cache.add(odr_decode(),
3610 sr->records->u.databaseOrSurDiagnostics, 1,
3615 if (apdu->which == Z_APDU_presentResponse)
3617 Z_PresentResponse *pr = apdu->u.presentResponse;
3621 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
3622 Z_SearchResponse *sr = new_apdu->u.searchResponse;
3623 sr->referenceId = pr->referenceId;
3624 *sr->resultCount = m_last_resultCount;
3625 sr->records = pr->records;
3626 sr->nextResultSetPosition = pr->nextResultSetPosition;
3627 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
3631 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
3633 m_cache.add(odr_decode(),
3634 pr->records->u.databaseOrSurDiagnostics,
3635 m_resultSetStartPoint, -1);
3636 m_resultSetStartPoint = 0;
3640 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
3642 Yaz_Proxy *server = m_server; // save it. send_to_client may destroy us
3645 server->send_to_client(apdu);
3646 if (apdu->which == Z_APDU_close)
3649 server->recv_GDU_more(true);
3652 void Yaz_Proxy::low_socket_close()
3657 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3658 if (m_lo_fd[i] >= 0)
3659 ::close(m_lo_fd[i]);
3663 void Yaz_Proxy::low_socket_open()
3668 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3669 m_lo_fd[i] = open("/dev/null", O_RDONLY);
3673 int Yaz_Proxy::server(const char *addr)
3675 int r = Z_Assoc::server(addr);
3678 yaz_log(YLOG_LOG, "%sStarted proxy "
3682 " on %s", m_session_str, addr);
3688 void Yaz_Proxy::base64_decode(const char *base64, char *buf, int buf_len)
3690 const char *base64_chars =
3691 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3692 int len = strlen(base64);
3696 for (int pos = 0; pos <= len; pos++)
3698 if (base64[pos] == '=' || buf_pos + 1 >= buf_len)
3701 const char *ch_ptr = strchr(base64_chars, base64[pos]);
3704 char ch = (char) (ch_ptr - base64_chars);
3708 buf[buf_pos] = ch << 2;
3711 buf[buf_pos++] += (ch & 0x30) >> 4;
3712 buf[buf_pos] = (ch & 0x0f) << 4;
3715 buf[buf_pos++] += (ch & 0x3c) >> 2;
3716 buf[buf_pos] = (ch & 0x03) << 6;
3719 buf[buf_pos++] += ch;
3726 buf[buf_pos] = '\0';
3732 * indent-tabs-mode: nil
3734 * vim: shiftwidth=4 tabstop=8 expandtab