1 /* $Id: yaz-proxy.cpp,v 1.65 2006-05-01 09:14:08 adam Exp $
2 Copyright (c) 1998-2006, Index Data.
4 This file is part of the yazproxy.
6 YAZ proxy is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
11 YAZ proxy is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with YAZ proxy; see the file LICENSE. If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
23 #define HAVE_SYS_STAT_H 1
24 #define HAVE_SYS_TYPES_H 1
34 #include <sys/types.h>
46 #include <yaz/marcdisp.h>
47 #include <yaz/yaz-iconv.h>
49 #include <yaz/diagbib1.h>
51 #include <yaz/pquery.h>
52 #include <yaz/otherinfo.h>
53 #include <yaz/charneg.h>
54 #include "msg-thread.h"
56 using namespace yazpp_1;
59 #define strncasecmp _strnicmp
62 #define USE_AUTH_MSG 1
65 class YAZ_EXPORT Auth_Msg : public IMsg_Thread {
68 IMsg_Thread *handle();
80 m_nmem = nmem_create();
88 IMsg_Thread *Auth_Msg::handle()
90 ODR decode = odr_createmem(ODR_DECODE);
93 odr_setbuf(decode, m_apdu_buf, m_apdu_len, 0);
94 int r = z_APDU(decode, &apdu, 0, 0);
97 yaz_log(YLOG_WARN, "decode failed in Auth_Msg::handle");
101 m_ret = m_proxy->handle_authentication(apdu);
107 void Auth_Msg::result()
109 if (m_proxy->dec_ref())
111 yaz_log(YLOG_LOG, "Auth_Msg::proxy deleted meanwhile");
115 odr_setbuf(m_proxy->odr_decode(), m_apdu_buf, m_apdu_len, 0);
117 int r = z_APDU(m_proxy->odr_decode(), &apdu, 0, 0);
119 yaz_log(YLOG_LOG, "Auth_Msg::result z_APDU failed");
120 m_proxy->result_authentication(apdu, m_ret);
127 void Yaz_Proxy::result_authentication(Z_APDU *apdu, int ret)
129 if (apdu == 0 || ret == 0)
131 Z_APDU *apdu_reject = zget_APDU(odr_encode(), Z_APDU_initResponse);
132 *apdu_reject->u.initResponse->result = 0;
133 send_to_client(apdu_reject);
138 if (apdu->which == Z_APDU_initRequest)
140 Yaz_ProxyConfig *cfg = check_reconfigure();
142 cfg->target_authentication(m_default_target, odr_encode(),
143 apdu->u.initRequest);
145 handle_incoming_Z_PDU_2(apdu);
149 static const char *apdu_name(Z_APDU *apdu)
153 case Z_APDU_initRequest:
154 return "initRequest";
155 case Z_APDU_initResponse:
156 return "initResponse";
157 case Z_APDU_searchRequest:
158 return "searchRequest";
159 case Z_APDU_searchResponse:
160 return "searchResponse";
161 case Z_APDU_presentRequest:
162 return "presentRequest";
163 case Z_APDU_presentResponse:
164 return "presentResponse";
165 case Z_APDU_deleteResultSetRequest:
166 return "deleteResultSetRequest";
167 case Z_APDU_deleteResultSetResponse:
168 return "deleteResultSetResponse";
169 case Z_APDU_scanRequest:
170 return "scanRequest";
171 case Z_APDU_scanResponse:
172 return "scanResponse";
173 case Z_APDU_sortRequest:
174 return "sortRequest";
175 case Z_APDU_sortResponse:
176 return "sortResponse";
177 case Z_APDU_extendedServicesRequest:
178 return "extendedServicesRequest";
179 case Z_APDU_extendedServicesResponse:
180 return "extendedServicesResponse";
187 static const char *gdu_name(Z_GDU *gdu)
192 return apdu_name(gdu->u.z3950);
193 case Z_GDU_HTTP_Request:
194 return "HTTP Request";
195 case Z_GDU_HTTP_Response:
196 return "HTTP Response";
198 return "Unknown request/response";
201 Yaz_Proxy::Yaz_Proxy(IPDU_Observable *the_PDU_Observable,
202 ISocketObservable *the_socket_observable,
205 Z_Assoc(the_PDU_Observable),
206 m_bw_stat(60), m_pdu_stat(60), m_search_stat(60)
208 m_PDU_Observable = the_PDU_Observable;
209 m_socket_observable = the_socket_observable;
214 m_keepalive_limit_bw = 500000;
215 m_keepalive_limit_pdu = 1000;
217 m_default_target = 0;
218 m_proxy_negotiation_charset = 0;
219 m_proxy_negotiation_lang = 0;
220 m_proxy_negotiation_default_charset = 0;
221 m_charset_converter = new Yaz_CharsetConverter;
225 m_client_idletime = 600;
226 m_target_idletime = 600;
227 m_optimize = xstrdup ("1");
228 strcpy(m_session_str, "0 ");
236 m_max_connect_period = 0;
238 m_limit_connect_period = 0;
239 m_timeout_mode = timeout_normal;
241 m_max_record_retrieve = 0;
245 m_flag_invalid_session = 0;
247 m_referenceId_mem = nmem_create();
249 m_marcxml_mode = none;
250 m_stylesheet_xsp = 0;
251 m_stylesheet_nprl = 0;
252 m_stylesheet_apdu = 0;
253 m_s2z_stylesheet = 0;
257 m_backend_charset = 0;
259 m_initRequest_apdu = 0;
260 m_initRequest_mem = 0;
261 m_initRequest_preferredMessageSize = 0;
262 m_initRequest_maximumRecordSize = 0;
263 m_initRequest_options = 0;
264 m_initRequest_version = 0;
265 m_initRequest_oi_negotiation_charsets = 0;
266 m_initRequest_oi_negotiation_num_charsets = 0;
267 m_initRequest_oi_negotiation_langs = 0;
268 m_initRequest_oi_negotiation_num_langs = 0;
269 m_initRequest_oi_negotiation_selected = 0;
270 m_apdu_invalid_session = 0;
271 m_mem_invalid_session = 0;
273 m_s2z_odr_search = 0;
275 m_s2z_search_apdu = 0;
276 m_s2z_present_apdu = 0;
277 m_http_keepalive = 0;
280 m_s2z_packing = Z_SRW_recordPacking_string;
281 #if HAVE_GETTIMEOFDAY
282 m_time_tv = xmalloc(sizeof(struct timeval));
283 struct timeval *tv = (struct timeval *) m_time_tv;
289 m_usemarcon_ini_stage1 = 0;
290 m_usemarcon_ini_stage2 = 0;
291 m_usemarcon = new Yaz_usemarcon();
296 m_main_ptr_dec = false;
300 void Yaz_Proxy::inc_ref()
305 Yaz_Proxy::~Yaz_Proxy()
307 yaz_log(YLOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
308 m_bytes_sent, m_bytes_recv);
309 nmem_destroy(m_initRequest_mem);
310 nmem_destroy(m_mem_invalid_session);
311 nmem_destroy(m_referenceId_mem);
313 xfree(m_proxyTarget);
314 xfree(m_default_target);
315 xfree(m_proxy_negotiation_charset);
316 xfree(m_proxy_negotiation_lang);
317 xfree(m_proxy_negotiation_default_charset);
318 delete m_charset_converter;
322 if (m_stylesheet_xsp)
323 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
329 xfree (m_backend_type);
330 xfree (m_backend_charset);
331 xfree (m_usemarcon_ini_stage1);
332 xfree (m_usemarcon_ini_stage2);
335 odr_destroy(m_s2z_odr_init);
336 if (m_s2z_odr_search)
337 odr_destroy(m_s2z_odr_search);
345 void Yaz_Proxy::set_debug_mode(int mode)
350 int Yaz_Proxy::set_config(const char *config)
353 m_config = new Yaz_ProxyConfig();
354 xfree(m_config_fname);
355 m_config_fname = xstrdup(config);
356 int r = m_config->read_xml(config);
360 m_config->get_generic_info(&m_log_mask, &m_max_clients,
361 &m_max_connect, &m_limit_connect, &period);
362 m_connect.set_period(period);
367 void Yaz_Proxy::set_default_target(const char *target)
369 xfree (m_default_target);
370 m_default_target = 0;
372 m_default_target = (char *) xstrdup (target);
375 void Yaz_Proxy::set_proxy_negotiation (const char *charset, const char *lang,
376 const char *default_charset)
378 yaz_log(YLOG_DEBUG, "%sSet the proxy negotiation: charset to '%s', "
379 "default charset to '%s', language to '%s'", m_session_str,
380 charset?charset:"none",
381 default_charset?default_charset:"none",
383 xfree (m_proxy_negotiation_charset);
384 xfree (m_proxy_negotiation_lang);
385 m_proxy_negotiation_charset = m_proxy_negotiation_lang = 0;
387 m_proxy_negotiation_charset = (char *) xstrdup (charset);
389 m_proxy_negotiation_lang = (char *) xstrdup (lang);
391 m_proxy_negotiation_default_charset =
392 (char *) xstrdup (default_charset);
395 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
398 return m_parent->check_reconfigure();
400 Yaz_ProxyConfig *cfg = m_config;
403 yaz_log(YLOG_LOG, "reconfigure");
405 if (m_config_fname && cfg)
407 yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
408 int r = cfg->read_xml(m_config_fname);
410 yaz_log(YLOG_WARN, "reconfigure failed");
415 cfg->get_generic_info(&m_log_mask, &m_max_clients,
416 &m_max_connect, &m_limit_connect,
418 m_connect.set_period(period);
422 yaz_log(YLOG_LOG, "reconfigure");
428 IPDU_Observer *Yaz_Proxy::sessionNotify(IPDU_Observable
429 *the_PDU_Observable, int fd)
433 char session_str[200];
434 const char *peername = the_PDU_Observable->getpeername();
435 if (m_log_mask & PROXY_LOG_IP_CLIENT)
436 sprintf(session_str, "%ld:%d %.80s %d ",
437 (long) time(0), m_session_no, peername, 0);
439 sprintf(session_str, "%ld:%d %d ",
440 (long) time(0), m_session_no, 0);
443 yaz_log (YLOG_LOG, "%sNew session %s", session_str, peername);
445 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable,
446 m_socket_observable, this);
448 new_proxy->m_config = 0;
449 new_proxy->m_config_fname = 0;
450 new_proxy->timeout(m_client_idletime);
451 new_proxy->m_target_idletime = m_target_idletime;
452 new_proxy->set_default_target(m_default_target);
453 new_proxy->m_max_clients = m_max_clients;
454 new_proxy->m_log_mask = m_log_mask;
455 new_proxy->m_session_no = m_session_no;
457 if (!strcmp(peername, "tcp:163.121.19.82")) // NIS GROUP
458 new_proxy->m_log_mask = 255;
460 new_proxy->set_APDU_log(get_APDU_log());
461 if (new_proxy->m_log_mask & PROXY_LOG_APDU_CLIENT)
462 new_proxy->set_APDU_yazlog(1);
464 new_proxy->set_APDU_yazlog(0);
465 strcpy(new_proxy->m_session_str, session_str);
466 new_proxy->m_peername = xstrdup(peername);
467 new_proxy->set_proxy_negotiation(m_proxy_negotiation_charset,
468 m_proxy_negotiation_lang, m_proxy_negotiation_default_charset);
469 // create thread object the first time we get an incoming connection
471 m_my_thread = new Msg_Thread(m_socket_observable, 1);
472 new_proxy->m_my_thread = m_my_thread;
476 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
479 Z_OtherInformationUnit *oi;
481 ent.proto = PROTO_Z3950;
482 ent.oclass = CLASS_USERINFO;
483 ent.value = (oid_value) VAL_COOKIE;
484 assert (oid_ent_to_oid (&ent, oid));
486 if (oid_ent_to_oid (&ent, oid) &&
487 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
488 oi->which == Z_OtherInfo_characterInfo)
489 return oi->information.characterInfo;
492 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
495 Z_OtherInformationUnit *oi;
497 ent.proto = PROTO_Z3950;
498 ent.oclass = CLASS_USERINFO;
499 ent.value = (oid_value) VAL_PROXY;
500 if (oid_ent_to_oid (&ent, oid) &&
501 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
502 oi->which == Z_OtherInfo_characterInfo)
503 return oi->information.characterInfo;
506 const char *Yaz_Proxy::load_balance(const char **url)
508 int zurl_in_use[MAX_ZURL_PLEX];
509 int zurl_in_spare[MAX_ZURL_PLEX];
513 for (i = 0; i<MAX_ZURL_PLEX; i++)
516 zurl_in_spare[i] = 0;
518 for (c = m_parent->m_clientPool; c; c = c->m_next)
520 for (i = 0; url[i]; i++)
521 if (!strcmp(url[i], c->get_hostname()))
524 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
528 int min_use = 100000;
529 int spare_for_min = 0;
531 const char *ret_min = 0;
532 const char *ret_spare = 0;
533 for (i = 0; url[i]; i++)
535 yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
536 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
537 if (min_use > zurl_in_use[i])
540 min_use = zurl_in_use[i];
541 spare_for_min = zurl_in_spare[i];
543 if (max_spare < zurl_in_spare[i])
546 max_spare = zurl_in_spare[i];
552 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
553 const char *proxy_host)
556 Yaz_Proxy *parent = m_parent;
557 Yaz_ProxyClient *c = m_client;
561 const char *url[MAX_ZURL_PLEX];
562 Yaz_ProxyConfig *cfg = check_reconfigure();
565 if (parent && parent->m_debug_mode)
567 // only to be enabled for debugging...
568 if (!strcmp(proxy_host, "stop"))
571 xfree(m_default_target);
572 m_default_target = xstrdup(proxy_host);
574 proxy_host = m_default_target;
575 int client_idletime = -1;
576 const char *cql2rpn_fname = 0;
577 const char *negotiation_charset = 0;
578 const char *negotiation_lang = 0;
579 const char *query_charset = 0;
580 const char *default_client_query_charset = 0;
581 url[0] = m_default_target;
586 cfg->get_target_info(proxy_host, url, &m_bw_max,
587 &m_pdu_max, &m_max_record_retrieve,
589 &m_target_idletime, &client_idletime,
590 &parent->m_max_clients,
591 &m_keepalive_limit_bw,
592 &m_keepalive_limit_pdu,
595 &negotiation_charset,
598 &default_client_query_charset);
600 if (client_idletime != -1)
602 m_client_idletime = client_idletime;
603 timeout(m_client_idletime);
606 // get those FILE descriptors available
607 m_parent->low_socket_close();
609 m_cql2rpn.set_pqf_file(cql2rpn_fname);
610 // reserve them again
611 m_parent->low_socket_open();
613 if (negotiation_charset || negotiation_lang || default_client_query_charset)
615 set_proxy_negotiation(negotiation_charset,
616 negotiation_lang, default_client_query_charset);
618 m_charset_converter->set_target_query_charset(query_charset);
621 yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
624 // we don't handle multiplexing for cookie session, so we just
625 // pick the first one in this case (anonymous users will be able
626 // to use any backend)
627 if (cookie && *cookie)
628 m_proxyTarget = (char*) xstrdup(url[0]);
630 m_proxyTarget = (char*) xstrdup(load_balance(url));
632 if (cookie && *cookie)
633 { // search in sessions with a cookie
634 for (c = parent->m_clientPool; c; c = c->m_next)
637 assert (*c->m_prev == c);
638 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
639 !strcmp(m_proxyTarget, c->get_hostname()))
642 // The following handles "cancel"
643 // If connection is busy (waiting for PDU) and
644 // we have an initRequest we can safely do re-open
645 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
647 yaz_log (YLOG_LOG, "%s REOPEN target=%s", m_session_str,
654 c->m_last_resultCount = 0;
655 c->m_sr_transform = 0;
657 c->m_resultSetStartPoint = 0;
658 c->m_target_idletime = m_target_idletime;
659 if (c->client(m_proxyTarget))
666 c->m_seqno = parent->m_seqno;
667 if (c->m_server && c->m_server != this)
668 c->m_server->m_client = 0;
671 yaz_log (YLOG_DEBUG, "get_client 1 %p %p", this, c);
676 else if (!c && apdu->which == Z_APDU_initRequest )
678 // anonymous sessions without cookie.
679 // if authentication is set it is NOT anonymous se we can't share them.
680 // If charset and lang negotiation is use it is NOT anonymous session too.
681 for (c = parent->m_clientPool; c; c = c->m_next)
684 assert(*c->m_prev == c);
685 if (c->m_server == 0 && c->m_cookie == 0 && c->m_waiting == 0
686 && c->compare_idAuthentication(apdu)
687 && c->compare_charset(apdu)
688 && !strcmp(m_proxyTarget, c->get_hostname()))
691 yaz_log (YLOG_LOG, "%sREUSE %d %s",
692 m_session_str, parent->m_seqno, c->get_hostname());
694 c->m_seqno = parent->m_seqno;
695 assert(c->m_server == 0);
698 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
699 c->set_APDU_yazlog(1);
701 c->set_APDU_yazlog(0);
713 if (apdu->which != Z_APDU_initRequest)
715 yaz_log (YLOG_LOG, "%sno init request as first PDU", m_session_str);
718 // go through list of clients - and find the lowest/oldest one.
719 Yaz_ProxyClient *c_min = 0;
721 int no_of_clients = 0;
722 if (parent->m_clientPool)
723 yaz_log (YLOG_DEBUG, "Existing sessions");
724 for (c = parent->m_clientPool; c; c = c->m_next)
726 yaz_log (YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
727 c->m_waiting, c->get_hostname(),
728 c->m_cookie ? c->m_cookie : "");
730 if (min_seq < 0 || c->m_seqno < min_seq)
732 min_seq = c->m_seqno;
736 if (no_of_clients >= parent->m_max_clients)
739 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
741 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
742 m_session_str, parent->m_max_clients, c->m_seqno);
743 if (c->m_server && c->m_server != this)
744 c->m_server->dec_ref();
748 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
749 m_session_str, parent->m_max_clients,
750 c->m_seqno, parent->m_seqno, c->get_hostname());
754 c->m_cookie = xstrdup(cookie);
755 c->m_seqno = parent->m_seqno;
756 if (c->m_server && c->m_server != this)
758 c->m_server->m_client = 0;
759 c->m_server->dec_ref();
762 c->m_target_idletime = m_target_idletime;
763 c->timeout(m_target_idletime);
765 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
766 c->set_APDU_yazlog(1);
768 c->set_APDU_yazlog(0);
775 yaz_log (YLOG_LOG, "%sNEW %d %s",
776 m_session_str, parent->m_seqno, m_proxyTarget);
777 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
778 c->m_next = parent->m_clientPool;
780 c->m_next->m_prev = &c->m_next;
781 parent->m_clientPool = c;
782 c->m_prev = &parent->m_clientPool;
788 c->m_cookie = xstrdup(cookie);
790 c->m_seqno = parent->m_seqno;
792 c->m_last_resultCount = 0;
795 c->m_sr_transform = 0;
797 c->m_resultSetStartPoint = 0;
799 if (c->client(m_proxyTarget))
804 c->m_target_idletime = m_target_idletime;
807 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
808 c->set_APDU_yazlog(1);
810 c->set_APDU_yazlog(0);
812 c->set_idAuthentication(apdu);
814 yaz_log (YLOG_DEBUG, "get_client 3 %p %p", this, c);
818 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
821 for (i = 0; i<num; i++)
824 Z_DefaultDiagFormat *r;
825 Z_DiagRec *p = pp[i];
826 if (p->which != Z_DiagRec_defaultFormat)
828 yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
832 r = p->u.defaultFormat;
833 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
834 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
835 yaz_log(YLOG_LOG, "%sError unknown diagnostic set", m_session_str);
838 case Z_DefaultDiagFormat_v2Addinfo:
839 yaz_log(YLOG_LOG, "%sError %d %s:%s",
841 *r->condition, diagbib1_str(*r->condition),
844 case Z_DefaultDiagFormat_v3Addinfo:
845 yaz_log(YLOG_LOG, "%sError %d %s:%s",
847 *r->condition, diagbib1_str(*r->condition),
854 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
856 if (!m_stylesheet_xsp || p->num_records <= 0)
858 return 0; /* no XSLT to be done ... */
861 m_stylesheet_offset = 0;
862 m_stylesheet_nprl = p;
863 m_stylesheet_apdu = apdu;
864 m_timeout_mode = timeout_xsl;
870 void Yaz_Proxy::convert_xsl_delay()
873 Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
874 if (npr->which == Z_NamePlusRecord_databaseRecord)
876 Z_External *r = npr->u.databaseRecord;
877 if (r->which == Z_External_octet)
880 fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
882 xmlDocPtr res, doc = xmlParseMemory(
883 (char*) r->u.octet_aligned->buf,
884 r->u.octet_aligned->len);
887 yaz_log(YLOG_LOG, "%sXSLT convert %d",
888 m_session_str, m_stylesheet_offset);
889 res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
896 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
898 m_stylesheet_nprl->records[m_stylesheet_offset]->
900 z_ext_record(odr_encode(), VAL_TEXT_XML,
901 (char*) out_buf, out_len);
910 m_stylesheet_offset++;
911 if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
913 m_timeout_mode = timeout_normal;
914 m_stylesheet_nprl = 0;
916 if (m_stylesheet_xsp)
917 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
919 m_stylesheet_xsp = 0;
920 timeout(m_client_idletime);
921 send_PDU_convert(m_stylesheet_apdu);
927 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
929 if (m_frontend_type != VAL_NONE)
932 for (i = 0; i < p->num_records; i++)
934 Z_NamePlusRecord *npr = p->records[i];
935 if (npr->which == Z_NamePlusRecord_databaseRecord)
937 Z_External *r = npr->u.databaseRecord;
938 if (r->which == Z_External_octet)
941 if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
943 if (!m_usemarcon->m_stage1)
945 m_usemarcon->m_stage1 = new CDetails();
947 m_usemarcon->m_stage1->SetIniFileName(m_usemarcon_ini_stage1);
948 m_usemarcon->m_stage1->SetMarcRecord((char*) r->u.octet_aligned->buf, r->u.octet_aligned->len);
949 int res = m_usemarcon->m_stage1->Start();
954 m_usemarcon->m_stage1->GetMarcRecord(converted, convlen);
955 if (m_usemarcon_ini_stage2 && *m_usemarcon_ini_stage2)
957 if (!m_usemarcon->m_stage2)
959 m_usemarcon->m_stage2 = new CDetails();
961 m_usemarcon->m_stage2->SetIniFileName(m_usemarcon_ini_stage2);
962 m_usemarcon->m_stage2->SetMarcRecord(converted, convlen);
963 res = m_usemarcon->m_stage2->Start();
967 m_usemarcon->m_stage2->GetMarcRecord(converted, convlen);
971 yaz_log(YLOG_LOG, "%sUSEMARCON stage 2 error %d", m_session_str, res);
974 npr->u.databaseRecord =
975 z_ext_record(odr_encode(),
983 yaz_log(YLOG_LOG, "%sUSEMARCON stage 1 error %d", m_session_str, res);
989 npr->u.databaseRecord =
990 z_ext_record(odr_encode(),
992 (char*) r->u.octet_aligned->buf,
993 r->u.octet_aligned->len);
1000 void Yaz_Proxy::convert_records_charset(Z_NamePlusRecordList *p,
1001 const char *backend_charset)
1003 int sel = m_charset_converter->get_client_charset_selected();
1004 const char *client_record_charset =
1005 m_charset_converter->get_client_query_charset();
1006 if (sel && backend_charset && client_record_charset &&
1007 strcmp(backend_charset, client_record_charset))
1010 yaz_iconv_t cd = yaz_iconv_open(client_record_charset,
1012 yaz_marc_t mt = yaz_marc_create();
1013 yaz_marc_xml(mt, YAZ_MARC_ISO2709);
1014 yaz_marc_iconv(mt, cd);
1015 for (i = 0; i < p->num_records; i++)
1017 Z_NamePlusRecord *npr = p->records[i];
1018 if (npr->which == Z_NamePlusRecord_databaseRecord)
1020 Z_External *r = npr->u.databaseRecord;
1021 oident *ent = oid_getentbyoid(r->direct_reference);
1022 if (!ent || ent->value == VAL_NONE)
1025 if (ent->value == VAL_SUTRS)
1027 WRBUF w = wrbuf_alloc();
1029 wrbuf_iconv_write(w, cd, (char*) r->u.octet_aligned->buf,
1030 r->u.octet_aligned->len);
1031 npr->u.databaseRecord =
1032 z_ext_record(odr_encode(), ent->value, wrbuf_buf(w),
1036 else if (ent->value == VAL_TEXT_XML)
1040 else if (r->which == Z_External_octet)
1044 if (yaz_marc_decode_buf(mt,
1045 (char*) r->u.octet_aligned->buf,
1046 r->u.octet_aligned->len,
1049 npr->u.databaseRecord =
1050 z_ext_record(odr_encode(), ent->value, result, rlen);
1051 yaz_log(YLOG_LOG, "%sRecoding MARC record",
1058 yaz_iconv_close(cd);
1059 yaz_marc_destroy(mt);
1063 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
1064 const char *backend_charset)
1067 if (!backend_charset)
1068 backend_charset = "MARC-8";
1069 yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
1070 yaz_marc_t mt = yaz_marc_create();
1071 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1072 yaz_marc_iconv(mt, cd);
1073 for (i = 0; i < p->num_records; i++)
1075 Z_NamePlusRecord *npr = p->records[i];
1076 if (npr->which == Z_NamePlusRecord_databaseRecord)
1078 Z_External *r = npr->u.databaseRecord;
1079 if (r->which == Z_External_OPAC)
1081 WRBUF w = wrbuf_alloc();
1083 yaz_opac_decode_wrbuf(mt, r->u.opac, w);
1084 npr->u.databaseRecord = z_ext_record(
1085 odr_encode(), VAL_TEXT_XML,
1086 wrbuf_buf(w), wrbuf_len(w)
1090 else if (r->which == Z_External_octet)
1094 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
1095 r->u.octet_aligned->len,
1098 npr->u.databaseRecord =
1099 z_ext_record(odr_encode(), VAL_TEXT_XML, result, rlen);
1105 yaz_iconv_close(cd);
1106 yaz_marc_destroy(mt);
1109 void Yaz_Proxy::logtime()
1111 #if HAVE_GETTIMEOFDAY
1112 struct timeval *tv = (struct timeval*) m_time_tv;
1116 gettimeofday(&tv1, 0);
1117 long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
1118 (tv1.tv_usec - tv->tv_usec);
1120 yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
1121 diff/1000000, (diff/1000)%1000);
1128 int Yaz_Proxy::send_http_response(int code)
1130 ODR o = odr_encode();
1131 Z_GDU *gdu = z_get_HTTP_Response(o, code);
1132 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1134 hres->version = odr_strdup(o, m_http_version);
1135 if (m_http_keepalive)
1136 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1140 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1142 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1146 int r = send_GDU(gdu, &len);
1147 m_bytes_sent += len;
1148 m_bw_stat.add_bytes(len);
1151 recv_GDU_more(true);
1156 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu, int http_code /* = 200 */)
1158 ODR o = odr_encode();
1159 const char *ctype = "text/xml";
1160 Z_GDU *gdu = z_get_HTTP_Response(o, http_code);
1161 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1163 hres->version = odr_strdup(o, m_http_version);
1164 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1165 if (m_http_keepalive)
1166 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1169 if (http_code == 401)
1170 z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate", "Basic realm=\"YAZ Proxy\"");
1172 static Z_SOAP_Handler soap_handlers[2] = {
1174 {"http://www.loc.gov/zing/srw/", 0,
1175 (Z_SOAP_fun) yaz_srw_codec},
1180 Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
1181 soap_package->which = Z_SOAP_generic;
1182 soap_package->u.generic =
1183 (Z_SOAP_Generic *) odr_malloc(o, sizeof(*soap_package->u.generic));
1184 soap_package->u.generic->no = 0;
1185 soap_package->u.generic->ns = soap_handlers[0].ns;
1186 soap_package->u.generic->p = (void *) srw_pdu;
1187 soap_package->ns = m_soap_ns;
1188 z_soap_codec_enc_xsl(o, &soap_package,
1189 &hres->content_buf, &hres->content_len,
1190 soap_handlers, 0, m_s2z_stylesheet);
1191 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1193 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1197 int r = send_GDU(gdu, &len);
1198 m_bytes_sent += len;
1199 m_bw_stat.add_bytes(len);
1202 recv_GDU_more(true);
1207 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
1209 ODR o = odr_encode();
1210 Z_SRW_diagnostic *diagnostic = (Z_SRW_diagnostic *)
1211 odr_malloc(o, sizeof(*diagnostic));
1212 int num_diagnostic = 1;
1213 yaz_mk_std_diagnostic(o, diagnostic, srw_error, add);
1214 return send_srw_search_response(diagnostic, num_diagnostic, srw_error == 3 ? 401 : 200);
1217 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
1218 Z_DefaultDiagFormat *ddf)
1220 int bib1_code = *ddf->condition;
1221 if (bib1_code == 109)
1223 srw_res->num_diagnostics = 1;
1224 srw_res->diagnostics = (Z_SRW_diagnostic *)
1225 odr_malloc(o, sizeof(*srw_res->diagnostics));
1226 yaz_mk_std_diagnostic(o, srw_res->diagnostics,
1227 yaz_diag_bib1_to_srw(*ddf->condition),
1232 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
1234 ODR o = odr_encode();
1235 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1236 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1238 srw_res->numberOfRecords = odr_intdup (o, hits);
1239 if (records && records->which == Z_Records_DBOSD)
1241 srw_res->num_records =
1242 records->u.databaseOrSurDiagnostics->num_records;
1244 srw_res->records = (Z_SRW_record *)
1245 odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
1246 for (i = 0; i < srw_res->num_records; i++)
1248 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
1249 if (npr->which != Z_NamePlusRecord_databaseRecord)
1251 srw_res->records[i].recordSchema = "diagnostic";
1252 srw_res->records[i].recordPacking = m_s2z_packing;
1253 srw_res->records[i].recordData_buf = "67";
1254 srw_res->records[i].recordData_len = 2;
1255 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1258 Z_External *r = npr->u.databaseRecord;
1259 oident *ent = oid_getentbyoid(r->direct_reference);
1260 if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
1262 srw_res->records[i].recordSchema = m_schema;
1263 srw_res->records[i].recordPacking = m_s2z_packing;
1264 srw_res->records[i].recordData_buf = (char*)
1265 r->u.octet_aligned->buf;
1266 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1267 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1271 srw_res->records[i].recordSchema = "diagnostic";
1272 srw_res->records[i].recordPacking = m_s2z_packing;
1273 srw_res->records[i].recordData_buf = "67";
1274 srw_res->records[i].recordData_len = 2;
1275 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1279 if (records && records->which == Z_Records_NSD)
1282 http_code = z_to_srw_diag(odr_encode(), srw_res,
1283 records->u.nonSurrogateDiagnostic);
1285 return send_http_response(http_code);
1287 return send_srw_response(srw_pdu);
1291 int Yaz_Proxy::send_srw_search_response(Z_SRW_diagnostic *diagnostics,
1292 int num_diagnostics, int http_code /* = 200 */)
1294 ODR o = odr_encode();
1295 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1296 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1298 srw_res->num_diagnostics = num_diagnostics;
1299 srw_res->diagnostics = diagnostics;
1300 return send_srw_response(srw_pdu, http_code);
1303 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1304 int num_diagnostics)
1306 Yaz_ProxyConfig *cfg = check_reconfigure();
1310 char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1311 m_s2z_database, &len);
1314 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1315 Z_SRW_explainResponse *er = res->u.explain_response;
1317 er->record.recordData_buf = b;
1318 er->record.recordData_len = len;
1319 er->record.recordPacking = m_s2z_packing;
1320 er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
1322 er->diagnostics = diagnostics;
1323 er->num_diagnostics = num_diagnostics;
1324 return send_srw_response(res);
1327 return send_http_response(404);
1330 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1334 if (apdu->which == Z_APDU_initResponse)
1336 Z_InitResponse *res = apdu->u.initResponse;
1337 if (*res->result == 0)
1339 send_to_srw_client_error(3, 0);
1341 else if (!m_s2z_search_apdu)
1343 send_srw_explain_response(0, 0);
1347 handle_incoming_Z_PDU(m_s2z_search_apdu);
1350 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1352 m_s2z_search_apdu = 0;
1353 Z_SearchResponse *res = apdu->u.searchResponse;
1354 m_s2z_hit_count = *res->resultCount;
1355 if (res->records && res->records->which == Z_Records_NSD)
1357 send_to_srw_client_ok(0, res->records, 1);
1359 else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1362 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1364 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1366 if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1368 *pr->numberOfRecordsRequested =
1369 1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1371 handle_incoming_Z_PDU(m_s2z_present_apdu);
1375 m_s2z_present_apdu = 0;
1376 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1379 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1382 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1384 m_s2z_present_apdu = 0;
1385 Z_PresentResponse *res = apdu->u.presentResponse;
1386 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1392 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1393 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1395 int r = send_Z_PDU(apdu, &len);
1396 m_bytes_sent += len;
1397 m_bw_stat.add_bytes(len);
1404 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1406 int kill_session = 0;
1407 Z_ReferenceId **new_id = get_referenceIdP(apdu);
1410 *new_id = m_referenceId;
1412 if (apdu->which == Z_APDU_searchResponse)
1414 Z_SearchResponse *sr = apdu->u.searchResponse;
1415 Z_Records *p = sr->records;
1416 if (p && p->which == Z_Records_NSD)
1418 Z_DiagRec dr, *dr_p = &dr;
1419 dr.which = Z_DiagRec_defaultFormat;
1420 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1422 *sr->searchStatus = 0;
1423 display_diagrecs(&dr_p, 1);
1427 if (p && p->which == Z_Records_DBOSD)
1431 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1434 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1435 if (m_marcxml_mode == marcxml)
1436 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1439 convert_records_charset(p->u.databaseOrSurDiagnostics,
1441 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1445 if (sr->resultCount)
1447 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1449 if (*sr->resultCount < 0)
1451 m_flag_invalid_session = 1;
1454 *sr->searchStatus = 0;
1456 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1457 *sr->resultCount = 0;
1462 else if (apdu->which == Z_APDU_presentResponse)
1464 Z_PresentResponse *sr = apdu->u.presentResponse;
1465 Z_Records *p = sr->records;
1466 if (p && p->which == Z_Records_NSD)
1468 Z_DiagRec dr, *dr_p = &dr;
1469 dr.which = Z_DiagRec_defaultFormat;
1470 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1471 if (*sr->presentStatus == Z_PresentStatus_success)
1472 *sr->presentStatus = Z_PresentStatus_failure;
1473 display_diagrecs(&dr_p, 1);
1475 if (p && p->which == Z_Records_DBOSD)
1479 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1482 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1483 if (m_marcxml_mode == marcxml)
1484 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1487 convert_records_charset(p->u.databaseOrSurDiagnostics,
1489 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1493 else if (apdu->which == Z_APDU_initResponse)
1495 //Get and check negotiation record
1496 //from init response.
1497 handle_charset_lang_negotiation(apdu);
1499 if (m_initRequest_options)
1502 (Odr_bitmask *)odr_malloc(odr_encode(),
1503 sizeof(Odr_bitmask));
1504 ODR_MASK_ZERO(nopt);
1507 for (i = 0; i<24; i++)
1508 if (ODR_MASK_GET(m_initRequest_options, i) &&
1509 ODR_MASK_GET(apdu->u.initResponse->options, i))
1510 ODR_MASK_SET(nopt, i);
1511 apdu->u.initResponse->options = nopt;
1513 if (m_initRequest_version)
1515 Z_ProtocolVersion *nopt =
1516 (Odr_bitmask *)odr_malloc(odr_encode(),
1517 sizeof(Odr_bitmask));
1518 ODR_MASK_ZERO(nopt);
1521 for (i = 0; i<8; i++)
1522 if (ODR_MASK_GET(m_initRequest_version, i) &&
1523 ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1524 ODR_MASK_SET(nopt, i);
1525 apdu->u.initResponse->protocolVersion = nopt;
1527 apdu->u.initResponse->preferredMessageSize =
1528 odr_intdup(odr_encode(),
1529 m_client->m_initResponse_preferredMessageSize >
1530 m_initRequest_preferredMessageSize ?
1531 m_initRequest_preferredMessageSize :
1532 m_client->m_initResponse_preferredMessageSize);
1533 apdu->u.initResponse->maximumRecordSize =
1534 odr_intdup(odr_encode(),
1535 m_client->m_initResponse_maximumRecordSize >
1536 m_initRequest_maximumRecordSize ?
1537 m_initRequest_maximumRecordSize :
1538 m_client->m_initResponse_maximumRecordSize);
1541 int r = send_PDU_convert(apdu);
1548 m_parent->pre_init();
1553 void Yaz_ProxyClient::set_idAuthentication(Z_APDU *apdu)
1555 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1557 odr_reset(m_idAuthentication_odr);
1558 z_IdAuthentication(m_idAuthentication_odr, &t, 1, 0);
1559 m_idAuthentication_ber_buf =
1560 odr_getbuf(m_idAuthentication_odr,
1561 &m_idAuthentication_ber_size, 0);
1564 bool Yaz_ProxyClient::compare_charset(Z_APDU *apdu)
1569 bool Yaz_ProxyClient::compare_idAuthentication(Z_APDU *apdu)
1571 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1572 ODR odr = odr_createmem(ODR_ENCODE);
1574 z_IdAuthentication(odr, &t, 1, 0);
1576 char *buf = odr_getbuf(odr, &sz, 0);
1577 if (buf && m_idAuthentication_ber_buf
1578 && sz == m_idAuthentication_ber_size
1579 && !memcmp(m_idAuthentication_ber_buf, buf, sz))
1585 if (!buf && !m_idAuthentication_ber_buf)
1590 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1593 const char *apdu_name_tmp = apdu_name(apdu);
1594 int r = send_Z_PDU(apdu, &len);
1595 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1596 yaz_log (YLOG_LOG, "%sSending %s to %s %d bytes",
1598 apdu_name_tmp, get_hostname(), len);
1599 m_bytes_sent += len;
1603 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1605 if (apdu->which == Z_APDU_presentRequest)
1607 Z_PresentRequest *pr = apdu->u.presentRequest;
1608 int toget = *pr->numberOfRecordsRequested;
1609 int start = *pr->resultSetStartPoint;
1611 yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1612 pr->resultSetId, start, toget);
1614 if (*m_parent->m_optimize == '0')
1617 if (!m_client->m_last_resultSetId)
1619 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1620 new_apdu->u.presentResponse->records =
1621 create_nonSurrogateDiagnostics(
1623 YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1625 send_to_client(new_apdu);
1628 if (start < 1 || toget < 0)
1630 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1631 new_apdu->u.presentResponse->records =
1632 create_nonSurrogateDiagnostics(
1634 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1636 send_to_client(new_apdu);
1639 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1641 if (start+toget-1 > m_client->m_last_resultCount)
1643 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1644 new_apdu->u.presentResponse->records =
1645 create_nonSurrogateDiagnostics(
1647 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1649 send_to_client(new_apdu);
1652 Z_NamePlusRecordList *npr;
1654 yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1655 m_session_str, start, toget, yaz_z3950oid_to_str(
1656 pr->preferredRecordSyntax, &oclass));
1658 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1659 pr->preferredRecordSyntax,
1660 pr->recordComposition))
1662 yaz_log (YLOG_LOG, "%sReturned cached records for present request",
1664 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1665 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1667 new_apdu->u.presentResponse->numberOfRecordsReturned
1668 = odr_intdup(odr_encode(), toget);
1670 new_apdu->u.presentResponse->records = (Z_Records*)
1671 odr_malloc(odr_encode(), sizeof(Z_Records));
1672 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1673 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1674 new_apdu->u.presentResponse->nextResultSetPosition =
1675 odr_intdup(odr_encode(), start+toget);
1677 send_to_client(new_apdu);
1683 if (apdu->which != Z_APDU_searchRequest)
1685 Z_SearchRequest *sr = apdu->u.searchRequest;
1686 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1687 Yaz_Z_Databases this_databases;
1689 this_databases.set(sr->num_databaseNames, (const char **)
1692 this_query->set_Z_Query(sr->query);
1694 // Check for non-negative piggyback params.
1695 if (*sr->smallSetUpperBound < 0
1696 || *sr->largeSetLowerBound < 0
1697 || *sr->mediumSetPresentNumber < 0)
1699 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1700 // Not a present request.. But can't find better diagnostic
1701 new_apdu->u.searchResponse->records =
1702 create_nonSurrogateDiagnostics(
1704 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 0);
1705 send_to_client(new_apdu);
1709 char query_str[120];
1710 this_query->print(query_str, sizeof(query_str)-1);
1711 yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1713 if (*m_parent->m_optimize != '0' &&
1714 m_client->m_last_ok && m_client->m_last_query &&
1715 m_client->m_last_query->match(this_query) &&
1716 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1717 m_client->m_last_databases.match(this_databases))
1720 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1721 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1723 Z_NamePlusRecordList *npr;
1724 int toget = *sr->mediumSetPresentNumber;
1725 Z_RecordComposition *comp = 0;
1727 if (toget > m_client->m_last_resultCount)
1728 toget = m_client->m_last_resultCount;
1730 if (sr->mediumSetElementSetNames)
1732 comp = (Z_RecordComposition *)
1733 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1734 comp->which = Z_RecordComp_simple;
1735 comp->u.simple = sr->mediumSetElementSetNames;
1738 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1739 sr->preferredRecordSyntax, comp))
1741 yaz_log (YLOG_LOG, "%sReturned cached records for medium set",
1743 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1744 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1745 new_apdu->u.searchResponse->resultCount =
1746 &m_client->m_last_resultCount;
1748 new_apdu->u.searchResponse->numberOfRecordsReturned
1749 = odr_intdup(odr_encode(), toget);
1751 new_apdu->u.searchResponse->presentStatus =
1752 odr_intdup(odr_encode(), Z_PresentStatus_success);
1753 new_apdu->u.searchResponse->records = (Z_Records*)
1754 odr_malloc(odr_encode(), sizeof(Z_Records));
1755 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1756 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1757 new_apdu->u.searchResponse->nextResultSetPosition =
1758 odr_intdup(odr_encode(), toget+1);
1759 send_to_client(new_apdu);
1765 // send present request (medium size)
1766 yaz_log (YLOG_LOG, "%sOptimizing search for medium set",
1769 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1770 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1771 pr->referenceId = sr->referenceId;
1772 pr->resultSetId = sr->resultSetName;
1773 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1774 *pr->numberOfRecordsRequested = toget;
1775 pr->recordComposition = comp;
1776 m_client->m_sr_transform = 1;
1780 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1781 m_client->m_last_resultCount <= 0)
1783 // large set. Return pseudo-search response immediately
1784 yaz_log (YLOG_LOG, "%sOptimizing search for large set",
1786 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1787 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1788 new_apdu->u.searchResponse->resultCount =
1789 &m_client->m_last_resultCount;
1790 send_to_client(new_apdu);
1795 Z_NamePlusRecordList *npr;
1796 int toget = m_client->m_last_resultCount;
1797 Z_RecordComposition *comp = 0;
1799 // send a present request (small set)
1801 if (sr->smallSetElementSetNames)
1803 comp = (Z_RecordComposition *)
1804 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1805 comp->which = Z_RecordComp_simple;
1806 comp->u.simple = sr->smallSetElementSetNames;
1809 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1810 sr->preferredRecordSyntax, comp))
1812 yaz_log (YLOG_LOG, "%sReturned cached records for small set",
1814 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1815 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1816 new_apdu->u.searchResponse->resultCount =
1817 &m_client->m_last_resultCount;
1819 new_apdu->u.searchResponse->numberOfRecordsReturned
1820 = odr_intdup(odr_encode(), toget);
1822 new_apdu->u.searchResponse->presentStatus =
1823 odr_intdup(odr_encode(), Z_PresentStatus_success);
1824 new_apdu->u.searchResponse->records = (Z_Records*)
1825 odr_malloc(odr_encode(), sizeof(Z_Records));
1826 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1827 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1828 new_apdu->u.searchResponse->nextResultSetPosition =
1829 odr_intdup(odr_encode(), toget+1);
1830 send_to_client(new_apdu);
1835 yaz_log (YLOG_LOG, "%sOptimizing search for small set",
1837 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1838 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1839 pr->referenceId = sr->referenceId;
1840 pr->resultSetId = sr->resultSetName;
1841 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1842 *pr->numberOfRecordsRequested = toget;
1843 pr->recordComposition = comp;
1844 m_client->m_sr_transform = 1;
1849 else // query doesn't match
1851 delete m_client->m_last_query;
1852 m_client->m_last_query = this_query;
1853 m_client->m_last_ok = 0;
1854 m_client->m_cache.clear();
1855 m_client->m_resultSetStartPoint = 0;
1857 xfree (m_client->m_last_resultSetId);
1858 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1860 m_client->m_last_databases.set(sr->num_databaseNames,
1861 (const char **) sr->databaseNames);
1867 void Yaz_Proxy::inc_request_no()
1870 char *cp = m_session_str + strlen(m_session_str)-1;
1873 while (*cp && *cp != ' ')
1876 sprintf(cp+1, "%d ", m_request_no);
1879 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1883 m_bytes_recv += len;
1885 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1886 yaz_log (YLOG_LOG, "%sReceiving %s from client %d bytes",
1887 m_session_str, gdu_name(apdu), len);
1890 // try to make a _bad_ attribute set ID .. Don't enable this in prod.
1891 if (apdu->which == Z_GDU_Z3950
1892 && apdu->u.z3950->which == Z_APDU_searchRequest)
1894 Z_SearchRequest *req = apdu->u.z3950->u.searchRequest;
1895 if (req->query && req->query->which == Z_Query_type_1)
1897 Z_RPNQuery *rpnquery = req->query->u.type_1;
1898 if (rpnquery->attributeSetId)
1900 rpnquery->attributeSetId[0] = -2;
1901 rpnquery->attributeSetId[1] = -1;
1902 yaz_log(YLOG_WARN, "%sBAD FIXUP TEST", m_session_str);
1908 #if HAVE_GETTIMEOFDAY
1909 gettimeofday((struct timeval *) m_time_tv, 0);
1911 m_bw_stat.add_bytes(len);
1912 m_pdu_stat.add_bytes(1);
1914 GDU *gdu = new GDU(apdu);
1916 if (gdu->get() == 0)
1919 yaz_log(YLOG_LOG, "%sUnable to encode package", m_session_str);
1924 m_in_queue.enqueue(gdu);
1925 recv_GDU_more(false);
1928 void Yaz_Proxy::HTTP_Forwarded(Z_GDU *z_gdu)
1930 if (z_gdu->which == Z_GDU_HTTP_Request)
1932 Z_HTTP_Request *hreq = z_gdu->u.HTTP_Request;
1933 const char *x_forwarded_for =
1934 z_HTTP_header_lookup(hreq->headers, "X-Forwarded-For");
1935 if (x_forwarded_for)
1938 m_peername = (char*) xmalloc(strlen(x_forwarded_for)+5);
1939 sprintf(m_peername, "tcp:%s", x_forwarded_for);
1941 yaz_log(YLOG_LOG, "%sHTTP Forwarded from %s", m_session_str,
1943 if (m_log_mask & PROXY_LOG_IP_CLIENT)
1944 sprintf(m_session_str, "%ld:%d %.80s %d ",
1945 (long) time(0), m_session_no, m_peername, m_request_no);
1947 sprintf(m_session_str, "%ld:%d %d ",
1948 (long) time(0), m_session_no, m_request_no);
1953 void Yaz_Proxy::connect_stat(bool &block, int &reduce)
1956 m_parent->m_connect.cleanup(false);
1957 m_parent->m_connect.add_connect(m_peername);
1959 int connect_total = m_parent->m_connect.get_total(m_peername);
1960 int max_connect = m_parent->m_max_connect;
1962 if (max_connect && connect_total > max_connect)
1964 yaz_log(YLOG_LOG, "%sconnect not accepted total=%d max=%d",
1965 m_session_str, connect_total, max_connect);
1970 yaz_log(YLOG_LOG, "%sconnect accepted total=%d", m_session_str,
1973 int limit_connect = m_parent->m_limit_connect;
1975 reduce = connect_total / limit_connect;
1980 void Yaz_Proxy::recv_GDU_reduce(GDU *gdu)
1982 HTTP_Forwarded(gdu->get());
1986 if (m_request_no == 1)
1990 connect_stat(block, reduce);
1994 m_timeout_mode = timeout_busy;
2000 int bw_total = m_bw_stat.get_total();
2001 int pdu_total = m_pdu_stat.get_total();
2002 int search_total = m_search_stat.get_total();
2004 assert(m_timeout_mode == timeout_busy);
2005 assert(m_timeout_gdu == 0);
2008 reduce += search_total / m_search_max;
2010 reduce += (bw_total/m_bw_max);
2013 if (pdu_total > m_pdu_max)
2015 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
2016 reduce = (reduce > nreduce) ? reduce : nreduce;
2022 /* uncomment to force a big reduce */
2023 m_timeout_mode = timeout_reduce;
2024 m_timeout_gdu = gdu;
2025 timeout(3); // call us reduce seconds later
2030 yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d search=%d limit-bw=%d limit-pdu=%d limit-search=%d",
2031 m_session_str, reduce, bw_total, pdu_total, search_total,
2032 m_bw_max, m_pdu_max, m_search_max);
2034 m_timeout_mode = timeout_reduce;
2035 m_timeout_gdu = gdu;
2036 timeout(reduce); // call us reduce seconds later
2039 recv_GDU_normal(gdu);
2042 void Yaz_Proxy::recv_GDU_more(bool normal)
2045 if (normal && m_timeout_mode == timeout_busy)
2046 m_timeout_mode = timeout_normal;
2047 while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
2049 m_timeout_mode = timeout_busy;
2057 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
2060 gdu->move_away_gdu(odr_decode(), &apdu);
2063 if (apdu->which == Z_GDU_Z3950)
2064 handle_incoming_Z_PDU(apdu->u.z3950);
2065 else if (apdu->which == Z_GDU_HTTP_Request)
2066 handle_incoming_HTTP(apdu->u.HTTP_Request);
2069 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
2071 if (m_max_record_retrieve)
2073 if (apdu->which == Z_APDU_presentRequest)
2075 Z_PresentRequest *pr = apdu->u.presentRequest;
2076 if (pr->numberOfRecordsRequested &&
2077 *pr->numberOfRecordsRequested > m_max_record_retrieve)
2078 *pr->numberOfRecordsRequested = m_max_record_retrieve;
2083 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
2085 if (apdu->which == Z_APDU_initRequest)
2087 if (m_initRequest_options &&
2088 !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
2089 (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
2091 // There is no negotiation proposal from
2092 // client's side. OK. The proxy negotiation
2094 Z_InitRequest *initRequest = apdu->u.initRequest;
2095 Z_OtherInformation **otherInfo;
2096 Z_OtherInformationUnit *oi;
2097 get_otherInfoAPDU(apdu, &otherInfo);
2098 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2101 ODR_MASK_SET(initRequest->options,
2102 Z_Options_negotiationModel);
2103 oi->which = Z_OtherInfo_externallyDefinedInfo;
2104 oi->information.externallyDefinedInfo =
2105 yaz_set_proposal_charneg(odr_encode(),
2106 (const char**)&m_proxy_negotiation_charset,
2107 m_proxy_negotiation_charset ? 1:0,
2108 (const char**)&m_proxy_negotiation_lang,
2109 m_proxy_negotiation_lang ? 1:0,
2113 else if (m_initRequest_options &&
2114 ODR_MASK_GET(m_initRequest_options,
2115 Z_Options_negotiationModel) &&
2116 m_charset_converter->get_target_query_charset())
2118 yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
2120 m_charset_converter->get_target_query_charset());
2121 Z_InitRequest *initRequest = apdu->u.initRequest;
2122 Z_CharSetandLanguageNegotiation *negotiation =
2123 yaz_get_charneg_record (initRequest->otherInfo);
2125 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2127 NMEM nmem = nmem_create();
2128 char **charsets = 0;
2129 int num_charsets = 0;
2133 yaz_get_proposal_charneg (nmem, negotiation,
2134 &charsets, &num_charsets,
2135 &langs, &num_langs, &selected);
2137 for (i = 0; i<num_charsets; i++)
2138 yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
2140 for (i = 0; i<num_langs; i++)
2141 yaz_log(YLOG_LOG, "%slang %s", m_session_str,
2144 const char *t_charset =
2145 m_charset_converter->get_target_query_charset();
2146 // sweep through charsets and pick the first supported
2148 for (i = 0; i<num_charsets; i++)
2150 const char *c_charset = charsets[i];
2151 if (!odr_set_charset(odr_decode(), t_charset, c_charset))
2154 if (i != num_charsets)
2156 // got one .. set up ODR for reverse direction
2157 const char *c_charset = charsets[i];
2158 odr_set_charset(odr_encode(), c_charset, t_charset);
2159 m_charset_converter->set_client_query_charset(c_charset);
2160 m_charset_converter->set_client_charset_selected(selected);
2163 ODR_MASK_CLEAR(m_initRequest_options,
2164 Z_Options_negotiationModel);
2165 yaz_del_charneg_record(&initRequest->otherInfo);
2169 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
2173 else if (m_charset_converter->get_target_query_charset() &&
2174 m_proxy_negotiation_default_charset)
2176 m_charset_converter->
2177 set_client_query_charset(m_proxy_negotiation_default_charset);
2180 else if (apdu->which == Z_APDU_initResponse)
2182 Z_InitResponse *initResponse = apdu->u.initResponse;
2183 Z_OtherInformation **otherInfo;
2184 get_otherInfoAPDU(apdu, &otherInfo);
2186 Z_CharSetandLanguageNegotiation *charneg = 0;
2188 if (otherInfo && *otherInfo &&
2189 ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel)
2190 && (charneg = yaz_get_charneg_record(*otherInfo)))
2196 yaz_get_response_charneg(m_referenceId_mem, charneg,
2197 &charset, &lang, &selected);
2199 yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
2200 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
2202 if (m_initRequest_options &&
2203 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
2205 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2208 else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2210 // negotiation-charset, negotiation-lang
2211 // elements of config file in use.
2213 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2216 // clear negotiation option.
2217 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2219 // Delete negotiation (charneg-3) entry.
2220 yaz_del_charneg_record(otherInfo);
2225 if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2227 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2230 else if (m_charset_converter->get_client_query_charset())
2232 Z_OtherInformation **otherInfo;
2233 Z_OtherInformationUnit *oi;
2234 get_otherInfoAPDU(apdu, &otherInfo);
2235 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2238 ODR_MASK_SET(initResponse->options,
2239 Z_Options_negotiationModel);
2240 if (m_initRequest_options)
2241 ODR_MASK_SET(m_initRequest_options,
2242 Z_Options_negotiationModel);
2244 oi->which = Z_OtherInfo_externallyDefinedInfo;
2245 oi->information.externallyDefinedInfo =
2246 yaz_set_response_charneg(
2248 m_charset_converter->get_client_query_charset(),
2250 m_charset_converter->get_client_charset_selected());
2257 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2259 const char *addinfo)
2261 Z_Records *rec = (Z_Records *)
2262 odr_malloc (odr, sizeof(*rec));
2264 odr_malloc (odr, sizeof(*err));
2265 Z_DiagRec *drec = (Z_DiagRec *)
2266 odr_malloc (odr, sizeof(*drec));
2267 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2268 odr_malloc (odr, sizeof(*dr));
2270 rec->which = Z_Records_NSD;
2271 rec->u.nonSurrogateDiagnostic = dr;
2272 dr->diagnosticSetId =
2273 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
2274 dr->condition = err;
2275 dr->which = Z_DefaultDiagFormat_v2Addinfo;
2276 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2280 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2282 if (apdu->which == Z_APDU_searchRequest &&
2283 apdu->u.searchRequest->query &&
2284 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2285 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2287 Z_RPNQuery *rpnquery = 0;
2288 Z_SearchRequest *sr = apdu->u.searchRequest;
2291 yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2292 sr->query->u.type_104->u.cql);
2294 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2295 &rpnquery, odr_encode(),
2298 yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2301 yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2302 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2304 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2305 new_apdu->u.searchResponse->records =
2306 create_nonSurrogateDiagnostics(odr_encode(),
2307 yaz_diag_srw_to_bib1(r),
2309 *new_apdu->u.searchResponse->searchStatus = 0;
2311 send_to_client(new_apdu);
2317 sr->query->which = Z_Query_type_1;
2318 sr->query->u.type_1 = rpnquery;
2325 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2327 if (apdu->which == Z_APDU_searchRequest &&
2328 apdu->u.searchRequest->query)
2330 if (apdu->u.searchRequest->query->which == Z_Query_type_1
2331 || apdu->u.searchRequest->query->which == Z_Query_type_101)
2334 m_charset_converter->set_client_query_charset("UTF-8");
2335 Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2336 m_charset_converter->convert_type_1(rpnquery, odr_encode());
2343 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2345 if (apdu->which == Z_APDU_searchRequest)
2347 Z_SearchRequest *sr = apdu->u.searchRequest;
2351 Yaz_ProxyConfig *cfg = check_reconfigure();
2353 err = cfg->check_query(odr_encode(), m_default_target,
2354 sr->query, &addinfo);
2357 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2359 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2360 new_apdu->u.searchResponse->records =
2361 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2362 *new_apdu->u.searchResponse->searchStatus = 0;
2364 send_to_client(new_apdu);
2372 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2374 if (apdu->which != Z_APDU_initRequest)
2375 return 1; // pass if no init request
2376 Z_InitRequest *req = apdu->u.initRequest;
2378 Yaz_ProxyConfig *cfg = check_reconfigure();
2380 return 1; // pass if no config
2383 if (req->idAuthentication == 0)
2385 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2388 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2390 ret = cfg->client_authentication(
2392 req->idAuthentication->u.idPass->userId,
2393 req->idAuthentication->u.idPass->groupId,
2394 req->idAuthentication->u.idPass->password,
2397 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2399 char user[64], pass[64];
2402 sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2403 ret = cfg->client_authentication(m_default_target, user, 0, pass,
2407 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2412 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2414 m_marcxml_mode = none;
2415 if (apdu->which == Z_APDU_searchRequest)
2417 Z_SearchRequest *sr = apdu->u.searchRequest;
2420 Yaz_ProxyConfig *cfg = check_reconfigure();
2422 Z_RecordComposition rc_temp, *rc = 0;
2423 if (sr->smallSetElementSetNames)
2425 rc_temp.which = Z_RecordComp_simple;
2426 rc_temp.u.simple = sr->smallSetElementSetNames;
2430 if (sr->preferredRecordSyntax)
2433 ent = oid_getentbyoid(sr->preferredRecordSyntax);
2434 m_frontend_type = ent->value;
2437 m_frontend_type = VAL_NONE;
2439 char *stylesheet_name = 0;
2441 err = cfg->check_syntax(odr_encode(),
2443 sr->preferredRecordSyntax, rc,
2444 &addinfo, &stylesheet_name, &m_schema,
2445 &m_backend_type, &m_backend_charset,
2446 &m_usemarcon_ini_stage1,
2447 &m_usemarcon_ini_stage2);
2448 if (stylesheet_name)
2450 m_parent->low_socket_close();
2453 if (m_stylesheet_xsp)
2454 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2455 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2458 m_stylesheet_offset = 0;
2459 xfree(stylesheet_name);
2461 m_parent->low_socket_open();
2465 sr->smallSetElementSetNames = 0;
2466 sr->mediumSetElementSetNames = 0;
2467 m_marcxml_mode = marcxml;
2471 sr->preferredRecordSyntax =
2472 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2476 sr->preferredRecordSyntax =
2477 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2482 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2484 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2485 new_apdu->u.searchResponse->records =
2486 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2487 *new_apdu->u.searchResponse->searchStatus = 0;
2489 send_to_client(new_apdu);
2493 else if (m_backend_type)
2495 sr->preferredRecordSyntax =
2496 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2499 else if (apdu->which == Z_APDU_presentRequest)
2501 Z_PresentRequest *pr = apdu->u.presentRequest;
2504 Yaz_ProxyConfig *cfg = check_reconfigure();
2506 if (pr->preferredRecordSyntax)
2509 ent = oid_getentbyoid(pr->preferredRecordSyntax);
2510 m_frontend_type = ent->value;
2513 m_frontend_type = VAL_NONE;
2515 char *stylesheet_name = 0;
2517 err = cfg->check_syntax(odr_encode(), m_default_target,
2518 pr->preferredRecordSyntax,
2519 pr->recordComposition,
2520 &addinfo, &stylesheet_name, &m_schema,
2521 &m_backend_type, &m_backend_charset,
2522 &m_usemarcon_ini_stage1,
2523 &m_usemarcon_ini_stage2
2525 if (stylesheet_name)
2527 m_parent->low_socket_close();
2530 if (m_stylesheet_xsp)
2531 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2532 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2535 m_stylesheet_offset = 0;
2536 xfree(stylesheet_name);
2538 m_parent->low_socket_open();
2542 pr->recordComposition = 0;
2543 m_marcxml_mode = marcxml;
2547 pr->preferredRecordSyntax =
2548 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2552 pr->preferredRecordSyntax =
2553 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2558 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2560 new_apdu->u.presentResponse->referenceId = pr->referenceId;
2561 new_apdu->u.presentResponse->records =
2562 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2563 *new_apdu->u.presentResponse->presentStatus =
2564 Z_PresentStatus_failure;
2566 send_to_client(new_apdu);
2570 else if (m_backend_type)
2572 pr->preferredRecordSyntax =
2573 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2579 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2583 Z_ElementSetNames *esn = (Z_ElementSetNames *)
2584 odr_malloc(o, sizeof(Z_ElementSetNames));
2585 esn->which = Z_ElementSetNames_generic;
2586 esn->u.generic = odr_strdup(o, schema);
2590 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2593 Yaz_ProxyConfig *cfg = check_reconfigure();
2595 t = cfg->get_explain_name(db, backend_db);
2597 if (m_client && m_default_target && t && strcmp(m_default_target, t))
2604 xfree(m_default_target);
2605 m_default_target = xstrdup(t);
2609 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2612 if (strcmp(hreq->method, "GET"))
2614 if (hreq->path[0] != '/')
2616 const char *cp = hreq->path;
2619 if (*cp == '/' && strchr("/.", cp[1]))
2624 Yaz_ProxyConfig *cfg = check_reconfigure();
2626 if (!cfg->get_file_access_info(hreq->path+1))
2629 const char *fname = hreq->path+1;
2630 if (stat(fname, &sbuf))
2632 yaz_log(YLOG_LOG|YLOG_ERRNO, "%sstat failed for %s", m_session_str,
2636 if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2638 yaz_log(YLOG_LOG, "%sNot a regular file %s", m_session_str, fname);
2641 if (sbuf.st_size > (off_t) 1000000)
2643 yaz_log(YLOG_WARN, "%sFile %s too large for transfer", m_session_str,
2648 ODR o = odr_encode();
2650 const char *ctype = cfg->check_mime_type(fname);
2651 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2652 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2654 hres->version = odr_strdup(o, m_http_version);
2655 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2656 if (m_http_keepalive)
2657 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2661 hres->content_len = sbuf.st_size;
2662 hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2663 FILE *f = fopen(fname, "rb");
2666 fread(hres->content_buf, 1, hres->content_len, f);
2673 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2675 yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
2679 send_GDU(gdu, &len);
2680 recv_GDU_more(true);
2684 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2688 odr_destroy(m_s2z_odr_init);
2691 if (m_s2z_odr_search)
2693 odr_destroy(m_s2z_odr_search);
2694 m_s2z_odr_search = 0;
2697 m_http_keepalive = 0;
2699 if (!strcmp(hreq->version, "1.0"))
2701 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2702 if (v && !strcmp(v, "Keep-Alive"))
2703 m_http_keepalive = 1;
2705 m_http_keepalive = 0;
2706 m_http_version = "1.0";
2710 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2711 if (v && !strcmp(v, "close"))
2712 m_http_keepalive = 0;
2714 m_http_keepalive = 1;
2715 m_http_version = "1.1";
2718 const char *a = z_HTTP_header_lookup(hreq->headers, "Authorization");
2719 char authorization_str[255];
2720 *authorization_str = '\0';
2721 if (a && strncasecmp(a, "Basic ", 6) == 0)
2722 base64_decode(a + 6, authorization_str, 254);
2724 Z_SRW_PDU *srw_pdu = 0;
2725 Z_SOAP *soap_package = 0;
2727 Z_SRW_diagnostic *diagnostic = 0;
2728 int num_diagnostic = 0;
2730 yaz_log(YLOG_LOG, "%s%s %s", m_session_str, hreq->method, hreq->path);
2732 if (file_access(hreq))
2736 else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2738 || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2739 &charset, &diagnostic, &num_diagnostic) == 0)
2741 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2742 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2743 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2744 m_s2z_init_apdu = 0;
2745 m_s2z_search_apdu = 0;
2746 m_s2z_present_apdu = 0;
2748 m_s2z_stylesheet = 0;
2750 Z_IdAuthentication *auth = NULL;
2751 if (*authorization_str)
2753 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2754 auth->which = Z_IdAuthentication_idPass;
2755 auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2756 auth->u.idPass->groupId = NULL;
2757 char *p = strchr(authorization_str, ':');
2762 auth->u.idPass->password = odr_strdup(m_s2z_odr_init, p);
2764 auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, authorization_str);
2767 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2770 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2772 const char *backend_db = srw_req->database;
2773 srw_get_client(srw_req->database, &backend_db);
2775 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2776 // recordXPath unsupported.
2777 if (srw_req->recordXPath)
2779 yaz_add_srw_diagnostic(odr_decode(),
2780 &diagnostic, &num_diagnostic,
2784 if (srw_req->sort_type != Z_SRW_sort_type_none)
2786 yaz_add_srw_diagnostic(odr_decode(),
2787 &diagnostic, &num_diagnostic,
2791 if (srw_req->stylesheet)
2793 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2795 // set packing for response records ..
2796 if (srw_req->recordPacking &&
2797 !strcmp(srw_req->recordPacking, "xml"))
2798 m_s2z_packing = Z_SRW_recordPacking_XML;
2800 m_s2z_packing = Z_SRW_recordPacking_string;
2804 Z_SRW_PDU *srw_pdu =
2805 yaz_srw_get(odr_encode(),
2806 Z_SRW_searchRetrieve_response);
2807 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2809 srw_res->diagnostics = diagnostic;
2810 srw_res->num_diagnostics = num_diagnostic;
2811 send_srw_response(srw_pdu);
2815 // prepare search PDU
2816 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2817 Z_APDU_searchRequest);
2818 Z_SearchRequest *z_searchRequest =
2819 m_s2z_search_apdu->u.searchRequest;
2821 z_searchRequest->num_databaseNames = 1;
2822 z_searchRequest->databaseNames = (char**)
2823 odr_malloc(m_s2z_odr_search, sizeof(char *));
2824 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2827 // query transformation
2828 Z_Query *query = (Z_Query *)
2829 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2830 z_searchRequest->query = query;
2832 if (srw_req->query_type == Z_SRW_query_type_cql)
2834 Z_External *ext = (Z_External *)
2835 odr_malloc(m_s2z_odr_search, sizeof(*ext));
2836 ext->direct_reference =
2837 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2838 ext->indirect_reference = 0;
2839 ext->descriptor = 0;
2840 ext->which = Z_External_CQL;
2841 ext->u.cql = srw_req->query.cql;
2843 query->which = Z_Query_type_104;
2844 query->u.type_104 = ext;
2846 else if (srw_req->query_type == Z_SRW_query_type_pqf)
2848 Z_RPNQuery *RPNquery;
2849 YAZ_PQF_Parser pqf_parser;
2851 pqf_parser = yaz_pqf_create ();
2853 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2854 srw_req->query.pqf);
2857 const char *pqf_msg;
2859 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2861 yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
2862 yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2864 send_to_srw_client_error(10, 0);
2867 query->which = Z_Query_type_1;
2868 query->u.type_1 = RPNquery;
2870 yaz_pqf_destroy (pqf_parser);
2874 send_to_srw_client_error(7, "query");
2879 m_s2z_present_apdu = 0;
2881 if (srw_req->maximumRecords)
2882 max = *srw_req->maximumRecords;
2884 if (srw_req->startRecord)
2885 start = *srw_req->startRecord;
2888 // Some backend, such as Voyager doesn't honor piggyback
2889 // So we use present always (0 &&).
2890 if (0 && start <= 1) // Z39.50 piggyback
2892 *z_searchRequest->smallSetUpperBound = max;
2893 *z_searchRequest->mediumSetPresentNumber = max;
2894 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2896 z_searchRequest->preferredRecordSyntax =
2897 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2899 if (srw_req->recordSchema)
2901 z_searchRequest->smallSetElementSetNames =
2902 z_searchRequest->mediumSetElementSetNames =
2903 mk_esn_from_schema(m_s2z_odr_search,
2904 srw_req->recordSchema);
2907 else // Z39.50 present
2909 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2910 Z_APDU_presentRequest);
2911 Z_PresentRequest *z_presentRequest =
2912 m_s2z_present_apdu->u.presentRequest;
2913 *z_presentRequest->resultSetStartPoint = start;
2914 *z_presentRequest->numberOfRecordsRequested = max;
2915 z_presentRequest->preferredRecordSyntax =
2916 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2918 if (srw_req->recordSchema)
2920 z_presentRequest->recordComposition =
2921 (Z_RecordComposition *)
2922 odr_malloc(m_s2z_odr_search,
2923 sizeof(Z_RecordComposition));
2924 z_presentRequest->recordComposition->which =
2925 Z_RecordComp_simple;
2926 z_presentRequest->recordComposition->u.simple =
2927 mk_esn_from_schema(m_s2z_odr_search,
2928 srw_req->recordSchema);
2934 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2935 Z_APDU_initRequest);
2937 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2939 // prevent m_initRequest_apdu memory from being grabbed
2940 // in Yaz_Proxy::handle_incoming_Z_PDU
2941 m_initRequest_apdu = m_s2z_init_apdu;
2942 handle_incoming_Z_PDU(m_s2z_init_apdu);
2947 handle_incoming_Z_PDU(m_s2z_search_apdu);
2951 else if (srw_pdu->which == Z_SRW_explain_request)
2953 Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
2955 const char *backend_db = srw_req->database;
2956 srw_get_client(srw_req->database, &backend_db);
2958 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2961 if (srw_req->stylesheet)
2963 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2965 if (srw_req->recordPacking &&
2966 !strcmp(srw_req->recordPacking, "xml"))
2967 m_s2z_packing = Z_SRW_recordPacking_XML;
2969 m_s2z_packing = Z_SRW_recordPacking_string;
2973 send_srw_explain_response(diagnostic, num_diagnostic);
2979 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2980 Z_APDU_initRequest);
2982 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2984 // prevent m_initRequest_apdu memory from being grabbed
2985 // in Yaz_Proxy::handle_incoming_Z_PDU
2986 m_initRequest_apdu = m_s2z_init_apdu;
2987 handle_incoming_Z_PDU(m_s2z_init_apdu);
2990 send_srw_explain_response(0, 0);
2993 else if (srw_pdu->which == Z_SRW_scan_request)
2995 m_s2z_database = odr_strdup(m_s2z_odr_init,
2996 srw_pdu->u.scan_request->database);
2998 yaz_add_srw_diagnostic(odr_decode(),
2999 &diagnostic, &num_diagnostic,
3001 Z_SRW_PDU *srw_pdu =
3002 yaz_srw_get(odr_encode(),
3003 Z_SRW_scan_response);
3004 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
3006 srw_res->diagnostics = diagnostic;
3007 srw_res->num_diagnostics = num_diagnostic;
3008 send_srw_response(srw_pdu);
3015 send_to_srw_client_error(4, 0);
3018 send_http_response(400);
3021 void Yaz_Proxy::handle_init(Z_APDU *apdu)
3024 Z_OtherInformation **oi;
3025 get_otherInfoAPDU(apdu, &oi);
3027 if (apdu->u.initRequest->implementationId)
3028 yaz_log(YLOG_LOG, "%simplementationId: %s",
3029 m_session_str, apdu->u.initRequest->implementationId);
3030 if (apdu->u.initRequest->implementationName)
3031 yaz_log(YLOG_LOG, "%simplementationName: %s",
3032 m_session_str, apdu->u.initRequest->implementationName);
3033 if (apdu->u.initRequest->implementationVersion)
3034 yaz_log(YLOG_LOG, "%simplementationVersion: %s",
3035 m_session_str, apdu->u.initRequest->implementationVersion);
3036 if (m_initRequest_apdu == 0)
3038 if (m_initRequest_mem)
3039 nmem_destroy(m_initRequest_mem);
3041 m_initRequest_apdu = apdu;
3042 m_initRequest_mem = odr_extract_mem(odr_decode());
3044 m_initRequest_preferredMessageSize = *apdu->u.initRequest->
3045 preferredMessageSize;
3046 *apdu->u.initRequest->preferredMessageSize = 1024*1024;
3047 m_initRequest_maximumRecordSize = *apdu->u.initRequest->
3049 *apdu->u.initRequest->maximumRecordSize = 1024*1024;
3051 Z_CharSetandLanguageNegotiation *charSetandLangRecord =
3052 yaz_get_charneg_record(*oi);
3054 // Save proposal charsets and langs.
3055 if (ODR_MASK_GET(apdu->u.initRequest->options,
3056 Z_Options_negotiationModel)
3057 && charSetandLangRecord)
3060 yaz_get_proposal_charneg(m_referenceId_mem,
3061 charSetandLangRecord,
3062 &m_initRequest_oi_negotiation_charsets,
3063 &m_initRequest_oi_negotiation_num_charsets,
3064 &m_initRequest_oi_negotiation_langs,
3065 &m_initRequest_oi_negotiation_num_langs,
3066 &m_initRequest_oi_negotiation_selected);
3068 for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
3070 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
3071 m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
3072 m_initRequest_oi_negotiation_charsets[i]:"none");
3074 for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
3076 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
3077 m_session_str, (m_initRequest_oi_negotiation_langs[i])?
3078 m_initRequest_oi_negotiation_langs[i]:"none");
3080 yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
3081 m_session_str, m_initRequest_oi_negotiation_selected);
3083 // save init options for the response..
3084 m_initRequest_options = apdu->u.initRequest->options;
3086 apdu->u.initRequest->options =
3087 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3088 sizeof(Odr_bitmask));
3089 ODR_MASK_ZERO(apdu->u.initRequest->options);
3091 for (i = 0; i<= 24; i++)
3092 ODR_MASK_SET(apdu->u.initRequest->options, i);
3093 // check negotiation option
3094 if (!ODR_MASK_GET(m_initRequest_options,
3095 Z_Options_negotiationModel))
3097 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3098 Z_Options_negotiationModel);
3100 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3101 Z_Options_concurrentOperations);
3103 m_initRequest_version = apdu->u.initRequest->protocolVersion;
3104 apdu->u.initRequest->protocolVersion =
3105 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3106 sizeof(Odr_bitmask));
3107 ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
3109 for (i = 0; i<= 8; i++)
3110 ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
3112 handle_charset_lang_negotiation(apdu);
3113 if (m_client->m_init_flag)
3115 if (handle_init_response_for_invalid_session(apdu))
3117 if (m_client->m_initResponse)
3119 Z_APDU *apdu2 = m_client->m_initResponse;
3120 apdu2->u.initResponse->otherInfo = 0;
3121 if (m_client->m_cookie && *m_client->m_cookie)
3122 set_otherInformationString(apdu2, VAL_COOKIE, 1,
3123 m_client->m_cookie);
3124 apdu2->u.initResponse->referenceId =
3125 apdu->u.initRequest->referenceId;
3126 apdu2->u.initResponse->options = m_client->m_initResponse_options;
3127 apdu2->u.initResponse->protocolVersion =
3128 m_client->m_initResponse_version;
3130 handle_charset_lang_negotiation(apdu2);
3132 if (m_timeout_mode == timeout_busy)
3133 m_timeout_mode = timeout_normal;
3134 send_to_client(apdu2);
3138 m_client->m_init_flag = 1;
3141 Auth_Msg *m = new Auth_Msg;
3143 z_APDU(odr_encode(), &apdu, 0, "encode");
3144 char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
3145 m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
3146 memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
3147 odr_reset(odr_encode());
3150 m_my_thread->put(m);
3152 int ret = handle_authentication(apdu);
3153 result_authentication(apdu, ret);
3157 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
3159 Z_ReferenceId **refid = get_referenceIdP(apdu);
3160 nmem_reset(m_referenceId_mem);
3161 if (refid && *refid)
3163 m_referenceId = (Z_ReferenceId *)
3164 nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
3165 m_referenceId->len = m_referenceId->size = (*refid)->len;
3166 m_referenceId->buf = (unsigned char *)
3167 nmem_malloc(m_referenceId_mem, (*refid)->len);
3168 memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
3173 if (!m_client && m_flag_invalid_session)
3175 // Got request for a session that is invalid..
3176 m_apdu_invalid_session = apdu; // save package
3177 m_mem_invalid_session = odr_extract_mem(odr_decode());
3178 apdu = m_initRequest_apdu; // but throw an init to the target
3181 if (apdu->which == Z_APDU_searchRequest)
3182 m_search_stat.add_bytes(1);
3184 // Determine our client.
3185 Z_OtherInformation **oi;
3186 get_otherInfoAPDU(apdu, &oi);
3187 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
3191 { // HTTP. Send not found
3192 send_http_response(404);
3197 // Z39.50 just shutdown
3203 m_client->m_server = this;
3205 if (apdu->which == Z_APDU_initRequest)
3208 handle_incoming_Z_PDU_2(apdu);
3211 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
3213 handle_max_record_retrieve(apdu);
3216 apdu = handle_syntax_validation(apdu);
3219 apdu = handle_query_transformation(apdu);
3222 apdu = handle_target_charset_conversion(apdu);
3225 apdu = handle_query_validation(apdu);
3228 apdu = result_set_optimize(apdu);
3232 m_client->timeout(m_target_idletime); // mark it active even
3233 recv_GDU_more(true);
3234 // though we didn't use it
3238 // delete other info construct completely if 0 elements
3239 Z_OtherInformation **oi;
3240 get_otherInfoAPDU(apdu, &oi);
3241 if (oi && *oi && (*oi)->num_elements == 0)
3244 if (apdu->which == Z_APDU_presentRequest &&
3245 m_client->m_resultSetStartPoint == 0)
3247 Z_PresentRequest *pr = apdu->u.presentRequest;
3248 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3249 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3251 m_client->m_resultSetStartPoint = 0;
3253 if (m_client->send_to_target(apdu) < 0)
3255 m_client->shutdown();
3258 m_client->m_waiting = 1;
3261 void Yaz_Proxy::connectNotify()
3265 void Yaz_Proxy::releaseClient()
3267 xfree(m_proxyTarget);
3269 m_flag_invalid_session = 0;
3270 // only keep if keep_alive flag is set...
3272 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3273 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3274 m_client->m_waiting == 0)
3276 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3278 m_client->get_hostname());
3279 yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3280 m_session_str, m_client->m_pdu_recv,
3281 m_client->m_bytes_sent + m_client->m_bytes_recv,
3282 m_keepalive_limit_bw, m_keepalive_limit_pdu);
3283 assert (m_client->m_waiting != 2);
3284 // Tell client (if any) that no server connection is there..
3285 m_client->m_server = 0;
3290 yaz_log (YLOG_LOG, "%sShutdown (client to proxy) close %s",
3292 m_client->get_hostname());
3293 assert (m_client->m_waiting != 2);
3299 yaz_log (YLOG_LOG, "%sshutdown (client to proxy) bad state",
3305 yaz_log (YLOG_LOG, "%sShutdown (client to proxy)",
3309 m_parent->pre_init();
3312 bool Yaz_Proxy::dec_ref()
3314 m_http_keepalive = 0;
3317 if (m_ref_count > 0)
3326 const char *Yaz_ProxyClient::get_session_str()
3330 return m_server->get_session_str();
3333 void Yaz_ProxyClient::shutdown()
3335 yaz_log (YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
3340 m_waiting = 1; // ensure it's released from Yaz_Proxy::releaseClient
3341 m_server->dec_ref();
3347 void Yaz_Proxy::failNotify()
3350 yaz_log (YLOG_LOG, "%sConnection closed by client", get_session_str());
3354 void Yaz_Proxy::send_response_fail_client(const char *addr)
3358 Z_SRW_diagnostic *diagnostic = 0;
3359 int num_diagnostic = 0;
3361 yaz_add_srw_diagnostic(odr_encode(),
3362 &diagnostic, &num_diagnostic,
3363 YAZ_SRW_SYSTEM_TEMPORARILY_UNAVAILABLE, addr);
3364 if (m_s2z_search_apdu)
3365 send_srw_search_response(diagnostic, num_diagnostic);
3367 send_srw_explain_response(diagnostic, num_diagnostic);
3370 void Yaz_ProxyClient::failNotify()
3373 m_server->inc_request_no();
3374 yaz_log (YLOG_LOG, "%sConnection closed by target %s",
3375 get_session_str(), get_hostname());
3378 m_server->send_response_fail_client(get_hostname());
3382 void Yaz_ProxyClient::connectNotify()
3384 const char *s = get_session_str();
3385 const char *h = get_hostname();
3386 yaz_log (YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
3388 timeout(m_target_idletime);
3393 IPDU_Observer *Yaz_ProxyClient::sessionNotify(IPDU_Observable
3394 *the_PDU_Observable, int fd)
3396 return new Yaz_ProxyClient(the_PDU_Observable, 0);
3399 Yaz_ProxyClient::~Yaz_ProxyClient()
3404 m_next->m_prev = m_prev;
3405 m_waiting = 2; // for debugging purposes only.
3406 odr_destroy(m_init_odr);
3407 odr_destroy(m_idAuthentication_odr);
3408 delete m_last_query;
3409 xfree (m_last_resultSetId);
3413 void Yaz_ProxyClient::pre_init_client()
3415 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
3416 Z_InitRequest *req = apdu->u.initRequest;
3419 for (i = 0; i<= 24; i++)
3420 ODR_MASK_SET(req->options, i);
3421 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3422 Z_Options_negotiationModel);
3423 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3424 Z_Options_concurrentOperations);
3425 for (i = 0; i<= 10; i++)
3426 ODR_MASK_SET(req->protocolVersion, i);
3428 if (send_to_target(apdu) < 0)
3439 void Yaz_Proxy::pre_init()
3442 const char *name = 0;
3443 const char *zurl_in_use[MAX_ZURL_PLEX];
3444 int limit_bw, limit_pdu, limit_req, limit_search;
3445 int target_idletime, client_idletime;
3447 int keepalive_limit_bw, keepalive_limit_pdu;
3449 const char *cql2rpn = 0;
3450 const char *authentication = 0;
3451 const char *negotiation_charset = 0;
3452 const char *negotiation_lang = 0;
3454 Yaz_ProxyConfig *cfg = check_reconfigure();
3458 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
3463 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
3464 &limit_bw, &limit_pdu, &limit_req,
3466 &target_idletime, &client_idletime,
3468 &keepalive_limit_bw,
3469 &keepalive_limit_pdu,
3473 &negotiation_charset,
3481 for (j = 0; zurl_in_use[j]; j++)
3485 int spare_waiting = 0;
3488 for (c = m_clientPool; c; c = c->m_next)
3490 if (!strcmp(zurl_in_use[j], c->get_hostname()))
3492 if (c->m_cookie == 0)
3494 if (c->m_server == 0)
3506 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
3507 "sparew=%d preinit=%d",m_session_str,
3508 name, zurl_in_use[j], in_use, other,
3509 spare, spare_waiting, pre_init);
3510 if (spare + spare_waiting < pre_init)
3512 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
3513 c->m_next = m_clientPool;
3515 c->m_next->m_prev = &c->m_next;
3517 c->m_prev = &m_clientPool;
3519 if (m_log_mask & PROXY_LOG_APDU_SERVER)
3520 c->set_APDU_yazlog(1);
3522 c->set_APDU_yazlog(0);
3524 if (c->client(zurl_in_use[j]))
3532 c->m_target_idletime = target_idletime;
3533 c->m_seqno = m_seqno++;
3540 void Yaz_Proxy::timeoutNotify()
3545 switch(m_timeout_mode)
3547 case timeout_normal:
3551 yaz_log (YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
3554 case timeout_reduce:
3555 timeout(m_client_idletime);
3556 m_timeout_mode = timeout_busy;
3557 gdu = m_timeout_gdu;
3559 recv_GDU_normal(gdu);
3562 assert(m_stylesheet_nprl);
3563 convert_xsl_delay();
3564 recv_GDU_more(true);
3574 void Yaz_Proxy::markInvalid()
3577 m_flag_invalid_session = 1;
3580 void Yaz_ProxyClient::timeoutNotify()
3583 m_server->inc_request_no();
3585 yaz_log (YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
3589 m_server->send_response_fail_client(get_hostname());
3591 Yaz_Proxy *proxy_root = m_root;
3595 proxy_root->pre_init();
3598 Yaz_ProxyClient::Yaz_ProxyClient(IPDU_Observable *the_PDU_Observable,
3599 Yaz_Proxy *parent) :
3600 Z_Assoc (the_PDU_Observable)
3607 m_last_resultSetId = 0;
3608 m_last_resultCount = 0;
3612 m_init_odr = odr_createmem (ODR_DECODE);
3614 m_initResponse_options = 0;
3615 m_initResponse_version = 0;
3616 m_initResponse_preferredMessageSize = 0;
3617 m_initResponse_maximumRecordSize = 0;
3618 m_resultSetStartPoint = 0;
3619 m_bytes_sent = m_bytes_recv = 0;
3623 m_target_idletime = 600;
3625 m_idAuthentication_odr = odr_createmem(ODR_ENCODE);
3626 m_idAuthentication_ber_buf = 0;
3627 m_idAuthentication_ber_size = 0;
3630 const char *Yaz_Proxy::option(const char *name, const char *value)
3632 if (!strcmp (name, "optimize")) {
3635 m_optimize = xstrdup (value);
3642 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
3647 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
3649 if (apdu->which == Z_GDU_Z3950)
3650 recv_Z_PDU(apdu->u.z3950, len);
3651 else if (apdu->which == Z_GDU_HTTP_Response)
3652 recv_HTTP_response(apdu->u.HTTP_Response, len);
3657 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
3659 if (!m_flag_invalid_session)
3661 m_flag_invalid_session = 0;
3662 handle_incoming_Z_PDU(m_apdu_invalid_session);
3663 assert (m_mem_invalid_session);
3664 nmem_destroy(m_mem_invalid_session);
3665 m_mem_invalid_session = 0;
3669 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
3671 m_bytes_recv += len;
3675 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
3676 yaz_log (YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
3677 apdu_name(apdu), get_hostname(), len);
3678 if (apdu->which == Z_APDU_initResponse)
3680 if (!m_server) // if this is a pre init session , check for more
3682 NMEM nmem = odr_extract_mem (odr_decode());
3683 odr_reset (m_init_odr);
3684 nmem_transfer (m_init_odr->mem, nmem);
3685 m_initResponse = apdu;
3686 m_initResponse_options = apdu->u.initResponse->options;
3687 m_initResponse_version = apdu->u.initResponse->protocolVersion;
3688 m_initResponse_preferredMessageSize =
3689 *apdu->u.initResponse->preferredMessageSize;
3690 m_initResponse_maximumRecordSize =
3691 *apdu->u.initResponse->maximumRecordSize;
3693 Z_InitResponse *ir = apdu->u.initResponse;
3695 // apply YAZ Proxy version
3696 char *imv0 = ir->implementationVersion;
3697 char *imv1 = (char*)
3698 odr_malloc(m_init_odr, 20 + (imv0 ? strlen(imv0) : 0));
3703 strcat(imv1, "/" VERSION);
3705 ir->implementationVersion = imv1;
3707 // apply YAZ Proxy implementation name
3708 char *im0 = ir->implementationName;
3710 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
3717 strcat(im1, "(YAZ Proxy)");
3718 ir->implementationName = im1;
3720 nmem_destroy (nmem);
3722 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
3725 if (apdu->which == Z_APDU_searchResponse)
3727 Z_SearchResponse *sr = apdu->u.searchResponse;
3728 m_last_resultCount = *sr->resultCount;
3729 int status = *sr->searchStatus;
3730 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
3734 if (sr->records && sr->records->which == Z_Records_DBOSD)
3736 m_cache.add(odr_decode(),
3737 sr->records->u.databaseOrSurDiagnostics, 1,
3742 if (apdu->which == Z_APDU_presentResponse)
3744 Z_PresentResponse *pr = apdu->u.presentResponse;
3748 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
3749 Z_SearchResponse *sr = new_apdu->u.searchResponse;
3750 sr->referenceId = pr->referenceId;
3751 *sr->resultCount = m_last_resultCount;
3752 sr->records = pr->records;
3753 sr->nextResultSetPosition = pr->nextResultSetPosition;
3754 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
3758 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
3760 m_cache.add(odr_decode(),
3761 pr->records->u.databaseOrSurDiagnostics,
3762 m_resultSetStartPoint, -1);
3763 m_resultSetStartPoint = 0;
3767 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
3769 Yaz_Proxy *server = m_server; // save it. send_to_client may destroy us
3772 server->send_to_client(apdu);
3773 if (apdu->which == Z_APDU_close)
3776 server->recv_GDU_more(true);
3779 void Yaz_Proxy::low_socket_close()
3784 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3785 if (m_lo_fd[i] >= 0)
3786 ::close(m_lo_fd[i]);
3790 void Yaz_Proxy::low_socket_open()
3795 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3796 m_lo_fd[i] = open("/dev/null", O_RDONLY);
3800 int Yaz_Proxy::server(const char *addr)
3802 int r = Z_Assoc::server(addr);
3805 yaz_log(YLOG_LOG, "%sStarted proxy "
3809 " on %s", m_session_str, addr);
3815 void Yaz_Proxy::base64_decode(const char *base64, char *buf, int buf_len)
3817 const char *base64_chars =
3818 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3819 int len = strlen(base64);
3823 for (int pos = 0; pos <= len; pos++)
3825 if (base64[pos] == '=' || buf_pos + 1 >= buf_len)
3828 const char *ch_ptr = strchr(base64_chars, base64[pos]);
3831 char ch = (char) (ch_ptr - base64_chars);
3835 buf[buf_pos] = ch << 2;
3838 buf[buf_pos++] += (ch & 0x30) >> 4;
3839 buf[buf_pos] = (ch & 0x0f) << 4;
3842 buf[buf_pos++] += (ch & 0x3c) >> 2;
3843 buf[buf_pos] = (ch & 0x03) << 6;
3846 buf[buf_pos++] += ch;
3853 buf[buf_pos] = '\0';
3859 * indent-tabs-mode: nil
3861 * vim: shiftwidth=4 tabstop=8 expandtab