1 /* $Id: yaz-proxy.cpp,v 1.60 2006-04-17 07:38: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;
300 void Yaz_Proxy::inc_ref()
305 Yaz_Proxy::~Yaz_Proxy()
307 yaz_log(YLOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
308 m_bytes_sent, m_bytes_recv);
309 nmem_destroy(m_initRequest_mem);
310 nmem_destroy(m_mem_invalid_session);
311 nmem_destroy(m_referenceId_mem);
313 xfree(m_proxyTarget);
314 xfree(m_default_target);
315 xfree(m_proxy_negotiation_charset);
316 xfree(m_proxy_negotiation_lang);
317 xfree(m_proxy_negotiation_default_charset);
318 delete m_charset_converter;
322 if (m_stylesheet_xsp)
323 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
329 xfree (m_backend_type);
330 xfree (m_backend_charset);
331 xfree (m_usemarcon_ini_stage1);
332 xfree (m_usemarcon_ini_stage2);
335 odr_destroy(m_s2z_odr_init);
336 if (m_s2z_odr_search)
337 odr_destroy(m_s2z_odr_search);
345 void Yaz_Proxy::set_debug_mode(int mode)
350 int Yaz_Proxy::set_config(const char *config)
353 m_config = new Yaz_ProxyConfig();
354 xfree(m_config_fname);
355 m_config_fname = xstrdup(config);
356 int r = m_config->read_xml(config);
360 m_config->get_generic_info(&m_log_mask, &m_max_clients,
361 &m_max_connect, &m_limit_connect, &period);
362 m_connect.set_period(period);
367 void Yaz_Proxy::set_default_target(const char *target)
369 xfree (m_default_target);
370 m_default_target = 0;
372 m_default_target = (char *) xstrdup (target);
375 void Yaz_Proxy::set_proxy_negotiation (const char *charset, const char *lang,
376 const char *default_charset)
378 yaz_log(YLOG_DEBUG, "%sSet the proxy negotiation: charset to '%s', "
379 "default charset to '%s', language to '%s'", m_session_str,
380 charset?charset:"none",
381 default_charset?default_charset:"none",
383 xfree (m_proxy_negotiation_charset);
384 xfree (m_proxy_negotiation_lang);
385 m_proxy_negotiation_charset = m_proxy_negotiation_lang = 0;
387 m_proxy_negotiation_charset = (char *) xstrdup (charset);
389 m_proxy_negotiation_lang = (char *) xstrdup (lang);
391 m_proxy_negotiation_default_charset =
392 (char *) xstrdup (default_charset);
395 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
398 return m_parent->check_reconfigure();
400 Yaz_ProxyConfig *cfg = m_config;
403 yaz_log(YLOG_LOG, "reconfigure");
405 if (m_config_fname && cfg)
407 yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
408 int r = cfg->read_xml(m_config_fname);
410 yaz_log(YLOG_WARN, "reconfigure failed");
415 cfg->get_generic_info(&m_log_mask, &m_max_clients,
416 &m_max_connect, &m_limit_connect,
418 m_connect.set_period(period);
422 yaz_log(YLOG_LOG, "reconfigure");
428 IPDU_Observer *Yaz_Proxy::sessionNotify(IPDU_Observable
429 *the_PDU_Observable, int fd)
433 char session_str[200];
434 const char *peername = the_PDU_Observable->getpeername();
435 if (m_log_mask & PROXY_LOG_IP_CLIENT)
436 sprintf(session_str, "%ld:%d %.80s %d ",
437 (long) time(0), m_session_no, peername, 0);
439 sprintf(session_str, "%ld:%d %d ",
440 (long) time(0), m_session_no, 0);
443 yaz_log (YLOG_LOG, "%sNew session %s", session_str, peername);
445 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable,
446 m_socket_observable, this);
448 new_proxy->m_config = 0;
449 new_proxy->m_config_fname = 0;
450 new_proxy->timeout(m_client_idletime);
451 new_proxy->m_target_idletime = m_target_idletime;
452 new_proxy->set_default_target(m_default_target);
453 new_proxy->m_max_clients = m_max_clients;
454 new_proxy->m_log_mask = m_log_mask;
456 if (!strcmp(peername, "tcp:163.121.19.82")) // NIS GROUP
457 new_proxy->m_log_mask = 255;
459 new_proxy->set_APDU_log(get_APDU_log());
460 if (new_proxy->m_log_mask & PROXY_LOG_APDU_CLIENT)
461 new_proxy->set_APDU_yazlog(1);
463 new_proxy->set_APDU_yazlog(0);
464 strcpy(new_proxy->m_session_str, session_str);
465 new_proxy->m_peername = xstrdup(peername);
466 new_proxy->set_proxy_negotiation(m_proxy_negotiation_charset,
467 m_proxy_negotiation_lang, m_proxy_negotiation_default_charset);
468 // create thread object the first time we get an incoming connection
470 m_my_thread = new Msg_Thread(m_socket_observable, 1);
471 new_proxy->m_my_thread = m_my_thread;
475 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
478 Z_OtherInformationUnit *oi;
480 ent.proto = PROTO_Z3950;
481 ent.oclass = CLASS_USERINFO;
482 ent.value = (oid_value) VAL_COOKIE;
483 assert (oid_ent_to_oid (&ent, oid));
485 if (oid_ent_to_oid (&ent, oid) &&
486 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
487 oi->which == Z_OtherInfo_characterInfo)
488 return oi->information.characterInfo;
491 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
494 Z_OtherInformationUnit *oi;
496 ent.proto = PROTO_Z3950;
497 ent.oclass = CLASS_USERINFO;
498 ent.value = (oid_value) VAL_PROXY;
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 const char *Yaz_Proxy::load_balance(const char **url)
507 int zurl_in_use[MAX_ZURL_PLEX];
508 int zurl_in_spare[MAX_ZURL_PLEX];
512 for (i = 0; i<MAX_ZURL_PLEX; i++)
515 zurl_in_spare[i] = 0;
517 for (c = m_parent->m_clientPool; c; c = c->m_next)
519 for (i = 0; url[i]; i++)
520 if (!strcmp(url[i], c->get_hostname()))
523 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
527 int min_use = 100000;
528 int spare_for_min = 0;
530 const char *ret_min = 0;
531 const char *ret_spare = 0;
532 for (i = 0; url[i]; i++)
534 yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
535 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
536 if (min_use > zurl_in_use[i])
539 min_use = zurl_in_use[i];
540 spare_for_min = zurl_in_spare[i];
542 if (max_spare < zurl_in_spare[i])
545 max_spare = zurl_in_spare[i];
551 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
552 const char *proxy_host)
555 Yaz_Proxy *parent = m_parent;
556 Yaz_ProxyClient *c = m_client;
560 const char *url[MAX_ZURL_PLEX];
561 Yaz_ProxyConfig *cfg = check_reconfigure();
564 if (parent && parent->m_debug_mode)
566 // only to be enabled for debugging...
567 if (!strcmp(proxy_host, "stop"))
570 xfree(m_default_target);
571 m_default_target = xstrdup(proxy_host);
573 proxy_host = m_default_target;
574 int client_idletime = -1;
575 const char *cql2rpn_fname = 0;
576 const char *negotiation_charset = 0;
577 const char *negotiation_lang = 0;
578 const char *query_charset = 0;
579 const char *default_client_query_charset = 0;
580 url[0] = m_default_target;
585 cfg->get_target_info(proxy_host, url, &m_bw_max,
586 &m_pdu_max, &m_max_record_retrieve,
588 &m_target_idletime, &client_idletime,
589 &parent->m_max_clients,
590 &m_keepalive_limit_bw,
591 &m_keepalive_limit_pdu,
594 &negotiation_charset,
597 &default_client_query_charset);
599 if (client_idletime != -1)
601 m_client_idletime = client_idletime;
602 timeout(m_client_idletime);
605 m_cql2rpn.set_pqf_file(cql2rpn_fname);
606 if (negotiation_charset || negotiation_lang || default_client_query_charset)
608 set_proxy_negotiation(negotiation_charset,
609 negotiation_lang, default_client_query_charset);
611 m_charset_converter->set_target_query_charset(query_charset);
614 yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
617 // we don't handle multiplexing for cookie session, so we just
618 // pick the first one in this case (anonymous users will be able
619 // to use any backend)
620 if (cookie && *cookie)
621 m_proxyTarget = (char*) xstrdup(url[0]);
623 m_proxyTarget = (char*) xstrdup(load_balance(url));
625 if (cookie && *cookie)
626 { // search in sessions with a cookie
627 for (c = parent->m_clientPool; c; c = c->m_next)
630 assert (*c->m_prev == c);
631 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
632 !strcmp(m_proxyTarget, c->get_hostname()))
635 // The following handles "cancel"
636 // If connection is busy (waiting for PDU) and
637 // we have an initRequest we can safely do re-open
638 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
640 yaz_log (YLOG_LOG, "%s REOPEN target=%s", m_session_str,
647 c->m_last_resultCount = 0;
648 c->m_sr_transform = 0;
650 c->m_resultSetStartPoint = 0;
651 c->m_target_idletime = m_target_idletime;
652 if (c->client(m_proxyTarget))
659 c->m_seqno = parent->m_seqno;
660 if (c->m_server && c->m_server != this)
661 c->m_server->m_client = 0;
664 yaz_log (YLOG_DEBUG, "get_client 1 %p %p", this, c);
669 else if (!c && apdu->which == Z_APDU_initRequest )
671 // anonymous sessions without cookie.
672 // if authentication is set it is NOT anonymous se we can't share them.
673 // If charset and lang negotiation is use it is NOT anonymous session too.
674 for (c = parent->m_clientPool; c; c = c->m_next)
677 assert(*c->m_prev == c);
678 if (c->m_server == 0 && c->m_cookie == 0 && c->m_waiting == 0
679 && c->compare_idAuthentication(apdu)
680 && c->compare_charset(apdu)
681 && !strcmp(m_proxyTarget, c->get_hostname()))
684 yaz_log (YLOG_LOG, "%sREUSE %d %s",
685 m_session_str, parent->m_seqno, c->get_hostname());
687 c->m_seqno = parent->m_seqno;
688 assert(c->m_server == 0);
691 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
692 c->set_APDU_yazlog(1);
694 c->set_APDU_yazlog(0);
706 if (apdu->which != Z_APDU_initRequest)
708 yaz_log (YLOG_LOG, "%sno init request as first PDU", m_session_str);
711 // go through list of clients - and find the lowest/oldest one.
712 Yaz_ProxyClient *c_min = 0;
714 int no_of_clients = 0;
715 if (parent->m_clientPool)
716 yaz_log (YLOG_DEBUG, "Existing sessions");
717 for (c = parent->m_clientPool; c; c = c->m_next)
719 yaz_log (YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
720 c->m_waiting, c->get_hostname(),
721 c->m_cookie ? c->m_cookie : "");
723 if (min_seq < 0 || c->m_seqno < min_seq)
725 min_seq = c->m_seqno;
729 if (no_of_clients >= parent->m_max_clients)
732 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
734 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
735 m_session_str, parent->m_max_clients, c->m_seqno);
736 if (c->m_server && c->m_server != this)
737 c->m_server->dec_ref(true);
741 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
742 m_session_str, parent->m_max_clients,
743 c->m_seqno, parent->m_seqno, c->get_hostname());
747 c->m_cookie = xstrdup(cookie);
748 c->m_seqno = parent->m_seqno;
749 if (c->m_server && c->m_server != this)
751 c->m_server->m_client = 0;
752 c->m_server->dec_ref(true);
755 c->m_target_idletime = m_target_idletime;
756 c->timeout(m_target_idletime);
758 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
759 c->set_APDU_yazlog(1);
761 c->set_APDU_yazlog(0);
768 yaz_log (YLOG_LOG, "%sNEW %d %s",
769 m_session_str, parent->m_seqno, m_proxyTarget);
770 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
771 c->m_next = parent->m_clientPool;
773 c->m_next->m_prev = &c->m_next;
774 parent->m_clientPool = c;
775 c->m_prev = &parent->m_clientPool;
781 c->m_cookie = xstrdup(cookie);
783 c->m_seqno = parent->m_seqno;
785 c->m_last_resultCount = 0;
788 c->m_sr_transform = 0;
790 c->m_resultSetStartPoint = 0;
792 if (c->client(m_proxyTarget))
797 c->m_target_idletime = m_target_idletime;
800 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
801 c->set_APDU_yazlog(1);
803 c->set_APDU_yazlog(0);
805 c->set_idAuthentication(apdu);
807 yaz_log (YLOG_DEBUG, "get_client 3 %p %p", this, c);
811 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
814 for (i = 0; i<num; i++)
817 Z_DefaultDiagFormat *r;
818 Z_DiagRec *p = pp[i];
819 if (p->which != Z_DiagRec_defaultFormat)
821 yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
825 r = p->u.defaultFormat;
826 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
827 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
828 yaz_log(YLOG_LOG, "%sError unknown diagnostic set", m_session_str);
831 case Z_DefaultDiagFormat_v2Addinfo:
832 yaz_log(YLOG_LOG, "%sError %d %s:%s",
834 *r->condition, diagbib1_str(*r->condition),
837 case Z_DefaultDiagFormat_v3Addinfo:
838 yaz_log(YLOG_LOG, "%sError %d %s:%s",
840 *r->condition, diagbib1_str(*r->condition),
847 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
849 if (!m_stylesheet_xsp || p->num_records <= 0)
851 return 0; /* no XSLT to be done ... */
854 m_stylesheet_offset = 0;
855 m_stylesheet_nprl = p;
856 m_stylesheet_apdu = apdu;
857 m_timeout_mode = timeout_xsl;
863 void Yaz_Proxy::convert_xsl_delay()
866 Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
867 if (npr->which == Z_NamePlusRecord_databaseRecord)
869 Z_External *r = npr->u.databaseRecord;
870 if (r->which == Z_External_octet)
873 fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
875 xmlDocPtr res, doc = xmlParseMemory(
876 (char*) r->u.octet_aligned->buf,
877 r->u.octet_aligned->len);
880 yaz_log(YLOG_LOG, "%sXSLT convert %d",
881 m_session_str, m_stylesheet_offset);
882 res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
889 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
891 m_stylesheet_nprl->records[m_stylesheet_offset]->
893 z_ext_record(odr_encode(), VAL_TEXT_XML,
894 (char*) out_buf, out_len);
903 m_stylesheet_offset++;
904 if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
906 m_timeout_mode = timeout_normal;
907 m_stylesheet_nprl = 0;
909 if (m_stylesheet_xsp)
910 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
912 m_stylesheet_xsp = 0;
913 timeout(m_client_idletime);
914 send_PDU_convert(m_stylesheet_apdu);
920 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
922 if (m_frontend_type != VAL_NONE)
925 for (i = 0; i < p->num_records; i++)
927 Z_NamePlusRecord *npr = p->records[i];
928 if (npr->which == Z_NamePlusRecord_databaseRecord)
930 Z_External *r = npr->u.databaseRecord;
931 if (r->which == Z_External_octet)
934 if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
936 if (!m_usemarcon->m_stage1)
938 m_usemarcon->m_stage1 = new CDetails();
940 m_usemarcon->m_stage1->SetIniFileName(m_usemarcon_ini_stage1);
941 m_usemarcon->m_stage1->SetMarcRecord((char*) r->u.octet_aligned->buf, r->u.octet_aligned->len);
942 int res = m_usemarcon->m_stage1->Start();
947 m_usemarcon->m_stage1->GetMarcRecord(converted, convlen);
948 if (m_usemarcon_ini_stage2 && *m_usemarcon_ini_stage2)
950 if (!m_usemarcon->m_stage2)
952 m_usemarcon->m_stage2 = new CDetails();
954 m_usemarcon->m_stage2->SetIniFileName(m_usemarcon_ini_stage2);
955 m_usemarcon->m_stage2->SetMarcRecord(converted, convlen);
956 res = m_usemarcon->m_stage2->Start();
960 m_usemarcon->m_stage2->GetMarcRecord(converted, convlen);
964 yaz_log(YLOG_LOG, "%sUSEMARCON stage 2 error %d", m_session_str, res);
967 npr->u.databaseRecord =
968 z_ext_record(odr_encode(),
976 yaz_log(YLOG_LOG, "%sUSEMARCON stage 1 error %d", m_session_str, res);
982 npr->u.databaseRecord =
983 z_ext_record(odr_encode(),
985 (char*) r->u.octet_aligned->buf,
986 r->u.octet_aligned->len);
993 void Yaz_Proxy::convert_records_charset(Z_NamePlusRecordList *p,
994 const char *backend_charset)
996 int sel = m_charset_converter->get_client_charset_selected();
997 const char *client_record_charset =
998 m_charset_converter->get_client_query_charset();
999 if (sel && backend_charset && client_record_charset &&
1000 strcmp(backend_charset, client_record_charset))
1003 yaz_iconv_t cd = yaz_iconv_open(client_record_charset,
1005 yaz_marc_t mt = yaz_marc_create();
1006 yaz_marc_xml(mt, YAZ_MARC_ISO2709);
1007 yaz_marc_iconv(mt, cd);
1008 for (i = 0; i < p->num_records; i++)
1010 Z_NamePlusRecord *npr = p->records[i];
1011 if (npr->which == Z_NamePlusRecord_databaseRecord)
1013 Z_External *r = npr->u.databaseRecord;
1014 oident *ent = oid_getentbyoid(r->direct_reference);
1015 if (!ent || ent->value == VAL_NONE)
1018 if (ent->value == VAL_SUTRS)
1020 WRBUF w = wrbuf_alloc();
1022 wrbuf_iconv_write(w, cd, (char*) r->u.octet_aligned->buf,
1023 r->u.octet_aligned->len);
1024 npr->u.databaseRecord =
1025 z_ext_record(odr_encode(), ent->value, wrbuf_buf(w),
1029 else if (ent->value == VAL_TEXT_XML)
1033 else if (r->which == Z_External_octet)
1037 if (yaz_marc_decode_buf(mt,
1038 (char*) r->u.octet_aligned->buf,
1039 r->u.octet_aligned->len,
1042 npr->u.databaseRecord =
1043 z_ext_record(odr_encode(), ent->value, result, rlen);
1044 yaz_log(YLOG_LOG, "%sRecoding MARC record",
1051 yaz_iconv_close(cd);
1052 yaz_marc_destroy(mt);
1056 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
1057 const char *backend_charset)
1060 if (!backend_charset)
1061 backend_charset = "MARC-8";
1062 yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
1063 yaz_marc_t mt = yaz_marc_create();
1064 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1065 yaz_marc_iconv(mt, cd);
1066 for (i = 0; i < p->num_records; i++)
1068 Z_NamePlusRecord *npr = p->records[i];
1069 if (npr->which == Z_NamePlusRecord_databaseRecord)
1071 Z_External *r = npr->u.databaseRecord;
1072 if (r->which == Z_External_OPAC)
1074 WRBUF w = wrbuf_alloc();
1076 yaz_opac_decode_wrbuf(mt, r->u.opac, w);
1077 npr->u.databaseRecord = z_ext_record(
1078 odr_encode(), VAL_TEXT_XML,
1079 wrbuf_buf(w), wrbuf_len(w)
1083 else if (r->which == Z_External_octet)
1087 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
1088 r->u.octet_aligned->len,
1091 npr->u.databaseRecord =
1092 z_ext_record(odr_encode(), VAL_TEXT_XML, result, rlen);
1098 yaz_iconv_close(cd);
1099 yaz_marc_destroy(mt);
1102 void Yaz_Proxy::logtime()
1104 #if HAVE_GETTIMEOFDAY
1105 struct timeval *tv = (struct timeval*) m_time_tv;
1109 gettimeofday(&tv1, 0);
1110 long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
1111 (tv1.tv_usec - tv->tv_usec);
1113 yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
1114 diff/1000000, (diff/1000)%1000);
1121 int Yaz_Proxy::send_http_response(int code)
1123 ODR o = odr_encode();
1124 Z_GDU *gdu = z_get_HTTP_Response(o, code);
1125 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1127 hres->version = odr_strdup(o, m_http_version);
1128 if (m_http_keepalive)
1129 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1133 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1135 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1139 int r = send_GDU(gdu, &len);
1140 m_bytes_sent += len;
1141 m_bw_stat.add_bytes(len);
1144 recv_GDU_more(true);
1149 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu, int http_code /* = 200 */)
1151 ODR o = odr_encode();
1152 const char *ctype = "text/xml";
1153 Z_GDU *gdu = z_get_HTTP_Response(o, http_code);
1154 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1156 hres->version = odr_strdup(o, m_http_version);
1157 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1158 if (m_http_keepalive)
1159 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1162 if (http_code == 401)
1163 z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate", "Basic realm=\"YAZ Proxy\"");
1165 static Z_SOAP_Handler soap_handlers[2] = {
1167 {"http://www.loc.gov/zing/srw/", 0,
1168 (Z_SOAP_fun) yaz_srw_codec},
1173 Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
1174 soap_package->which = Z_SOAP_generic;
1175 soap_package->u.generic =
1176 (Z_SOAP_Generic *) odr_malloc(o, sizeof(*soap_package->u.generic));
1177 soap_package->u.generic->no = 0;
1178 soap_package->u.generic->ns = soap_handlers[0].ns;
1179 soap_package->u.generic->p = (void *) srw_pdu;
1180 soap_package->ns = m_soap_ns;
1181 z_soap_codec_enc_xsl(o, &soap_package,
1182 &hres->content_buf, &hres->content_len,
1183 soap_handlers, 0, m_s2z_stylesheet);
1184 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1186 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1190 int r = send_GDU(gdu, &len);
1191 m_bytes_sent += len;
1192 m_bw_stat.add_bytes(len);
1195 recv_GDU_more(true);
1200 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
1202 ODR o = odr_encode();
1203 Z_SRW_diagnostic *diagnostic = (Z_SRW_diagnostic *)
1204 odr_malloc(o, sizeof(*diagnostic));
1205 int num_diagnostic = 1;
1206 yaz_mk_std_diagnostic(o, diagnostic, srw_error, add);
1207 return send_srw_search_response(diagnostic, num_diagnostic, srw_error == 3 ? 401 : 200);
1210 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
1211 Z_DefaultDiagFormat *ddf)
1213 int bib1_code = *ddf->condition;
1214 if (bib1_code == 109)
1216 srw_res->num_diagnostics = 1;
1217 srw_res->diagnostics = (Z_SRW_diagnostic *)
1218 odr_malloc(o, sizeof(*srw_res->diagnostics));
1219 yaz_mk_std_diagnostic(o, srw_res->diagnostics,
1220 yaz_diag_bib1_to_srw(*ddf->condition),
1225 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
1227 ODR o = odr_encode();
1228 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1229 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1231 srw_res->numberOfRecords = odr_intdup (o, hits);
1232 if (records && records->which == Z_Records_DBOSD)
1234 srw_res->num_records =
1235 records->u.databaseOrSurDiagnostics->num_records;
1237 srw_res->records = (Z_SRW_record *)
1238 odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
1239 for (i = 0; i < srw_res->num_records; i++)
1241 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
1242 if (npr->which != Z_NamePlusRecord_databaseRecord)
1244 srw_res->records[i].recordSchema = "diagnostic";
1245 srw_res->records[i].recordPacking = m_s2z_packing;
1246 srw_res->records[i].recordData_buf = "67";
1247 srw_res->records[i].recordData_len = 2;
1248 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1251 Z_External *r = npr->u.databaseRecord;
1252 oident *ent = oid_getentbyoid(r->direct_reference);
1253 if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
1255 srw_res->records[i].recordSchema = m_schema;
1256 srw_res->records[i].recordPacking = m_s2z_packing;
1257 srw_res->records[i].recordData_buf = (char*)
1258 r->u.octet_aligned->buf;
1259 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1260 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1264 srw_res->records[i].recordSchema = "diagnostic";
1265 srw_res->records[i].recordPacking = m_s2z_packing;
1266 srw_res->records[i].recordData_buf = "67";
1267 srw_res->records[i].recordData_len = 2;
1268 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1272 if (records && records->which == Z_Records_NSD)
1275 http_code = z_to_srw_diag(odr_encode(), srw_res,
1276 records->u.nonSurrogateDiagnostic);
1278 return send_http_response(http_code);
1280 return send_srw_response(srw_pdu);
1284 int Yaz_Proxy::send_srw_search_response(Z_SRW_diagnostic *diagnostics,
1285 int num_diagnostics, int http_code /* = 200 */)
1287 ODR o = odr_encode();
1288 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1289 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1291 srw_res->num_diagnostics = num_diagnostics;
1292 srw_res->diagnostics = diagnostics;
1293 return send_srw_response(srw_pdu, http_code);
1296 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1297 int num_diagnostics)
1299 Yaz_ProxyConfig *cfg = check_reconfigure();
1303 char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1304 m_s2z_database, &len);
1307 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1308 Z_SRW_explainResponse *er = res->u.explain_response;
1310 er->record.recordData_buf = b;
1311 er->record.recordData_len = len;
1312 er->record.recordPacking = m_s2z_packing;
1313 er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
1315 er->diagnostics = diagnostics;
1316 er->num_diagnostics = num_diagnostics;
1317 return send_srw_response(res);
1320 return send_http_response(404);
1323 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1327 if (apdu->which == Z_APDU_initResponse)
1329 Z_InitResponse *res = apdu->u.initResponse;
1330 if (*res->result == 0)
1332 send_to_srw_client_error(3, 0);
1334 else if (!m_s2z_search_apdu)
1336 send_srw_explain_response(0, 0);
1340 handle_incoming_Z_PDU(m_s2z_search_apdu);
1343 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1345 m_s2z_search_apdu = 0;
1346 Z_SearchResponse *res = apdu->u.searchResponse;
1347 m_s2z_hit_count = *res->resultCount;
1348 if (res->records && res->records->which == Z_Records_NSD)
1350 send_to_srw_client_ok(0, res->records, 1);
1352 else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1355 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1357 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1359 if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1361 *pr->numberOfRecordsRequested =
1362 1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1364 handle_incoming_Z_PDU(m_s2z_present_apdu);
1368 m_s2z_present_apdu = 0;
1369 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1372 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1375 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1377 m_s2z_present_apdu = 0;
1378 Z_PresentResponse *res = apdu->u.presentResponse;
1379 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1385 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1386 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1388 int r = send_Z_PDU(apdu, &len);
1389 m_bytes_sent += len;
1390 m_bw_stat.add_bytes(len);
1397 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1399 int kill_session = 0;
1400 Z_ReferenceId **new_id = get_referenceIdP(apdu);
1403 *new_id = m_referenceId;
1405 if (apdu->which == Z_APDU_searchResponse)
1407 Z_SearchResponse *sr = apdu->u.searchResponse;
1408 Z_Records *p = sr->records;
1409 if (p && p->which == Z_Records_NSD)
1411 Z_DiagRec dr, *dr_p = &dr;
1412 dr.which = Z_DiagRec_defaultFormat;
1413 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1415 *sr->searchStatus = 0;
1416 display_diagrecs(&dr_p, 1);
1420 if (p && p->which == Z_Records_DBOSD)
1424 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1427 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1428 if (m_marcxml_mode == marcxml)
1429 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1432 convert_records_charset(p->u.databaseOrSurDiagnostics,
1434 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1438 if (sr->resultCount)
1440 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1442 if (*sr->resultCount < 0)
1444 m_flag_invalid_session = 1;
1447 *sr->searchStatus = 0;
1449 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1450 *sr->resultCount = 0;
1455 else if (apdu->which == Z_APDU_presentResponse)
1457 Z_PresentResponse *sr = apdu->u.presentResponse;
1458 Z_Records *p = sr->records;
1459 if (p && p->which == Z_Records_NSD)
1461 Z_DiagRec dr, *dr_p = &dr;
1462 dr.which = Z_DiagRec_defaultFormat;
1463 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1464 if (*sr->presentStatus == Z_PresentStatus_success)
1465 *sr->presentStatus = Z_PresentStatus_failure;
1466 display_diagrecs(&dr_p, 1);
1468 if (p && p->which == Z_Records_DBOSD)
1472 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1475 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1476 if (m_marcxml_mode == marcxml)
1477 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1480 convert_records_charset(p->u.databaseOrSurDiagnostics,
1482 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1486 else if (apdu->which == Z_APDU_initResponse)
1488 //Get and check negotiation record
1489 //from init response.
1490 handle_charset_lang_negotiation(apdu);
1492 if (m_initRequest_options)
1495 (Odr_bitmask *)odr_malloc(odr_encode(),
1496 sizeof(Odr_bitmask));
1497 ODR_MASK_ZERO(nopt);
1500 for (i = 0; i<24; i++)
1501 if (ODR_MASK_GET(m_initRequest_options, i) &&
1502 ODR_MASK_GET(apdu->u.initResponse->options, i))
1503 ODR_MASK_SET(nopt, i);
1504 apdu->u.initResponse->options = nopt;
1506 if (m_initRequest_version)
1508 Z_ProtocolVersion *nopt =
1509 (Odr_bitmask *)odr_malloc(odr_encode(),
1510 sizeof(Odr_bitmask));
1511 ODR_MASK_ZERO(nopt);
1514 for (i = 0; i<8; i++)
1515 if (ODR_MASK_GET(m_initRequest_version, i) &&
1516 ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1517 ODR_MASK_SET(nopt, i);
1518 apdu->u.initResponse->protocolVersion = nopt;
1520 apdu->u.initResponse->preferredMessageSize =
1521 odr_intdup(odr_encode(),
1522 m_client->m_initResponse_preferredMessageSize >
1523 m_initRequest_preferredMessageSize ?
1524 m_initRequest_preferredMessageSize :
1525 m_client->m_initResponse_preferredMessageSize);
1526 apdu->u.initResponse->maximumRecordSize =
1527 odr_intdup(odr_encode(),
1528 m_client->m_initResponse_maximumRecordSize >
1529 m_initRequest_maximumRecordSize ?
1530 m_initRequest_maximumRecordSize :
1531 m_client->m_initResponse_maximumRecordSize);
1534 int r = send_PDU_convert(apdu);
1541 m_parent->pre_init();
1546 void Yaz_ProxyClient::set_idAuthentication(Z_APDU *apdu)
1548 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1550 odr_reset(m_idAuthentication_odr);
1551 z_IdAuthentication(m_idAuthentication_odr, &t, 1, 0);
1552 m_idAuthentication_ber_buf =
1553 odr_getbuf(m_idAuthentication_odr,
1554 &m_idAuthentication_ber_size, 0);
1557 bool Yaz_ProxyClient::compare_charset(Z_APDU *apdu)
1562 bool Yaz_ProxyClient::compare_idAuthentication(Z_APDU *apdu)
1564 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1565 ODR odr = odr_createmem(ODR_ENCODE);
1567 z_IdAuthentication(odr, &t, 1, 0);
1569 char *buf = odr_getbuf(odr, &sz, 0);
1570 if (buf && m_idAuthentication_ber_buf
1571 && sz == m_idAuthentication_ber_size
1572 && !memcmp(m_idAuthentication_ber_buf, buf, sz))
1578 if (!buf && !m_idAuthentication_ber_buf)
1583 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1586 const char *apdu_name_tmp = apdu_name(apdu);
1587 int r = send_Z_PDU(apdu, &len);
1588 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1589 yaz_log (YLOG_LOG, "%sSending %s to %s %d bytes",
1591 apdu_name_tmp, get_hostname(), len);
1592 m_bytes_sent += len;
1596 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1598 if (apdu->which == Z_APDU_presentRequest)
1600 Z_PresentRequest *pr = apdu->u.presentRequest;
1601 int toget = *pr->numberOfRecordsRequested;
1602 int start = *pr->resultSetStartPoint;
1604 yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1605 pr->resultSetId, start, toget);
1607 if (*m_parent->m_optimize == '0')
1610 if (!m_client->m_last_resultSetId)
1612 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1613 new_apdu->u.presentResponse->records =
1614 create_nonSurrogateDiagnostics(odr_encode(), 30,
1616 send_to_client(new_apdu);
1619 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1621 if (start+toget-1 > m_client->m_last_resultCount)
1623 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1624 new_apdu->u.presentResponse->records =
1625 create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
1626 send_to_client(new_apdu);
1629 Z_NamePlusRecordList *npr;
1631 yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1632 m_session_str, start, toget, yaz_z3950oid_to_str(
1633 pr->preferredRecordSyntax, &oclass));
1635 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1636 pr->preferredRecordSyntax,
1637 pr->recordComposition))
1639 yaz_log (YLOG_LOG, "%sReturned cached records for present request",
1641 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1642 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1644 new_apdu->u.presentResponse->numberOfRecordsReturned
1645 = odr_intdup(odr_encode(), toget);
1647 new_apdu->u.presentResponse->records = (Z_Records*)
1648 odr_malloc(odr_encode(), sizeof(Z_Records));
1649 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1650 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1651 new_apdu->u.presentResponse->nextResultSetPosition =
1652 odr_intdup(odr_encode(), start+toget);
1654 send_to_client(new_apdu);
1660 if (apdu->which != Z_APDU_searchRequest)
1662 Z_SearchRequest *sr = apdu->u.searchRequest;
1663 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1664 Yaz_Z_Databases this_databases;
1666 this_databases.set(sr->num_databaseNames, (const char **)
1669 this_query->set_Z_Query(sr->query);
1671 char query_str[120];
1672 this_query->print(query_str, sizeof(query_str)-1);
1673 yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1675 if (*m_parent->m_optimize != '0' &&
1676 m_client->m_last_ok && m_client->m_last_query &&
1677 m_client->m_last_query->match(this_query) &&
1678 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1679 m_client->m_last_databases.match(this_databases))
1682 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1683 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1685 Z_NamePlusRecordList *npr;
1686 int toget = *sr->mediumSetPresentNumber;
1687 Z_RecordComposition *comp = 0;
1689 if (toget > m_client->m_last_resultCount)
1690 toget = m_client->m_last_resultCount;
1692 if (sr->mediumSetElementSetNames)
1694 comp = (Z_RecordComposition *)
1695 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1696 comp->which = Z_RecordComp_simple;
1697 comp->u.simple = sr->mediumSetElementSetNames;
1700 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1701 sr->preferredRecordSyntax, comp))
1703 yaz_log (YLOG_LOG, "%sReturned cached records for medium set",
1705 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1706 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1707 new_apdu->u.searchResponse->resultCount =
1708 &m_client->m_last_resultCount;
1710 new_apdu->u.searchResponse->numberOfRecordsReturned
1711 = odr_intdup(odr_encode(), toget);
1713 new_apdu->u.searchResponse->presentStatus =
1714 odr_intdup(odr_encode(), Z_PresentStatus_success);
1715 new_apdu->u.searchResponse->records = (Z_Records*)
1716 odr_malloc(odr_encode(), sizeof(Z_Records));
1717 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1718 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1719 new_apdu->u.searchResponse->nextResultSetPosition =
1720 odr_intdup(odr_encode(), toget+1);
1721 send_to_client(new_apdu);
1727 // send present request (medium size)
1728 yaz_log (YLOG_LOG, "%sOptimizing search for medium set",
1731 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1732 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1733 pr->referenceId = sr->referenceId;
1734 pr->resultSetId = sr->resultSetName;
1735 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1736 *pr->numberOfRecordsRequested = toget;
1737 pr->recordComposition = comp;
1738 m_client->m_sr_transform = 1;
1742 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1743 m_client->m_last_resultCount <= 0)
1745 // large set. Return pseudo-search response immediately
1746 yaz_log (YLOG_LOG, "%sOptimizing search for large set",
1748 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1749 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1750 new_apdu->u.searchResponse->resultCount =
1751 &m_client->m_last_resultCount;
1752 send_to_client(new_apdu);
1757 Z_NamePlusRecordList *npr;
1758 int toget = m_client->m_last_resultCount;
1759 Z_RecordComposition *comp = 0;
1761 // send a present request (small set)
1763 if (sr->smallSetElementSetNames)
1765 comp = (Z_RecordComposition *)
1766 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1767 comp->which = Z_RecordComp_simple;
1768 comp->u.simple = sr->smallSetElementSetNames;
1771 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1772 sr->preferredRecordSyntax, comp))
1774 yaz_log (YLOG_LOG, "%sReturned cached records for small set",
1776 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1777 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1778 new_apdu->u.searchResponse->resultCount =
1779 &m_client->m_last_resultCount;
1781 new_apdu->u.searchResponse->numberOfRecordsReturned
1782 = odr_intdup(odr_encode(), toget);
1784 new_apdu->u.searchResponse->presentStatus =
1785 odr_intdup(odr_encode(), Z_PresentStatus_success);
1786 new_apdu->u.searchResponse->records = (Z_Records*)
1787 odr_malloc(odr_encode(), sizeof(Z_Records));
1788 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1789 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1790 new_apdu->u.searchResponse->nextResultSetPosition =
1791 odr_intdup(odr_encode(), toget+1);
1792 send_to_client(new_apdu);
1797 yaz_log (YLOG_LOG, "%sOptimizing search for small set",
1799 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1800 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1801 pr->referenceId = sr->referenceId;
1802 pr->resultSetId = sr->resultSetName;
1803 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1804 *pr->numberOfRecordsRequested = toget;
1805 pr->recordComposition = comp;
1806 m_client->m_sr_transform = 1;
1811 else // query doesn't match
1813 delete m_client->m_last_query;
1814 m_client->m_last_query = this_query;
1815 m_client->m_last_ok = 0;
1816 m_client->m_cache.clear();
1817 m_client->m_resultSetStartPoint = 0;
1819 xfree (m_client->m_last_resultSetId);
1820 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1822 m_client->m_last_databases.set(sr->num_databaseNames,
1823 (const char **) sr->databaseNames);
1829 void Yaz_Proxy::inc_request_no()
1832 char *cp = m_session_str + strlen(m_session_str)-1;
1835 while (*cp && *cp != ' ')
1838 sprintf(cp+1, "%d ", m_request_no);
1841 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1845 m_bytes_recv += len;
1847 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1848 yaz_log (YLOG_LOG, "%sReceiving %s from client %d bytes",
1849 m_session_str, gdu_name(apdu), len);
1852 // try to make a _bad_ attribute set ID .. Don't enable this in prod.
1853 if (apdu->which == Z_GDU_Z3950
1854 && apdu->u.z3950->which == Z_APDU_searchRequest)
1856 Z_SearchRequest *req = apdu->u.z3950->u.searchRequest;
1857 if (req->query && req->query->which == Z_Query_type_1)
1859 Z_RPNQuery *rpnquery = req->query->u.type_1;
1860 if (rpnquery->attributeSetId)
1862 rpnquery->attributeSetId[0] = -2;
1863 rpnquery->attributeSetId[1] = -1;
1864 yaz_log(YLOG_WARN, "%sBAD FIXUP TEST", m_session_str);
1870 #if HAVE_GETTIMEOFDAY
1871 gettimeofday((struct timeval *) m_time_tv, 0);
1873 m_bw_stat.add_bytes(len);
1874 m_pdu_stat.add_bytes(1);
1876 GDU *gdu = new GDU(apdu);
1878 if (gdu->get() == 0)
1881 yaz_log(YLOG_LOG, "%sUnable to encode package", m_session_str);
1886 m_in_queue.enqueue(gdu);
1887 recv_GDU_more(false);
1890 void Yaz_Proxy::HTTP_Forwarded(Z_GDU *z_gdu)
1892 if (z_gdu->which == Z_GDU_HTTP_Request)
1894 Z_HTTP_Request *hreq = z_gdu->u.HTTP_Request;
1895 const char *x_forwarded_for =
1896 z_HTTP_header_lookup(hreq->headers, "X-Forwarded-For");
1897 if (x_forwarded_for)
1900 m_peername = (char*) xmalloc(strlen(x_forwarded_for)+5);
1901 sprintf(m_peername, "tcp:%s", x_forwarded_for);
1903 yaz_log(YLOG_LOG, "%sHTTP Forwarded from %s", m_session_str,
1905 if (m_log_mask & PROXY_LOG_IP_CLIENT)
1906 sprintf(m_session_str, "%ld:%d %.80s %d ",
1907 (long) time(0), m_session_no, m_peername, m_request_no);
1909 sprintf(m_session_str, "%ld:%d %d ",
1910 (long) time(0), m_session_no, m_request_no);
1915 void Yaz_Proxy::connect_stat(bool &block, int &reduce)
1918 m_parent->m_connect.cleanup(false);
1919 m_parent->m_connect.add_connect(m_peername);
1921 int connect_total = m_parent->m_connect.get_total(m_peername);
1922 int max_connect = m_parent->m_max_connect;
1924 if (max_connect && connect_total > max_connect)
1926 yaz_log(YLOG_LOG, "%sconnect not accepted total=%d max=%d",
1927 m_session_str, connect_total, max_connect);
1932 yaz_log(YLOG_LOG, "%sconnect accepted total=%d", m_session_str,
1935 int limit_connect = m_parent->m_limit_connect;
1937 reduce = connect_total / limit_connect;
1942 void Yaz_Proxy::recv_GDU_reduce(GDU *gdu)
1944 HTTP_Forwarded(gdu->get());
1948 if (m_request_no == 1)
1952 connect_stat(block, reduce);
1956 m_timeout_mode = timeout_busy;
1962 int bw_total = m_bw_stat.get_total();
1963 int pdu_total = m_pdu_stat.get_total();
1964 int search_total = m_search_stat.get_total();
1966 assert(m_timeout_mode == timeout_busy);
1967 assert(m_timeout_gdu == 0);
1970 reduce += search_total / m_search_max;
1972 reduce += (bw_total/m_bw_max);
1975 if (pdu_total > m_pdu_max)
1977 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1978 reduce = (reduce > nreduce) ? reduce : nreduce;
1984 /* uncomment to force a big reduce */
1985 m_timeout_mode = timeout_reduce;
1986 m_timeout_gdu = gdu;
1987 timeout(3); // call us reduce seconds later
1992 yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d search=%d limit-bw=%d limit-pdu=%d limit-search=%d",
1993 m_session_str, reduce, bw_total, pdu_total, search_total,
1994 m_bw_max, m_pdu_max, m_search_max);
1996 m_timeout_mode = timeout_reduce;
1997 m_timeout_gdu = gdu;
1998 timeout(reduce); // call us reduce seconds later
2001 recv_GDU_normal(gdu);
2004 void Yaz_Proxy::recv_GDU_more(bool normal)
2007 if (normal && m_timeout_mode == timeout_busy)
2008 m_timeout_mode = timeout_normal;
2009 while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
2011 m_timeout_mode = timeout_busy;
2019 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
2022 gdu->move_away_gdu(odr_decode(), &apdu);
2025 if (apdu->which == Z_GDU_Z3950)
2026 handle_incoming_Z_PDU(apdu->u.z3950);
2027 else if (apdu->which == Z_GDU_HTTP_Request)
2028 handle_incoming_HTTP(apdu->u.HTTP_Request);
2031 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
2033 if (m_max_record_retrieve)
2035 if (apdu->which == Z_APDU_presentRequest)
2037 Z_PresentRequest *pr = apdu->u.presentRequest;
2038 if (pr->numberOfRecordsRequested &&
2039 *pr->numberOfRecordsRequested > m_max_record_retrieve)
2040 *pr->numberOfRecordsRequested = m_max_record_retrieve;
2045 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
2047 if (apdu->which == Z_APDU_initRequest)
2049 if (m_initRequest_options &&
2050 !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
2051 (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
2053 // There is no negotiation proposal from
2054 // client's side. OK. The proxy negotiation
2056 Z_InitRequest *initRequest = apdu->u.initRequest;
2057 Z_OtherInformation **otherInfo;
2058 Z_OtherInformationUnit *oi;
2059 get_otherInfoAPDU(apdu, &otherInfo);
2060 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2063 ODR_MASK_SET(initRequest->options,
2064 Z_Options_negotiationModel);
2065 oi->which = Z_OtherInfo_externallyDefinedInfo;
2066 oi->information.externallyDefinedInfo =
2067 yaz_set_proposal_charneg(odr_encode(),
2068 (const char**)&m_proxy_negotiation_charset,
2069 m_proxy_negotiation_charset ? 1:0,
2070 (const char**)&m_proxy_negotiation_lang,
2071 m_proxy_negotiation_lang ? 1:0,
2075 else if (m_initRequest_options &&
2076 ODR_MASK_GET(m_initRequest_options,
2077 Z_Options_negotiationModel) &&
2078 m_charset_converter->get_target_query_charset())
2080 yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
2082 m_charset_converter->get_target_query_charset());
2083 Z_InitRequest *initRequest = apdu->u.initRequest;
2084 Z_CharSetandLanguageNegotiation *negotiation =
2085 yaz_get_charneg_record (initRequest->otherInfo);
2087 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2089 NMEM nmem = nmem_create();
2090 char **charsets = 0;
2091 int num_charsets = 0;
2095 yaz_get_proposal_charneg (nmem, negotiation,
2096 &charsets, &num_charsets,
2097 &langs, &num_langs, &selected);
2099 for (i = 0; i<num_charsets; i++)
2100 yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
2102 for (i = 0; i<num_langs; i++)
2103 yaz_log(YLOG_LOG, "%slang %s", m_session_str,
2106 const char *t_charset =
2107 m_charset_converter->get_target_query_charset();
2108 // sweep through charsets and pick the first supported
2110 for (i = 0; i<num_charsets; i++)
2112 const char *c_charset = charsets[i];
2113 if (!odr_set_charset(odr_decode(), t_charset, c_charset))
2116 if (i != num_charsets)
2118 // got one .. set up ODR for reverse direction
2119 const char *c_charset = charsets[i];
2120 odr_set_charset(odr_encode(), c_charset, t_charset);
2121 m_charset_converter->set_client_query_charset(c_charset);
2122 m_charset_converter->set_client_charset_selected(selected);
2125 ODR_MASK_CLEAR(m_initRequest_options,
2126 Z_Options_negotiationModel);
2127 yaz_del_charneg_record(&initRequest->otherInfo);
2131 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
2135 else if (m_charset_converter->get_target_query_charset() &&
2136 m_proxy_negotiation_default_charset)
2138 m_charset_converter->
2139 set_client_query_charset(m_proxy_negotiation_default_charset);
2142 else if (apdu->which == Z_APDU_initResponse)
2144 Z_InitResponse *initResponse = apdu->u.initResponse;
2145 Z_OtherInformation **otherInfo;
2146 get_otherInfoAPDU(apdu, &otherInfo);
2148 Z_CharSetandLanguageNegotiation *charneg = 0;
2150 if (otherInfo && *otherInfo &&
2151 ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel)
2152 && (charneg = yaz_get_charneg_record(*otherInfo)))
2158 yaz_get_response_charneg(m_referenceId_mem, charneg,
2159 &charset, &lang, &selected);
2161 yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
2162 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
2164 if (m_initRequest_options &&
2165 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
2167 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2170 else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2172 // negotiation-charset, negotiation-lang
2173 // elements of config file in use.
2175 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2178 // clear negotiation option.
2179 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2181 // Delete negotiation (charneg-3) entry.
2182 yaz_del_charneg_record(otherInfo);
2187 if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2189 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2192 else if (m_charset_converter->get_client_query_charset())
2194 Z_OtherInformation **otherInfo;
2195 Z_OtherInformationUnit *oi;
2196 get_otherInfoAPDU(apdu, &otherInfo);
2197 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2200 ODR_MASK_SET(initResponse->options,
2201 Z_Options_negotiationModel);
2202 if (m_initRequest_options)
2203 ODR_MASK_SET(m_initRequest_options,
2204 Z_Options_negotiationModel);
2206 oi->which = Z_OtherInfo_externallyDefinedInfo;
2207 oi->information.externallyDefinedInfo =
2208 yaz_set_response_charneg(
2210 m_charset_converter->get_client_query_charset(),
2212 m_charset_converter->get_client_charset_selected());
2219 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2221 const char *addinfo)
2223 Z_Records *rec = (Z_Records *)
2224 odr_malloc (odr, sizeof(*rec));
2226 odr_malloc (odr, sizeof(*err));
2227 Z_DiagRec *drec = (Z_DiagRec *)
2228 odr_malloc (odr, sizeof(*drec));
2229 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2230 odr_malloc (odr, sizeof(*dr));
2232 rec->which = Z_Records_NSD;
2233 rec->u.nonSurrogateDiagnostic = dr;
2234 dr->diagnosticSetId =
2235 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
2236 dr->condition = err;
2237 dr->which = Z_DefaultDiagFormat_v2Addinfo;
2238 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2242 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2244 if (apdu->which == Z_APDU_searchRequest &&
2245 apdu->u.searchRequest->query &&
2246 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2247 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2249 Z_RPNQuery *rpnquery = 0;
2250 Z_SearchRequest *sr = apdu->u.searchRequest;
2253 yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2254 sr->query->u.type_104->u.cql);
2256 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2257 &rpnquery, odr_encode(),
2260 yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2263 yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2264 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2266 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2267 new_apdu->u.searchResponse->records =
2268 create_nonSurrogateDiagnostics(odr_encode(),
2269 yaz_diag_srw_to_bib1(r),
2271 *new_apdu->u.searchResponse->searchStatus = 0;
2273 send_to_client(new_apdu);
2279 sr->query->which = Z_Query_type_1;
2280 sr->query->u.type_1 = rpnquery;
2287 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2289 if (apdu->which == Z_APDU_searchRequest &&
2290 apdu->u.searchRequest->query)
2292 if (apdu->u.searchRequest->query->which == Z_Query_type_1
2293 || apdu->u.searchRequest->query->which == Z_Query_type_101)
2296 m_charset_converter->set_client_query_charset("UTF-8");
2297 Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2298 m_charset_converter->convert_type_1(rpnquery, odr_encode());
2305 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2307 if (apdu->which == Z_APDU_searchRequest)
2309 Z_SearchRequest *sr = apdu->u.searchRequest;
2313 Yaz_ProxyConfig *cfg = check_reconfigure();
2315 err = cfg->check_query(odr_encode(), m_default_target,
2316 sr->query, &addinfo);
2319 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2321 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2322 new_apdu->u.searchResponse->records =
2323 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2324 *new_apdu->u.searchResponse->searchStatus = 0;
2326 send_to_client(new_apdu);
2334 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2336 if (apdu->which != Z_APDU_initRequest)
2337 return 1; // pass if no init request
2338 Z_InitRequest *req = apdu->u.initRequest;
2340 Yaz_ProxyConfig *cfg = check_reconfigure();
2342 return 1; // pass if no config
2345 if (req->idAuthentication == 0)
2347 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2350 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2352 ret = cfg->client_authentication(
2354 req->idAuthentication->u.idPass->userId,
2355 req->idAuthentication->u.idPass->groupId,
2356 req->idAuthentication->u.idPass->password,
2359 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2361 char user[64], pass[64];
2364 sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2365 ret = cfg->client_authentication(m_default_target, user, 0, pass,
2369 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2374 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2376 m_marcxml_mode = none;
2377 if (apdu->which == Z_APDU_searchRequest)
2379 Z_SearchRequest *sr = apdu->u.searchRequest;
2382 Yaz_ProxyConfig *cfg = check_reconfigure();
2384 Z_RecordComposition rc_temp, *rc = 0;
2385 if (sr->smallSetElementSetNames)
2387 rc_temp.which = Z_RecordComp_simple;
2388 rc_temp.u.simple = sr->smallSetElementSetNames;
2392 if (sr->preferredRecordSyntax)
2395 ent = oid_getentbyoid(sr->preferredRecordSyntax);
2396 m_frontend_type = ent->value;
2399 m_frontend_type = VAL_NONE;
2401 char *stylesheet_name = 0;
2403 err = cfg->check_syntax(odr_encode(),
2405 sr->preferredRecordSyntax, rc,
2406 &addinfo, &stylesheet_name, &m_schema,
2407 &m_backend_type, &m_backend_charset,
2408 &m_usemarcon_ini_stage1,
2409 &m_usemarcon_ini_stage2);
2410 if (stylesheet_name)
2412 m_parent->low_socket_close();
2415 if (m_stylesheet_xsp)
2416 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2417 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2420 m_stylesheet_offset = 0;
2421 xfree(stylesheet_name);
2423 m_parent->low_socket_open();
2427 sr->smallSetElementSetNames = 0;
2428 sr->mediumSetElementSetNames = 0;
2429 m_marcxml_mode = marcxml;
2433 sr->preferredRecordSyntax =
2434 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2438 sr->preferredRecordSyntax =
2439 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2444 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2446 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2447 new_apdu->u.searchResponse->records =
2448 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2449 *new_apdu->u.searchResponse->searchStatus = 0;
2451 send_to_client(new_apdu);
2455 else if (m_backend_type)
2457 sr->preferredRecordSyntax =
2458 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2461 else if (apdu->which == Z_APDU_presentRequest)
2463 Z_PresentRequest *pr = apdu->u.presentRequest;
2466 Yaz_ProxyConfig *cfg = check_reconfigure();
2468 if (pr->preferredRecordSyntax)
2471 ent = oid_getentbyoid(pr->preferredRecordSyntax);
2472 m_frontend_type = ent->value;
2475 m_frontend_type = VAL_NONE;
2477 char *stylesheet_name = 0;
2479 err = cfg->check_syntax(odr_encode(), m_default_target,
2480 pr->preferredRecordSyntax,
2481 pr->recordComposition,
2482 &addinfo, &stylesheet_name, &m_schema,
2483 &m_backend_type, &m_backend_charset,
2484 &m_usemarcon_ini_stage1,
2485 &m_usemarcon_ini_stage2
2487 if (stylesheet_name)
2489 m_parent->low_socket_close();
2492 if (m_stylesheet_xsp)
2493 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2494 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2497 m_stylesheet_offset = 0;
2498 xfree(stylesheet_name);
2500 m_parent->low_socket_open();
2504 pr->recordComposition = 0;
2505 m_marcxml_mode = marcxml;
2509 pr->preferredRecordSyntax =
2510 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2514 pr->preferredRecordSyntax =
2515 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2520 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2522 new_apdu->u.presentResponse->referenceId = pr->referenceId;
2523 new_apdu->u.presentResponse->records =
2524 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2525 *new_apdu->u.presentResponse->presentStatus =
2526 Z_PresentStatus_failure;
2528 send_to_client(new_apdu);
2532 else if (m_backend_type)
2534 pr->preferredRecordSyntax =
2535 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2541 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2545 Z_ElementSetNames *esn = (Z_ElementSetNames *)
2546 odr_malloc(o, sizeof(Z_ElementSetNames));
2547 esn->which = Z_ElementSetNames_generic;
2548 esn->u.generic = odr_strdup(o, schema);
2552 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2555 Yaz_ProxyConfig *cfg = check_reconfigure();
2557 t = cfg->get_explain_name(db, backend_db);
2559 if (m_client && m_default_target && t && strcmp(m_default_target, t))
2566 xfree(m_default_target);
2567 m_default_target = xstrdup(t);
2571 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2574 if (strcmp(hreq->method, "GET"))
2576 if (hreq->path[0] != '/')
2578 const char *cp = hreq->path;
2581 if (*cp == '/' && strchr("/.", cp[1]))
2586 Yaz_ProxyConfig *cfg = check_reconfigure();
2588 if (!cfg->get_file_access_info(hreq->path+1))
2591 const char *fname = hreq->path+1;
2592 if (stat(fname, &sbuf))
2594 yaz_log(YLOG_LOG|YLOG_ERRNO, "%sstat failed for %s", m_session_str,
2598 if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2600 yaz_log(YLOG_LOG, "%sNot a regular file %s", m_session_str, fname);
2603 if (sbuf.st_size > (off_t) 1000000)
2605 yaz_log(YLOG_WARN, "%sFile %s too large for transfer", m_session_str,
2610 ODR o = odr_encode();
2612 const char *ctype = cfg->check_mime_type(fname);
2613 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2614 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2616 hres->version = odr_strdup(o, m_http_version);
2617 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2618 if (m_http_keepalive)
2619 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2623 hres->content_len = sbuf.st_size;
2624 hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2625 FILE *f = fopen(fname, "rb");
2628 fread(hres->content_buf, 1, hres->content_len, f);
2635 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2637 yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
2641 send_GDU(gdu, &len);
2642 recv_GDU_more(true);
2646 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2650 odr_destroy(m_s2z_odr_init);
2653 if (m_s2z_odr_search)
2655 odr_destroy(m_s2z_odr_search);
2656 m_s2z_odr_search = 0;
2659 m_http_keepalive = 0;
2661 if (!strcmp(hreq->version, "1.0"))
2663 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2664 if (v && !strcmp(v, "Keep-Alive"))
2665 m_http_keepalive = 1;
2667 m_http_keepalive = 0;
2668 m_http_version = "1.0";
2672 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2673 if (v && !strcmp(v, "close"))
2674 m_http_keepalive = 0;
2676 m_http_keepalive = 1;
2677 m_http_version = "1.1";
2680 const char *a = z_HTTP_header_lookup(hreq->headers, "Authorization");
2681 char authorization_str[255];
2682 *authorization_str = '\0';
2683 if (a && strncasecmp(a, "Basic ", 6) == 0)
2684 base64_decode(a + 6, authorization_str, 254);
2686 Z_SRW_PDU *srw_pdu = 0;
2687 Z_SOAP *soap_package = 0;
2689 Z_SRW_diagnostic *diagnostic = 0;
2690 int num_diagnostic = 0;
2692 yaz_log(YLOG_LOG, "%s%s %s", m_session_str, hreq->method, hreq->path);
2694 if (file_access(hreq))
2698 else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2700 || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2701 &charset, &diagnostic, &num_diagnostic) == 0)
2703 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2704 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2705 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2706 m_s2z_init_apdu = 0;
2707 m_s2z_search_apdu = 0;
2708 m_s2z_present_apdu = 0;
2710 m_s2z_stylesheet = 0;
2712 Z_IdAuthentication *auth = NULL;
2713 if (*authorization_str)
2715 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2716 auth->which = Z_IdAuthentication_idPass;
2717 auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2718 auth->u.idPass->groupId = NULL;
2719 char *p = strchr(authorization_str, ':');
2724 auth->u.idPass->password = odr_strdup(m_s2z_odr_init, p);
2726 auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, authorization_str);
2729 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2732 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2734 const char *backend_db = srw_req->database;
2735 srw_get_client(srw_req->database, &backend_db);
2737 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2738 // recordXPath unsupported.
2739 if (srw_req->recordXPath)
2741 yaz_add_srw_diagnostic(odr_decode(),
2742 &diagnostic, &num_diagnostic,
2746 if (srw_req->sort_type != Z_SRW_sort_type_none)
2748 yaz_add_srw_diagnostic(odr_decode(),
2749 &diagnostic, &num_diagnostic,
2753 if (srw_req->stylesheet)
2755 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2757 // set packing for response records ..
2758 if (srw_req->recordPacking &&
2759 !strcmp(srw_req->recordPacking, "xml"))
2760 m_s2z_packing = Z_SRW_recordPacking_XML;
2762 m_s2z_packing = Z_SRW_recordPacking_string;
2766 Z_SRW_PDU *srw_pdu =
2767 yaz_srw_get(odr_encode(),
2768 Z_SRW_searchRetrieve_response);
2769 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2771 srw_res->diagnostics = diagnostic;
2772 srw_res->num_diagnostics = num_diagnostic;
2773 send_srw_response(srw_pdu);
2777 // prepare search PDU
2778 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2779 Z_APDU_searchRequest);
2780 Z_SearchRequest *z_searchRequest =
2781 m_s2z_search_apdu->u.searchRequest;
2783 z_searchRequest->num_databaseNames = 1;
2784 z_searchRequest->databaseNames = (char**)
2785 odr_malloc(m_s2z_odr_search, sizeof(char *));
2786 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2789 // query transformation
2790 Z_Query *query = (Z_Query *)
2791 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2792 z_searchRequest->query = query;
2794 if (srw_req->query_type == Z_SRW_query_type_cql)
2796 Z_External *ext = (Z_External *)
2797 odr_malloc(m_s2z_odr_search, sizeof(*ext));
2798 ext->direct_reference =
2799 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2800 ext->indirect_reference = 0;
2801 ext->descriptor = 0;
2802 ext->which = Z_External_CQL;
2803 ext->u.cql = srw_req->query.cql;
2805 query->which = Z_Query_type_104;
2806 query->u.type_104 = ext;
2808 else if (srw_req->query_type == Z_SRW_query_type_pqf)
2810 Z_RPNQuery *RPNquery;
2811 YAZ_PQF_Parser pqf_parser;
2813 pqf_parser = yaz_pqf_create ();
2815 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2816 srw_req->query.pqf);
2819 const char *pqf_msg;
2821 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2823 yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
2824 yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2826 send_to_srw_client_error(10, 0);
2829 query->which = Z_Query_type_1;
2830 query->u.type_1 = RPNquery;
2832 yaz_pqf_destroy (pqf_parser);
2836 send_to_srw_client_error(7, "query");
2841 m_s2z_present_apdu = 0;
2843 if (srw_req->maximumRecords)
2844 max = *srw_req->maximumRecords;
2846 if (srw_req->startRecord)
2847 start = *srw_req->startRecord;
2850 // Some backend, such as Voyager doesn't honor piggyback
2851 // So we use present always (0 &&).
2852 if (0 && start <= 1) // Z39.50 piggyback
2854 *z_searchRequest->smallSetUpperBound = max;
2855 *z_searchRequest->mediumSetPresentNumber = max;
2856 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2858 z_searchRequest->preferredRecordSyntax =
2859 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2861 if (srw_req->recordSchema)
2863 z_searchRequest->smallSetElementSetNames =
2864 z_searchRequest->mediumSetElementSetNames =
2865 mk_esn_from_schema(m_s2z_odr_search,
2866 srw_req->recordSchema);
2869 else // Z39.50 present
2871 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2872 Z_APDU_presentRequest);
2873 Z_PresentRequest *z_presentRequest =
2874 m_s2z_present_apdu->u.presentRequest;
2875 *z_presentRequest->resultSetStartPoint = start;
2876 *z_presentRequest->numberOfRecordsRequested = max;
2877 z_presentRequest->preferredRecordSyntax =
2878 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2880 if (srw_req->recordSchema)
2882 z_presentRequest->recordComposition =
2883 (Z_RecordComposition *)
2884 odr_malloc(m_s2z_odr_search,
2885 sizeof(Z_RecordComposition));
2886 z_presentRequest->recordComposition->which =
2887 Z_RecordComp_simple;
2888 z_presentRequest->recordComposition->u.simple =
2889 mk_esn_from_schema(m_s2z_odr_search,
2890 srw_req->recordSchema);
2896 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2897 Z_APDU_initRequest);
2899 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2901 // prevent m_initRequest_apdu memory from being grabbed
2902 // in Yaz_Proxy::handle_incoming_Z_PDU
2903 m_initRequest_apdu = m_s2z_init_apdu;
2904 handle_incoming_Z_PDU(m_s2z_init_apdu);
2909 handle_incoming_Z_PDU(m_s2z_search_apdu);
2913 else if (srw_pdu->which == Z_SRW_explain_request)
2915 Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
2917 const char *backend_db = srw_req->database;
2918 srw_get_client(srw_req->database, &backend_db);
2920 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2923 if (srw_req->stylesheet)
2925 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2927 if (srw_req->recordPacking &&
2928 !strcmp(srw_req->recordPacking, "xml"))
2929 m_s2z_packing = Z_SRW_recordPacking_XML;
2931 m_s2z_packing = Z_SRW_recordPacking_string;
2935 send_srw_explain_response(diagnostic, num_diagnostic);
2941 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2942 Z_APDU_initRequest);
2944 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2946 // prevent m_initRequest_apdu memory from being grabbed
2947 // in Yaz_Proxy::handle_incoming_Z_PDU
2948 m_initRequest_apdu = m_s2z_init_apdu;
2949 handle_incoming_Z_PDU(m_s2z_init_apdu);
2952 send_srw_explain_response(0, 0);
2955 else if (srw_pdu->which == Z_SRW_scan_request)
2957 m_s2z_database = odr_strdup(m_s2z_odr_init,
2958 srw_pdu->u.scan_request->database);
2960 yaz_add_srw_diagnostic(odr_decode(),
2961 &diagnostic, &num_diagnostic,
2963 Z_SRW_PDU *srw_pdu =
2964 yaz_srw_get(odr_encode(),
2965 Z_SRW_scan_response);
2966 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
2968 srw_res->diagnostics = diagnostic;
2969 srw_res->num_diagnostics = num_diagnostic;
2970 send_srw_response(srw_pdu);
2977 send_to_srw_client_error(4, 0);
2980 send_http_response(400);
2983 void Yaz_Proxy::handle_init(Z_APDU *apdu)
2986 Z_OtherInformation **oi;
2987 get_otherInfoAPDU(apdu, &oi);
2989 if (apdu->u.initRequest->implementationId)
2990 yaz_log(YLOG_LOG, "%simplementationId: %s",
2991 m_session_str, apdu->u.initRequest->implementationId);
2992 if (apdu->u.initRequest->implementationName)
2993 yaz_log(YLOG_LOG, "%simplementationName: %s",
2994 m_session_str, apdu->u.initRequest->implementationName);
2995 if (apdu->u.initRequest->implementationVersion)
2996 yaz_log(YLOG_LOG, "%simplementationVersion: %s",
2997 m_session_str, apdu->u.initRequest->implementationVersion);
2998 if (m_initRequest_apdu == 0)
3000 if (m_initRequest_mem)
3001 nmem_destroy(m_initRequest_mem);
3003 m_initRequest_apdu = apdu;
3004 m_initRequest_mem = odr_extract_mem(odr_decode());
3006 m_initRequest_preferredMessageSize = *apdu->u.initRequest->
3007 preferredMessageSize;
3008 *apdu->u.initRequest->preferredMessageSize = 1024*1024;
3009 m_initRequest_maximumRecordSize = *apdu->u.initRequest->
3011 *apdu->u.initRequest->maximumRecordSize = 1024*1024;
3013 Z_CharSetandLanguageNegotiation *charSetandLangRecord =
3014 yaz_get_charneg_record(*oi);
3016 // Save proposal charsets and langs.
3017 if (ODR_MASK_GET(apdu->u.initRequest->options,
3018 Z_Options_negotiationModel)
3019 && charSetandLangRecord)
3022 yaz_get_proposal_charneg(m_referenceId_mem,
3023 charSetandLangRecord,
3024 &m_initRequest_oi_negotiation_charsets,
3025 &m_initRequest_oi_negotiation_num_charsets,
3026 &m_initRequest_oi_negotiation_langs,
3027 &m_initRequest_oi_negotiation_num_langs,
3028 &m_initRequest_oi_negotiation_selected);
3030 for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
3032 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
3033 m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
3034 m_initRequest_oi_negotiation_charsets[i]:"none");
3036 for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
3038 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
3039 m_session_str, (m_initRequest_oi_negotiation_langs[i])?
3040 m_initRequest_oi_negotiation_langs[i]:"none");
3042 yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
3043 m_session_str, m_initRequest_oi_negotiation_selected);
3045 // save init options for the response..
3046 m_initRequest_options = apdu->u.initRequest->options;
3048 apdu->u.initRequest->options =
3049 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3050 sizeof(Odr_bitmask));
3051 ODR_MASK_ZERO(apdu->u.initRequest->options);
3053 for (i = 0; i<= 24; i++)
3054 ODR_MASK_SET(apdu->u.initRequest->options, i);
3055 // check negotiation option
3056 if (!ODR_MASK_GET(m_initRequest_options,
3057 Z_Options_negotiationModel))
3059 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3060 Z_Options_negotiationModel);
3062 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3063 Z_Options_concurrentOperations);
3065 m_initRequest_version = apdu->u.initRequest->protocolVersion;
3066 apdu->u.initRequest->protocolVersion =
3067 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3068 sizeof(Odr_bitmask));
3069 ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
3071 for (i = 0; i<= 8; i++)
3072 ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
3074 handle_charset_lang_negotiation(apdu);
3075 if (m_client->m_init_flag)
3077 if (handle_init_response_for_invalid_session(apdu))
3079 if (m_client->m_initResponse)
3081 Z_APDU *apdu2 = m_client->m_initResponse;
3082 apdu2->u.initResponse->otherInfo = 0;
3083 if (m_client->m_cookie && *m_client->m_cookie)
3084 set_otherInformationString(apdu2, VAL_COOKIE, 1,
3085 m_client->m_cookie);
3086 apdu2->u.initResponse->referenceId =
3087 apdu->u.initRequest->referenceId;
3088 apdu2->u.initResponse->options = m_client->m_initResponse_options;
3089 apdu2->u.initResponse->protocolVersion =
3090 m_client->m_initResponse_version;
3092 handle_charset_lang_negotiation(apdu2);
3094 send_to_client(apdu2);
3095 m_timeout_mode = timeout_normal;
3099 m_client->m_init_flag = 1;
3102 Auth_Msg *m = new Auth_Msg;
3104 z_APDU(odr_encode(), &apdu, 0, "encode");
3105 char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
3106 m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
3107 memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
3108 odr_reset(odr_encode());
3111 m_my_thread->put(m);
3113 int ret = handle_authentication(apdu);
3114 result_authentication(apdu, ret);
3118 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
3120 Z_ReferenceId **refid = get_referenceIdP(apdu);
3121 nmem_reset(m_referenceId_mem);
3122 if (refid && *refid)
3124 m_referenceId = (Z_ReferenceId *)
3125 nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
3126 m_referenceId->len = m_referenceId->size = (*refid)->len;
3127 m_referenceId->buf = (unsigned char *)
3128 nmem_malloc(m_referenceId_mem, (*refid)->len);
3129 memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
3134 if (!m_client && m_flag_invalid_session)
3136 // Got request for a session that is invalid..
3137 m_apdu_invalid_session = apdu; // save package
3138 m_mem_invalid_session = odr_extract_mem(odr_decode());
3139 apdu = m_initRequest_apdu; // but throw an init to the target
3142 if (apdu->which == Z_APDU_searchRequest)
3143 m_search_stat.add_bytes(1);
3145 // Determine our client.
3146 Z_OtherInformation **oi;
3147 get_otherInfoAPDU(apdu, &oi);
3148 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
3152 { // HTTP. Send not found
3153 send_http_response(404);
3158 // Z39.50 just shutdown
3164 m_client->m_server = this;
3166 if (apdu->which == Z_APDU_initRequest)
3169 handle_incoming_Z_PDU_2(apdu);
3172 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
3174 handle_max_record_retrieve(apdu);
3177 apdu = handle_syntax_validation(apdu);
3180 apdu = handle_query_transformation(apdu);
3183 apdu = handle_target_charset_conversion(apdu);
3186 apdu = handle_query_validation(apdu);
3189 apdu = result_set_optimize(apdu);
3193 m_client->timeout(m_target_idletime); // mark it active even
3194 recv_GDU_more(true);
3195 // though we didn't use it
3199 // delete other info construct completely if 0 elements
3200 Z_OtherInformation **oi;
3201 get_otherInfoAPDU(apdu, &oi);
3202 if (oi && *oi && (*oi)->num_elements == 0)
3205 if (apdu->which == Z_APDU_presentRequest &&
3206 m_client->m_resultSetStartPoint == 0)
3208 Z_PresentRequest *pr = apdu->u.presentRequest;
3209 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3210 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3212 m_client->m_resultSetStartPoint = 0;
3214 if (m_client->send_to_target(apdu) < 0)
3216 m_client->shutdown();
3219 m_client->m_waiting = 1;
3222 void Yaz_Proxy::connectNotify()
3226 void Yaz_Proxy::releaseClient()
3228 xfree(m_proxyTarget);
3230 m_flag_invalid_session = 0;
3231 // only keep if keep_alive flag is set...
3233 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3234 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3235 m_client->m_waiting == 0)
3237 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3239 m_client->get_hostname());
3240 yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3241 m_session_str, m_client->m_pdu_recv,
3242 m_client->m_bytes_sent + m_client->m_bytes_recv,
3243 m_keepalive_limit_bw, m_keepalive_limit_pdu);
3244 assert (m_client->m_waiting != 2);
3245 // Tell client (if any) that no server connection is there..
3246 m_client->m_server = 0;
3251 yaz_log (YLOG_LOG, "%sShutdown (client to proxy) close %s",
3253 m_client->get_hostname());
3254 assert (m_client->m_waiting != 2);
3260 yaz_log (YLOG_LOG, "%sshutdown (client to proxy) bad state",
3266 yaz_log (YLOG_LOG, "%sShutdown (client to proxy)",
3270 m_parent->pre_init();
3273 bool Yaz_Proxy::dec_ref(bool main_ptr)
3276 assert(m_ref_count > 0);
3281 m_main_ptr_dec = true;
3284 m_http_keepalive = 0;
3287 if (m_ref_count > 0)
3296 const char *Yaz_ProxyClient::get_session_str()
3300 return m_server->get_session_str();
3303 void Yaz_ProxyClient::shutdown()
3305 yaz_log (YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
3310 m_waiting = 1; // ensure it's released from Yaz_Proxy::releaseClient
3311 m_server->dec_ref(true);
3317 void Yaz_Proxy::failNotify()
3320 yaz_log (YLOG_LOG, "%sConnection closed by client", get_session_str());
3324 void Yaz_Proxy::send_response_fail_client(const char *addr)
3328 Z_SRW_diagnostic *diagnostic = 0;
3329 int num_diagnostic = 0;
3331 yaz_add_srw_diagnostic(odr_encode(),
3332 &diagnostic, &num_diagnostic,
3333 YAZ_SRW_SYSTEM_TEMPORARILY_UNAVAILABLE, addr);
3334 if (m_s2z_search_apdu)
3335 send_srw_search_response(diagnostic, num_diagnostic);
3337 send_srw_explain_response(diagnostic, num_diagnostic);
3340 void Yaz_ProxyClient::failNotify()
3343 m_server->inc_request_no();
3344 yaz_log (YLOG_LOG, "%sConnection closed by target %s",
3345 get_session_str(), get_hostname());
3348 m_server->send_response_fail_client(get_hostname());
3352 void Yaz_ProxyClient::connectNotify()
3354 const char *s = get_session_str();
3355 const char *h = get_hostname();
3356 yaz_log (YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
3358 timeout(m_target_idletime);
3363 IPDU_Observer *Yaz_ProxyClient::sessionNotify(IPDU_Observable
3364 *the_PDU_Observable, int fd)
3366 return new Yaz_ProxyClient(the_PDU_Observable, 0);
3369 Yaz_ProxyClient::~Yaz_ProxyClient()
3374 m_next->m_prev = m_prev;
3375 m_waiting = 2; // for debugging purposes only.
3376 odr_destroy(m_init_odr);
3377 odr_destroy(m_idAuthentication_odr);
3378 delete m_last_query;
3379 xfree (m_last_resultSetId);
3383 void Yaz_ProxyClient::pre_init_client()
3385 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
3386 Z_InitRequest *req = apdu->u.initRequest;
3389 for (i = 0; i<= 24; i++)
3390 ODR_MASK_SET(req->options, i);
3391 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3392 Z_Options_negotiationModel);
3393 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3394 Z_Options_concurrentOperations);
3395 for (i = 0; i<= 10; i++)
3396 ODR_MASK_SET(req->protocolVersion, i);
3398 if (send_to_target(apdu) < 0)
3409 void Yaz_Proxy::pre_init()
3412 const char *name = 0;
3413 const char *zurl_in_use[MAX_ZURL_PLEX];
3414 int limit_bw, limit_pdu, limit_req, limit_search;
3415 int target_idletime, client_idletime;
3417 int keepalive_limit_bw, keepalive_limit_pdu;
3419 const char *cql2rpn = 0;
3420 const char *authentication = 0;
3421 const char *negotiation_charset = 0;
3422 const char *negotiation_lang = 0;
3424 Yaz_ProxyConfig *cfg = check_reconfigure();
3428 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
3433 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
3434 &limit_bw, &limit_pdu, &limit_req,
3436 &target_idletime, &client_idletime,
3438 &keepalive_limit_bw,
3439 &keepalive_limit_pdu,
3443 &negotiation_charset,
3451 for (j = 0; zurl_in_use[j]; j++)
3455 int spare_waiting = 0;
3458 for (c = m_clientPool; c; c = c->m_next)
3460 if (!strcmp(zurl_in_use[j], c->get_hostname()))
3462 if (c->m_cookie == 0)
3464 if (c->m_server == 0)
3476 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
3477 "sparew=%d preinit=%d",m_session_str,
3478 name, zurl_in_use[j], in_use, other,
3479 spare, spare_waiting, pre_init);
3480 if (spare + spare_waiting < pre_init)
3482 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
3483 c->m_next = m_clientPool;
3485 c->m_next->m_prev = &c->m_next;
3487 c->m_prev = &m_clientPool;
3489 if (m_log_mask & PROXY_LOG_APDU_SERVER)
3490 c->set_APDU_yazlog(1);
3492 c->set_APDU_yazlog(0);
3494 if (c->client(zurl_in_use[j]))
3502 c->m_target_idletime = target_idletime;
3503 c->m_seqno = m_seqno++;
3510 void Yaz_Proxy::timeoutNotify()
3515 switch(m_timeout_mode)
3517 case timeout_normal:
3521 yaz_log (YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
3524 case timeout_reduce:
3525 timeout(m_client_idletime);
3526 m_timeout_mode = timeout_busy;
3527 gdu = m_timeout_gdu;
3529 recv_GDU_normal(gdu);
3532 assert(m_stylesheet_nprl);
3533 convert_xsl_delay();
3534 recv_GDU_more(true);
3544 void Yaz_Proxy::markInvalid()
3547 m_flag_invalid_session = 1;
3550 void Yaz_ProxyClient::timeoutNotify()
3553 m_server->inc_request_no();
3555 yaz_log (YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
3559 m_server->send_response_fail_client(get_hostname());
3561 Yaz_Proxy *proxy_root = m_root;
3565 proxy_root->pre_init();
3568 Yaz_ProxyClient::Yaz_ProxyClient(IPDU_Observable *the_PDU_Observable,
3569 Yaz_Proxy *parent) :
3570 Z_Assoc (the_PDU_Observable)
3577 m_last_resultSetId = 0;
3578 m_last_resultCount = 0;
3582 m_init_odr = odr_createmem (ODR_DECODE);
3584 m_initResponse_options = 0;
3585 m_initResponse_version = 0;
3586 m_initResponse_preferredMessageSize = 0;
3587 m_initResponse_maximumRecordSize = 0;
3588 m_resultSetStartPoint = 0;
3589 m_bytes_sent = m_bytes_recv = 0;
3593 m_target_idletime = 600;
3595 m_idAuthentication_odr = odr_createmem(ODR_ENCODE);
3596 m_idAuthentication_ber_buf = 0;
3597 m_idAuthentication_ber_size = 0;
3600 const char *Yaz_Proxy::option(const char *name, const char *value)
3602 if (!strcmp (name, "optimize")) {
3605 m_optimize = xstrdup (value);
3612 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
3617 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
3619 if (apdu->which == Z_GDU_Z3950)
3620 recv_Z_PDU(apdu->u.z3950, len);
3621 else if (apdu->which == Z_GDU_HTTP_Response)
3622 recv_HTTP_response(apdu->u.HTTP_Response, len);
3627 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
3629 if (!m_flag_invalid_session)
3631 m_flag_invalid_session = 0;
3632 handle_incoming_Z_PDU(m_apdu_invalid_session);
3633 assert (m_mem_invalid_session);
3634 nmem_destroy(m_mem_invalid_session);
3635 m_mem_invalid_session = 0;
3639 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
3641 m_bytes_recv += len;
3645 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
3646 yaz_log (YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
3647 apdu_name(apdu), get_hostname(), len);
3648 if (apdu->which == Z_APDU_initResponse)
3650 if (!m_server) // if this is a pre init session , check for more
3652 NMEM nmem = odr_extract_mem (odr_decode());
3653 odr_reset (m_init_odr);
3654 nmem_transfer (m_init_odr->mem, nmem);
3655 m_initResponse = apdu;
3656 m_initResponse_options = apdu->u.initResponse->options;
3657 m_initResponse_version = apdu->u.initResponse->protocolVersion;
3658 m_initResponse_preferredMessageSize =
3659 *apdu->u.initResponse->preferredMessageSize;
3660 m_initResponse_maximumRecordSize =
3661 *apdu->u.initResponse->maximumRecordSize;
3663 Z_InitResponse *ir = apdu->u.initResponse;
3665 // apply YAZ Proxy version
3666 char *imv0 = ir->implementationVersion;
3667 char *imv1 = (char*)
3668 odr_malloc(m_init_odr, 20 + (imv0 ? strlen(imv0) : 0));
3672 strcat(imv1, "/" VERSION);
3673 ir->implementationVersion = imv1;
3675 // apply YAZ Proxy implementation name
3676 char *im0 = ir->implementationName;
3678 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
3685 strcat(im1, "(YAZ Proxy)");
3686 ir->implementationName = im1;
3688 nmem_destroy (nmem);
3690 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
3693 if (apdu->which == Z_APDU_searchResponse)
3695 Z_SearchResponse *sr = apdu->u.searchResponse;
3696 m_last_resultCount = *sr->resultCount;
3697 int status = *sr->searchStatus;
3698 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
3702 if (sr->records && sr->records->which == Z_Records_DBOSD)
3704 m_cache.add(odr_decode(),
3705 sr->records->u.databaseOrSurDiagnostics, 1,
3710 if (apdu->which == Z_APDU_presentResponse)
3712 Z_PresentResponse *pr = apdu->u.presentResponse;
3716 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
3717 Z_SearchResponse *sr = new_apdu->u.searchResponse;
3718 sr->referenceId = pr->referenceId;
3719 *sr->resultCount = m_last_resultCount;
3720 sr->records = pr->records;
3721 sr->nextResultSetPosition = pr->nextResultSetPosition;
3722 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
3726 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
3728 m_cache.add(odr_decode(),
3729 pr->records->u.databaseOrSurDiagnostics,
3730 m_resultSetStartPoint, -1);
3731 m_resultSetStartPoint = 0;
3735 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
3737 Yaz_Proxy *server = m_server; // save it. send_to_client may destroy us
3740 server->send_to_client(apdu);
3741 if (apdu->which == Z_APDU_close)
3744 server->recv_GDU_more(true);
3747 void Yaz_Proxy::low_socket_close()
3752 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3753 if (m_lo_fd[i] >= 0)
3754 ::close(m_lo_fd[i]);
3758 void Yaz_Proxy::low_socket_open()
3763 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3764 m_lo_fd[i] = open("/dev/null", O_RDONLY);
3768 int Yaz_Proxy::server(const char *addr)
3770 int r = Z_Assoc::server(addr);
3773 yaz_log(YLOG_LOG, "%sStarted proxy "
3777 " on %s", m_session_str, addr);
3783 void Yaz_Proxy::base64_decode(const char *base64, char *buf, int buf_len)
3785 const char *base64_chars =
3786 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3787 int len = strlen(base64);
3791 for (int pos = 0; pos <= len; pos++)
3793 if (base64[pos] == '=' || buf_pos + 1 >= buf_len)
3796 const char *ch_ptr = strchr(base64_chars, base64[pos]);
3799 char ch = (char) (ch_ptr - base64_chars);
3803 buf[buf_pos] = ch << 2;
3806 buf[buf_pos++] += (ch & 0x30) >> 4;
3807 buf[buf_pos] = (ch & 0x0f) << 4;
3810 buf[buf_pos++] += (ch & 0x3c) >> 2;
3811 buf[buf_pos] = (ch & 0x03) << 6;
3814 buf[buf_pos++] += ch;
3821 buf[buf_pos] = '\0';
3827 * indent-tabs-mode: nil
3829 * vim: shiftwidth=4 tabstop=8 expandtab