1 /* This file is part of YAZ proxy
2 Copyright (C) 1998-2011 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;
276 m_s2z_search_apdu = 0;
277 m_s2z_present_apdu = 0;
279 m_http_keepalive = 0;
282 m_s2z_packing = Z_SRW_recordPacking_string;
283 #if HAVE_GETTIMEOFDAY
284 m_time_tv = xmalloc(sizeof(struct timeval));
285 struct timeval *tv = (struct timeval *) m_time_tv;
291 m_usemarcon_ini_stage1 = 0;
292 m_usemarcon_ini_stage2 = 0;
293 m_usemarcon = new Yaz_usemarcon();
296 m_backend_elementset = 0;
299 m_main_ptr_dec = false;
301 m_num_msg_threads = 0;
304 void Yaz_Proxy::inc_ref()
309 Yaz_Proxy::~Yaz_Proxy()
311 yaz_log(YLOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
312 m_bytes_sent, m_bytes_recv);
313 nmem_destroy(m_initRequest_mem);
314 nmem_destroy(m_mem_invalid_session);
315 nmem_destroy(m_referenceId_mem);
317 xfree(m_proxyTarget);
318 xfree(m_default_target);
319 xfree(m_proxy_negotiation_charset);
320 xfree(m_proxy_negotiation_lang);
321 xfree(m_proxy_negotiation_default_charset);
322 delete m_charset_converter;
326 if (m_stylesheet_xsp)
327 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
333 xfree(m_backend_type);
334 xfree(m_backend_charset);
335 xfree(m_usemarcon_ini_stage1);
336 xfree(m_usemarcon_ini_stage2);
337 xfree(m_backend_elementset);
340 odr_destroy(m_s2z_odr_init);
341 if (m_s2z_odr_search)
342 odr_destroy(m_s2z_odr_search);
344 odr_destroy(m_s2z_odr_scan);
352 void Yaz_Proxy::set_debug_mode(int mode)
357 int Yaz_Proxy::set_config(const char *config)
360 m_config = new Yaz_ProxyConfig();
361 xfree(m_config_fname);
362 m_config_fname = xstrdup(config);
363 int r = m_config->read_xml(config);
367 m_config->get_generic_info(&m_log_mask, &m_max_clients,
368 &m_max_connect, &m_limit_connect, &period,
370 m_connect.set_period(period);
375 void Yaz_Proxy::set_default_target(const char *target)
377 xfree(m_default_target);
378 m_default_target = 0;
380 m_default_target = (char *) xstrdup(target);
383 void Yaz_Proxy::set_proxy_negotiation(const char *charset, const char *lang,
384 const char *default_charset)
386 yaz_log(YLOG_DEBUG, "%sSet the proxy negotiation: charset to '%s', "
387 "default charset to '%s', language to '%s'", m_session_str,
388 charset?charset:"none",
389 default_charset?default_charset:"none",
391 xfree(m_proxy_negotiation_charset);
392 xfree(m_proxy_negotiation_lang);
393 m_proxy_negotiation_charset = m_proxy_negotiation_lang = 0;
395 m_proxy_negotiation_charset = (char *) xstrdup(charset);
397 m_proxy_negotiation_lang = (char *) xstrdup(lang);
399 m_proxy_negotiation_default_charset =
400 (char *) xstrdup(default_charset);
403 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
406 return m_parent->check_reconfigure();
408 Yaz_ProxyConfig *cfg = m_config;
411 yaz_log(YLOG_LOG, "reconfigure");
412 if (m_config_fname && cfg)
414 yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
415 int r = cfg->read_xml(m_config_fname);
417 yaz_log(YLOG_WARN, "reconfigure failed");
422 cfg->get_generic_info(&m_log_mask, &m_max_clients,
423 &m_max_connect, &m_limit_connect,
424 &period, &m_num_msg_threads);
425 m_connect.set_period(period);
429 yaz_log(YLOG_LOG, "reconfigure");
435 IPDU_Observer *Yaz_Proxy::sessionNotify(IPDU_Observable
436 *the_PDU_Observable, int fd)
440 char session_str[200];
441 const char *peername = the_PDU_Observable->getpeername();
443 peername = "nullpeer";
445 if (m_log_mask & PROXY_LOG_IP_CLIENT)
446 sprintf(session_str, "%ld:%d %.80s %d ",
447 (long) time(0), m_session_no, peername, 0);
449 sprintf(session_str, "%ld:%d %d ",
450 (long) time(0), m_session_no, 0);
453 yaz_log(YLOG_LOG, "%sNew session %s", session_str, peername);
455 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable,
456 m_socket_observable, this);
458 new_proxy->m_config = 0;
459 new_proxy->m_config_fname = 0;
460 new_proxy->timeout(m_client_idletime);
461 new_proxy->m_target_idletime = m_target_idletime;
462 new_proxy->set_default_target(m_default_target);
463 new_proxy->m_max_clients = m_max_clients;
464 new_proxy->m_log_mask = m_log_mask;
465 new_proxy->m_session_no = m_session_no;
466 new_proxy->m_num_msg_threads = m_num_msg_threads;
469 // in case we want to watch a particular client..
470 if (!strcmp(peername, "tcp:163.121.19.82")) // NIS GROUP
471 new_proxy->m_log_mask = 255;
474 new_proxy->set_APDU_log(get_APDU_log());
475 if (new_proxy->m_log_mask & PROXY_LOG_APDU_CLIENT)
476 new_proxy->set_APDU_yazlog(1);
478 new_proxy->set_APDU_yazlog(0);
479 strcpy(new_proxy->m_session_str, session_str);
480 new_proxy->m_peername = xstrdup(peername);
481 new_proxy->set_proxy_negotiation(m_proxy_negotiation_charset,
482 m_proxy_negotiation_lang, m_proxy_negotiation_default_charset);
483 // create thread object the first time we get an incoming connection
484 if (!m_my_thread && m_num_msg_threads > 0)
486 yaz_log(YLOG_LOG, "%sStarting message thread management. number=%d",
487 session_str, m_num_msg_threads);
488 m_my_thread = new Msg_Thread(m_socket_observable, m_num_msg_threads);
490 new_proxy->m_my_thread = m_my_thread;
494 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
496 Z_OtherInformationUnit *oi =
497 update_otherInformation(otherInfo, 0, yaz_oid_userinfo_cookie, 1, 1);
499 if (oi && oi->which == Z_OtherInfo_characterInfo)
500 return oi->information.characterInfo;
504 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
506 Z_OtherInformationUnit *oi =
507 update_otherInformation(otherInfo, 0, yaz_oid_userinfo_proxy, 1, 1);
509 if (oi && oi->which == Z_OtherInfo_characterInfo)
510 return oi->information.characterInfo;
513 const char *Yaz_Proxy::load_balance(const char **url)
515 int zurl_in_use[MAX_ZURL_PLEX];
516 int zurl_in_spare[MAX_ZURL_PLEX];
520 for (i = 0; i<MAX_ZURL_PLEX; i++)
523 zurl_in_spare[i] = 0;
525 for (c = m_parent->m_clientPool; c; c = c->m_next)
527 for (i = 0; url[i]; i++)
528 if (!strcmp(url[i], c->get_hostname()))
531 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
535 int min_use = 100000;
536 int spare_for_min = 0;
538 const char *ret_min = 0;
539 const char *ret_spare = 0;
540 for (i = 0; url[i]; i++)
542 yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
543 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
544 if (min_use > zurl_in_use[i])
547 min_use = zurl_in_use[i];
548 spare_for_min = zurl_in_spare[i];
550 if (max_spare < zurl_in_spare[i])
553 max_spare = zurl_in_spare[i];
559 int Yaz_Proxy::get_number_of_connections()
561 int no_connections = 0;
564 for (c = m_parent->m_clientPool; c; c = c->m_next)
567 assert(*c->m_prev == c);
568 if (!strcmp(m_proxyTarget, c->get_hostname()))
573 yaz_log(YLOG_LOG, "%sExisting %s connections: %d", m_session_str, m_proxyTarget,
575 return no_connections;
578 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
579 const char *proxy_host, int *http_code)
582 Yaz_Proxy *parent = m_parent;
583 Yaz_ProxyClient *c = m_client;
587 const char *url[MAX_ZURL_PLEX];
588 Yaz_ProxyConfig *cfg = check_reconfigure();
591 if (parent && parent->m_debug_mode)
593 // only to be enabled for debugging...
594 if (!strcmp(proxy_host, "stop"))
597 xfree(m_default_target);
598 m_default_target = xstrdup(proxy_host);
600 proxy_host = m_default_target;
601 int client_idletime = -1;
602 const char *cql2rpn_fname = 0;
603 const char *negotiation_charset = 0;
604 const char *negotiation_lang = 0;
605 const char *query_charset = 0;
606 const char *default_client_query_charset = 0;
607 url[0] = m_default_target;
612 cfg->get_target_info(proxy_host, url, &m_bw_max,
613 &m_pdu_max, &m_max_record_retrieve,
615 &m_target_idletime, &client_idletime,
617 &parent->m_max_clients,
618 &m_keepalive_limit_bw,
619 &m_keepalive_limit_pdu,
622 &negotiation_charset,
625 &default_client_query_charset);
627 if (client_idletime != -1)
629 m_client_idletime = client_idletime;
630 timeout(m_client_idletime);
633 // get those FILE descriptors available
634 m_parent->low_socket_close();
636 m_cql2rpn.set_pqf_file(cql2rpn_fname);
637 // reserve them again
638 m_parent->low_socket_open();
640 if (negotiation_charset || negotiation_lang || default_client_query_charset)
642 set_proxy_negotiation(negotiation_charset,
643 negotiation_lang, default_client_query_charset);
645 m_charset_converter->set_target_query_charset(query_charset);
648 yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
651 // we don't handle multiplexing for cookie session, so we just
652 // pick the first one in this case (anonymous users will be able
653 // to use any backend)
654 if (cookie && *cookie)
655 m_proxyTarget = (char*) xstrdup(url[0]);
657 m_proxyTarget = (char*) xstrdup(load_balance(url));
659 if (cookie && *cookie)
660 { // search in sessions with a cookie
661 for (c = parent->m_clientPool; c; c = c->m_next)
664 assert(*c->m_prev == c);
665 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
666 !strcmp(m_proxyTarget, c->get_hostname()))
669 // The following handles "cancel"
670 // If connection is busy (waiting for PDU) and
671 // we have an initRequest we can safely do re-open
672 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
674 yaz_log(YLOG_LOG, "%s REOPEN target=%s", m_session_str,
681 c->m_last_resultCount = 0;
682 c->m_sr_transform = 0;
684 c->m_resultSetStartPoint = 0;
685 c->m_target_idletime = m_target_idletime;
686 if (c->client(m_proxyTarget))
693 c->m_seqno = parent->m_seqno;
694 if (c->m_server && c->m_server != this)
695 c->m_server->m_client = 0;
698 yaz_log(YLOG_DEBUG, "get_client 1 %p %p", this, c);
703 else if (!c && apdu->which == Z_APDU_initRequest )
705 // anonymous sessions without cookie.
706 // if authentication is set it is NOT anonymous se we can't share them.
707 // If charset and lang negotiation is use it is NOT anonymous session too.
708 for (c = parent->m_clientPool; c; c = c->m_next)
711 assert(*c->m_prev == c);
712 if (c->m_server == 0 && c->m_cookie == 0 && c->m_waiting == 0
713 && c->compare_idAuthentication(apdu)
714 && c->compare_charset(apdu)
715 && !strcmp(m_proxyTarget, c->get_hostname()))
718 yaz_log(YLOG_LOG, "%sREUSE %d %s",
719 m_session_str, parent->m_seqno, c->get_hostname());
721 c->m_seqno = parent->m_seqno;
722 assert(c->m_server == 0);
725 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
726 c->set_APDU_yazlog(1);
728 c->set_APDU_yazlog(0);
740 if (apdu->which != Z_APDU_initRequest)
742 yaz_log(YLOG_LOG, "%sno init request as first PDU", m_session_str);
747 int no_in_use = get_number_of_connections();
748 if (no_in_use >= m_max_sockets)
750 yaz_log(YLOG_LOG, "%smax sockets reached %d", m_session_str,
755 // go through list of clients - and find the lowest/oldest one.
756 Yaz_ProxyClient *c_min = 0;
758 int no_of_clients = 0;
759 if (parent->m_clientPool)
760 yaz_log(YLOG_DEBUG, "Existing sessions");
761 for (c = parent->m_clientPool; c; c = c->m_next)
763 yaz_log(YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
764 c->m_waiting, c->get_hostname(),
765 c->m_cookie ? c->m_cookie : "");
767 if (min_seq < 0 || c->m_seqno < min_seq)
769 min_seq = c->m_seqno;
773 if (no_of_clients >= parent->m_max_clients)
776 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
778 yaz_log(YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
779 m_session_str, parent->m_max_clients, c->m_seqno);
780 if (c->m_server && c->m_server != this)
781 c->m_server->dec_ref();
785 yaz_log(YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
786 m_session_str, parent->m_max_clients,
787 c->m_seqno, parent->m_seqno, c->get_hostname());
791 c->m_cookie = xstrdup(cookie);
792 c->m_seqno = parent->m_seqno;
793 if (c->m_server && c->m_server != this)
795 c->m_server->m_client = 0;
796 c->m_server->dec_ref();
799 c->m_target_idletime = m_target_idletime;
800 c->timeout(m_target_idletime);
802 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
803 c->set_APDU_yazlog(1);
805 c->set_APDU_yazlog(0);
813 yaz_log(YLOG_LOG, "%sNEW %d %s",
814 m_session_str, parent->m_seqno, m_proxyTarget);
815 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
816 c->m_next = parent->m_clientPool;
818 c->m_next->m_prev = &c->m_next;
819 parent->m_clientPool = c;
820 c->m_prev = &parent->m_clientPool;
826 c->m_cookie = xstrdup(cookie);
828 c->m_seqno = parent->m_seqno;
830 c->m_last_resultCount = 0;
833 c->m_sr_transform = 0;
835 c->m_resultSetStartPoint = 0;
837 if (c->client(m_proxyTarget))
842 c->m_target_idletime = m_target_idletime;
845 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
846 c->set_APDU_yazlog(1);
848 c->set_APDU_yazlog(0);
850 c->set_idAuthentication(apdu);
852 yaz_log(YLOG_DEBUG, "get_client 3 %p %p", this, c);
856 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
859 for (i = 0; i<num; i++)
861 Z_DefaultDiagFormat *r;
862 Z_DiagRec *p = pp[i];
863 if (p->which != Z_DiagRec_defaultFormat)
865 yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
869 r = p->u.defaultFormat;
872 case Z_DefaultDiagFormat_v2Addinfo:
873 yaz_log(YLOG_LOG, "%sError " ODR_INT_PRINTF " %s:%s",
875 *r->condition, diagbib1_str(*r->condition),
878 case Z_DefaultDiagFormat_v3Addinfo:
879 yaz_log(YLOG_LOG, "%sError " ODR_INT_PRINTF " %s:%s",
881 *r->condition, diagbib1_str(*r->condition),
888 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
890 if (!m_stylesheet_xsp || p->num_records <= 0)
892 return 0; /* no XSLT to be done ... */
895 m_stylesheet_offset = 0;
896 m_stylesheet_nprl = p;
897 m_stylesheet_apdu = apdu;
898 m_timeout_mode = timeout_xsl;
904 void Yaz_Proxy::convert_xsl_delay()
907 Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
908 if (npr->which == Z_NamePlusRecord_databaseRecord)
910 Z_External *r = npr->u.databaseRecord;
911 if (r->which == Z_External_octet)
914 fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
916 xmlDocPtr res, doc = xmlParseMemory(
917 (char*) r->u.octet_aligned->buf,
918 r->u.octet_aligned->len);
921 yaz_log(YLOG_LOG, "%sXSLT convert %d",
922 m_session_str, m_stylesheet_offset);
923 res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
930 xmlDocDumpFormatMemory(res, &out_buf, &out_len, 1);
931 m_stylesheet_nprl->records[m_stylesheet_offset]->
933 z_ext_record_oid(odr_encode(), yaz_oid_recsyn_xml,
934 (char*) out_buf, out_len);
943 m_stylesheet_offset++;
944 if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
946 m_timeout_mode = timeout_normal;
947 m_stylesheet_nprl = 0;
949 if (m_stylesheet_xsp)
950 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
952 m_stylesheet_xsp = 0;
953 timeout(m_client_idletime);
954 send_PDU_convert(m_stylesheet_apdu);
960 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
962 if (m_frontend_type[0] != -1)
965 for (i = 0; i < p->num_records; i++)
967 Z_NamePlusRecord *npr = p->records[i];
968 if (npr->which == Z_NamePlusRecord_databaseRecord)
970 Z_External *r = npr->u.databaseRecord;
971 if (r->which == Z_External_octet)
974 if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
975 yaz_log(YLOG_LOG, "%sError: USEMARCON requested but not available",
979 yaz_log(YLOG_DEBUG, "%sUSEMARCON stage1=%s stage2=%s",
981 m_usemarcon_ini_stage1 ? m_usemarcon_ini_stage1 : "(none)",
982 m_usemarcon_ini_stage2 ? m_usemarcon_ini_stage2 : "(none)");
985 if (m_usemarcon->convert(m_usemarcon_ini_stage1, m_usemarcon_ini_stage2,
986 (char*) r->u.octet_aligned->buf, r->u.octet_aligned->len,
987 &converted, &convlen))
989 npr->u.databaseRecord =
990 z_ext_record_oid(odr_encode(),
999 npr->u.databaseRecord =
1000 z_ext_record_oid(odr_encode(),
1002 (char*) r->u.octet_aligned->buf,
1003 r->u.octet_aligned->len);
1010 void Yaz_Proxy::convert_records_charset(Z_NamePlusRecordList *p,
1011 const char *backend_charset)
1013 int sel = m_charset_converter->get_client_charset_selected();
1014 const char *client_record_charset =
1015 m_charset_converter->get_client_query_charset();
1016 if (sel && backend_charset && client_record_charset &&
1017 strcmp(backend_charset, client_record_charset))
1020 yaz_iconv_t cd = yaz_iconv_open(client_record_charset,
1022 yaz_marc_t mt = yaz_marc_create();
1023 yaz_marc_xml(mt, YAZ_MARC_ISO2709);
1024 yaz_marc_iconv(mt, cd);
1025 for (i = 0; i < p->num_records; i++)
1027 Z_NamePlusRecord *npr = p->records[i];
1028 if (npr->which == Z_NamePlusRecord_databaseRecord)
1030 Z_External *r = npr->u.databaseRecord;
1031 const Odr_oid *oid = r->direct_reference;
1035 if (!oid_oidcmp(oid, yaz_oid_recsyn_sutrs))
1037 WRBUF w = wrbuf_alloc();
1039 wrbuf_iconv_write(w, cd, (char*) r->u.octet_aligned->buf,
1040 r->u.octet_aligned->len);
1041 npr->u.databaseRecord =
1042 z_ext_record_oid(odr_encode(), oid, wrbuf_buf(w),
1046 else if (!oid_oidcmp(oid, yaz_oid_recsyn_xml))
1050 else if (r->which == Z_External_octet)
1054 if (yaz_marc_decode_buf(mt,
1055 (char*) r->u.octet_aligned->buf,
1056 r->u.octet_aligned->len,
1059 npr->u.databaseRecord =
1060 z_ext_record_oid(odr_encode(), oid, result, rlen);
1061 yaz_log(YLOG_LOG, "%sRecoding MARC record",
1068 yaz_iconv_close(cd);
1069 yaz_marc_destroy(mt);
1073 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
1074 const char *backend_charset)
1077 if (!backend_charset)
1078 backend_charset = "MARC-8";
1079 yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
1080 yaz_marc_t mt = yaz_marc_create();
1081 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1082 yaz_marc_iconv(mt, cd);
1083 for (i = 0; i < p->num_records; i++)
1085 Z_NamePlusRecord *npr = p->records[i];
1086 if (npr->which == Z_NamePlusRecord_databaseRecord)
1088 Z_External *r = npr->u.databaseRecord;
1089 if (r->which == Z_External_OPAC)
1091 WRBUF w = wrbuf_alloc();
1093 yaz_opac_decode_wrbuf(mt, r->u.opac, w);
1094 npr->u.databaseRecord = z_ext_record_oid(
1095 odr_encode(), yaz_oid_recsyn_xml,
1096 wrbuf_buf(w), wrbuf_len(w));
1099 else if (r->which == Z_External_octet)
1103 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
1104 r->u.octet_aligned->len,
1107 npr->u.databaseRecord =
1108 z_ext_record_oid(odr_encode(), yaz_oid_recsyn_xml,
1115 yaz_iconv_close(cd);
1116 yaz_marc_destroy(mt);
1119 void Yaz_Proxy::logtime()
1121 #if HAVE_GETTIMEOFDAY
1122 struct timeval *tv = (struct timeval*) m_time_tv;
1126 gettimeofday(&tv1, 0);
1127 long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
1128 (tv1.tv_usec - tv->tv_usec);
1130 yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
1131 diff/1000000, (diff/1000)%1000);
1138 int Yaz_Proxy::send_http_response(int code)
1140 ODR o = odr_encode();
1141 Z_GDU *gdu = z_get_HTTP_Response(o, code);
1142 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1144 hres->version = odr_strdup(o, m_http_version);
1145 if (m_http_keepalive)
1146 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1150 z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate",
1151 "Basic realm=\"YAZ Proxy\"");
1154 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1156 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1160 int r = send_GDU(gdu, &len);
1161 m_bytes_sent += len;
1162 m_bw_stat.add_bytes(len);
1165 recv_GDU_more(true);
1170 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu, int http_code /* = 200 */)
1172 ODR o = odr_encode();
1173 const char *ctype = "text/xml";
1174 Z_GDU *gdu = z_get_HTTP_Response(o, http_code);
1175 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1177 hres->version = odr_strdup(o, m_http_version);
1178 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1179 if (m_http_keepalive)
1180 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1183 if (http_code == 401)
1184 z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate", "Basic realm=\"YAZ Proxy\"");
1186 static Z_SOAP_Handler soap_handlers[2] = {
1188 { (char*) "http://www.loc.gov/zing/srw/", 0,
1189 (Z_SOAP_fun) yaz_srw_codec},
1194 Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
1195 soap_package->which = Z_SOAP_generic;
1196 soap_package->u.generic =
1197 (Z_SOAP_Generic *) odr_malloc(o, sizeof(*soap_package->u.generic));
1198 soap_package->u.generic->no = 0;
1199 soap_package->u.generic->ns = soap_handlers[0].ns;
1200 soap_package->u.generic->p = (void *) srw_pdu;
1201 soap_package->ns = m_soap_ns;
1202 z_soap_codec_enc_xsl(o, &soap_package,
1203 &hres->content_buf, &hres->content_len,
1204 soap_handlers, 0, m_s2z_stylesheet);
1205 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1207 yaz_log(YLOG_LOG, "%sSending %s to client", m_session_str,
1211 int r = send_GDU(gdu, &len);
1212 m_bytes_sent += len;
1213 m_bw_stat.add_bytes(len);
1216 recv_GDU_more(true);
1221 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
1223 ODR o = odr_encode();
1224 Z_SRW_diagnostic *diagnostic = (Z_SRW_diagnostic *)
1225 odr_malloc(o, sizeof(*diagnostic));
1226 int num_diagnostic = 1;
1227 yaz_mk_std_diagnostic(o, diagnostic, srw_error, add);
1228 return send_srw_search_response(diagnostic, num_diagnostic, srw_error == 3 ? 401 : 200);
1231 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
1232 Z_DefaultDiagFormat *ddf)
1234 int bib1_code = *ddf->condition;
1235 if (bib1_code == 109)
1237 srw_res->num_diagnostics = 1;
1238 srw_res->diagnostics = (Z_SRW_diagnostic *)
1239 odr_malloc(o, sizeof(*srw_res->diagnostics));
1240 yaz_mk_std_diagnostic(o, srw_res->diagnostics,
1241 yaz_diag_bib1_to_srw(*ddf->condition),
1246 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_scanResponse *srw_res,
1249 if (dr->which == Z_DiagRec_defaultFormat)
1251 int bib1_code = *dr->u.defaultFormat->condition;
1252 if (bib1_code == 109)
1254 srw_res->num_diagnostics = 1;
1255 srw_res->diagnostics = (Z_SRW_diagnostic *)
1256 odr_malloc(o, sizeof(*srw_res->diagnostics));
1257 yaz_mk_std_diagnostic(o, srw_res->diagnostics,
1258 yaz_diag_bib1_to_srw(*dr->u.defaultFormat->condition),
1259 dr->u.defaultFormat->u.v2Addinfo);
1264 #if YAZ_HAS_MK_SURROGATE
1266 static void yazproxy_mk_sru_surrogate(ODR o, Z_SRW_record *record, int pos,
1267 int code, const char *details)
1269 const char *message = yaz_diag_srw_str(code);
1272 len += strlen(message);
1274 len += strlen(details);
1276 record->recordData_buf = (char *) odr_malloc(o, len);
1278 sprintf(record->recordData_buf, "<diagnostic "
1279 "xmlns=\"http://www.loc.gov/zing/srw/diagnostic/\">\n"
1280 " <uri>info:srw/diagnostic/1/%d</uri>\n", code);
1282 sprintf(record->recordData_buf + strlen(record->recordData_buf),
1283 " <details>%s</details>\n", details);
1285 sprintf(record->recordData_buf + strlen(record->recordData_buf),
1286 " <message>%s</message>\n", message);
1287 sprintf(record->recordData_buf + strlen(record->recordData_buf),
1289 record->recordData_len = strlen(record->recordData_buf);
1290 record->recordPosition = odr_intdup(o, pos);
1291 record->recordSchema = odr_strdup(o, "info:srw/schema/1/diagnostics-v1.1");
1295 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
1297 ODR o = odr_encode();
1298 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1299 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1301 srw_res->numberOfRecords = odr_intdup (o, hits);
1302 if (records && records->which == Z_Records_DBOSD)
1304 srw_res->num_records =
1305 records->u.databaseOrSurDiagnostics->num_records;
1307 srw_res->records = (Z_SRW_record *)
1308 odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
1309 for (i = 0; i < srw_res->num_records; i++)
1311 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
1312 if (npr->which != Z_NamePlusRecord_databaseRecord)
1314 #if YAZ_HAS_MK_SURROGATE
1315 yaz_mk_sru_surrogate(
1316 o, srw_res->records + i, i+start,
1317 YAZ_SRW_RECORD_NOT_AVAILABLE_IN_THIS_SCHEMA, 0);
1319 yazproxy_mk_sru_surrogate(
1320 o, srw_res->records + i, i+start,
1321 YAZ_SRW_RECORD_NOT_AVAILABLE_IN_THIS_SCHEMA, 0);
1325 Z_External *r = npr->u.databaseRecord;
1327 if (r->which == Z_External_octet
1328 && !oid_oidcmp(r->direct_reference, yaz_oid_recsyn_xml))
1330 srw_res->records[i].recordSchema = m_schema;
1331 srw_res->records[i].recordPacking = m_s2z_packing;
1332 srw_res->records[i].recordData_buf = (char*)
1333 r->u.octet_aligned->buf;
1334 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1335 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1339 #if YAZ_HAS_MK_SURROGATE
1340 yaz_mk_sru_surrogate(
1341 o, srw_res->records + i, i+start,
1342 YAZ_SRW_RECORD_NOT_AVAILABLE_IN_THIS_SCHEMA, 0);
1344 yazproxy_mk_sru_surrogate(
1345 o, srw_res->records + i, i+start,
1346 YAZ_SRW_RECORD_NOT_AVAILABLE_IN_THIS_SCHEMA, 0);
1351 if (records && records->which == Z_Records_NSD)
1354 http_code = z_to_srw_diag(odr_encode(), srw_res,
1355 records->u.nonSurrogateDiagnostic);
1357 return send_http_response(http_code);
1359 return send_srw_response(srw_pdu);
1363 int Yaz_Proxy::send_to_srw_client_ok(Z_ListEntries *entries)
1365 ODR o = odr_encode();
1366 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_scan_response);
1367 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
1369 if (entries && entries->num_entries > 0)
1371 srw_res->num_terms = entries->num_entries;
1373 srw_res->terms = (Z_SRW_scanTerm *)
1374 odr_malloc(o, srw_res->num_terms * sizeof(Z_SRW_scanTerm));
1375 for (i = 0; i < srw_res->num_terms; i++)
1377 if (entries->entries[i]->which == Z_Entry_termInfo)
1379 switch(entries->entries[i]->u.termInfo->term->which)
1381 case Z_Term_general:
1382 srw_res->terms[i].value = odr_strdupn(o,
1383 (char *) entries->entries[i]->u.termInfo->term->u.general->buf,
1384 entries->entries[i]->u.termInfo->term->u.general->len);
1387 srw_res->terms[i].value = NULL;
1389 if (entries->entries[i]->u.termInfo->globalOccurrences != NULL)
1390 srw_res->terms[i].numberOfRecords = odr_intdup(o,
1391 *entries->entries[i]->u.termInfo->globalOccurrences);
1393 srw_res->terms[i].numberOfRecords = NULL;
1394 if (entries->entries[i]->u.termInfo->displayTerm != NULL)
1395 srw_res->terms[i].displayTerm = odr_strdup(o,
1396 entries->entries[i]->u.termInfo->displayTerm);
1398 srw_res->terms[i].displayTerm = NULL;
1399 srw_res->terms[i].whereInList = NULL;
1403 if (entries && entries->num_nonsurrogateDiagnostics > 0)
1406 http_code = z_to_srw_diag(odr_encode(), srw_res,
1407 entries->nonsurrogateDiagnostics[0]);
1409 return send_http_response(http_code);
1411 return send_srw_response(srw_pdu);
1415 int Yaz_Proxy::send_srw_search_response(Z_SRW_diagnostic *diagnostics,
1416 int num_diagnostics, int http_code /* = 200 */)
1418 ODR o = odr_encode();
1419 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1420 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1422 srw_res->num_diagnostics = num_diagnostics;
1423 srw_res->diagnostics = diagnostics;
1424 return send_srw_response(srw_pdu, http_code);
1427 int Yaz_Proxy::send_srw_scan_response(Z_SRW_diagnostic *diagnostics,
1428 int num_diagnostics, int http_code /* = 200 */)
1430 ODR o = odr_encode();
1431 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_scan_response);
1432 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
1434 srw_res->num_diagnostics = num_diagnostics;
1435 srw_res->diagnostics = diagnostics;
1436 return send_srw_response(srw_pdu, http_code);
1439 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1440 int num_diagnostics)
1442 int http_status = 404;
1443 Yaz_ProxyConfig *cfg = check_reconfigure();
1447 char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1448 m_s2z_database, &len, &http_status);
1451 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1452 Z_SRW_explainResponse *er = res->u.explain_response;
1454 er->record.recordData_buf = b;
1455 er->record.recordData_len = len;
1456 er->record.recordPacking = m_s2z_packing;
1457 er->record.recordSchema = odr_strdup(odr_encode(),
1458 "http://explain.z3950.org/dtd/2.0/");
1460 er->diagnostics = diagnostics;
1461 er->num_diagnostics = num_diagnostics;
1462 return send_srw_response(res);
1465 return send_http_response(http_status);
1468 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1472 if (apdu->which == Z_APDU_initResponse)
1474 Z_InitResponse *res = apdu->u.initResponse;
1475 if (*res->result == 0)
1477 send_to_srw_client_error(3, 0);
1479 else if (m_s2z_search_apdu)
1481 handle_incoming_Z_PDU(m_s2z_search_apdu);
1483 else if (m_s2z_scan_apdu)
1485 handle_incoming_Z_PDU(m_s2z_scan_apdu);
1489 send_srw_explain_response(0, 0);
1492 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1494 m_s2z_search_apdu = 0;
1495 Z_SearchResponse *res = apdu->u.searchResponse;
1496 m_s2z_hit_count = *res->resultCount;
1497 if (res->records && res->records->which == Z_Records_NSD)
1499 send_to_srw_client_ok(0, res->records, 1);
1501 else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1504 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1506 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1508 if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1510 *pr->numberOfRecordsRequested =
1511 1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1513 handle_incoming_Z_PDU(m_s2z_present_apdu);
1517 m_s2z_present_apdu = 0;
1518 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1521 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1524 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1526 m_s2z_present_apdu = 0;
1527 Z_PresentResponse *res = apdu->u.presentResponse;
1528 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1530 else if (m_s2z_scan_apdu && apdu->which == Z_APDU_scanResponse)
1532 Z_ScanResponse *res = apdu->u.scanResponse;
1533 send_to_srw_client_ok(res->entries);
1539 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1540 yaz_log(YLOG_LOG, "%sSending %s to client", m_session_str,
1542 int r = send_Z_PDU(apdu, &len);
1543 m_bytes_sent += len;
1544 m_bw_stat.add_bytes(len);
1551 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1553 int kill_session = 0;
1554 Z_ReferenceId **new_id = get_referenceIdP(apdu);
1557 *new_id = m_referenceId;
1559 if (apdu->which == Z_APDU_searchResponse)
1561 Z_SearchResponse *sr = apdu->u.searchResponse;
1562 Z_Records *p = sr->records;
1563 if (p && p->which == Z_Records_NSD)
1565 Z_DiagRec dr, *dr_p = &dr;
1566 dr.which = Z_DiagRec_defaultFormat;
1567 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1569 *sr->searchStatus = 0;
1570 display_diagrecs(&dr_p, 1);
1574 if (p && p->which == Z_Records_DBOSD)
1578 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1581 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1582 if (m_marcxml_mode == marcxml)
1583 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1586 convert_records_charset(p->u.databaseOrSurDiagnostics,
1588 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1592 if (sr->resultCount)
1594 yaz_log(YLOG_LOG, "%s" ODR_INT_PRINTF " hits", m_session_str,
1596 if (*sr->resultCount < 0)
1598 m_flag_invalid_session = 1;
1601 *sr->searchStatus = 0;
1603 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1604 *sr->resultCount = 0;
1609 else if (apdu->which == Z_APDU_presentResponse)
1611 Z_PresentResponse *sr = apdu->u.presentResponse;
1612 Z_Records *p = sr->records;
1613 if (p && p->which == Z_Records_NSD)
1615 Z_DiagRec dr, *dr_p = &dr;
1616 dr.which = Z_DiagRec_defaultFormat;
1617 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1618 if (*sr->presentStatus == Z_PresentStatus_success)
1619 *sr->presentStatus = Z_PresentStatus_failure;
1620 display_diagrecs(&dr_p, 1);
1622 if (p && p->which == Z_Records_DBOSD)
1626 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1629 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1630 if (m_marcxml_mode == marcxml)
1631 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1634 convert_records_charset(p->u.databaseOrSurDiagnostics,
1636 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1640 else if (apdu->which == Z_APDU_initResponse)
1642 //Get and check negotiation record
1643 //from init response.
1644 handle_charset_lang_negotiation(apdu);
1646 if (m_initRequest_options)
1649 (Odr_bitmask *)odr_malloc(odr_encode(),
1650 sizeof(Odr_bitmask));
1651 ODR_MASK_ZERO(nopt);
1654 for (i = 0; i<24; i++)
1655 if (ODR_MASK_GET(m_initRequest_options, i) &&
1656 ODR_MASK_GET(apdu->u.initResponse->options, i))
1657 ODR_MASK_SET(nopt, i);
1658 apdu->u.initResponse->options = nopt;
1660 if (m_initRequest_version)
1662 Z_ProtocolVersion *nopt =
1663 (Odr_bitmask *)odr_malloc(odr_encode(),
1664 sizeof(Odr_bitmask));
1665 ODR_MASK_ZERO(nopt);
1668 for (i = 0; i<8; i++)
1669 if (ODR_MASK_GET(m_initRequest_version, i) &&
1670 ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1671 ODR_MASK_SET(nopt, i);
1672 apdu->u.initResponse->protocolVersion = nopt;
1674 apdu->u.initResponse->preferredMessageSize =
1675 odr_intdup(odr_encode(),
1676 m_client->m_initResponse_preferredMessageSize >
1677 m_initRequest_preferredMessageSize ?
1678 m_initRequest_preferredMessageSize :
1679 m_client->m_initResponse_preferredMessageSize);
1680 apdu->u.initResponse->maximumRecordSize =
1681 odr_intdup(odr_encode(),
1682 m_client->m_initResponse_maximumRecordSize >
1683 m_initRequest_maximumRecordSize ?
1684 m_initRequest_maximumRecordSize :
1685 m_client->m_initResponse_maximumRecordSize);
1688 int r = send_PDU_convert(apdu);
1695 m_parent->pre_init();
1700 void Yaz_ProxyClient::set_idAuthentication(Z_APDU *apdu)
1702 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1704 odr_reset(m_idAuthentication_odr);
1705 z_IdAuthentication(m_idAuthentication_odr, &t, 1, 0);
1706 m_idAuthentication_ber_buf =
1707 odr_getbuf(m_idAuthentication_odr,
1708 &m_idAuthentication_ber_size, 0);
1711 bool Yaz_ProxyClient::compare_charset(Z_APDU *apdu)
1716 bool Yaz_ProxyClient::compare_idAuthentication(Z_APDU *apdu)
1718 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1719 ODR odr = odr_createmem(ODR_ENCODE);
1721 z_IdAuthentication(odr, &t, 1, 0);
1723 char *buf = odr_getbuf(odr, &sz, 0);
1724 if (buf && m_idAuthentication_ber_buf
1725 && sz == m_idAuthentication_ber_size
1726 && !memcmp(m_idAuthentication_ber_buf, buf, sz))
1732 if (!buf && !m_idAuthentication_ber_buf)
1737 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1740 const char *apdu_name_tmp = apdu_name(apdu);
1741 int r = send_Z_PDU(apdu, &len);
1742 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1743 yaz_log(YLOG_LOG, "%sSending %s to %s %d bytes",
1745 apdu_name_tmp, get_hostname(), len);
1746 m_bytes_sent += len;
1750 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1752 if (apdu->which == Z_APDU_presentRequest)
1754 Z_PresentRequest *pr = apdu->u.presentRequest;
1755 int toget = *pr->numberOfRecordsRequested;
1756 int start = *pr->resultSetStartPoint;
1758 yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1759 pr->resultSetId, start, toget);
1761 if (*m_parent->m_optimize == '0')
1764 if (!m_client->m_last_resultSetId)
1766 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1767 new_apdu->u.presentResponse->records =
1768 create_nonSurrogateDiagnostics(
1770 YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1772 send_to_client(new_apdu);
1775 if (start < 1 || toget < 0)
1777 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1778 new_apdu->u.presentResponse->records =
1779 create_nonSurrogateDiagnostics(
1781 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1783 send_to_client(new_apdu);
1786 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1788 if (start+toget-1 > m_client->m_last_resultCount)
1790 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1791 new_apdu->u.presentResponse->records =
1792 create_nonSurrogateDiagnostics(
1794 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1796 send_to_client(new_apdu);
1799 Z_NamePlusRecordList *npr;
1801 yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1802 m_session_str, start, toget, yaz_z3950oid_to_str(
1803 pr->preferredRecordSyntax, &oclass));
1805 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1806 pr->preferredRecordSyntax,
1807 pr->recordComposition))
1809 yaz_log(YLOG_LOG, "%sReturned cached records for present request",
1811 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1812 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1814 new_apdu->u.presentResponse->numberOfRecordsReturned
1815 = odr_intdup(odr_encode(), toget);
1817 new_apdu->u.presentResponse->records = (Z_Records*)
1818 odr_malloc(odr_encode(), sizeof(Z_Records));
1819 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1820 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1821 new_apdu->u.presentResponse->nextResultSetPosition =
1822 odr_intdup(odr_encode(), start+toget);
1824 send_to_client(new_apdu);
1830 if (apdu->which != Z_APDU_searchRequest)
1832 Z_SearchRequest *sr = apdu->u.searchRequest;
1833 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1834 Yaz_Z_Databases this_databases;
1836 this_databases.set(sr->num_databaseNames, (const char **)
1839 this_query->set_Z_Query(sr->query);
1841 // Check for non-negative piggyback params.
1842 if (*sr->smallSetUpperBound < 0
1843 || *sr->largeSetLowerBound < 0
1844 || *sr->mediumSetPresentNumber < 0)
1846 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1847 // Not a present request.. But can't find better diagnostic
1848 new_apdu->u.searchResponse->records =
1849 create_nonSurrogateDiagnostics(
1851 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 0);
1852 send_to_client(new_apdu);
1856 char query_str[4096];
1857 this_query->print(query_str, sizeof(query_str)-1);
1858 yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1860 if (*m_parent->m_optimize != '0' &&
1861 m_client->m_last_ok && m_client->m_last_query &&
1862 m_client->m_last_query->match(this_query) &&
1863 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1864 m_client->m_last_databases.match(this_databases))
1867 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1868 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1870 Z_NamePlusRecordList *npr;
1871 int toget = *sr->mediumSetPresentNumber;
1872 Z_RecordComposition *comp = 0;
1874 if (toget > m_client->m_last_resultCount)
1875 toget = m_client->m_last_resultCount;
1877 if (sr->mediumSetElementSetNames)
1879 comp = (Z_RecordComposition *)
1880 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1881 comp->which = Z_RecordComp_simple;
1882 comp->u.simple = sr->mediumSetElementSetNames;
1885 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1886 sr->preferredRecordSyntax, comp))
1888 yaz_log(YLOG_LOG, "%sReturned cached records for medium set",
1890 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1891 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1892 new_apdu->u.searchResponse->resultCount =
1893 &m_client->m_last_resultCount;
1895 new_apdu->u.searchResponse->numberOfRecordsReturned
1896 = odr_intdup(odr_encode(), toget);
1898 new_apdu->u.searchResponse->presentStatus =
1899 odr_intdup(odr_encode(), Z_PresentStatus_success);
1900 new_apdu->u.searchResponse->records = (Z_Records*)
1901 odr_malloc(odr_encode(), sizeof(Z_Records));
1902 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1903 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1904 new_apdu->u.searchResponse->nextResultSetPosition =
1905 odr_intdup(odr_encode(), toget+1);
1906 send_to_client(new_apdu);
1912 // send present request (medium size)
1913 yaz_log(YLOG_LOG, "%sOptimizing search for medium set",
1916 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1917 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1918 pr->referenceId = sr->referenceId;
1919 pr->resultSetId = sr->resultSetName;
1920 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1921 *pr->numberOfRecordsRequested = toget;
1922 pr->recordComposition = comp;
1923 m_client->m_sr_transform = 1;
1927 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1928 m_client->m_last_resultCount <= 0)
1930 // large set. Return pseudo-search response immediately
1931 yaz_log(YLOG_LOG, "%sOptimizing search for large set",
1933 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1934 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1935 new_apdu->u.searchResponse->resultCount =
1936 &m_client->m_last_resultCount;
1937 send_to_client(new_apdu);
1942 Z_NamePlusRecordList *npr;
1943 int toget = m_client->m_last_resultCount;
1944 Z_RecordComposition *comp = 0;
1946 // send a present request (small set)
1948 if (sr->smallSetElementSetNames)
1950 comp = (Z_RecordComposition *)
1951 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1952 comp->which = Z_RecordComp_simple;
1953 comp->u.simple = sr->smallSetElementSetNames;
1956 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1957 sr->preferredRecordSyntax, comp))
1959 yaz_log(YLOG_LOG, "%sReturned cached records for small set",
1961 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1962 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1963 new_apdu->u.searchResponse->resultCount =
1964 &m_client->m_last_resultCount;
1966 new_apdu->u.searchResponse->numberOfRecordsReturned
1967 = odr_intdup(odr_encode(), toget);
1969 new_apdu->u.searchResponse->presentStatus =
1970 odr_intdup(odr_encode(), Z_PresentStatus_success);
1971 new_apdu->u.searchResponse->records = (Z_Records*)
1972 odr_malloc(odr_encode(), sizeof(Z_Records));
1973 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1974 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1975 new_apdu->u.searchResponse->nextResultSetPosition =
1976 odr_intdup(odr_encode(), toget+1);
1977 send_to_client(new_apdu);
1982 yaz_log(YLOG_LOG, "%sOptimizing search for small set",
1984 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1985 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1986 pr->referenceId = sr->referenceId;
1987 pr->resultSetId = sr->resultSetName;
1988 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1989 *pr->numberOfRecordsRequested = toget;
1990 pr->recordComposition = comp;
1991 m_client->m_sr_transform = 1;
1996 else // query doesn't match
1998 delete m_client->m_last_query;
1999 m_client->m_last_query = this_query;
2000 m_client->m_last_ok = 0;
2001 m_client->m_cache.clear();
2002 m_client->m_resultSetStartPoint = 0;
2004 xfree(m_client->m_last_resultSetId);
2005 m_client->m_last_resultSetId = xstrdup(sr->resultSetName);
2007 m_client->m_last_databases.set(sr->num_databaseNames,
2008 (const char **) sr->databaseNames);
2014 void Yaz_Proxy::inc_request_no()
2017 char *cp = m_session_str + strlen(m_session_str)-1;
2020 while (*cp && *cp != ' ')
2023 sprintf(cp+1, "%d ", m_request_no);
2026 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
2030 m_bytes_recv += len;
2032 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2033 yaz_log(YLOG_LOG, "%sReceiving %s from client %d bytes",
2034 m_session_str, gdu_name(apdu), len);
2037 // try to make a _bad_ attribute set ID .. Don't enable this in prod.
2038 if (apdu->which == Z_GDU_Z3950
2039 && apdu->u.z3950->which == Z_APDU_searchRequest)
2041 Z_SearchRequest *req = apdu->u.z3950->u.searchRequest;
2042 if (req->query && req->query->which == Z_Query_type_1)
2044 Z_RPNQuery *rpnquery = req->query->u.type_1;
2045 if (rpnquery->attributeSetId)
2047 rpnquery->attributeSetId[0] = -2;
2048 rpnquery->attributeSetId[1] = -1;
2049 yaz_log(YLOG_WARN, "%sBAD FIXUP TEST", m_session_str);
2055 #if HAVE_GETTIMEOFDAY
2056 gettimeofday((struct timeval *) m_time_tv, 0);
2058 m_bw_stat.add_bytes(len);
2059 m_pdu_stat.add_bytes(1);
2061 GDU *gdu = new GDU(apdu);
2063 if (gdu->get() == 0)
2066 yaz_log(YLOG_LOG, "%sUnable to encode package", m_session_str);
2071 m_in_queue.enqueue(gdu);
2072 recv_GDU_more(false);
2075 void Yaz_Proxy::HTTP_Forwarded(Z_GDU *z_gdu)
2077 if (z_gdu->which == Z_GDU_HTTP_Request)
2079 Z_HTTP_Request *hreq = z_gdu->u.HTTP_Request;
2080 const char *x_forwarded_for =
2081 z_HTTP_header_lookup(hreq->headers, "X-Forwarded-For");
2082 if (x_forwarded_for)
2085 m_peername = (char*) xmalloc(strlen(x_forwarded_for)+5);
2086 sprintf(m_peername, "tcp:%s", x_forwarded_for);
2088 yaz_log(YLOG_LOG, "%sHTTP Forwarded from %s", m_session_str,
2090 if (m_log_mask & PROXY_LOG_IP_CLIENT)
2091 sprintf(m_session_str, "%ld:%d %.80s %d ",
2092 (long) time(0), m_session_no, m_peername, m_request_no);
2094 sprintf(m_session_str, "%ld:%d %d ",
2095 (long) time(0), m_session_no, m_request_no);
2100 void Yaz_Proxy::connect_stat(bool &block, int &reduce)
2103 m_parent->m_connect.cleanup(false);
2104 m_parent->m_connect.add_connect(m_peername);
2106 int connect_total = m_parent->m_connect.get_total(m_peername);
2107 int max_connect = m_parent->m_max_connect;
2109 if (max_connect && connect_total > max_connect)
2111 yaz_log(YLOG_LOG, "%sconnect not accepted total=%d max=%d",
2112 m_session_str, connect_total, max_connect);
2117 yaz_log(YLOG_LOG, "%sconnect accepted total=%d", m_session_str,
2120 int limit_connect = m_parent->m_limit_connect;
2122 reduce = connect_total / limit_connect;
2127 void Yaz_Proxy::recv_GDU_reduce(GDU *gdu)
2129 HTTP_Forwarded(gdu->get());
2133 if (m_request_no == 1)
2137 connect_stat(block, reduce);
2141 m_timeout_mode = timeout_busy;
2147 int bw_total = m_bw_stat.get_total();
2148 int pdu_total = m_pdu_stat.get_total();
2149 int search_total = m_search_stat.get_total();
2151 assert(m_timeout_mode == timeout_busy);
2152 assert(m_timeout_gdu == 0);
2155 reduce += search_total / m_search_max;
2157 reduce += (bw_total/m_bw_max);
2160 if (pdu_total > m_pdu_max)
2162 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
2163 reduce = (reduce > nreduce) ? reduce : nreduce;
2169 /* uncomment to force a big reduce */
2170 m_timeout_mode = timeout_reduce;
2171 m_timeout_gdu = gdu;
2172 timeout(3); // call us reduce seconds later
2177 yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d search=%d limit-bw=%d limit-pdu=%d limit-search=%d",
2178 m_session_str, reduce, bw_total, pdu_total, search_total,
2179 m_bw_max, m_pdu_max, m_search_max);
2181 m_timeout_mode = timeout_reduce;
2182 m_timeout_gdu = gdu;
2183 timeout(reduce); // call us reduce seconds later
2186 recv_GDU_normal(gdu);
2189 void Yaz_Proxy::recv_GDU_more(bool normal)
2192 if (normal && m_timeout_mode == timeout_busy)
2193 m_timeout_mode = timeout_normal;
2194 while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
2196 m_timeout_mode = timeout_busy;
2204 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
2207 gdu->move_away_gdu(odr_decode(), &apdu);
2210 if (apdu->which == Z_GDU_Z3950)
2211 handle_incoming_Z_PDU(apdu->u.z3950);
2212 else if (apdu->which == Z_GDU_HTTP_Request)
2213 handle_incoming_HTTP(apdu->u.HTTP_Request);
2216 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
2218 if (m_max_record_retrieve)
2220 if (apdu->which == Z_APDU_presentRequest)
2222 Z_PresentRequest *pr = apdu->u.presentRequest;
2223 if (pr->numberOfRecordsRequested &&
2224 *pr->numberOfRecordsRequested > m_max_record_retrieve)
2225 *pr->numberOfRecordsRequested = m_max_record_retrieve;
2230 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
2232 if (apdu->which == Z_APDU_initRequest)
2234 if (m_initRequest_options &&
2235 !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
2236 (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
2238 // There is no negotiation proposal from
2239 // client's side. OK. The proxy negotiation
2241 Z_InitRequest *initRequest = apdu->u.initRequest;
2242 Z_OtherInformation **otherInfo;
2243 Z_OtherInformationUnit *oi;
2244 get_otherInfoAPDU(apdu, &otherInfo);
2245 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2248 ODR_MASK_SET(initRequest->options,
2249 Z_Options_negotiationModel);
2250 oi->which = Z_OtherInfo_externallyDefinedInfo;
2251 oi->information.externallyDefinedInfo =
2252 yaz_set_proposal_charneg(odr_encode(),
2253 (const char**)&m_proxy_negotiation_charset,
2254 m_proxy_negotiation_charset ? 1:0,
2255 (const char**)&m_proxy_negotiation_lang,
2256 m_proxy_negotiation_lang ? 1:0,
2260 else if (m_initRequest_options &&
2261 ODR_MASK_GET(m_initRequest_options,
2262 Z_Options_negotiationModel) &&
2263 m_charset_converter->get_target_query_charset())
2265 yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
2267 m_charset_converter->get_target_query_charset());
2268 Z_InitRequest *initRequest = apdu->u.initRequest;
2269 Z_CharSetandLanguageNegotiation *negotiation =
2270 yaz_get_charneg_record (initRequest->otherInfo);
2272 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2274 NMEM nmem = nmem_create();
2275 char **charsets = 0;
2276 int num_charsets = 0;
2280 yaz_get_proposal_charneg (nmem, negotiation,
2281 &charsets, &num_charsets,
2282 &langs, &num_langs, &selected);
2284 for (i = 0; i<num_charsets; i++)
2285 yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
2287 for (i = 0; i<num_langs; i++)
2288 yaz_log(YLOG_LOG, "%slang %s", m_session_str,
2291 const char *t_charset =
2292 m_charset_converter->get_target_query_charset();
2293 // sweep through charsets and pick the first supported
2295 for (i = 0; i<num_charsets; i++)
2297 const char *c_charset = charsets[i];
2298 if (!odr_set_charset(odr_decode(), t_charset, c_charset))
2301 if (i != num_charsets)
2303 // got one .. set up ODR for reverse direction
2304 const char *c_charset = charsets[i];
2305 odr_set_charset(odr_encode(), c_charset, t_charset);
2306 m_charset_converter->set_client_query_charset(c_charset);
2307 m_charset_converter->set_client_charset_selected(selected);
2310 ODR_MASK_CLEAR(m_initRequest_options,
2311 Z_Options_negotiationModel);
2312 yaz_del_charneg_record(&initRequest->otherInfo);
2316 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
2320 else if (m_charset_converter->get_target_query_charset() &&
2321 m_proxy_negotiation_default_charset)
2323 m_charset_converter->
2324 set_client_query_charset(m_proxy_negotiation_default_charset);
2327 else if (apdu->which == Z_APDU_initResponse)
2329 Z_InitResponse *initResponse = apdu->u.initResponse;
2330 Z_OtherInformation **otherInfo;
2331 get_otherInfoAPDU(apdu, &otherInfo);
2333 Z_CharSetandLanguageNegotiation *charneg = 0;
2335 if (otherInfo && *otherInfo &&
2336 ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel)
2337 && (charneg = yaz_get_charneg_record(*otherInfo)))
2343 yaz_get_response_charneg(m_referenceId_mem, charneg,
2344 &charset, &lang, &selected);
2346 yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
2347 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
2349 if (m_initRequest_options &&
2350 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
2352 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2355 else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2357 // negotiation-charset, negotiation-lang
2358 // elements of config file in use.
2360 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2363 // clear negotiation option.
2364 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2366 // Delete negotiation (charneg-3) entry.
2367 yaz_del_charneg_record(otherInfo);
2372 if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2374 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2377 else if (m_charset_converter->get_client_query_charset())
2379 Z_OtherInformation **otherInfo;
2380 Z_OtherInformationUnit *oi;
2381 get_otherInfoAPDU(apdu, &otherInfo);
2382 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2385 ODR_MASK_SET(initResponse->options,
2386 Z_Options_negotiationModel);
2387 if (m_initRequest_options)
2388 ODR_MASK_SET(m_initRequest_options,
2389 Z_Options_negotiationModel);
2391 oi->which = Z_OtherInfo_externallyDefinedInfo;
2392 oi->information.externallyDefinedInfo =
2393 yaz_set_response_charneg(
2395 m_charset_converter->get_client_query_charset(),
2397 m_charset_converter->get_client_charset_selected());
2404 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2406 const char *addinfo)
2408 Z_Records *rec = (Z_Records *)
2409 odr_malloc (odr, sizeof(*rec));
2410 Odr_int *err = (Odr_int *)
2411 odr_malloc (odr, sizeof(*err));
2412 Z_DiagRec *drec = (Z_DiagRec *)
2413 odr_malloc (odr, sizeof(*drec));
2414 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2415 odr_malloc (odr, sizeof(*dr));
2417 rec->which = Z_Records_NSD;
2418 rec->u.nonSurrogateDiagnostic = dr;
2419 dr->diagnosticSetId = odr_oiddup(odr, yaz_oid_diagset_bib_1);
2420 dr->condition = err;
2421 dr->which = Z_DefaultDiagFormat_v2Addinfo;
2422 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2426 Z_ListEntries *Yaz_Proxy::create_nonSurrogateDiagnostics2(ODR odr,
2428 const char *addinfo)
2430 Z_ListEntries *rec = (Z_ListEntries *)
2431 odr_malloc (odr, sizeof(*rec));
2432 Odr_int *err = (Odr_int *)
2433 odr_malloc (odr, sizeof(*err));
2434 Z_DiagRec *drec = (Z_DiagRec *)
2435 odr_malloc (odr, sizeof(*drec));
2436 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2437 odr_malloc (odr, sizeof(*dr));
2439 drec->which = Z_DiagRec_defaultFormat;
2440 drec->u.defaultFormat = dr;
2441 rec->num_entries = 0;
2442 rec->entries = NULL;
2443 rec->num_nonsurrogateDiagnostics = 1;
2444 rec->nonsurrogateDiagnostics =
2445 (Z_DiagRec **)odr_malloc(odr, sizeof(Z_DiagRec *));
2446 rec->nonsurrogateDiagnostics[0] = drec;
2447 dr->diagnosticSetId = odr_oiddup(odr, yaz_oid_diagset_bib_1);
2448 dr->condition = err;
2449 dr->which = Z_DefaultDiagFormat_v2Addinfo;
2450 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2454 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2456 if (apdu->which == Z_APDU_searchRequest &&
2457 apdu->u.searchRequest->query &&
2458 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2459 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2461 Z_RPNQuery *rpnquery = 0;
2462 Z_SearchRequest *sr = apdu->u.searchRequest;
2465 yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2466 sr->query->u.type_104->u.cql);
2468 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2469 &rpnquery, odr_encode(),
2472 yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2475 yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2476 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2478 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2479 new_apdu->u.searchResponse->records =
2480 create_nonSurrogateDiagnostics(odr_encode(),
2481 yaz_diag_srw_to_bib1(r),
2483 *new_apdu->u.searchResponse->searchStatus = 0;
2485 send_to_client(new_apdu);
2491 sr->query->which = Z_Query_type_1;
2492 sr->query->u.type_1 = rpnquery;
2496 else if (apdu->which == Z_APDU_scanRequest)
2498 Z_RPNQuery *rpnquery = 0;
2499 Z_ScanRequest *sr = apdu->u.scanRequest;
2502 yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2503 sr->termListAndStartPoint->term->u.characterString);
2505 int r = m_cql2rpn.query_transform(sr->termListAndStartPoint->term->u.characterString,
2506 &rpnquery, odr_encode(),
2509 yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2512 yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2513 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_scanResponse);
2515 new_apdu->u.scanResponse->referenceId = sr->referenceId;
2516 new_apdu->u.scanResponse->entries =
2517 create_nonSurrogateDiagnostics2(odr_encode(),
2518 yaz_diag_srw_to_bib1(r),
2520 *new_apdu->u.scanResponse->scanStatus = Z_Scan_failure;
2522 send_to_client(new_apdu);
2528 sr->attributeSet = rpnquery->attributeSetId;
2529 if (rpnquery->RPNStructure->which == Z_RPNStructure_simple)
2530 sr->termListAndStartPoint = rpnquery->RPNStructure->u.simple->u.attributesPlusTerm;
2537 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2539 if (apdu->which == Z_APDU_searchRequest &&
2540 apdu->u.searchRequest->query)
2542 if (apdu->u.searchRequest->query->which == Z_Query_type_1
2543 || apdu->u.searchRequest->query->which == Z_Query_type_101)
2546 m_charset_converter->set_client_query_charset("UTF-8");
2547 Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2548 m_charset_converter->convert_type_1(rpnquery, odr_encode());
2551 else if (apdu->which == Z_APDU_scanRequest &&
2552 apdu->u.scanRequest->termListAndStartPoint)
2554 if (apdu->u.scanRequest->termListAndStartPoint->term)
2556 m_charset_converter->set_client_query_charset("UTF-8");
2557 Z_Term *term = apdu->u.scanRequest->termListAndStartPoint->term;
2558 m_charset_converter->convert_term(term, odr_encode());
2564 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2566 if (apdu->which == Z_APDU_searchRequest)
2568 Z_SearchRequest *sr = apdu->u.searchRequest;
2572 Yaz_ProxyConfig *cfg = check_reconfigure();
2574 err = cfg->check_query(odr_encode(), m_default_target,
2575 sr->query, &addinfo);
2578 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2580 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2581 new_apdu->u.searchResponse->records =
2582 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2583 *new_apdu->u.searchResponse->searchStatus = 0;
2585 send_to_client(new_apdu);
2590 else if (apdu->which == Z_APDU_scanRequest)
2592 Z_ScanRequest *sr = apdu->u.scanRequest;
2596 Yaz_ProxyConfig *cfg = check_reconfigure();
2597 // Something like this needs to be implemented later:
2600 err = cfg->check_type_1_attributes(odr_encode(), m_default_target,
2601 sr->termListAndStartPoint->attributes, &addinfo);
2605 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_scanResponse);
2607 new_apdu->u.scanResponse->referenceId = sr->referenceId;
2608 new_apdu->u.scanResponse->entries =
2609 create_nonSurrogateDiagnostics2(odr_encode(), err, addinfo);
2610 *new_apdu->u.scanResponse->scanStatus = Z_Scan_failure;
2612 send_to_client(new_apdu);
2621 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2623 if (apdu->which != Z_APDU_initRequest)
2624 return 1; // pass if no init request
2625 Z_InitRequest *req = apdu->u.initRequest;
2627 Yaz_ProxyConfig *cfg = check_reconfigure();
2629 return 1; // pass if no config
2632 if (req->idAuthentication == 0)
2634 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2637 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2639 ret = cfg->client_authentication(
2641 req->idAuthentication->u.idPass->userId,
2642 req->idAuthentication->u.idPass->groupId,
2643 req->idAuthentication->u.idPass->password,
2646 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2648 char user[64], pass[64];
2651 sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2652 ret = cfg->client_authentication(m_default_target, user, 0, pass,
2656 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2661 int Yaz_Proxy::handle_global_authentication(Z_APDU *apdu)
2663 if (apdu->which != Z_APDU_initRequest)
2664 return 1; // pass if no init request
2665 Z_InitRequest *req = apdu->u.initRequest;
2667 Yaz_ProxyConfig *cfg = check_reconfigure();
2669 return 1; // pass if no config
2672 if (req->idAuthentication == 0)
2674 ret = cfg->global_client_authentication(0, 0, 0,
2677 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2679 ret = cfg->global_client_authentication(
2680 req->idAuthentication->u.idPass->userId,
2681 req->idAuthentication->u.idPass->groupId,
2682 req->idAuthentication->u.idPass->password,
2685 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2687 char user[64], pass[64];
2690 sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2691 ret = cfg->global_client_authentication(user, 0, pass,
2695 ret = cfg->global_client_authentication(0, 0, 0, m_peername);
2699 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2701 m_marcxml_mode = none;
2702 if (apdu->which == Z_APDU_searchRequest)
2704 Z_SearchRequest *sr = apdu->u.searchRequest;
2707 Yaz_ProxyConfig *cfg = check_reconfigure();
2709 Z_RecordComposition rc_temp, *rc = 0;
2710 if (sr->smallSetElementSetNames)
2712 rc_temp.which = Z_RecordComp_simple;
2713 rc_temp.u.simple = sr->smallSetElementSetNames;
2717 if (sr->preferredRecordSyntax)
2718 oid_oidcpy(m_frontend_type, sr->preferredRecordSyntax);
2720 m_frontend_type[0] = -1;
2722 char *stylesheet_name = 0;
2724 err = cfg->check_syntax(odr_encode(),
2726 sr->preferredRecordSyntax, rc,
2727 &addinfo, &stylesheet_name, &m_schema,
2728 &m_backend_type, &m_backend_charset,
2729 &m_usemarcon_ini_stage1,
2730 &m_usemarcon_ini_stage2,
2731 &m_backend_elementset);
2732 if (stylesheet_name)
2734 m_parent->low_socket_close();
2737 if (m_stylesheet_xsp)
2738 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2739 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2742 m_stylesheet_offset = 0;
2743 xfree(stylesheet_name);
2745 m_parent->low_socket_open();
2749 sr->smallSetElementSetNames = 0;
2750 sr->mediumSetElementSetNames = 0;
2751 m_marcxml_mode = marcxml;
2752 sr->preferredRecordSyntax =
2753 yaz_string_to_oid_odr(
2754 yaz_oid_std(), CLASS_RECSYN,
2755 m_backend_type ? m_backend_type : "usmarc",
2760 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2762 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2763 new_apdu->u.searchResponse->records =
2764 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2765 *new_apdu->u.searchResponse->searchStatus = 0;
2767 send_to_client(new_apdu);
2771 else if (m_backend_type)
2773 sr->preferredRecordSyntax =
2774 yaz_string_to_oid_odr(yaz_oid_std(), CLASS_RECSYN,
2775 m_backend_type, odr_encode());
2777 if (m_backend_elementset)
2779 Z_ElementSetNames *esn = mk_esn_from_schema(odr_encode(),
2780 m_backend_elementset);
2781 sr->smallSetElementSetNames = esn;
2782 sr->mediumSetElementSetNames = esn;
2785 else if (apdu->which == Z_APDU_presentRequest)
2787 Z_PresentRequest *pr = apdu->u.presentRequest;
2790 Yaz_ProxyConfig *cfg = check_reconfigure();
2792 if (pr->preferredRecordSyntax)
2793 oid_oidcpy(m_frontend_type, pr->preferredRecordSyntax);
2795 m_frontend_type[0] = -1;
2797 char *stylesheet_name = 0;
2799 err = cfg->check_syntax(odr_encode(), m_default_target,
2800 pr->preferredRecordSyntax,
2801 pr->recordComposition,
2802 &addinfo, &stylesheet_name, &m_schema,
2803 &m_backend_type, &m_backend_charset,
2804 &m_usemarcon_ini_stage1,
2805 &m_usemarcon_ini_stage2,
2806 &m_backend_elementset);
2807 if (stylesheet_name)
2809 m_parent->low_socket_close();
2812 if (m_stylesheet_xsp)
2813 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2814 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2817 m_stylesheet_offset = 0;
2818 xfree(stylesheet_name);
2820 m_parent->low_socket_open();
2824 pr->recordComposition = 0;
2825 m_marcxml_mode = marcxml;
2827 pr->preferredRecordSyntax =
2828 yaz_string_to_oid_odr(
2829 yaz_oid_std(), CLASS_RECSYN,
2830 m_backend_type ? m_backend_type : "usmarc",
2835 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2837 new_apdu->u.presentResponse->referenceId = pr->referenceId;
2838 new_apdu->u.presentResponse->records =
2839 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2840 *new_apdu->u.presentResponse->presentStatus =
2841 Z_PresentStatus_failure;
2843 send_to_client(new_apdu);
2847 else if (m_backend_type)
2849 pr->preferredRecordSyntax =
2850 yaz_string_to_oid_odr(yaz_oid_std(),
2851 CLASS_RECSYN, m_backend_type,
2854 if (m_backend_elementset)
2856 Z_ElementSetNames *esn = mk_esn_from_schema(odr_encode(),
2857 m_backend_elementset);
2858 Z_RecordComposition *comp = (Z_RecordComposition *)
2859 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
2860 comp->which = Z_RecordComp_simple;
2861 comp->u.simple = esn;
2862 pr->recordComposition = comp;
2868 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2872 Z_ElementSetNames *esn = (Z_ElementSetNames *)
2873 odr_malloc(o, sizeof(Z_ElementSetNames));
2874 esn->which = Z_ElementSetNames_generic;
2875 esn->u.generic = odr_strdup(o, schema);
2879 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2882 Yaz_ProxyConfig *cfg = check_reconfigure();
2884 t = cfg->get_explain_name(db, backend_db);
2886 if (m_client && m_default_target && t && strcmp(m_default_target, t))
2893 xfree(m_default_target);
2894 m_default_target = xstrdup(t);
2898 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2901 if (strcmp(hreq->method, "GET"))
2903 if (hreq->path[0] != '/')
2905 const char *cp = hreq->path;
2908 if (*cp == '/' && strchr("/.", cp[1]))
2913 Yaz_ProxyConfig *cfg = check_reconfigure();
2915 if (!cfg->get_file_access_info(hreq->path+1))
2918 const char *fname = hreq->path+1;
2919 if (stat(fname, &sbuf))
2921 yaz_log(YLOG_LOG|YLOG_ERRNO, "%sstat failed for %s", m_session_str,
2925 if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2927 yaz_log(YLOG_LOG, "%sNot a regular file %s", m_session_str, fname);
2930 if (sbuf.st_size > (off_t) 1000000)
2932 yaz_log(YLOG_WARN, "%sFile %s too large for transfer", m_session_str,
2937 ODR o = odr_encode();
2939 const char *ctype = cfg->check_mime_type(fname);
2940 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2941 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2943 hres->version = odr_strdup(o, m_http_version);
2944 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2945 if (m_http_keepalive)
2946 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2950 hres->content_len = sbuf.st_size;
2951 hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2952 FILE *f = fopen(fname, "rb");
2955 fread(hres->content_buf, 1, hres->content_len, f);
2962 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2964 yaz_log(YLOG_LOG, "%sSending file %s to client", m_session_str,
2968 send_GDU(gdu, &len);
2969 recv_GDU_more(true);
2973 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2977 odr_destroy(m_s2z_odr_init);
2980 if (m_s2z_odr_search)
2982 odr_destroy(m_s2z_odr_search);
2983 m_s2z_odr_search = 0;
2987 odr_destroy(m_s2z_odr_scan);
2991 m_http_keepalive = 0;
2993 if (!strcmp(hreq->version, "1.0"))
2995 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2996 if (v && !strcmp(v, "Keep-Alive"))
2997 m_http_keepalive = 1;
2999 m_http_keepalive = 0;
3000 m_http_version = "1.0";
3004 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
3005 if (v && !strcmp(v, "close"))
3006 m_http_keepalive = 0;
3008 m_http_keepalive = 1;
3009 m_http_version = "1.1";
3012 const char *a = z_HTTP_header_lookup(hreq->headers, "Authorization");
3013 char authorization_str[255];
3014 *authorization_str = '\0';
3015 if (a && strncasecmp(a, "Basic ", 6) == 0)
3016 base64_decode(a + 6, authorization_str, 254);
3018 Z_SRW_PDU *srw_pdu = 0;
3019 Z_SOAP *soap_package = 0;
3021 Z_SRW_diagnostic *diagnostic = 0;
3022 int num_diagnostic = 0;
3024 yaz_log(YLOG_LOG, "%s%s %s", m_session_str, hreq->method, hreq->path);
3026 if (file_access(hreq))
3030 else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
3032 || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
3033 &charset, &diagnostic, &num_diagnostic) == 0)
3035 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
3036 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
3037 m_s2z_odr_scan = odr_createmem(ODR_ENCODE);
3038 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
3039 m_s2z_init_apdu = 0;
3040 m_s2z_search_apdu = 0;
3041 m_s2z_present_apdu = 0;
3042 m_s2z_scan_apdu = 0;
3044 m_s2z_stylesheet = 0;
3046 Z_IdAuthentication *auth = NULL;
3047 if (srw_pdu->username && !srw_pdu->password)
3049 yaz_log(YLOG_LOG, "username: %s\n", srw_pdu->username);
3050 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
3051 auth->which = Z_IdAuthentication_open;
3052 auth->u.open = odr_strdup(m_s2z_odr_init, srw_pdu->username);
3054 else if (srw_pdu->username && srw_pdu->password)
3056 yaz_log(YLOG_LOG, "username/password: %s/%s\n",
3057 srw_pdu->username, srw_pdu->password);
3058 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
3059 auth->which = Z_IdAuthentication_idPass;
3060 auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
3061 auth->u.idPass->groupId = NULL;
3062 auth->u.idPass->password = odr_strdup(m_s2z_odr_init, srw_pdu->password);
3063 auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, srw_pdu->username);
3067 if (*authorization_str)
3069 yaz_log(YLOG_LOG, "authorization_str present: %s\n", authorization_str);
3070 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
3071 auth->which = Z_IdAuthentication_idPass;
3072 auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
3073 auth->u.idPass->groupId = NULL;
3074 char *p = strchr(authorization_str, ':');
3079 auth->u.idPass->password = odr_strdup(m_s2z_odr_init, p);
3081 auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, authorization_str);
3085 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
3088 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
3090 const char *backend_db = srw_req->database;
3091 srw_get_client(srw_req->database, &backend_db);
3093 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
3094 // recordXPath unsupported.
3095 if (srw_req->recordXPath)
3097 yaz_add_srw_diagnostic(odr_decode(),
3098 &diagnostic, &num_diagnostic,
3102 if (srw_req->sort_type != Z_SRW_sort_type_none)
3104 yaz_add_srw_diagnostic(odr_decode(),
3105 &diagnostic, &num_diagnostic,
3109 if (srw_req->stylesheet)
3111 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
3113 // set packing for response records ..
3114 if (srw_req->recordPacking &&
3115 !strcmp(srw_req->recordPacking, "xml"))
3116 m_s2z_packing = Z_SRW_recordPacking_XML;
3118 m_s2z_packing = Z_SRW_recordPacking_string;
3122 Z_SRW_PDU *srw_pdu =
3123 yaz_srw_get(odr_encode(),
3124 Z_SRW_searchRetrieve_response);
3125 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
3127 srw_res->diagnostics = diagnostic;
3128 srw_res->num_diagnostics = num_diagnostic;
3129 send_srw_response(srw_pdu);
3133 // prepare search PDU
3134 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
3135 Z_APDU_searchRequest);
3136 Z_SearchRequest *z_searchRequest =
3137 m_s2z_search_apdu->u.searchRequest;
3139 z_searchRequest->num_databaseNames = 1;
3140 z_searchRequest->databaseNames = (char**)
3141 odr_malloc(m_s2z_odr_search, sizeof(char *));
3142 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
3145 // query transformation
3146 Z_Query *query = (Z_Query *)
3147 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
3148 z_searchRequest->query = query;
3150 if (srw_req->query_type == Z_SRW_query_type_cql)
3152 Z_External *ext = (Z_External *)
3153 odr_malloc(m_s2z_odr_search, sizeof(*ext));
3154 ext->direct_reference =
3155 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
3156 ext->indirect_reference = 0;
3157 ext->descriptor = 0;
3158 ext->which = Z_External_CQL;
3159 ext->u.cql = srw_req->query.cql;
3161 query->which = Z_Query_type_104;
3162 query->u.type_104 = ext;
3164 else if (srw_req->query_type == Z_SRW_query_type_pqf)
3166 Z_RPNQuery *RPNquery;
3167 YAZ_PQF_Parser pqf_parser;
3169 pqf_parser = yaz_pqf_create ();
3171 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
3172 srw_req->query.pqf);
3175 const char *pqf_msg;
3177 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
3179 yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
3180 yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
3182 send_to_srw_client_error(10, 0);
3185 query->which = Z_Query_type_1;
3186 query->u.type_1 = RPNquery;
3188 yaz_pqf_destroy (pqf_parser);
3192 send_to_srw_client_error(7, "query");
3197 m_s2z_present_apdu = 0;
3199 if (srw_req->maximumRecords)
3200 max = *srw_req->maximumRecords;
3202 if (srw_req->startRecord)
3203 start = *srw_req->startRecord;
3206 // Some backend, such as Voyager doesn't honor piggyback
3207 // So we use present always (0 &&).
3208 if (0 && start <= 1) // Z39.50 piggyback
3210 *z_searchRequest->smallSetUpperBound = max;
3211 *z_searchRequest->mediumSetPresentNumber = max;
3212 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
3214 z_searchRequest->preferredRecordSyntax =
3215 odr_oiddup(m_s2z_odr_search, yaz_oid_recsyn_xml);
3217 if (srw_req->recordSchema)
3219 z_searchRequest->smallSetElementSetNames =
3220 z_searchRequest->mediumSetElementSetNames =
3221 mk_esn_from_schema(m_s2z_odr_search,
3222 srw_req->recordSchema);
3225 else // Z39.50 present
3227 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
3228 Z_APDU_presentRequest);
3229 Z_PresentRequest *z_presentRequest =
3230 m_s2z_present_apdu->u.presentRequest;
3231 *z_presentRequest->resultSetStartPoint = start;
3232 *z_presentRequest->numberOfRecordsRequested = max;
3234 z_presentRequest->preferredRecordSyntax =
3235 odr_oiddup(m_s2z_odr_search, yaz_oid_recsyn_xml);
3236 if (srw_req->recordSchema)
3238 z_presentRequest->recordComposition =
3239 (Z_RecordComposition *)
3240 odr_malloc(m_s2z_odr_search,
3241 sizeof(Z_RecordComposition));
3242 z_presentRequest->recordComposition->which =
3243 Z_RecordComp_simple;
3244 z_presentRequest->recordComposition->u.simple =
3245 mk_esn_from_schema(m_s2z_odr_search,
3246 srw_req->recordSchema);
3252 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
3253 Z_APDU_initRequest);
3255 ODR_MASK_SET(m_s2z_init_apdu->u.initRequest->options, Z_Options_scan);
3256 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
3258 // prevent m_initRequest_apdu memory from being grabbed
3259 // in Yaz_Proxy::handle_incoming_Z_PDU
3260 m_initRequest_apdu = m_s2z_init_apdu;
3261 handle_incoming_Z_PDU(m_s2z_init_apdu);
3266 handle_incoming_Z_PDU(m_s2z_search_apdu);
3270 else if (srw_pdu->which == Z_SRW_explain_request)
3272 Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
3274 const char *backend_db = srw_req->database;
3275 srw_get_client(srw_req->database, &backend_db);
3277 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
3280 if (srw_req->stylesheet)
3282 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
3284 if (srw_req->recordPacking &&
3285 !strcmp(srw_req->recordPacking, "xml"))
3286 m_s2z_packing = Z_SRW_recordPacking_XML;
3288 m_s2z_packing = Z_SRW_recordPacking_string;
3292 send_srw_explain_response(diagnostic, num_diagnostic);
3298 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
3299 Z_APDU_initRequest);
3301 ODR_MASK_SET(m_s2z_init_apdu->u.initRequest->options, Z_Options_scan);
3302 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
3304 // prevent m_initRequest_apdu memory from being grabbed
3305 // in Yaz_Proxy::handle_incoming_Z_PDU
3306 m_initRequest_apdu = m_s2z_init_apdu;
3307 handle_incoming_Z_PDU(m_s2z_init_apdu);
3310 send_srw_explain_response(0, 0);
3313 else if (srw_pdu->which == Z_SRW_scan_request)
3315 Z_SRW_scanRequest *srw_req = srw_pdu->u.scan_request;
3317 const char *backend_db = srw_req->database;
3318 srw_get_client(srw_req->database, &backend_db);
3320 m_s2z_database = odr_strdup(m_s2z_odr_init,
3323 if (srw_req->stylesheet)
3325 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
3328 m_s2z_scan_apdu = zget_APDU(m_s2z_odr_scan,
3329 Z_APDU_scanRequest);
3330 Z_ScanRequest *z_scanRequest =
3331 m_s2z_scan_apdu->u.scanRequest;
3333 z_scanRequest->num_databaseNames = 1;
3334 z_scanRequest->databaseNames = (char**)
3335 odr_malloc(m_s2z_odr_scan, sizeof(char *));
3336 z_scanRequest->databaseNames[0] = odr_strdup(m_s2z_odr_scan,
3339 // query transformation
3340 if (srw_req->query_type == Z_SRW_query_type_cql)
3342 z_scanRequest->termListAndStartPoint =
3343 (Z_AttributesPlusTerm *)odr_malloc(m_s2z_odr_scan, sizeof(Z_AttributesPlusTerm));
3344 z_scanRequest->termListAndStartPoint->attributes = NULL;
3345 z_scanRequest->termListAndStartPoint->term =
3346 (Z_Term *)odr_malloc(m_s2z_odr_scan, sizeof(Z_Term));
3347 z_scanRequest->termListAndStartPoint->term->which =
3348 Z_Term_characterString;
3349 z_scanRequest->termListAndStartPoint->term->u.characterString =
3350 odr_strdup(m_s2z_odr_scan, srw_req->scanClause.cql);
3353 if (srw_req->responsePosition)
3354 z_scanRequest->preferredPositionInResponse =
3355 odr_intdup(m_s2z_odr_scan, *srw_req->responsePosition);
3356 if (srw_req->maximumTerms)
3357 *z_scanRequest->numberOfTermsRequested = *srw_req->maximumTerms;
3361 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
3362 Z_APDU_initRequest);
3364 ODR_MASK_SET(m_s2z_init_apdu->u.initRequest->options, Z_Options_scan);
3365 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
3367 // prevent m_initRequest_apdu memory from being grabbed
3368 // in Yaz_Proxy::handle_incoming_Z_PDU
3369 m_initRequest_apdu = m_s2z_init_apdu;
3370 handle_incoming_Z_PDU(m_s2z_init_apdu);
3375 handle_incoming_Z_PDU(m_s2z_scan_apdu);
3383 send_to_srw_client_error(4, 0);
3386 send_http_response(400);
3389 void Yaz_Proxy::handle_init(Z_APDU *apdu)
3392 Z_OtherInformation **oi;
3393 get_otherInfoAPDU(apdu, &oi);
3395 if (apdu->u.initRequest->implementationId)
3396 yaz_log(YLOG_LOG, "%simplementationId: %s",
3397 m_session_str, apdu->u.initRequest->implementationId);
3398 if (apdu->u.initRequest->implementationName)
3399 yaz_log(YLOG_LOG, "%simplementationName: %s",
3400 m_session_str, apdu->u.initRequest->implementationName);
3401 if (apdu->u.initRequest->implementationVersion)
3402 yaz_log(YLOG_LOG, "%simplementationVersion: %s",
3403 m_session_str, apdu->u.initRequest->implementationVersion);
3404 if (m_initRequest_apdu == 0)
3406 if (m_initRequest_mem)
3407 nmem_destroy(m_initRequest_mem);
3409 m_initRequest_apdu = apdu;
3410 m_initRequest_mem = odr_extract_mem(odr_decode());
3412 m_initRequest_preferredMessageSize = *apdu->u.initRequest->
3413 preferredMessageSize;
3414 *apdu->u.initRequest->preferredMessageSize = 64*1024*1024;
3415 m_initRequest_maximumRecordSize = *apdu->u.initRequest->
3417 *apdu->u.initRequest->maximumRecordSize = 64*1024*1024;
3419 Z_CharSetandLanguageNegotiation *charSetandLangRecord =
3420 yaz_get_charneg_record(*oi);
3422 // Save proposal charsets and langs.
3423 if (ODR_MASK_GET(apdu->u.initRequest->options,
3424 Z_Options_negotiationModel)
3425 && charSetandLangRecord)
3428 yaz_get_proposal_charneg(m_referenceId_mem,
3429 charSetandLangRecord,
3430 &m_initRequest_oi_negotiation_charsets,
3431 &m_initRequest_oi_negotiation_num_charsets,
3432 &m_initRequest_oi_negotiation_langs,
3433 &m_initRequest_oi_negotiation_num_langs,
3434 &m_initRequest_oi_negotiation_selected);
3436 for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
3438 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
3439 m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
3440 m_initRequest_oi_negotiation_charsets[i]:"none");
3442 for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
3444 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
3445 m_session_str, (m_initRequest_oi_negotiation_langs[i])?
3446 m_initRequest_oi_negotiation_langs[i]:"none");
3448 yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
3449 m_session_str, m_initRequest_oi_negotiation_selected);
3451 // save init options for the response..
3452 m_initRequest_options = apdu->u.initRequest->options;
3454 apdu->u.initRequest->options =
3455 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3456 sizeof(Odr_bitmask));
3457 ODR_MASK_ZERO(apdu->u.initRequest->options);
3459 for (i = 0; i<= 24; i++)
3460 ODR_MASK_SET(apdu->u.initRequest->options, i);
3461 // check negotiation option
3462 if (!ODR_MASK_GET(m_initRequest_options,
3463 Z_Options_negotiationModel))
3465 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3466 Z_Options_negotiationModel);
3468 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3469 Z_Options_concurrentOperations);
3471 m_initRequest_version = apdu->u.initRequest->protocolVersion;
3472 apdu->u.initRequest->protocolVersion =
3473 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3474 sizeof(Odr_bitmask));
3475 ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
3477 for (i = 0; i<= 8; i++)
3478 ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
3480 handle_charset_lang_negotiation(apdu);
3481 if (m_client->m_init_flag)
3483 if (handle_init_response_for_invalid_session(apdu))
3485 if (m_client->m_initResponse)
3487 Z_APDU *apdu2 = m_client->m_initResponse;
3488 apdu2->u.initResponse->otherInfo = 0;
3489 if (m_client->m_cookie && *m_client->m_cookie)
3490 set_otherInformationString(apdu2, yaz_oid_userinfo_cookie,
3491 1, m_client->m_cookie);
3492 apdu2->u.initResponse->referenceId =
3493 apdu->u.initRequest->referenceId;
3494 apdu2->u.initResponse->options = m_client->m_initResponse_options;
3495 apdu2->u.initResponse->protocolVersion =
3496 m_client->m_initResponse_version;
3498 handle_charset_lang_negotiation(apdu2);
3500 if (m_timeout_mode == timeout_busy)
3501 m_timeout_mode = timeout_normal;
3502 send_to_client(apdu2);
3506 m_client->m_init_flag = 1;
3508 if (m_num_msg_threads && m_my_thread)
3510 Auth_Msg *m = new Auth_Msg;
3512 z_APDU(odr_encode(), &apdu, 0, "encode");
3513 char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
3514 m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
3515 memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
3516 odr_reset(odr_encode());
3519 m_my_thread->put(m);
3523 int ret = handle_authentication(apdu);
3524 result_authentication(apdu, ret);
3528 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
3530 Z_ReferenceId **refid = get_referenceIdP(apdu);
3531 nmem_reset(m_referenceId_mem);
3532 if (refid && *refid)
3534 m_referenceId = (Z_ReferenceId *)
3535 nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
3536 m_referenceId->len = m_referenceId->size = (*refid)->len;
3537 m_referenceId->buf = (unsigned char *)
3538 nmem_malloc(m_referenceId_mem, (*refid)->len);
3539 memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
3544 if (!m_client && m_flag_invalid_session)
3546 // Got request for a session that is invalid..
3547 m_apdu_invalid_session = apdu; // save package
3548 m_mem_invalid_session = odr_extract_mem(odr_decode());
3549 apdu = m_initRequest_apdu; // but throw an init to the target
3552 if (apdu->which == Z_APDU_searchRequest)
3553 m_search_stat.add_bytes(1);
3555 // Handle global authentication
3556 if (!handle_global_authentication(apdu))
3559 { // HTTP. Send unauthorized
3560 send_http_response(401);
3565 // Z39.50 just shutdown
3572 // Determine our client.
3573 Z_OtherInformation **oi;
3574 get_otherInfoAPDU(apdu, &oi);
3575 int http_code = 404;
3576 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi), &http_code);
3580 { // HTTP. Send not found
3581 send_http_response(http_code);
3586 // Z39.50 just shutdown
3592 m_client->m_server = this;
3594 if (apdu->which == Z_APDU_initRequest)
3597 handle_incoming_Z_PDU_2(apdu);
3600 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
3602 handle_max_record_retrieve(apdu);
3605 apdu = handle_syntax_validation(apdu);
3608 apdu = handle_query_transformation(apdu);
3611 apdu = handle_target_charset_conversion(apdu);
3614 apdu = handle_query_validation(apdu);
3617 apdu = result_set_optimize(apdu);
3621 m_client->timeout(m_target_idletime); // mark it active even
3622 recv_GDU_more(true);
3623 // though we didn't use it
3627 // delete other info construct completely if 0 elements
3628 Z_OtherInformation **oi;
3629 get_otherInfoAPDU(apdu, &oi);
3630 if (oi && *oi && (*oi)->num_elements == 0)
3633 if (apdu->which == Z_APDU_presentRequest &&
3634 m_client->m_resultSetStartPoint == 0)
3636 Z_PresentRequest *pr = apdu->u.presentRequest;
3637 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3638 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3640 m_client->m_resultSetStartPoint = 0;
3642 if (m_client->send_to_target(apdu) < 0)
3644 m_client->shutdown();
3647 m_client->m_waiting = 1;
3650 void Yaz_Proxy::connectNotify()
3654 void Yaz_Proxy::releaseClient()
3656 xfree(m_proxyTarget);
3658 m_flag_invalid_session = 0;
3659 // only keep if keep_alive flag is set...
3661 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3662 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3663 m_client->m_waiting == 0)
3665 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3667 m_client->get_hostname());
3668 yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3669 m_session_str, m_client->m_pdu_recv,
3670 m_client->m_bytes_sent + m_client->m_bytes_recv,
3671 m_keepalive_limit_bw, m_keepalive_limit_pdu);
3672 assert (m_client->m_waiting != 2);
3673 // Tell client (if any) that no server connection is there..
3674 m_client->m_server = 0;
3679 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) close %s",
3681 m_client->get_hostname());
3682 assert (m_client->m_waiting != 2);
3688 yaz_log(YLOG_LOG, "%sshutdown (client to proxy) bad state",
3694 yaz_log(YLOG_LOG, "%sShutdown (client to proxy)",
3698 m_parent->pre_init();
3701 bool Yaz_Proxy::dec_ref()
3703 m_http_keepalive = 0;
3706 if (m_ref_count > 0)
3715 const char *Yaz_ProxyClient::get_session_str()
3719 return m_server->get_session_str();
3722 void Yaz_ProxyClient::shutdown()
3724 yaz_log(YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
3729 m_waiting = 1; // ensure it's released from Yaz_Proxy::releaseClient
3730 m_server->dec_ref();
3736 void Yaz_Proxy::failNotify()
3739 yaz_log(YLOG_LOG, "%sConnection closed by client", get_session_str());
3743 void Yaz_Proxy::send_response_fail_client(const char *addr)
3747 Z_SRW_diagnostic *diagnostic = 0;
3748 int num_diagnostic = 0;
3750 yaz_add_srw_diagnostic(odr_encode(),
3751 &diagnostic, &num_diagnostic,
3752 YAZ_SRW_SYSTEM_TEMPORARILY_UNAVAILABLE, addr);
3753 if (m_s2z_search_apdu)
3754 send_srw_search_response(diagnostic, num_diagnostic);
3755 else if (m_s2z_scan_apdu)
3756 send_srw_scan_response(diagnostic, num_diagnostic);
3758 send_srw_explain_response(diagnostic, num_diagnostic);
3762 void Yaz_ProxyClient::failNotify()
3765 m_server->inc_request_no();
3766 yaz_log(YLOG_LOG, "%sConnection closed by target %s",
3767 get_session_str(), get_hostname());
3770 m_server->send_response_fail_client(get_hostname());
3774 void Yaz_ProxyClient::connectNotify()
3776 const char *s = get_session_str();
3777 const char *h = get_hostname();
3778 yaz_log(YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
3780 timeout(m_target_idletime);
3785 IPDU_Observer *Yaz_ProxyClient::sessionNotify(IPDU_Observable
3786 *the_PDU_Observable, int fd)
3788 return new Yaz_ProxyClient(the_PDU_Observable, 0);
3791 Yaz_ProxyClient::~Yaz_ProxyClient()
3796 m_next->m_prev = m_prev;
3797 m_waiting = 2; // for debugging purposes only.
3798 odr_destroy(m_init_odr);
3799 odr_destroy(m_idAuthentication_odr);
3800 delete m_last_query;
3801 xfree(m_last_resultSetId);
3805 void Yaz_ProxyClient::pre_init_client()
3807 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
3808 Z_InitRequest *req = apdu->u.initRequest;
3811 for (i = 0; i<= 24; i++)
3812 ODR_MASK_SET(req->options, i);
3813 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3814 Z_Options_negotiationModel);
3815 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3816 Z_Options_concurrentOperations);
3817 for (i = 0; i<= 10; i++)
3818 ODR_MASK_SET(req->protocolVersion, i);
3820 if (send_to_target(apdu) < 0)
3831 void Yaz_Proxy::pre_init()
3834 const char *name = 0;
3835 const char *zurl_in_use[MAX_ZURL_PLEX];
3836 int limit_bw, limit_pdu, limit_req, limit_search;
3837 int target_idletime, client_idletime;
3838 int max_sockets = m_max_sockets;
3840 int keepalive_limit_bw, keepalive_limit_pdu;
3842 const char *cql2rpn = 0;
3843 const char *authentication = 0;
3844 const char *negotiation_charset = 0;
3845 const char *negotiation_lang = 0;
3847 Yaz_ProxyConfig *cfg = check_reconfigure();
3851 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
3856 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
3857 &limit_bw, &limit_pdu, &limit_req,
3859 &target_idletime, &client_idletime,
3862 &keepalive_limit_bw,
3863 &keepalive_limit_pdu,
3867 &negotiation_charset,
3875 for (j = 0; zurl_in_use[j]; j++)
3879 int spare_waiting = 0;
3882 for (c = m_clientPool; c; c = c->m_next)
3884 if (!strcmp(zurl_in_use[j], c->get_hostname()))
3886 if (c->m_cookie == 0)
3888 if (c->m_server == 0)
3900 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
3901 "sparew=%d preinit=%d",m_session_str,
3902 name, zurl_in_use[j], in_use, other,
3903 spare, spare_waiting, pre_init);
3904 if (spare + spare_waiting < pre_init
3905 && in_use + spare + spare_waiting + other < max_sockets)
3907 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
3908 c->m_next = m_clientPool;
3910 c->m_next->m_prev = &c->m_next;
3912 c->m_prev = &m_clientPool;
3914 if (m_log_mask & PROXY_LOG_APDU_SERVER)
3915 c->set_APDU_yazlog(1);
3917 c->set_APDU_yazlog(0);
3919 if (c->client(zurl_in_use[j]))
3927 c->m_target_idletime = target_idletime;
3928 c->m_seqno = m_seqno++;
3935 void Yaz_Proxy::timeoutNotify()
3940 switch(m_timeout_mode)
3942 case timeout_normal:
3946 yaz_log(YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
3949 case timeout_reduce:
3950 timeout(m_client_idletime);
3951 m_timeout_mode = timeout_busy;
3952 gdu = m_timeout_gdu;
3954 recv_GDU_normal(gdu);
3957 assert(m_stylesheet_nprl);
3958 convert_xsl_delay();
3959 recv_GDU_more(true);
3969 void Yaz_Proxy::markInvalid()
3972 m_flag_invalid_session = 1;
3975 void Yaz_ProxyClient::timeoutNotify()
3978 m_server->inc_request_no();
3980 yaz_log(YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
3984 m_server->send_response_fail_client(get_hostname());
3986 Yaz_Proxy *proxy_root = m_root;
3990 proxy_root->pre_init();
3993 Yaz_ProxyClient::Yaz_ProxyClient(IPDU_Observable *the_PDU_Observable,
3994 Yaz_Proxy *parent) :
3995 Z_Assoc (the_PDU_Observable)
4002 m_last_resultSetId = 0;
4003 m_last_resultCount = 0;
4007 m_init_odr = odr_createmem (ODR_DECODE);
4009 m_initResponse_options = 0;
4010 m_initResponse_version = 0;
4011 m_initResponse_preferredMessageSize = 0;
4012 m_initResponse_maximumRecordSize = 0;
4013 m_resultSetStartPoint = 0;
4014 m_bytes_sent = m_bytes_recv = 0;
4018 m_target_idletime = 600;
4020 m_idAuthentication_odr = odr_createmem(ODR_ENCODE);
4021 m_idAuthentication_ber_buf = 0;
4022 m_idAuthentication_ber_size = 0;
4025 const char *Yaz_Proxy::option(const char *name, const char *value)
4027 if (!strcmp (name, "optimize")) {
4030 m_optimize = xstrdup(value);
4037 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
4042 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
4044 if (apdu->which == Z_GDU_Z3950)
4045 recv_Z_PDU(apdu->u.z3950, len);
4046 else if (apdu->which == Z_GDU_HTTP_Response)
4047 recv_HTTP_response(apdu->u.HTTP_Response, len);
4052 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
4054 if (!m_flag_invalid_session)
4056 m_flag_invalid_session = 0;
4057 handle_incoming_Z_PDU(m_apdu_invalid_session);
4058 assert (m_mem_invalid_session);
4059 nmem_destroy(m_mem_invalid_session);
4060 m_mem_invalid_session = 0;
4064 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
4066 m_bytes_recv += len;
4070 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
4071 yaz_log(YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
4072 apdu_name(apdu), get_hostname(), len);
4073 if (apdu->which == Z_APDU_initResponse)
4075 if (!m_server) // if this is a pre init session , check for more
4077 NMEM nmem = odr_extract_mem (odr_decode());
4078 odr_reset (m_init_odr);
4079 nmem_transfer (m_init_odr->mem, nmem);
4080 m_initResponse = apdu;
4081 m_initResponse_options = apdu->u.initResponse->options;
4082 m_initResponse_version = apdu->u.initResponse->protocolVersion;
4083 m_initResponse_preferredMessageSize =
4084 *apdu->u.initResponse->preferredMessageSize;
4085 m_initResponse_maximumRecordSize =
4086 *apdu->u.initResponse->maximumRecordSize;
4088 Z_InitResponse *ir = apdu->u.initResponse;
4090 // apply YAZ Proxy version
4091 char *imv0 = ir->implementationVersion;
4092 char *imv1 = (char*)
4093 odr_malloc(m_init_odr, 20 + (imv0 ? strlen(imv0) : 0));
4098 strcat(imv1, "/" VERSION);
4100 ir->implementationVersion = imv1;
4102 // apply YAZ Proxy implementation name
4103 char *im0 = ir->implementationName;
4105 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
4112 strcat(im1, "(YAZ Proxy)");
4113 ir->implementationName = im1;
4115 nmem_destroy (nmem);
4117 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
4120 if (apdu->which == Z_APDU_searchResponse)
4122 Z_SearchResponse *sr = apdu->u.searchResponse;
4123 m_last_resultCount = *sr->resultCount;
4124 int status = *sr->searchStatus;
4125 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
4129 if (sr->records && sr->records->which == Z_Records_DBOSD)
4131 m_cache.add(odr_decode(),
4132 sr->records->u.databaseOrSurDiagnostics, 1,
4137 if (apdu->which == Z_APDU_presentResponse)
4139 Z_PresentResponse *pr = apdu->u.presentResponse;
4143 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
4144 Z_SearchResponse *sr = new_apdu->u.searchResponse;
4145 sr->referenceId = pr->referenceId;
4146 *sr->resultCount = m_last_resultCount;
4147 sr->records = pr->records;
4148 sr->nextResultSetPosition = pr->nextResultSetPosition;
4149 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
4153 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
4155 m_cache.add(odr_decode(),
4156 pr->records->u.databaseOrSurDiagnostics,
4157 m_resultSetStartPoint, -1);
4158 m_resultSetStartPoint = 0;
4162 set_otherInformationString(apdu, yaz_oid_userinfo_cookie, 1, m_cookie);
4164 Yaz_Proxy *server = m_server; // save it. send_to_client may destroy us
4167 server->send_to_client(apdu);
4168 if (apdu->which == Z_APDU_close)
4171 server->recv_GDU_more(true);
4174 void Yaz_Proxy::low_socket_close()
4179 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
4180 if (m_lo_fd[i] >= 0)
4181 ::close(m_lo_fd[i]);
4185 void Yaz_Proxy::low_socket_open()
4190 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
4191 m_lo_fd[i] = open("/dev/null", O_RDONLY);
4195 int Yaz_Proxy::server(const char *addr)
4197 int r = Z_Assoc::server(addr);
4200 yaz_log(YLOG_LOG, "%sStarted proxy "
4204 " on %s", m_session_str, addr);
4210 void Yaz_Proxy::base64_decode(const char *base64, char *buf, int buf_len)
4212 const char *base64_chars =
4213 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4214 int len = strlen(base64);
4218 for (int pos = 0; pos <= len; pos++)
4220 if (base64[pos] == '=' || buf_pos + 1 >= buf_len)
4223 const char *ch_ptr = strchr(base64_chars, base64[pos]);
4226 char ch = (char) (ch_ptr - base64_chars);
4230 buf[buf_pos] = ch << 2;
4233 buf[buf_pos++] += (ch & 0x30) >> 4;
4234 buf[buf_pos] = (ch & 0x0f) << 4;
4237 buf[buf_pos++] += (ch & 0x3c) >> 2;
4238 buf[buf_pos] = (ch & 0x03) << 6;
4241 buf[buf_pos++] += ch;
4248 buf[buf_pos] = '\0';
4254 * c-file-style: "Stroustrup"
4255 * indent-tabs-mode: nil
4257 * vim: shiftwidth=4 tabstop=8 expandtab