1 /* This file is part of YAZ proxy
2 Copyright (C) 1998-2009 Index Data
4 YAZ proxy is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
9 YAZ proxy is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 #define HAVE_SYS_STAT_H 1
21 #define HAVE_SYS_TYPES_H 1
31 #include <sys/types.h>
43 #include <yaz/marcdisp.h>
44 #include <yaz/yaz-iconv.h>
46 #include <yaz/diagbib1.h>
48 #include <yaz/pquery.h>
49 #include <yaz/otherinfo.h>
50 #include <yaz/charneg.h>
51 #include <yaz/oid_db.h>
52 #include "msg-thread.h"
54 #if YAZ_VERSIONL >= 0x03001D
55 #define YAZ_HAS_MK_SURROGATE 1
57 #define YAZ_HAS_MK_SURROGATE 0
60 using namespace yazpp_1;
63 #define strncasecmp _strnicmp
66 class YAZ_EXPORT Auth_Msg : public IMsg_Thread {
69 IMsg_Thread *handle();
81 m_nmem = nmem_create();
89 IMsg_Thread *Auth_Msg::handle()
91 ODR decode = odr_createmem(ODR_DECODE);
94 odr_setbuf(decode, m_apdu_buf, m_apdu_len, 0);
95 int r = z_APDU(decode, &apdu, 0, 0);
98 yaz_log(YLOG_WARN, "decode failed in Auth_Msg::handle");
102 m_ret = m_proxy->handle_authentication(apdu);
108 void Auth_Msg::result()
110 if (m_proxy->dec_ref())
112 yaz_log(YLOG_LOG, "Auth_Msg::proxy deleted meanwhile");
116 odr_setbuf(m_proxy->odr_decode(), m_apdu_buf, m_apdu_len, 0);
118 int r = z_APDU(m_proxy->odr_decode(), &apdu, 0, 0);
120 yaz_log(YLOG_LOG, "Auth_Msg::result z_APDU failed");
121 m_proxy->result_authentication(apdu, m_ret);
126 void Yaz_Proxy::result_authentication(Z_APDU *apdu, int ret)
128 if (apdu == 0 || ret == 0)
130 Z_APDU *apdu_reject = zget_APDU(odr_encode(), Z_APDU_initResponse);
131 *apdu_reject->u.initResponse->result = 0;
132 send_to_client(apdu_reject);
137 if (apdu->which == Z_APDU_initRequest)
139 Yaz_ProxyConfig *cfg = check_reconfigure();
141 cfg->target_authentication(m_default_target, odr_encode(),
142 apdu->u.initRequest);
144 handle_incoming_Z_PDU_2(apdu);
148 static const char *apdu_name(Z_APDU *apdu)
152 case Z_APDU_initRequest:
153 return "initRequest";
154 case Z_APDU_initResponse:
155 return "initResponse";
156 case Z_APDU_searchRequest:
157 return "searchRequest";
158 case Z_APDU_searchResponse:
159 return "searchResponse";
160 case Z_APDU_presentRequest:
161 return "presentRequest";
162 case Z_APDU_presentResponse:
163 return "presentResponse";
164 case Z_APDU_deleteResultSetRequest:
165 return "deleteResultSetRequest";
166 case Z_APDU_deleteResultSetResponse:
167 return "deleteResultSetResponse";
168 case Z_APDU_scanRequest:
169 return "scanRequest";
170 case Z_APDU_scanResponse:
171 return "scanResponse";
172 case Z_APDU_sortRequest:
173 return "sortRequest";
174 case Z_APDU_sortResponse:
175 return "sortResponse";
176 case Z_APDU_extendedServicesRequest:
177 return "extendedServicesRequest";
178 case Z_APDU_extendedServicesResponse:
179 return "extendedServicesResponse";
186 static const char *gdu_name(Z_GDU *gdu)
191 return apdu_name(gdu->u.z3950);
192 case Z_GDU_HTTP_Request:
193 return "HTTP Request";
194 case Z_GDU_HTTP_Response:
195 return "HTTP Response";
197 return "Unknown request/response";
200 Yaz_Proxy::Yaz_Proxy(IPDU_Observable *the_PDU_Observable,
201 ISocketObservable *the_socket_observable,
204 Z_Assoc(the_PDU_Observable),
205 m_bw_stat(60), m_pdu_stat(60), m_search_stat(60)
207 m_PDU_Observable = the_PDU_Observable;
208 m_socket_observable = the_socket_observable;
213 m_keepalive_limit_bw = 500000;
214 m_keepalive_limit_pdu = 1000;
216 m_default_target = 0;
217 m_proxy_negotiation_charset = 0;
218 m_proxy_negotiation_lang = 0;
219 m_proxy_negotiation_default_charset = 0;
220 m_charset_converter = new Yaz_CharsetConverter;
224 m_client_idletime = 600;
225 m_target_idletime = 600;
226 m_max_sockets = 1024;
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;
258 m_frontend_type[0] = -1;
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_num_msg_threads = 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,
364 m_connect.set_period(period);
369 void Yaz_Proxy::set_default_target(const char *target)
371 xfree(m_default_target);
372 m_default_target = 0;
374 m_default_target = (char *) xstrdup(target);
377 void Yaz_Proxy::set_proxy_negotiation(const char *charset, const char *lang,
378 const char *default_charset)
380 yaz_log(YLOG_DEBUG, "%sSet the proxy negotiation: charset to '%s', "
381 "default charset to '%s', language to '%s'", m_session_str,
382 charset?charset:"none",
383 default_charset?default_charset:"none",
385 xfree(m_proxy_negotiation_charset);
386 xfree(m_proxy_negotiation_lang);
387 m_proxy_negotiation_charset = m_proxy_negotiation_lang = 0;
389 m_proxy_negotiation_charset = (char *) xstrdup(charset);
391 m_proxy_negotiation_lang = (char *) xstrdup(lang);
393 m_proxy_negotiation_default_charset =
394 (char *) xstrdup(default_charset);
397 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
400 return m_parent->check_reconfigure();
402 Yaz_ProxyConfig *cfg = m_config;
405 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,
418 &period, &m_num_msg_threads);
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();
437 peername = "nullpeer";
439 if (m_log_mask & PROXY_LOG_IP_CLIENT)
440 sprintf(session_str, "%ld:%d %.80s %d ",
441 (long) time(0), m_session_no, peername, 0);
443 sprintf(session_str, "%ld:%d %d ",
444 (long) time(0), m_session_no, 0);
447 yaz_log(YLOG_LOG, "%sNew session %s", session_str, peername);
449 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable,
450 m_socket_observable, this);
452 new_proxy->m_config = 0;
453 new_proxy->m_config_fname = 0;
454 new_proxy->timeout(m_client_idletime);
455 new_proxy->m_target_idletime = m_target_idletime;
456 new_proxy->set_default_target(m_default_target);
457 new_proxy->m_max_clients = m_max_clients;
458 new_proxy->m_log_mask = m_log_mask;
459 new_proxy->m_session_no = m_session_no;
460 new_proxy->m_num_msg_threads = m_num_msg_threads;
463 // in case we want to watch a particular client..
464 if (!strcmp(peername, "tcp:163.121.19.82")) // NIS GROUP
465 new_proxy->m_log_mask = 255;
468 new_proxy->set_APDU_log(get_APDU_log());
469 if (new_proxy->m_log_mask & PROXY_LOG_APDU_CLIENT)
470 new_proxy->set_APDU_yazlog(1);
472 new_proxy->set_APDU_yazlog(0);
473 strcpy(new_proxy->m_session_str, session_str);
474 new_proxy->m_peername = xstrdup(peername);
475 new_proxy->set_proxy_negotiation(m_proxy_negotiation_charset,
476 m_proxy_negotiation_lang, m_proxy_negotiation_default_charset);
477 // create thread object the first time we get an incoming connection
478 if (!m_my_thread && m_num_msg_threads > 0)
480 yaz_log(YLOG_LOG, "%sStarting message thread management. number=%d",
481 session_str, m_num_msg_threads);
482 m_my_thread = new Msg_Thread(m_socket_observable, m_num_msg_threads);
484 new_proxy->m_my_thread = m_my_thread;
488 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
490 Z_OtherInformationUnit *oi =
491 update_otherInformation(otherInfo, 0, yaz_oid_userinfo_cookie, 1, 1);
493 if (oi && oi->which == Z_OtherInfo_characterInfo)
494 return oi->information.characterInfo;
498 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
500 Z_OtherInformationUnit *oi =
501 update_otherInformation(otherInfo, 0, yaz_oid_userinfo_proxy, 1, 1);
503 if (oi && oi->which == Z_OtherInfo_characterInfo)
504 return oi->information.characterInfo;
507 const char *Yaz_Proxy::load_balance(const char **url)
509 int zurl_in_use[MAX_ZURL_PLEX];
510 int zurl_in_spare[MAX_ZURL_PLEX];
514 for (i = 0; i<MAX_ZURL_PLEX; i++)
517 zurl_in_spare[i] = 0;
519 for (c = m_parent->m_clientPool; c; c = c->m_next)
521 for (i = 0; url[i]; i++)
522 if (!strcmp(url[i], c->get_hostname()))
525 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
529 int min_use = 100000;
530 int spare_for_min = 0;
532 const char *ret_min = 0;
533 const char *ret_spare = 0;
534 for (i = 0; url[i]; i++)
536 yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
537 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
538 if (min_use > zurl_in_use[i])
541 min_use = zurl_in_use[i];
542 spare_for_min = zurl_in_spare[i];
544 if (max_spare < zurl_in_spare[i])
547 max_spare = zurl_in_spare[i];
553 int Yaz_Proxy::get_number_of_connections()
555 int no_connections = 0;
558 for (c = m_parent->m_clientPool; c; c = c->m_next)
561 assert(*c->m_prev == c);
562 if (!strcmp(m_proxyTarget, c->get_hostname()))
567 yaz_log(YLOG_LOG, "%sExisting %s connections: %d", m_session_str, m_proxyTarget,
569 return no_connections;
572 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
573 const char *proxy_host, int *http_code)
576 Yaz_Proxy *parent = m_parent;
577 Yaz_ProxyClient *c = m_client;
581 const char *url[MAX_ZURL_PLEX];
582 Yaz_ProxyConfig *cfg = check_reconfigure();
585 if (parent && parent->m_debug_mode)
587 // only to be enabled for debugging...
588 if (!strcmp(proxy_host, "stop"))
591 xfree(m_default_target);
592 m_default_target = xstrdup(proxy_host);
594 proxy_host = m_default_target;
595 int client_idletime = -1;
596 const char *cql2rpn_fname = 0;
597 const char *negotiation_charset = 0;
598 const char *negotiation_lang = 0;
599 const char *query_charset = 0;
600 const char *default_client_query_charset = 0;
601 url[0] = m_default_target;
606 cfg->get_target_info(proxy_host, url, &m_bw_max,
607 &m_pdu_max, &m_max_record_retrieve,
609 &m_target_idletime, &client_idletime,
611 &parent->m_max_clients,
612 &m_keepalive_limit_bw,
613 &m_keepalive_limit_pdu,
616 &negotiation_charset,
619 &default_client_query_charset);
621 if (client_idletime != -1)
623 m_client_idletime = client_idletime;
624 timeout(m_client_idletime);
627 // get those FILE descriptors available
628 m_parent->low_socket_close();
630 m_cql2rpn.set_pqf_file(cql2rpn_fname);
631 // reserve them again
632 m_parent->low_socket_open();
634 if (negotiation_charset || negotiation_lang || default_client_query_charset)
636 set_proxy_negotiation(negotiation_charset,
637 negotiation_lang, default_client_query_charset);
639 m_charset_converter->set_target_query_charset(query_charset);
642 yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
645 // we don't handle multiplexing for cookie session, so we just
646 // pick the first one in this case (anonymous users will be able
647 // to use any backend)
648 if (cookie && *cookie)
649 m_proxyTarget = (char*) xstrdup(url[0]);
651 m_proxyTarget = (char*) xstrdup(load_balance(url));
653 if (cookie && *cookie)
654 { // search in sessions with a cookie
655 for (c = parent->m_clientPool; c; c = c->m_next)
658 assert(*c->m_prev == c);
659 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
660 !strcmp(m_proxyTarget, c->get_hostname()))
663 // The following handles "cancel"
664 // If connection is busy (waiting for PDU) and
665 // we have an initRequest we can safely do re-open
666 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
668 yaz_log(YLOG_LOG, "%s REOPEN target=%s", m_session_str,
675 c->m_last_resultCount = 0;
676 c->m_sr_transform = 0;
678 c->m_resultSetStartPoint = 0;
679 c->m_target_idletime = m_target_idletime;
680 if (c->client(m_proxyTarget))
687 c->m_seqno = parent->m_seqno;
688 if (c->m_server && c->m_server != this)
689 c->m_server->m_client = 0;
692 yaz_log(YLOG_DEBUG, "get_client 1 %p %p", this, c);
697 else if (!c && apdu->which == Z_APDU_initRequest )
699 // anonymous sessions without cookie.
700 // if authentication is set it is NOT anonymous se we can't share them.
701 // If charset and lang negotiation is use it is NOT anonymous session too.
702 for (c = parent->m_clientPool; c; c = c->m_next)
705 assert(*c->m_prev == c);
706 if (c->m_server == 0 && c->m_cookie == 0 && c->m_waiting == 0
707 && c->compare_idAuthentication(apdu)
708 && c->compare_charset(apdu)
709 && !strcmp(m_proxyTarget, c->get_hostname()))
712 yaz_log(YLOG_LOG, "%sREUSE %d %s",
713 m_session_str, parent->m_seqno, c->get_hostname());
715 c->m_seqno = parent->m_seqno;
716 assert(c->m_server == 0);
719 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
720 c->set_APDU_yazlog(1);
722 c->set_APDU_yazlog(0);
734 if (apdu->which != Z_APDU_initRequest)
736 yaz_log(YLOG_LOG, "%sno init request as first PDU", m_session_str);
741 int no_in_use = get_number_of_connections();
742 if (no_in_use >= m_max_sockets)
744 yaz_log(YLOG_LOG, "%smax sockets reached %d", m_session_str,
749 // go through list of clients - and find the lowest/oldest one.
750 Yaz_ProxyClient *c_min = 0;
752 int no_of_clients = 0;
753 if (parent->m_clientPool)
754 yaz_log(YLOG_DEBUG, "Existing sessions");
755 for (c = parent->m_clientPool; c; c = c->m_next)
757 yaz_log(YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
758 c->m_waiting, c->get_hostname(),
759 c->m_cookie ? c->m_cookie : "");
761 if (min_seq < 0 || c->m_seqno < min_seq)
763 min_seq = c->m_seqno;
767 if (no_of_clients >= parent->m_max_clients)
770 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
772 yaz_log(YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
773 m_session_str, parent->m_max_clients, c->m_seqno);
774 if (c->m_server && c->m_server != this)
775 c->m_server->dec_ref();
779 yaz_log(YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
780 m_session_str, parent->m_max_clients,
781 c->m_seqno, parent->m_seqno, c->get_hostname());
785 c->m_cookie = xstrdup(cookie);
786 c->m_seqno = parent->m_seqno;
787 if (c->m_server && c->m_server != this)
789 c->m_server->m_client = 0;
790 c->m_server->dec_ref();
793 c->m_target_idletime = m_target_idletime;
794 c->timeout(m_target_idletime);
796 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
797 c->set_APDU_yazlog(1);
799 c->set_APDU_yazlog(0);
807 yaz_log(YLOG_LOG, "%sNEW %d %s",
808 m_session_str, parent->m_seqno, m_proxyTarget);
809 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
810 c->m_next = parent->m_clientPool;
812 c->m_next->m_prev = &c->m_next;
813 parent->m_clientPool = c;
814 c->m_prev = &parent->m_clientPool;
820 c->m_cookie = xstrdup(cookie);
822 c->m_seqno = parent->m_seqno;
824 c->m_last_resultCount = 0;
827 c->m_sr_transform = 0;
829 c->m_resultSetStartPoint = 0;
831 if (c->client(m_proxyTarget))
836 c->m_target_idletime = m_target_idletime;
839 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
840 c->set_APDU_yazlog(1);
842 c->set_APDU_yazlog(0);
844 c->set_idAuthentication(apdu);
846 yaz_log(YLOG_DEBUG, "get_client 3 %p %p", this, c);
850 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
853 for (i = 0; i<num; i++)
855 Z_DefaultDiagFormat *r;
856 Z_DiagRec *p = pp[i];
857 if (p->which != Z_DiagRec_defaultFormat)
859 yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
863 r = p->u.defaultFormat;
866 case Z_DefaultDiagFormat_v2Addinfo:
867 yaz_log(YLOG_LOG, "%sError %d %s:%s",
869 *r->condition, diagbib1_str(*r->condition),
872 case Z_DefaultDiagFormat_v3Addinfo:
873 yaz_log(YLOG_LOG, "%sError %d %s:%s",
875 *r->condition, diagbib1_str(*r->condition),
882 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
884 if (!m_stylesheet_xsp || p->num_records <= 0)
886 return 0; /* no XSLT to be done ... */
889 m_stylesheet_offset = 0;
890 m_stylesheet_nprl = p;
891 m_stylesheet_apdu = apdu;
892 m_timeout_mode = timeout_xsl;
898 void Yaz_Proxy::convert_xsl_delay()
901 Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
902 if (npr->which == Z_NamePlusRecord_databaseRecord)
904 Z_External *r = npr->u.databaseRecord;
905 if (r->which == Z_External_octet)
908 fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
910 xmlDocPtr res, doc = xmlParseMemory(
911 (char*) r->u.octet_aligned->buf,
912 r->u.octet_aligned->len);
915 yaz_log(YLOG_LOG, "%sXSLT convert %d",
916 m_session_str, m_stylesheet_offset);
917 res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
924 xmlDocDumpFormatMemory(res, &out_buf, &out_len, 1);
925 m_stylesheet_nprl->records[m_stylesheet_offset]->
927 z_ext_record_oid(odr_encode(), yaz_oid_recsyn_xml,
928 (char*) out_buf, out_len);
937 m_stylesheet_offset++;
938 if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
940 m_timeout_mode = timeout_normal;
941 m_stylesheet_nprl = 0;
943 if (m_stylesheet_xsp)
944 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
946 m_stylesheet_xsp = 0;
947 timeout(m_client_idletime);
948 send_PDU_convert(m_stylesheet_apdu);
954 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
956 if (m_frontend_type[0] != -1)
959 for (i = 0; i < p->num_records; i++)
961 Z_NamePlusRecord *npr = p->records[i];
962 if (npr->which == Z_NamePlusRecord_databaseRecord)
964 Z_External *r = npr->u.databaseRecord;
965 if (r->which == Z_External_octet)
968 if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
969 yaz_log(YLOG_LOG, "%sError: USEMARCON requested but not available",
973 yaz_log(YLOG_DEBUG, "%sUSEMARCON stage1=%s stage2=%s",
975 m_usemarcon_ini_stage1 ? m_usemarcon_ini_stage1 : "(none)",
976 m_usemarcon_ini_stage2 ? m_usemarcon_ini_stage2 : "(none)");
979 if (m_usemarcon->convert(m_usemarcon_ini_stage1, m_usemarcon_ini_stage2,
980 (char*) r->u.octet_aligned->buf, r->u.octet_aligned->len,
981 &converted, &convlen))
983 npr->u.databaseRecord =
984 z_ext_record_oid(odr_encode(),
993 npr->u.databaseRecord =
994 z_ext_record_oid(odr_encode(),
996 (char*) r->u.octet_aligned->buf,
997 r->u.octet_aligned->len);
1004 void Yaz_Proxy::convert_records_charset(Z_NamePlusRecordList *p,
1005 const char *backend_charset)
1007 int sel = m_charset_converter->get_client_charset_selected();
1008 const char *client_record_charset =
1009 m_charset_converter->get_client_query_charset();
1010 if (sel && backend_charset && client_record_charset &&
1011 strcmp(backend_charset, client_record_charset))
1014 yaz_iconv_t cd = yaz_iconv_open(client_record_charset,
1016 yaz_marc_t mt = yaz_marc_create();
1017 yaz_marc_xml(mt, YAZ_MARC_ISO2709);
1018 yaz_marc_iconv(mt, cd);
1019 for (i = 0; i < p->num_records; i++)
1021 Z_NamePlusRecord *npr = p->records[i];
1022 if (npr->which == Z_NamePlusRecord_databaseRecord)
1024 Z_External *r = npr->u.databaseRecord;
1025 const Odr_oid *oid = r->direct_reference;
1029 if (!oid_oidcmp(oid, yaz_oid_recsyn_sutrs))
1031 WRBUF w = wrbuf_alloc();
1033 wrbuf_iconv_write(w, cd, (char*) r->u.octet_aligned->buf,
1034 r->u.octet_aligned->len);
1035 npr->u.databaseRecord =
1036 z_ext_record_oid(odr_encode(), oid, wrbuf_buf(w),
1040 else if (!oid_oidcmp(oid, yaz_oid_recsyn_xml))
1044 else if (r->which == Z_External_octet)
1048 if (yaz_marc_decode_buf(mt,
1049 (char*) r->u.octet_aligned->buf,
1050 r->u.octet_aligned->len,
1053 npr->u.databaseRecord =
1054 z_ext_record_oid(odr_encode(), oid, result, rlen);
1055 yaz_log(YLOG_LOG, "%sRecoding MARC record",
1062 yaz_iconv_close(cd);
1063 yaz_marc_destroy(mt);
1067 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
1068 const char *backend_charset)
1071 if (!backend_charset)
1072 backend_charset = "MARC-8";
1073 yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
1074 yaz_marc_t mt = yaz_marc_create();
1075 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1076 yaz_marc_iconv(mt, cd);
1077 for (i = 0; i < p->num_records; i++)
1079 Z_NamePlusRecord *npr = p->records[i];
1080 if (npr->which == Z_NamePlusRecord_databaseRecord)
1082 Z_External *r = npr->u.databaseRecord;
1083 if (r->which == Z_External_OPAC)
1085 WRBUF w = wrbuf_alloc();
1087 yaz_opac_decode_wrbuf(mt, r->u.opac, w);
1088 npr->u.databaseRecord = z_ext_record_oid(
1089 odr_encode(), yaz_oid_recsyn_xml,
1090 wrbuf_buf(w), wrbuf_len(w));
1093 else if (r->which == Z_External_octet)
1097 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
1098 r->u.octet_aligned->len,
1101 npr->u.databaseRecord =
1102 z_ext_record_oid(odr_encode(), yaz_oid_recsyn_xml,
1109 yaz_iconv_close(cd);
1110 yaz_marc_destroy(mt);
1113 void Yaz_Proxy::logtime()
1115 #if HAVE_GETTIMEOFDAY
1116 struct timeval *tv = (struct timeval*) m_time_tv;
1120 gettimeofday(&tv1, 0);
1121 long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
1122 (tv1.tv_usec - tv->tv_usec);
1124 yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
1125 diff/1000000, (diff/1000)%1000);
1132 int Yaz_Proxy::send_http_response(int code)
1134 ODR o = odr_encode();
1135 Z_GDU *gdu = z_get_HTTP_Response(o, code);
1136 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1138 hres->version = odr_strdup(o, m_http_version);
1139 if (m_http_keepalive)
1140 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1144 z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate",
1145 "Basic realm=\"YAZ Proxy\"");
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 { (char*) "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 #if YAZ_HAS_MK_SURROGATE
1242 static void yazproxy_mk_sru_surrogate(ODR o, Z_SRW_record *record, int pos,
1243 int code, const char *details)
1245 const char *message = yaz_diag_srw_str(code);
1248 len += strlen(message);
1250 len += strlen(details);
1252 record->recordData_buf = (char *) odr_malloc(o, len);
1254 sprintf(record->recordData_buf, "<diagnostic "
1255 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
1256 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
1258 sprintf(record->recordData_buf + strlen(record->recordData_buf),
1259 " <details>%s</details>\n", details);
1261 sprintf(record->recordData_buf + strlen(record->recordData_buf),
1262 " <message>%s</message>\n", message);
1263 sprintf(record->recordData_buf + strlen(record->recordData_buf),
1265 record->recordData_len = strlen(record->recordData_buf);
1266 record->recordPosition = odr_intdup(o, pos);
1267 record->recordSchema = odr_strdup(o, "info:srw/schema/1/diagnostics-v1.1");
1271 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
1273 ODR o = odr_encode();
1274 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1275 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1277 srw_res->numberOfRecords = odr_intdup (o, hits);
1278 if (records && records->which == Z_Records_DBOSD)
1280 srw_res->num_records =
1281 records->u.databaseOrSurDiagnostics->num_records;
1283 srw_res->records = (Z_SRW_record *)
1284 odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
1285 for (i = 0; i < srw_res->num_records; i++)
1287 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
1288 if (npr->which != Z_NamePlusRecord_databaseRecord)
1290 #if YAZ_HAS_MK_SURROGATE
1291 yaz_mk_sru_surrogate(
1292 o, srw_res->records + i, i+start,
1293 YAZ_SRW_RECORD_NOT_AVAILABLE_IN_THIS_SCHEMA, 0);
1295 yazproxy_mk_sru_surrogate(
1296 o, srw_res->records + i, i+start,
1297 YAZ_SRW_RECORD_NOT_AVAILABLE_IN_THIS_SCHEMA, 0);
1301 Z_External *r = npr->u.databaseRecord;
1303 if (r->which == Z_External_octet
1304 && !oid_oidcmp(r->direct_reference, yaz_oid_recsyn_xml))
1306 srw_res->records[i].recordSchema = m_schema;
1307 srw_res->records[i].recordPacking = m_s2z_packing;
1308 srw_res->records[i].recordData_buf = (char*)
1309 r->u.octet_aligned->buf;
1310 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1311 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1315 #if YAZ_HAS_MK_SURROGATE
1316 yaz_mk_sru_surrogate(
1317 o, srw_res->records + i, i+start,
1318 YAZ_SRW_RECORD_NOT_AVAILABLE_IN_THIS_SCHEMA, 0);
1320 yazproxy_mk_sru_surrogate(
1321 o, srw_res->records + i, i+start,
1322 YAZ_SRW_RECORD_NOT_AVAILABLE_IN_THIS_SCHEMA, 0);
1327 if (records && records->which == Z_Records_NSD)
1330 http_code = z_to_srw_diag(odr_encode(), srw_res,
1331 records->u.nonSurrogateDiagnostic);
1333 return send_http_response(http_code);
1335 return send_srw_response(srw_pdu);
1339 int Yaz_Proxy::send_srw_search_response(Z_SRW_diagnostic *diagnostics,
1340 int num_diagnostics, int http_code /* = 200 */)
1342 ODR o = odr_encode();
1343 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1344 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1346 srw_res->num_diagnostics = num_diagnostics;
1347 srw_res->diagnostics = diagnostics;
1348 return send_srw_response(srw_pdu, http_code);
1351 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1352 int num_diagnostics)
1354 int http_status = 404;
1355 Yaz_ProxyConfig *cfg = check_reconfigure();
1359 char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1360 m_s2z_database, &len, &http_status);
1363 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1364 Z_SRW_explainResponse *er = res->u.explain_response;
1366 er->record.recordData_buf = b;
1367 er->record.recordData_len = len;
1368 er->record.recordPacking = m_s2z_packing;
1369 er->record.recordSchema = odr_strdup(odr_encode(),
1370 "http://explain.z3950.org/dtd/2.0/");
1372 er->diagnostics = diagnostics;
1373 er->num_diagnostics = num_diagnostics;
1374 return send_srw_response(res);
1377 return send_http_response(http_status);
1380 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1384 if (apdu->which == Z_APDU_initResponse)
1386 Z_InitResponse *res = apdu->u.initResponse;
1387 if (*res->result == 0)
1389 send_to_srw_client_error(3, 0);
1391 else if (!m_s2z_search_apdu)
1393 send_srw_explain_response(0, 0);
1397 handle_incoming_Z_PDU(m_s2z_search_apdu);
1400 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1402 m_s2z_search_apdu = 0;
1403 Z_SearchResponse *res = apdu->u.searchResponse;
1404 m_s2z_hit_count = *res->resultCount;
1405 if (res->records && res->records->which == Z_Records_NSD)
1407 send_to_srw_client_ok(0, res->records, 1);
1409 else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1412 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1414 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1416 if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1418 *pr->numberOfRecordsRequested =
1419 1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1421 handle_incoming_Z_PDU(m_s2z_present_apdu);
1425 m_s2z_present_apdu = 0;
1426 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1429 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1432 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1434 m_s2z_present_apdu = 0;
1435 Z_PresentResponse *res = apdu->u.presentResponse;
1436 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1442 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1443 yaz_log(YLOG_LOG, "%sSending %s to client", m_session_str,
1445 int r = send_Z_PDU(apdu, &len);
1446 m_bytes_sent += len;
1447 m_bw_stat.add_bytes(len);
1454 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1456 int kill_session = 0;
1457 Z_ReferenceId **new_id = get_referenceIdP(apdu);
1460 *new_id = m_referenceId;
1462 if (apdu->which == Z_APDU_searchResponse)
1464 Z_SearchResponse *sr = apdu->u.searchResponse;
1465 Z_Records *p = sr->records;
1466 if (p && p->which == Z_Records_NSD)
1468 Z_DiagRec dr, *dr_p = &dr;
1469 dr.which = Z_DiagRec_defaultFormat;
1470 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1472 *sr->searchStatus = 0;
1473 display_diagrecs(&dr_p, 1);
1477 if (p && p->which == Z_Records_DBOSD)
1481 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1484 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1485 if (m_marcxml_mode == marcxml)
1486 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1489 convert_records_charset(p->u.databaseOrSurDiagnostics,
1491 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1495 if (sr->resultCount)
1497 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1499 if (*sr->resultCount < 0)
1501 m_flag_invalid_session = 1;
1504 *sr->searchStatus = 0;
1506 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1507 *sr->resultCount = 0;
1512 else if (apdu->which == Z_APDU_presentResponse)
1514 Z_PresentResponse *sr = apdu->u.presentResponse;
1515 Z_Records *p = sr->records;
1516 if (p && p->which == Z_Records_NSD)
1518 Z_DiagRec dr, *dr_p = &dr;
1519 dr.which = Z_DiagRec_defaultFormat;
1520 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1521 if (*sr->presentStatus == Z_PresentStatus_success)
1522 *sr->presentStatus = Z_PresentStatus_failure;
1523 display_diagrecs(&dr_p, 1);
1525 if (p && p->which == Z_Records_DBOSD)
1529 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1532 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1533 if (m_marcxml_mode == marcxml)
1534 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1537 convert_records_charset(p->u.databaseOrSurDiagnostics,
1539 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1543 else if (apdu->which == Z_APDU_initResponse)
1545 //Get and check negotiation record
1546 //from init response.
1547 handle_charset_lang_negotiation(apdu);
1549 if (m_initRequest_options)
1552 (Odr_bitmask *)odr_malloc(odr_encode(),
1553 sizeof(Odr_bitmask));
1554 ODR_MASK_ZERO(nopt);
1557 for (i = 0; i<24; i++)
1558 if (ODR_MASK_GET(m_initRequest_options, i) &&
1559 ODR_MASK_GET(apdu->u.initResponse->options, i))
1560 ODR_MASK_SET(nopt, i);
1561 apdu->u.initResponse->options = nopt;
1563 if (m_initRequest_version)
1565 Z_ProtocolVersion *nopt =
1566 (Odr_bitmask *)odr_malloc(odr_encode(),
1567 sizeof(Odr_bitmask));
1568 ODR_MASK_ZERO(nopt);
1571 for (i = 0; i<8; i++)
1572 if (ODR_MASK_GET(m_initRequest_version, i) &&
1573 ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1574 ODR_MASK_SET(nopt, i);
1575 apdu->u.initResponse->protocolVersion = nopt;
1577 apdu->u.initResponse->preferredMessageSize =
1578 odr_intdup(odr_encode(),
1579 m_client->m_initResponse_preferredMessageSize >
1580 m_initRequest_preferredMessageSize ?
1581 m_initRequest_preferredMessageSize :
1582 m_client->m_initResponse_preferredMessageSize);
1583 apdu->u.initResponse->maximumRecordSize =
1584 odr_intdup(odr_encode(),
1585 m_client->m_initResponse_maximumRecordSize >
1586 m_initRequest_maximumRecordSize ?
1587 m_initRequest_maximumRecordSize :
1588 m_client->m_initResponse_maximumRecordSize);
1591 int r = send_PDU_convert(apdu);
1598 m_parent->pre_init();
1603 void Yaz_ProxyClient::set_idAuthentication(Z_APDU *apdu)
1605 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1607 odr_reset(m_idAuthentication_odr);
1608 z_IdAuthentication(m_idAuthentication_odr, &t, 1, 0);
1609 m_idAuthentication_ber_buf =
1610 odr_getbuf(m_idAuthentication_odr,
1611 &m_idAuthentication_ber_size, 0);
1614 bool Yaz_ProxyClient::compare_charset(Z_APDU *apdu)
1619 bool Yaz_ProxyClient::compare_idAuthentication(Z_APDU *apdu)
1621 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1622 ODR odr = odr_createmem(ODR_ENCODE);
1624 z_IdAuthentication(odr, &t, 1, 0);
1626 char *buf = odr_getbuf(odr, &sz, 0);
1627 if (buf && m_idAuthentication_ber_buf
1628 && sz == m_idAuthentication_ber_size
1629 && !memcmp(m_idAuthentication_ber_buf, buf, sz))
1635 if (!buf && !m_idAuthentication_ber_buf)
1640 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1643 const char *apdu_name_tmp = apdu_name(apdu);
1644 int r = send_Z_PDU(apdu, &len);
1645 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1646 yaz_log(YLOG_LOG, "%sSending %s to %s %d bytes",
1648 apdu_name_tmp, get_hostname(), len);
1649 m_bytes_sent += len;
1653 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1655 if (apdu->which == Z_APDU_presentRequest)
1657 Z_PresentRequest *pr = apdu->u.presentRequest;
1658 int toget = *pr->numberOfRecordsRequested;
1659 int start = *pr->resultSetStartPoint;
1661 yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1662 pr->resultSetId, start, toget);
1664 if (*m_parent->m_optimize == '0')
1667 if (!m_client->m_last_resultSetId)
1669 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1670 new_apdu->u.presentResponse->records =
1671 create_nonSurrogateDiagnostics(
1673 YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1675 send_to_client(new_apdu);
1678 if (start < 1 || toget < 0)
1680 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1681 new_apdu->u.presentResponse->records =
1682 create_nonSurrogateDiagnostics(
1684 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1686 send_to_client(new_apdu);
1689 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1691 if (start+toget-1 > m_client->m_last_resultCount)
1693 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1694 new_apdu->u.presentResponse->records =
1695 create_nonSurrogateDiagnostics(
1697 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1699 send_to_client(new_apdu);
1702 Z_NamePlusRecordList *npr;
1704 yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1705 m_session_str, start, toget, yaz_z3950oid_to_str(
1706 pr->preferredRecordSyntax, &oclass));
1708 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1709 pr->preferredRecordSyntax,
1710 pr->recordComposition))
1712 yaz_log(YLOG_LOG, "%sReturned cached records for present request",
1714 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1715 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1717 new_apdu->u.presentResponse->numberOfRecordsReturned
1718 = odr_intdup(odr_encode(), toget);
1720 new_apdu->u.presentResponse->records = (Z_Records*)
1721 odr_malloc(odr_encode(), sizeof(Z_Records));
1722 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1723 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1724 new_apdu->u.presentResponse->nextResultSetPosition =
1725 odr_intdup(odr_encode(), start+toget);
1727 send_to_client(new_apdu);
1733 if (apdu->which != Z_APDU_searchRequest)
1735 Z_SearchRequest *sr = apdu->u.searchRequest;
1736 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1737 Yaz_Z_Databases this_databases;
1739 this_databases.set(sr->num_databaseNames, (const char **)
1742 this_query->set_Z_Query(sr->query);
1744 // Check for non-negative piggyback params.
1745 if (*sr->smallSetUpperBound < 0
1746 || *sr->largeSetLowerBound < 0
1747 || *sr->mediumSetPresentNumber < 0)
1749 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1750 // Not a present request.. But can't find better diagnostic
1751 new_apdu->u.searchResponse->records =
1752 create_nonSurrogateDiagnostics(
1754 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 0);
1755 send_to_client(new_apdu);
1759 char query_str[4096];
1760 this_query->print(query_str, sizeof(query_str)-1);
1761 yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1763 if (*m_parent->m_optimize != '0' &&
1764 m_client->m_last_ok && m_client->m_last_query &&
1765 m_client->m_last_query->match(this_query) &&
1766 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1767 m_client->m_last_databases.match(this_databases))
1770 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1771 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1773 Z_NamePlusRecordList *npr;
1774 int toget = *sr->mediumSetPresentNumber;
1775 Z_RecordComposition *comp = 0;
1777 if (toget > m_client->m_last_resultCount)
1778 toget = m_client->m_last_resultCount;
1780 if (sr->mediumSetElementSetNames)
1782 comp = (Z_RecordComposition *)
1783 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1784 comp->which = Z_RecordComp_simple;
1785 comp->u.simple = sr->mediumSetElementSetNames;
1788 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1789 sr->preferredRecordSyntax, comp))
1791 yaz_log(YLOG_LOG, "%sReturned cached records for medium set",
1793 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1794 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1795 new_apdu->u.searchResponse->resultCount =
1796 &m_client->m_last_resultCount;
1798 new_apdu->u.searchResponse->numberOfRecordsReturned
1799 = odr_intdup(odr_encode(), toget);
1801 new_apdu->u.searchResponse->presentStatus =
1802 odr_intdup(odr_encode(), Z_PresentStatus_success);
1803 new_apdu->u.searchResponse->records = (Z_Records*)
1804 odr_malloc(odr_encode(), sizeof(Z_Records));
1805 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1806 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1807 new_apdu->u.searchResponse->nextResultSetPosition =
1808 odr_intdup(odr_encode(), toget+1);
1809 send_to_client(new_apdu);
1815 // send present request (medium size)
1816 yaz_log(YLOG_LOG, "%sOptimizing search for medium set",
1819 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1820 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1821 pr->referenceId = sr->referenceId;
1822 pr->resultSetId = sr->resultSetName;
1823 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1824 *pr->numberOfRecordsRequested = toget;
1825 pr->recordComposition = comp;
1826 m_client->m_sr_transform = 1;
1830 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1831 m_client->m_last_resultCount <= 0)
1833 // large set. Return pseudo-search response immediately
1834 yaz_log(YLOG_LOG, "%sOptimizing search for large set",
1836 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1837 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1838 new_apdu->u.searchResponse->resultCount =
1839 &m_client->m_last_resultCount;
1840 send_to_client(new_apdu);
1845 Z_NamePlusRecordList *npr;
1846 int toget = m_client->m_last_resultCount;
1847 Z_RecordComposition *comp = 0;
1849 // send a present request (small set)
1851 if (sr->smallSetElementSetNames)
1853 comp = (Z_RecordComposition *)
1854 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1855 comp->which = Z_RecordComp_simple;
1856 comp->u.simple = sr->smallSetElementSetNames;
1859 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1860 sr->preferredRecordSyntax, comp))
1862 yaz_log(YLOG_LOG, "%sReturned cached records for small set",
1864 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1865 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1866 new_apdu->u.searchResponse->resultCount =
1867 &m_client->m_last_resultCount;
1869 new_apdu->u.searchResponse->numberOfRecordsReturned
1870 = odr_intdup(odr_encode(), toget);
1872 new_apdu->u.searchResponse->presentStatus =
1873 odr_intdup(odr_encode(), Z_PresentStatus_success);
1874 new_apdu->u.searchResponse->records = (Z_Records*)
1875 odr_malloc(odr_encode(), sizeof(Z_Records));
1876 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1877 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1878 new_apdu->u.searchResponse->nextResultSetPosition =
1879 odr_intdup(odr_encode(), toget+1);
1880 send_to_client(new_apdu);
1885 yaz_log(YLOG_LOG, "%sOptimizing search for small set",
1887 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1888 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1889 pr->referenceId = sr->referenceId;
1890 pr->resultSetId = sr->resultSetName;
1891 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1892 *pr->numberOfRecordsRequested = toget;
1893 pr->recordComposition = comp;
1894 m_client->m_sr_transform = 1;
1899 else // query doesn't match
1901 delete m_client->m_last_query;
1902 m_client->m_last_query = this_query;
1903 m_client->m_last_ok = 0;
1904 m_client->m_cache.clear();
1905 m_client->m_resultSetStartPoint = 0;
1907 xfree(m_client->m_last_resultSetId);
1908 m_client->m_last_resultSetId = xstrdup(sr->resultSetName);
1910 m_client->m_last_databases.set(sr->num_databaseNames,
1911 (const char **) sr->databaseNames);
1917 void Yaz_Proxy::inc_request_no()
1920 char *cp = m_session_str + strlen(m_session_str)-1;
1923 while (*cp && *cp != ' ')
1926 sprintf(cp+1, "%d ", m_request_no);
1929 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1933 m_bytes_recv += len;
1935 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1936 yaz_log(YLOG_LOG, "%sReceiving %s from client %d bytes",
1937 m_session_str, gdu_name(apdu), len);
1940 // try to make a _bad_ attribute set ID .. Don't enable this in prod.
1941 if (apdu->which == Z_GDU_Z3950
1942 && apdu->u.z3950->which == Z_APDU_searchRequest)
1944 Z_SearchRequest *req = apdu->u.z3950->u.searchRequest;
1945 if (req->query && req->query->which == Z_Query_type_1)
1947 Z_RPNQuery *rpnquery = req->query->u.type_1;
1948 if (rpnquery->attributeSetId)
1950 rpnquery->attributeSetId[0] = -2;
1951 rpnquery->attributeSetId[1] = -1;
1952 yaz_log(YLOG_WARN, "%sBAD FIXUP TEST", m_session_str);
1958 #if HAVE_GETTIMEOFDAY
1959 gettimeofday((struct timeval *) m_time_tv, 0);
1961 m_bw_stat.add_bytes(len);
1962 m_pdu_stat.add_bytes(1);
1964 GDU *gdu = new GDU(apdu);
1966 if (gdu->get() == 0)
1969 yaz_log(YLOG_LOG, "%sUnable to encode package", m_session_str);
1974 m_in_queue.enqueue(gdu);
1975 recv_GDU_more(false);
1978 void Yaz_Proxy::HTTP_Forwarded(Z_GDU *z_gdu)
1980 if (z_gdu->which == Z_GDU_HTTP_Request)
1982 Z_HTTP_Request *hreq = z_gdu->u.HTTP_Request;
1983 const char *x_forwarded_for =
1984 z_HTTP_header_lookup(hreq->headers, "X-Forwarded-For");
1985 if (x_forwarded_for)
1988 m_peername = (char*) xmalloc(strlen(x_forwarded_for)+5);
1989 sprintf(m_peername, "tcp:%s", x_forwarded_for);
1991 yaz_log(YLOG_LOG, "%sHTTP Forwarded from %s", m_session_str,
1993 if (m_log_mask & PROXY_LOG_IP_CLIENT)
1994 sprintf(m_session_str, "%ld:%d %.80s %d ",
1995 (long) time(0), m_session_no, m_peername, m_request_no);
1997 sprintf(m_session_str, "%ld:%d %d ",
1998 (long) time(0), m_session_no, m_request_no);
2003 void Yaz_Proxy::connect_stat(bool &block, int &reduce)
2006 m_parent->m_connect.cleanup(false);
2007 m_parent->m_connect.add_connect(m_peername);
2009 int connect_total = m_parent->m_connect.get_total(m_peername);
2010 int max_connect = m_parent->m_max_connect;
2012 if (max_connect && connect_total > max_connect)
2014 yaz_log(YLOG_LOG, "%sconnect not accepted total=%d max=%d",
2015 m_session_str, connect_total, max_connect);
2020 yaz_log(YLOG_LOG, "%sconnect accepted total=%d", m_session_str,
2023 int limit_connect = m_parent->m_limit_connect;
2025 reduce = connect_total / limit_connect;
2030 void Yaz_Proxy::recv_GDU_reduce(GDU *gdu)
2032 HTTP_Forwarded(gdu->get());
2036 if (m_request_no == 1)
2040 connect_stat(block, reduce);
2044 m_timeout_mode = timeout_busy;
2050 int bw_total = m_bw_stat.get_total();
2051 int pdu_total = m_pdu_stat.get_total();
2052 int search_total = m_search_stat.get_total();
2054 assert(m_timeout_mode == timeout_busy);
2055 assert(m_timeout_gdu == 0);
2058 reduce += search_total / m_search_max;
2060 reduce += (bw_total/m_bw_max);
2063 if (pdu_total > m_pdu_max)
2065 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
2066 reduce = (reduce > nreduce) ? reduce : nreduce;
2072 /* uncomment to force a big reduce */
2073 m_timeout_mode = timeout_reduce;
2074 m_timeout_gdu = gdu;
2075 timeout(3); // call us reduce seconds later
2080 yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d search=%d limit-bw=%d limit-pdu=%d limit-search=%d",
2081 m_session_str, reduce, bw_total, pdu_total, search_total,
2082 m_bw_max, m_pdu_max, m_search_max);
2084 m_timeout_mode = timeout_reduce;
2085 m_timeout_gdu = gdu;
2086 timeout(reduce); // call us reduce seconds later
2089 recv_GDU_normal(gdu);
2092 void Yaz_Proxy::recv_GDU_more(bool normal)
2095 if (normal && m_timeout_mode == timeout_busy)
2096 m_timeout_mode = timeout_normal;
2097 while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
2099 m_timeout_mode = timeout_busy;
2107 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
2110 gdu->move_away_gdu(odr_decode(), &apdu);
2113 if (apdu->which == Z_GDU_Z3950)
2114 handle_incoming_Z_PDU(apdu->u.z3950);
2115 else if (apdu->which == Z_GDU_HTTP_Request)
2116 handle_incoming_HTTP(apdu->u.HTTP_Request);
2119 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
2121 if (m_max_record_retrieve)
2123 if (apdu->which == Z_APDU_presentRequest)
2125 Z_PresentRequest *pr = apdu->u.presentRequest;
2126 if (pr->numberOfRecordsRequested &&
2127 *pr->numberOfRecordsRequested > m_max_record_retrieve)
2128 *pr->numberOfRecordsRequested = m_max_record_retrieve;
2133 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
2135 if (apdu->which == Z_APDU_initRequest)
2137 if (m_initRequest_options &&
2138 !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
2139 (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
2141 // There is no negotiation proposal from
2142 // client's side. OK. The proxy negotiation
2144 Z_InitRequest *initRequest = apdu->u.initRequest;
2145 Z_OtherInformation **otherInfo;
2146 Z_OtherInformationUnit *oi;
2147 get_otherInfoAPDU(apdu, &otherInfo);
2148 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2151 ODR_MASK_SET(initRequest->options,
2152 Z_Options_negotiationModel);
2153 oi->which = Z_OtherInfo_externallyDefinedInfo;
2154 oi->information.externallyDefinedInfo =
2155 yaz_set_proposal_charneg(odr_encode(),
2156 (const char**)&m_proxy_negotiation_charset,
2157 m_proxy_negotiation_charset ? 1:0,
2158 (const char**)&m_proxy_negotiation_lang,
2159 m_proxy_negotiation_lang ? 1:0,
2163 else if (m_initRequest_options &&
2164 ODR_MASK_GET(m_initRequest_options,
2165 Z_Options_negotiationModel) &&
2166 m_charset_converter->get_target_query_charset())
2168 yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
2170 m_charset_converter->get_target_query_charset());
2171 Z_InitRequest *initRequest = apdu->u.initRequest;
2172 Z_CharSetandLanguageNegotiation *negotiation =
2173 yaz_get_charneg_record (initRequest->otherInfo);
2175 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2177 NMEM nmem = nmem_create();
2178 char **charsets = 0;
2179 int num_charsets = 0;
2183 yaz_get_proposal_charneg (nmem, negotiation,
2184 &charsets, &num_charsets,
2185 &langs, &num_langs, &selected);
2187 for (i = 0; i<num_charsets; i++)
2188 yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
2190 for (i = 0; i<num_langs; i++)
2191 yaz_log(YLOG_LOG, "%slang %s", m_session_str,
2194 const char *t_charset =
2195 m_charset_converter->get_target_query_charset();
2196 // sweep through charsets and pick the first supported
2198 for (i = 0; i<num_charsets; i++)
2200 const char *c_charset = charsets[i];
2201 if (!odr_set_charset(odr_decode(), t_charset, c_charset))
2204 if (i != num_charsets)
2206 // got one .. set up ODR for reverse direction
2207 const char *c_charset = charsets[i];
2208 odr_set_charset(odr_encode(), c_charset, t_charset);
2209 m_charset_converter->set_client_query_charset(c_charset);
2210 m_charset_converter->set_client_charset_selected(selected);
2213 ODR_MASK_CLEAR(m_initRequest_options,
2214 Z_Options_negotiationModel);
2215 yaz_del_charneg_record(&initRequest->otherInfo);
2219 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
2223 else if (m_charset_converter->get_target_query_charset() &&
2224 m_proxy_negotiation_default_charset)
2226 m_charset_converter->
2227 set_client_query_charset(m_proxy_negotiation_default_charset);
2230 else if (apdu->which == Z_APDU_initResponse)
2232 Z_InitResponse *initResponse = apdu->u.initResponse;
2233 Z_OtherInformation **otherInfo;
2234 get_otherInfoAPDU(apdu, &otherInfo);
2236 Z_CharSetandLanguageNegotiation *charneg = 0;
2238 if (otherInfo && *otherInfo &&
2239 ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel)
2240 && (charneg = yaz_get_charneg_record(*otherInfo)))
2246 yaz_get_response_charneg(m_referenceId_mem, charneg,
2247 &charset, &lang, &selected);
2249 yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
2250 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
2252 if (m_initRequest_options &&
2253 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
2255 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2258 else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2260 // negotiation-charset, negotiation-lang
2261 // elements of config file in use.
2263 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2266 // clear negotiation option.
2267 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2269 // Delete negotiation (charneg-3) entry.
2270 yaz_del_charneg_record(otherInfo);
2275 if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2277 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2280 else if (m_charset_converter->get_client_query_charset())
2282 Z_OtherInformation **otherInfo;
2283 Z_OtherInformationUnit *oi;
2284 get_otherInfoAPDU(apdu, &otherInfo);
2285 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2288 ODR_MASK_SET(initResponse->options,
2289 Z_Options_negotiationModel);
2290 if (m_initRequest_options)
2291 ODR_MASK_SET(m_initRequest_options,
2292 Z_Options_negotiationModel);
2294 oi->which = Z_OtherInfo_externallyDefinedInfo;
2295 oi->information.externallyDefinedInfo =
2296 yaz_set_response_charneg(
2298 m_charset_converter->get_client_query_charset(),
2300 m_charset_converter->get_client_charset_selected());
2307 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2309 const char *addinfo)
2311 Z_Records *rec = (Z_Records *)
2312 odr_malloc (odr, sizeof(*rec));
2314 odr_malloc (odr, sizeof(*err));
2315 Z_DiagRec *drec = (Z_DiagRec *)
2316 odr_malloc (odr, sizeof(*drec));
2317 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2318 odr_malloc (odr, sizeof(*dr));
2320 rec->which = Z_Records_NSD;
2321 rec->u.nonSurrogateDiagnostic = dr;
2322 dr->diagnosticSetId = odr_oiddup(odr, yaz_oid_diagset_bib_1);
2323 dr->condition = err;
2324 dr->which = Z_DefaultDiagFormat_v2Addinfo;
2325 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2329 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2331 if (apdu->which == Z_APDU_searchRequest &&
2332 apdu->u.searchRequest->query &&
2333 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2334 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2336 Z_RPNQuery *rpnquery = 0;
2337 Z_SearchRequest *sr = apdu->u.searchRequest;
2340 yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2341 sr->query->u.type_104->u.cql);
2343 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2344 &rpnquery, odr_encode(),
2347 yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2350 yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2351 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2353 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2354 new_apdu->u.searchResponse->records =
2355 create_nonSurrogateDiagnostics(odr_encode(),
2356 yaz_diag_srw_to_bib1(r),
2358 *new_apdu->u.searchResponse->searchStatus = 0;
2360 send_to_client(new_apdu);
2366 sr->query->which = Z_Query_type_1;
2367 sr->query->u.type_1 = rpnquery;
2374 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2376 if (apdu->which == Z_APDU_searchRequest &&
2377 apdu->u.searchRequest->query)
2379 if (apdu->u.searchRequest->query->which == Z_Query_type_1
2380 || apdu->u.searchRequest->query->which == Z_Query_type_101)
2383 m_charset_converter->set_client_query_charset("UTF-8");
2384 Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2385 m_charset_converter->convert_type_1(rpnquery, odr_encode());
2392 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2394 if (apdu->which == Z_APDU_searchRequest)
2396 Z_SearchRequest *sr = apdu->u.searchRequest;
2400 Yaz_ProxyConfig *cfg = check_reconfigure();
2402 err = cfg->check_query(odr_encode(), m_default_target,
2403 sr->query, &addinfo);
2406 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2408 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2409 new_apdu->u.searchResponse->records =
2410 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2411 *new_apdu->u.searchResponse->searchStatus = 0;
2413 send_to_client(new_apdu);
2421 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2423 if (apdu->which != Z_APDU_initRequest)
2424 return 1; // pass if no init request
2425 Z_InitRequest *req = apdu->u.initRequest;
2427 Yaz_ProxyConfig *cfg = check_reconfigure();
2429 return 1; // pass if no config
2432 if (req->idAuthentication == 0)
2434 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2437 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2439 ret = cfg->client_authentication(
2441 req->idAuthentication->u.idPass->userId,
2442 req->idAuthentication->u.idPass->groupId,
2443 req->idAuthentication->u.idPass->password,
2446 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2448 char user[64], pass[64];
2451 sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2452 ret = cfg->client_authentication(m_default_target, user, 0, pass,
2456 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2461 int Yaz_Proxy::handle_global_authentication(Z_APDU *apdu)
2463 if (apdu->which != Z_APDU_initRequest)
2464 return 1; // pass if no init request
2465 Z_InitRequest *req = apdu->u.initRequest;
2467 Yaz_ProxyConfig *cfg = check_reconfigure();
2469 return 1; // pass if no config
2472 if (req->idAuthentication == 0)
2474 ret = cfg->global_client_authentication(0, 0, 0,
2477 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2479 ret = cfg->global_client_authentication(
2480 req->idAuthentication->u.idPass->userId,
2481 req->idAuthentication->u.idPass->groupId,
2482 req->idAuthentication->u.idPass->password,
2485 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2487 char user[64], pass[64];
2490 sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2491 ret = cfg->global_client_authentication(user, 0, pass,
2495 ret = cfg->global_client_authentication(0, 0, 0, m_peername);
2499 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2501 m_marcxml_mode = none;
2502 if (apdu->which == Z_APDU_searchRequest)
2504 Z_SearchRequest *sr = apdu->u.searchRequest;
2507 Yaz_ProxyConfig *cfg = check_reconfigure();
2509 Z_RecordComposition rc_temp, *rc = 0;
2510 if (sr->smallSetElementSetNames)
2512 rc_temp.which = Z_RecordComp_simple;
2513 rc_temp.u.simple = sr->smallSetElementSetNames;
2517 if (sr->preferredRecordSyntax)
2518 oid_oidcpy(m_frontend_type, sr->preferredRecordSyntax);
2520 m_frontend_type[0] = -1;
2522 char *stylesheet_name = 0;
2524 err = cfg->check_syntax(odr_encode(),
2526 sr->preferredRecordSyntax, rc,
2527 &addinfo, &stylesheet_name, &m_schema,
2528 &m_backend_type, &m_backend_charset,
2529 &m_usemarcon_ini_stage1,
2530 &m_usemarcon_ini_stage2);
2531 if (stylesheet_name)
2533 m_parent->low_socket_close();
2536 if (m_stylesheet_xsp)
2537 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2538 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2541 m_stylesheet_offset = 0;
2542 xfree(stylesheet_name);
2544 m_parent->low_socket_open();
2548 sr->smallSetElementSetNames = 0;
2549 sr->mediumSetElementSetNames = 0;
2550 m_marcxml_mode = marcxml;
2551 sr->preferredRecordSyntax =
2552 yaz_string_to_oid_odr(
2553 yaz_oid_std(), CLASS_RECSYN,
2554 m_backend_type ? m_backend_type : "usmarc",
2559 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2561 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2562 new_apdu->u.searchResponse->records =
2563 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2564 *new_apdu->u.searchResponse->searchStatus = 0;
2566 send_to_client(new_apdu);
2570 else if (m_backend_type)
2572 sr->preferredRecordSyntax =
2573 yaz_string_to_oid_odr(yaz_oid_std(), CLASS_RECSYN,
2574 m_backend_type, odr_encode());
2577 else if (apdu->which == Z_APDU_presentRequest)
2579 Z_PresentRequest *pr = apdu->u.presentRequest;
2582 Yaz_ProxyConfig *cfg = check_reconfigure();
2584 if (pr->preferredRecordSyntax)
2585 oid_oidcpy(m_frontend_type, pr->preferredRecordSyntax);
2587 m_frontend_type[0] = -1;
2589 char *stylesheet_name = 0;
2591 err = cfg->check_syntax(odr_encode(), m_default_target,
2592 pr->preferredRecordSyntax,
2593 pr->recordComposition,
2594 &addinfo, &stylesheet_name, &m_schema,
2595 &m_backend_type, &m_backend_charset,
2596 &m_usemarcon_ini_stage1,
2597 &m_usemarcon_ini_stage2
2599 if (stylesheet_name)
2601 m_parent->low_socket_close();
2604 if (m_stylesheet_xsp)
2605 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2606 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2609 m_stylesheet_offset = 0;
2610 xfree(stylesheet_name);
2612 m_parent->low_socket_open();
2616 pr->recordComposition = 0;
2617 m_marcxml_mode = marcxml;
2619 pr->preferredRecordSyntax =
2620 yaz_string_to_oid_odr(
2621 yaz_oid_std(), CLASS_RECSYN,
2622 m_backend_type ? m_backend_type : "usmarc",
2627 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2629 new_apdu->u.presentResponse->referenceId = pr->referenceId;
2630 new_apdu->u.presentResponse->records =
2631 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2632 *new_apdu->u.presentResponse->presentStatus =
2633 Z_PresentStatus_failure;
2635 send_to_client(new_apdu);
2639 else if (m_backend_type)
2641 pr->preferredRecordSyntax =
2642 yaz_string_to_oid_odr(yaz_oid_std(),
2643 CLASS_RECSYN, m_backend_type,
2650 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2654 Z_ElementSetNames *esn = (Z_ElementSetNames *)
2655 odr_malloc(o, sizeof(Z_ElementSetNames));
2656 esn->which = Z_ElementSetNames_generic;
2657 esn->u.generic = odr_strdup(o, schema);
2661 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2664 Yaz_ProxyConfig *cfg = check_reconfigure();
2666 t = cfg->get_explain_name(db, backend_db);
2668 if (m_client && m_default_target && t && strcmp(m_default_target, t))
2675 xfree(m_default_target);
2676 m_default_target = xstrdup(t);
2680 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2683 if (strcmp(hreq->method, "GET"))
2685 if (hreq->path[0] != '/')
2687 const char *cp = hreq->path;
2690 if (*cp == '/' && strchr("/.", cp[1]))
2695 Yaz_ProxyConfig *cfg = check_reconfigure();
2697 if (!cfg->get_file_access_info(hreq->path+1))
2700 const char *fname = hreq->path+1;
2701 if (stat(fname, &sbuf))
2703 yaz_log(YLOG_LOG|YLOG_ERRNO, "%sstat failed for %s", m_session_str,
2707 if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2709 yaz_log(YLOG_LOG, "%sNot a regular file %s", m_session_str, fname);
2712 if (sbuf.st_size > (off_t) 1000000)
2714 yaz_log(YLOG_WARN, "%sFile %s too large for transfer", m_session_str,
2719 ODR o = odr_encode();
2721 const char *ctype = cfg->check_mime_type(fname);
2722 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2723 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2725 hres->version = odr_strdup(o, m_http_version);
2726 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2727 if (m_http_keepalive)
2728 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2732 hres->content_len = sbuf.st_size;
2733 hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2734 FILE *f = fopen(fname, "rb");
2737 fread(hres->content_buf, 1, hres->content_len, f);
2744 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2746 yaz_log(YLOG_LOG, "%sSending file %s to client", m_session_str,
2750 send_GDU(gdu, &len);
2751 recv_GDU_more(true);
2755 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2759 odr_destroy(m_s2z_odr_init);
2762 if (m_s2z_odr_search)
2764 odr_destroy(m_s2z_odr_search);
2765 m_s2z_odr_search = 0;
2768 m_http_keepalive = 0;
2770 if (!strcmp(hreq->version, "1.0"))
2772 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2773 if (v && !strcmp(v, "Keep-Alive"))
2774 m_http_keepalive = 1;
2776 m_http_keepalive = 0;
2777 m_http_version = "1.0";
2781 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2782 if (v && !strcmp(v, "close"))
2783 m_http_keepalive = 0;
2785 m_http_keepalive = 1;
2786 m_http_version = "1.1";
2789 const char *a = z_HTTP_header_lookup(hreq->headers, "Authorization");
2790 char authorization_str[255];
2791 *authorization_str = '\0';
2792 if (a && strncasecmp(a, "Basic ", 6) == 0)
2793 base64_decode(a + 6, authorization_str, 254);
2795 Z_SRW_PDU *srw_pdu = 0;
2796 Z_SOAP *soap_package = 0;
2798 Z_SRW_diagnostic *diagnostic = 0;
2799 int num_diagnostic = 0;
2801 yaz_log(YLOG_LOG, "%s%s %s", m_session_str, hreq->method, hreq->path);
2803 if (file_access(hreq))
2807 else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2809 || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2810 &charset, &diagnostic, &num_diagnostic) == 0)
2812 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2813 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2814 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2815 m_s2z_init_apdu = 0;
2816 m_s2z_search_apdu = 0;
2817 m_s2z_present_apdu = 0;
2819 m_s2z_stylesheet = 0;
2821 Z_IdAuthentication *auth = NULL;
2822 if (srw_pdu->username && !srw_pdu->password)
2824 yaz_log(YLOG_LOG, "username: %s\n", srw_pdu->username);
2825 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2826 auth->which = Z_IdAuthentication_open;
2827 auth->u.open = odr_strdup(m_s2z_odr_init, srw_pdu->username);
2829 else if (srw_pdu->username && srw_pdu->password)
2831 yaz_log(YLOG_LOG, "username/password: %s/%s\n",
2832 srw_pdu->username, srw_pdu->password);
2833 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2834 auth->which = Z_IdAuthentication_idPass;
2835 auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2836 auth->u.idPass->groupId = NULL;
2837 auth->u.idPass->password = odr_strdup(m_s2z_odr_init, srw_pdu->password);
2838 auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, srw_pdu->username);
2842 if (*authorization_str)
2844 yaz_log(YLOG_LOG, "authorization_str present: %s\n", authorization_str);
2845 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2846 auth->which = Z_IdAuthentication_idPass;
2847 auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2848 auth->u.idPass->groupId = NULL;
2849 char *p = strchr(authorization_str, ':');
2854 auth->u.idPass->password = odr_strdup(m_s2z_odr_init, p);
2856 auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, authorization_str);
2860 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2863 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2865 const char *backend_db = srw_req->database;
2866 srw_get_client(srw_req->database, &backend_db);
2868 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2869 // recordXPath unsupported.
2870 if (srw_req->recordXPath)
2872 yaz_add_srw_diagnostic(odr_decode(),
2873 &diagnostic, &num_diagnostic,
2877 if (srw_req->sort_type != Z_SRW_sort_type_none)
2879 yaz_add_srw_diagnostic(odr_decode(),
2880 &diagnostic, &num_diagnostic,
2884 if (srw_req->stylesheet)
2886 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2888 // set packing for response records ..
2889 if (srw_req->recordPacking &&
2890 !strcmp(srw_req->recordPacking, "xml"))
2891 m_s2z_packing = Z_SRW_recordPacking_XML;
2893 m_s2z_packing = Z_SRW_recordPacking_string;
2897 Z_SRW_PDU *srw_pdu =
2898 yaz_srw_get(odr_encode(),
2899 Z_SRW_searchRetrieve_response);
2900 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2902 srw_res->diagnostics = diagnostic;
2903 srw_res->num_diagnostics = num_diagnostic;
2904 send_srw_response(srw_pdu);
2908 // prepare search PDU
2909 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2910 Z_APDU_searchRequest);
2911 Z_SearchRequest *z_searchRequest =
2912 m_s2z_search_apdu->u.searchRequest;
2914 z_searchRequest->num_databaseNames = 1;
2915 z_searchRequest->databaseNames = (char**)
2916 odr_malloc(m_s2z_odr_search, sizeof(char *));
2917 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2920 // query transformation
2921 Z_Query *query = (Z_Query *)
2922 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2923 z_searchRequest->query = query;
2925 if (srw_req->query_type == Z_SRW_query_type_cql)
2927 Z_External *ext = (Z_External *)
2928 odr_malloc(m_s2z_odr_search, sizeof(*ext));
2929 ext->direct_reference =
2930 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2931 ext->indirect_reference = 0;
2932 ext->descriptor = 0;
2933 ext->which = Z_External_CQL;
2934 ext->u.cql = srw_req->query.cql;
2936 query->which = Z_Query_type_104;
2937 query->u.type_104 = ext;
2939 else if (srw_req->query_type == Z_SRW_query_type_pqf)
2941 Z_RPNQuery *RPNquery;
2942 YAZ_PQF_Parser pqf_parser;
2944 pqf_parser = yaz_pqf_create ();
2946 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2947 srw_req->query.pqf);
2950 const char *pqf_msg;
2952 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2954 yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
2955 yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2957 send_to_srw_client_error(10, 0);
2960 query->which = Z_Query_type_1;
2961 query->u.type_1 = RPNquery;
2963 yaz_pqf_destroy (pqf_parser);
2967 send_to_srw_client_error(7, "query");
2972 m_s2z_present_apdu = 0;
2974 if (srw_req->maximumRecords)
2975 max = *srw_req->maximumRecords;
2977 if (srw_req->startRecord)
2978 start = *srw_req->startRecord;
2981 // Some backend, such as Voyager doesn't honor piggyback
2982 // So we use present always (0 &&).
2983 if (0 && start <= 1) // Z39.50 piggyback
2985 *z_searchRequest->smallSetUpperBound = max;
2986 *z_searchRequest->mediumSetPresentNumber = max;
2987 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2989 z_searchRequest->preferredRecordSyntax =
2990 odr_oiddup(m_s2z_odr_search, yaz_oid_recsyn_xml);
2992 if (srw_req->recordSchema)
2994 z_searchRequest->smallSetElementSetNames =
2995 z_searchRequest->mediumSetElementSetNames =
2996 mk_esn_from_schema(m_s2z_odr_search,
2997 srw_req->recordSchema);
3000 else // Z39.50 present
3002 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
3003 Z_APDU_presentRequest);
3004 Z_PresentRequest *z_presentRequest =
3005 m_s2z_present_apdu->u.presentRequest;
3006 *z_presentRequest->resultSetStartPoint = start;
3007 *z_presentRequest->numberOfRecordsRequested = max;
3009 z_presentRequest->preferredRecordSyntax =
3010 odr_oiddup(m_s2z_odr_search, yaz_oid_recsyn_xml);
3011 if (srw_req->recordSchema)
3013 z_presentRequest->recordComposition =
3014 (Z_RecordComposition *)
3015 odr_malloc(m_s2z_odr_search,
3016 sizeof(Z_RecordComposition));
3017 z_presentRequest->recordComposition->which =
3018 Z_RecordComp_simple;
3019 z_presentRequest->recordComposition->u.simple =
3020 mk_esn_from_schema(m_s2z_odr_search,
3021 srw_req->recordSchema);
3027 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
3028 Z_APDU_initRequest);
3030 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
3032 // prevent m_initRequest_apdu memory from being grabbed
3033 // in Yaz_Proxy::handle_incoming_Z_PDU
3034 m_initRequest_apdu = m_s2z_init_apdu;
3035 handle_incoming_Z_PDU(m_s2z_init_apdu);
3040 handle_incoming_Z_PDU(m_s2z_search_apdu);
3044 else if (srw_pdu->which == Z_SRW_explain_request)
3046 Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
3048 const char *backend_db = srw_req->database;
3049 srw_get_client(srw_req->database, &backend_db);
3051 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
3054 if (srw_req->stylesheet)
3056 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
3058 if (srw_req->recordPacking &&
3059 !strcmp(srw_req->recordPacking, "xml"))
3060 m_s2z_packing = Z_SRW_recordPacking_XML;
3062 m_s2z_packing = Z_SRW_recordPacking_string;
3066 send_srw_explain_response(diagnostic, num_diagnostic);
3072 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
3073 Z_APDU_initRequest);
3075 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
3077 // prevent m_initRequest_apdu memory from being grabbed
3078 // in Yaz_Proxy::handle_incoming_Z_PDU
3079 m_initRequest_apdu = m_s2z_init_apdu;
3080 handle_incoming_Z_PDU(m_s2z_init_apdu);
3083 send_srw_explain_response(0, 0);
3086 else if (srw_pdu->which == Z_SRW_scan_request)
3088 m_s2z_database = odr_strdup(m_s2z_odr_init,
3089 srw_pdu->u.scan_request->database);
3091 yaz_add_srw_diagnostic(odr_decode(),
3092 &diagnostic, &num_diagnostic,
3094 Z_SRW_PDU *srw_pdu =
3095 yaz_srw_get(odr_encode(),
3096 Z_SRW_scan_response);
3097 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
3099 srw_res->diagnostics = diagnostic;
3100 srw_res->num_diagnostics = num_diagnostic;
3101 send_srw_response(srw_pdu);
3108 send_to_srw_client_error(4, 0);
3111 send_http_response(400);
3114 void Yaz_Proxy::handle_init(Z_APDU *apdu)
3117 Z_OtherInformation **oi;
3118 get_otherInfoAPDU(apdu, &oi);
3120 if (apdu->u.initRequest->implementationId)
3121 yaz_log(YLOG_LOG, "%simplementationId: %s",
3122 m_session_str, apdu->u.initRequest->implementationId);
3123 if (apdu->u.initRequest->implementationName)
3124 yaz_log(YLOG_LOG, "%simplementationName: %s",
3125 m_session_str, apdu->u.initRequest->implementationName);
3126 if (apdu->u.initRequest->implementationVersion)
3127 yaz_log(YLOG_LOG, "%simplementationVersion: %s",
3128 m_session_str, apdu->u.initRequest->implementationVersion);
3129 if (m_initRequest_apdu == 0)
3131 if (m_initRequest_mem)
3132 nmem_destroy(m_initRequest_mem);
3134 m_initRequest_apdu = apdu;
3135 m_initRequest_mem = odr_extract_mem(odr_decode());
3137 m_initRequest_preferredMessageSize = *apdu->u.initRequest->
3138 preferredMessageSize;
3139 *apdu->u.initRequest->preferredMessageSize = 1024*1024;
3140 m_initRequest_maximumRecordSize = *apdu->u.initRequest->
3142 *apdu->u.initRequest->maximumRecordSize = 1024*1024;
3144 Z_CharSetandLanguageNegotiation *charSetandLangRecord =
3145 yaz_get_charneg_record(*oi);
3147 // Save proposal charsets and langs.
3148 if (ODR_MASK_GET(apdu->u.initRequest->options,
3149 Z_Options_negotiationModel)
3150 && charSetandLangRecord)
3153 yaz_get_proposal_charneg(m_referenceId_mem,
3154 charSetandLangRecord,
3155 &m_initRequest_oi_negotiation_charsets,
3156 &m_initRequest_oi_negotiation_num_charsets,
3157 &m_initRequest_oi_negotiation_langs,
3158 &m_initRequest_oi_negotiation_num_langs,
3159 &m_initRequest_oi_negotiation_selected);
3161 for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
3163 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
3164 m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
3165 m_initRequest_oi_negotiation_charsets[i]:"none");
3167 for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
3169 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
3170 m_session_str, (m_initRequest_oi_negotiation_langs[i])?
3171 m_initRequest_oi_negotiation_langs[i]:"none");
3173 yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
3174 m_session_str, m_initRequest_oi_negotiation_selected);
3176 // save init options for the response..
3177 m_initRequest_options = apdu->u.initRequest->options;
3179 apdu->u.initRequest->options =
3180 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3181 sizeof(Odr_bitmask));
3182 ODR_MASK_ZERO(apdu->u.initRequest->options);
3184 for (i = 0; i<= 24; i++)
3185 ODR_MASK_SET(apdu->u.initRequest->options, i);
3186 // check negotiation option
3187 if (!ODR_MASK_GET(m_initRequest_options,
3188 Z_Options_negotiationModel))
3190 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3191 Z_Options_negotiationModel);
3193 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3194 Z_Options_concurrentOperations);
3196 m_initRequest_version = apdu->u.initRequest->protocolVersion;
3197 apdu->u.initRequest->protocolVersion =
3198 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3199 sizeof(Odr_bitmask));
3200 ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
3202 for (i = 0; i<= 8; i++)
3203 ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
3205 handle_charset_lang_negotiation(apdu);
3206 if (m_client->m_init_flag)
3208 if (handle_init_response_for_invalid_session(apdu))
3210 if (m_client->m_initResponse)
3212 Z_APDU *apdu2 = m_client->m_initResponse;
3213 apdu2->u.initResponse->otherInfo = 0;
3214 if (m_client->m_cookie && *m_client->m_cookie)
3215 set_otherInformationString(apdu2, yaz_oid_userinfo_cookie,
3216 1, m_client->m_cookie);
3217 apdu2->u.initResponse->referenceId =
3218 apdu->u.initRequest->referenceId;
3219 apdu2->u.initResponse->options = m_client->m_initResponse_options;
3220 apdu2->u.initResponse->protocolVersion =
3221 m_client->m_initResponse_version;
3223 handle_charset_lang_negotiation(apdu2);
3225 if (m_timeout_mode == timeout_busy)
3226 m_timeout_mode = timeout_normal;
3227 send_to_client(apdu2);
3231 m_client->m_init_flag = 1;
3233 if (m_num_msg_threads && m_my_thread)
3235 Auth_Msg *m = new Auth_Msg;
3237 z_APDU(odr_encode(), &apdu, 0, "encode");
3238 char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
3239 m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
3240 memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
3241 odr_reset(odr_encode());
3244 m_my_thread->put(m);
3248 int ret = handle_authentication(apdu);
3249 result_authentication(apdu, ret);
3253 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
3255 Z_ReferenceId **refid = get_referenceIdP(apdu);
3256 nmem_reset(m_referenceId_mem);
3257 if (refid && *refid)
3259 m_referenceId = (Z_ReferenceId *)
3260 nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
3261 m_referenceId->len = m_referenceId->size = (*refid)->len;
3262 m_referenceId->buf = (unsigned char *)
3263 nmem_malloc(m_referenceId_mem, (*refid)->len);
3264 memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
3269 if (!m_client && m_flag_invalid_session)
3271 // Got request for a session that is invalid..
3272 m_apdu_invalid_session = apdu; // save package
3273 m_mem_invalid_session = odr_extract_mem(odr_decode());
3274 apdu = m_initRequest_apdu; // but throw an init to the target
3277 if (apdu->which == Z_APDU_searchRequest)
3278 m_search_stat.add_bytes(1);
3280 // Handle global authentication
3281 if (!handle_global_authentication(apdu))
3284 { // HTTP. Send unauthorized
3285 send_http_response(401);
3290 // Z39.50 just shutdown
3297 // Determine our client.
3298 Z_OtherInformation **oi;
3299 get_otherInfoAPDU(apdu, &oi);
3300 int http_code = 404;
3301 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi), &http_code);
3305 { // HTTP. Send not found
3306 send_http_response(http_code);
3311 // Z39.50 just shutdown
3317 m_client->m_server = this;
3319 if (apdu->which == Z_APDU_initRequest)
3322 handle_incoming_Z_PDU_2(apdu);
3325 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
3327 handle_max_record_retrieve(apdu);
3330 apdu = handle_syntax_validation(apdu);
3333 apdu = handle_query_transformation(apdu);
3336 apdu = handle_target_charset_conversion(apdu);
3339 apdu = handle_query_validation(apdu);
3342 apdu = result_set_optimize(apdu);
3346 m_client->timeout(m_target_idletime); // mark it active even
3347 recv_GDU_more(true);
3348 // though we didn't use it
3352 // delete other info construct completely if 0 elements
3353 Z_OtherInformation **oi;
3354 get_otherInfoAPDU(apdu, &oi);
3355 if (oi && *oi && (*oi)->num_elements == 0)
3358 if (apdu->which == Z_APDU_presentRequest &&
3359 m_client->m_resultSetStartPoint == 0)
3361 Z_PresentRequest *pr = apdu->u.presentRequest;
3362 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3363 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3365 m_client->m_resultSetStartPoint = 0;
3367 if (m_client->send_to_target(apdu) < 0)
3369 m_client->shutdown();
3372 m_client->m_waiting = 1;
3375 void Yaz_Proxy::connectNotify()
3379 void Yaz_Proxy::releaseClient()
3381 xfree(m_proxyTarget);
3383 m_flag_invalid_session = 0;
3384 // only keep if keep_alive flag is set...
3386 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3387 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3388 m_client->m_waiting == 0)
3390 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3392 m_client->get_hostname());
3393 yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3394 m_session_str, m_client->m_pdu_recv,
3395 m_client->m_bytes_sent + m_client->m_bytes_recv,
3396 m_keepalive_limit_bw, m_keepalive_limit_pdu);
3397 assert (m_client->m_waiting != 2);
3398 // Tell client (if any) that no server connection is there..
3399 m_client->m_server = 0;
3404 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) close %s",
3406 m_client->get_hostname());
3407 assert (m_client->m_waiting != 2);
3413 yaz_log(YLOG_LOG, "%sshutdown (client to proxy) bad state",
3419 yaz_log(YLOG_LOG, "%sShutdown (client to proxy)",
3423 m_parent->pre_init();
3426 bool Yaz_Proxy::dec_ref()
3428 m_http_keepalive = 0;
3431 if (m_ref_count > 0)
3440 const char *Yaz_ProxyClient::get_session_str()
3444 return m_server->get_session_str();
3447 void Yaz_ProxyClient::shutdown()
3449 yaz_log(YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
3454 m_waiting = 1; // ensure it's released from Yaz_Proxy::releaseClient
3455 m_server->dec_ref();
3461 void Yaz_Proxy::failNotify()
3464 yaz_log(YLOG_LOG, "%sConnection closed by client", get_session_str());
3468 void Yaz_Proxy::send_response_fail_client(const char *addr)
3472 Z_SRW_diagnostic *diagnostic = 0;
3473 int num_diagnostic = 0;
3475 yaz_add_srw_diagnostic(odr_encode(),
3476 &diagnostic, &num_diagnostic,
3477 YAZ_SRW_SYSTEM_TEMPORARILY_UNAVAILABLE, addr);
3478 if (m_s2z_search_apdu)
3479 send_srw_search_response(diagnostic, num_diagnostic);
3481 send_srw_explain_response(diagnostic, num_diagnostic);
3485 void Yaz_ProxyClient::failNotify()
3488 m_server->inc_request_no();
3489 yaz_log(YLOG_LOG, "%sConnection closed by target %s",
3490 get_session_str(), get_hostname());
3493 m_server->send_response_fail_client(get_hostname());
3497 void Yaz_ProxyClient::connectNotify()
3499 const char *s = get_session_str();
3500 const char *h = get_hostname();
3501 yaz_log(YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
3503 timeout(m_target_idletime);
3508 IPDU_Observer *Yaz_ProxyClient::sessionNotify(IPDU_Observable
3509 *the_PDU_Observable, int fd)
3511 return new Yaz_ProxyClient(the_PDU_Observable, 0);
3514 Yaz_ProxyClient::~Yaz_ProxyClient()
3519 m_next->m_prev = m_prev;
3520 m_waiting = 2; // for debugging purposes only.
3521 odr_destroy(m_init_odr);
3522 odr_destroy(m_idAuthentication_odr);
3523 delete m_last_query;
3524 xfree(m_last_resultSetId);
3528 void Yaz_ProxyClient::pre_init_client()
3530 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
3531 Z_InitRequest *req = apdu->u.initRequest;
3534 for (i = 0; i<= 24; i++)
3535 ODR_MASK_SET(req->options, i);
3536 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3537 Z_Options_negotiationModel);
3538 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3539 Z_Options_concurrentOperations);
3540 for (i = 0; i<= 10; i++)
3541 ODR_MASK_SET(req->protocolVersion, i);
3543 if (send_to_target(apdu) < 0)
3554 void Yaz_Proxy::pre_init()
3557 const char *name = 0;
3558 const char *zurl_in_use[MAX_ZURL_PLEX];
3559 int limit_bw, limit_pdu, limit_req, limit_search;
3560 int target_idletime, client_idletime;
3563 int keepalive_limit_bw, keepalive_limit_pdu;
3565 const char *cql2rpn = 0;
3566 const char *authentication = 0;
3567 const char *negotiation_charset = 0;
3568 const char *negotiation_lang = 0;
3570 Yaz_ProxyConfig *cfg = check_reconfigure();
3574 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
3579 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
3580 &limit_bw, &limit_pdu, &limit_req,
3582 &target_idletime, &client_idletime,
3585 &keepalive_limit_bw,
3586 &keepalive_limit_pdu,
3590 &negotiation_charset,
3598 for (j = 0; zurl_in_use[j]; j++)
3602 int spare_waiting = 0;
3605 for (c = m_clientPool; c; c = c->m_next)
3607 if (!strcmp(zurl_in_use[j], c->get_hostname()))
3609 if (c->m_cookie == 0)
3611 if (c->m_server == 0)
3623 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
3624 "sparew=%d preinit=%d",m_session_str,
3625 name, zurl_in_use[j], in_use, other,
3626 spare, spare_waiting, pre_init);
3627 if (spare + spare_waiting < pre_init
3628 && in_use + spare + spare_waiting + other < max_sockets)
3630 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
3631 c->m_next = m_clientPool;
3633 c->m_next->m_prev = &c->m_next;
3635 c->m_prev = &m_clientPool;
3637 if (m_log_mask & PROXY_LOG_APDU_SERVER)
3638 c->set_APDU_yazlog(1);
3640 c->set_APDU_yazlog(0);
3642 if (c->client(zurl_in_use[j]))
3650 c->m_target_idletime = target_idletime;
3651 c->m_seqno = m_seqno++;
3658 void Yaz_Proxy::timeoutNotify()
3663 switch(m_timeout_mode)
3665 case timeout_normal:
3669 yaz_log(YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
3672 case timeout_reduce:
3673 timeout(m_client_idletime);
3674 m_timeout_mode = timeout_busy;
3675 gdu = m_timeout_gdu;
3677 recv_GDU_normal(gdu);
3680 assert(m_stylesheet_nprl);
3681 convert_xsl_delay();
3682 recv_GDU_more(true);
3692 void Yaz_Proxy::markInvalid()
3695 m_flag_invalid_session = 1;
3698 void Yaz_ProxyClient::timeoutNotify()
3701 m_server->inc_request_no();
3703 yaz_log(YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
3707 m_server->send_response_fail_client(get_hostname());
3709 Yaz_Proxy *proxy_root = m_root;
3713 proxy_root->pre_init();
3716 Yaz_ProxyClient::Yaz_ProxyClient(IPDU_Observable *the_PDU_Observable,
3717 Yaz_Proxy *parent) :
3718 Z_Assoc (the_PDU_Observable)
3725 m_last_resultSetId = 0;
3726 m_last_resultCount = 0;
3730 m_init_odr = odr_createmem (ODR_DECODE);
3732 m_initResponse_options = 0;
3733 m_initResponse_version = 0;
3734 m_initResponse_preferredMessageSize = 0;
3735 m_initResponse_maximumRecordSize = 0;
3736 m_resultSetStartPoint = 0;
3737 m_bytes_sent = m_bytes_recv = 0;
3741 m_target_idletime = 600;
3743 m_idAuthentication_odr = odr_createmem(ODR_ENCODE);
3744 m_idAuthentication_ber_buf = 0;
3745 m_idAuthentication_ber_size = 0;
3748 const char *Yaz_Proxy::option(const char *name, const char *value)
3750 if (!strcmp (name, "optimize")) {
3753 m_optimize = xstrdup(value);
3760 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
3765 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
3767 if (apdu->which == Z_GDU_Z3950)
3768 recv_Z_PDU(apdu->u.z3950, len);
3769 else if (apdu->which == Z_GDU_HTTP_Response)
3770 recv_HTTP_response(apdu->u.HTTP_Response, len);
3775 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
3777 if (!m_flag_invalid_session)
3779 m_flag_invalid_session = 0;
3780 handle_incoming_Z_PDU(m_apdu_invalid_session);
3781 assert (m_mem_invalid_session);
3782 nmem_destroy(m_mem_invalid_session);
3783 m_mem_invalid_session = 0;
3787 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
3789 m_bytes_recv += len;
3793 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
3794 yaz_log(YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
3795 apdu_name(apdu), get_hostname(), len);
3796 if (apdu->which == Z_APDU_initResponse)
3798 if (!m_server) // if this is a pre init session , check for more
3800 NMEM nmem = odr_extract_mem (odr_decode());
3801 odr_reset (m_init_odr);
3802 nmem_transfer (m_init_odr->mem, nmem);
3803 m_initResponse = apdu;
3804 m_initResponse_options = apdu->u.initResponse->options;
3805 m_initResponse_version = apdu->u.initResponse->protocolVersion;
3806 m_initResponse_preferredMessageSize =
3807 *apdu->u.initResponse->preferredMessageSize;
3808 m_initResponse_maximumRecordSize =
3809 *apdu->u.initResponse->maximumRecordSize;
3811 Z_InitResponse *ir = apdu->u.initResponse;
3813 // apply YAZ Proxy version
3814 char *imv0 = ir->implementationVersion;
3815 char *imv1 = (char*)
3816 odr_malloc(m_init_odr, 20 + (imv0 ? strlen(imv0) : 0));
3821 strcat(imv1, "/" VERSION);
3823 ir->implementationVersion = imv1;
3825 // apply YAZ Proxy implementation name
3826 char *im0 = ir->implementationName;
3828 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
3835 strcat(im1, "(YAZ Proxy)");
3836 ir->implementationName = im1;
3838 nmem_destroy (nmem);
3840 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
3843 if (apdu->which == Z_APDU_searchResponse)
3845 Z_SearchResponse *sr = apdu->u.searchResponse;
3846 m_last_resultCount = *sr->resultCount;
3847 int status = *sr->searchStatus;
3848 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
3852 if (sr->records && sr->records->which == Z_Records_DBOSD)
3854 m_cache.add(odr_decode(),
3855 sr->records->u.databaseOrSurDiagnostics, 1,
3860 if (apdu->which == Z_APDU_presentResponse)
3862 Z_PresentResponse *pr = apdu->u.presentResponse;
3866 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
3867 Z_SearchResponse *sr = new_apdu->u.searchResponse;
3868 sr->referenceId = pr->referenceId;
3869 *sr->resultCount = m_last_resultCount;
3870 sr->records = pr->records;
3871 sr->nextResultSetPosition = pr->nextResultSetPosition;
3872 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
3876 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
3878 m_cache.add(odr_decode(),
3879 pr->records->u.databaseOrSurDiagnostics,
3880 m_resultSetStartPoint, -1);
3881 m_resultSetStartPoint = 0;
3885 set_otherInformationString(apdu, yaz_oid_userinfo_cookie, 1, m_cookie);
3887 Yaz_Proxy *server = m_server; // save it. send_to_client may destroy us
3890 server->send_to_client(apdu);
3891 if (apdu->which == Z_APDU_close)
3894 server->recv_GDU_more(true);
3897 void Yaz_Proxy::low_socket_close()
3902 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3903 if (m_lo_fd[i] >= 0)
3904 ::close(m_lo_fd[i]);
3908 void Yaz_Proxy::low_socket_open()
3913 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3914 m_lo_fd[i] = open("/dev/null", O_RDONLY);
3918 int Yaz_Proxy::server(const char *addr)
3920 int r = Z_Assoc::server(addr);
3923 yaz_log(YLOG_LOG, "%sStarted proxy "
3927 " on %s", m_session_str, addr);
3933 void Yaz_Proxy::base64_decode(const char *base64, char *buf, int buf_len)
3935 const char *base64_chars =
3936 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3937 int len = strlen(base64);
3941 for (int pos = 0; pos <= len; pos++)
3943 if (base64[pos] == '=' || buf_pos + 1 >= buf_len)
3946 const char *ch_ptr = strchr(base64_chars, base64[pos]);
3949 char ch = (char) (ch_ptr - base64_chars);
3953 buf[buf_pos] = ch << 2;
3956 buf[buf_pos++] += (ch & 0x30) >> 4;
3957 buf[buf_pos] = (ch & 0x0f) << 4;
3960 buf[buf_pos++] += (ch & 0x3c) >> 2;
3961 buf[buf_pos] = (ch & 0x03) << 6;
3964 buf[buf_pos++] += ch;
3971 buf[buf_pos] = '\0';
3977 * c-file-style: "Stroustrup"
3978 * indent-tabs-mode: nil
3980 * vim: shiftwidth=4 tabstop=8 expandtab