1 /* $Id: yaz-proxy.cpp,v 1.69 2006-06-28 23:38:23 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 class YAZ_EXPORT Auth_Msg : public IMsg_Thread {
65 IMsg_Thread *handle();
77 m_nmem = nmem_create();
85 IMsg_Thread *Auth_Msg::handle()
87 ODR decode = odr_createmem(ODR_DECODE);
90 odr_setbuf(decode, m_apdu_buf, m_apdu_len, 0);
91 int r = z_APDU(decode, &apdu, 0, 0);
94 yaz_log(YLOG_WARN, "decode failed in Auth_Msg::handle");
98 m_ret = m_proxy->handle_authentication(apdu);
104 void Auth_Msg::result()
106 if (m_proxy->dec_ref())
108 yaz_log(YLOG_LOG, "Auth_Msg::proxy deleted meanwhile");
112 odr_setbuf(m_proxy->odr_decode(), m_apdu_buf, m_apdu_len, 0);
114 int r = z_APDU(m_proxy->odr_decode(), &apdu, 0, 0);
116 yaz_log(YLOG_LOG, "Auth_Msg::result z_APDU failed");
117 m_proxy->result_authentication(apdu, m_ret);
122 void Yaz_Proxy::result_authentication(Z_APDU *apdu, int ret)
124 if (apdu == 0 || ret == 0)
126 Z_APDU *apdu_reject = zget_APDU(odr_encode(), Z_APDU_initResponse);
127 *apdu_reject->u.initResponse->result = 0;
128 send_to_client(apdu_reject);
133 if (apdu->which == Z_APDU_initRequest)
135 Yaz_ProxyConfig *cfg = check_reconfigure();
137 cfg->target_authentication(m_default_target, odr_encode(),
138 apdu->u.initRequest);
140 handle_incoming_Z_PDU_2(apdu);
144 static const char *apdu_name(Z_APDU *apdu)
148 case Z_APDU_initRequest:
149 return "initRequest";
150 case Z_APDU_initResponse:
151 return "initResponse";
152 case Z_APDU_searchRequest:
153 return "searchRequest";
154 case Z_APDU_searchResponse:
155 return "searchResponse";
156 case Z_APDU_presentRequest:
157 return "presentRequest";
158 case Z_APDU_presentResponse:
159 return "presentResponse";
160 case Z_APDU_deleteResultSetRequest:
161 return "deleteResultSetRequest";
162 case Z_APDU_deleteResultSetResponse:
163 return "deleteResultSetResponse";
164 case Z_APDU_scanRequest:
165 return "scanRequest";
166 case Z_APDU_scanResponse:
167 return "scanResponse";
168 case Z_APDU_sortRequest:
169 return "sortRequest";
170 case Z_APDU_sortResponse:
171 return "sortResponse";
172 case Z_APDU_extendedServicesRequest:
173 return "extendedServicesRequest";
174 case Z_APDU_extendedServicesResponse:
175 return "extendedServicesResponse";
182 static const char *gdu_name(Z_GDU *gdu)
187 return apdu_name(gdu->u.z3950);
188 case Z_GDU_HTTP_Request:
189 return "HTTP Request";
190 case Z_GDU_HTTP_Response:
191 return "HTTP Response";
193 return "Unknown request/response";
196 Yaz_Proxy::Yaz_Proxy(IPDU_Observable *the_PDU_Observable,
197 ISocketObservable *the_socket_observable,
200 Z_Assoc(the_PDU_Observable),
201 m_bw_stat(60), m_pdu_stat(60), m_search_stat(60)
203 m_PDU_Observable = the_PDU_Observable;
204 m_socket_observable = the_socket_observable;
209 m_keepalive_limit_bw = 500000;
210 m_keepalive_limit_pdu = 1000;
212 m_default_target = 0;
213 m_proxy_negotiation_charset = 0;
214 m_proxy_negotiation_lang = 0;
215 m_proxy_negotiation_default_charset = 0;
216 m_charset_converter = new Yaz_CharsetConverter;
220 m_client_idletime = 600;
221 m_target_idletime = 600;
222 m_optimize = xstrdup ("1");
223 strcpy(m_session_str, "0 ");
231 m_max_connect_period = 0;
233 m_limit_connect_period = 0;
234 m_timeout_mode = timeout_normal;
236 m_max_record_retrieve = 0;
240 m_flag_invalid_session = 0;
242 m_referenceId_mem = nmem_create();
244 m_marcxml_mode = none;
245 m_stylesheet_xsp = 0;
246 m_stylesheet_nprl = 0;
247 m_stylesheet_apdu = 0;
248 m_s2z_stylesheet = 0;
252 m_backend_charset = 0;
254 m_initRequest_apdu = 0;
255 m_initRequest_mem = 0;
256 m_initRequest_preferredMessageSize = 0;
257 m_initRequest_maximumRecordSize = 0;
258 m_initRequest_options = 0;
259 m_initRequest_version = 0;
260 m_initRequest_oi_negotiation_charsets = 0;
261 m_initRequest_oi_negotiation_num_charsets = 0;
262 m_initRequest_oi_negotiation_langs = 0;
263 m_initRequest_oi_negotiation_num_langs = 0;
264 m_initRequest_oi_negotiation_selected = 0;
265 m_apdu_invalid_session = 0;
266 m_mem_invalid_session = 0;
268 m_s2z_odr_search = 0;
270 m_s2z_search_apdu = 0;
271 m_s2z_present_apdu = 0;
272 m_http_keepalive = 0;
275 m_s2z_packing = Z_SRW_recordPacking_string;
276 #if HAVE_GETTIMEOFDAY
277 m_time_tv = xmalloc(sizeof(struct timeval));
278 struct timeval *tv = (struct timeval *) m_time_tv;
284 m_usemarcon_ini_stage1 = 0;
285 m_usemarcon_ini_stage2 = 0;
286 m_usemarcon = new Yaz_usemarcon();
291 m_main_ptr_dec = false;
293 m_num_msg_threads = 0;
296 void Yaz_Proxy::inc_ref()
301 Yaz_Proxy::~Yaz_Proxy()
303 yaz_log(YLOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
304 m_bytes_sent, m_bytes_recv);
305 nmem_destroy(m_initRequest_mem);
306 nmem_destroy(m_mem_invalid_session);
307 nmem_destroy(m_referenceId_mem);
309 xfree(m_proxyTarget);
310 xfree(m_default_target);
311 xfree(m_proxy_negotiation_charset);
312 xfree(m_proxy_negotiation_lang);
313 xfree(m_proxy_negotiation_default_charset);
314 delete m_charset_converter;
318 if (m_stylesheet_xsp)
319 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
325 xfree (m_backend_type);
326 xfree (m_backend_charset);
327 xfree (m_usemarcon_ini_stage1);
328 xfree (m_usemarcon_ini_stage2);
331 odr_destroy(m_s2z_odr_init);
332 if (m_s2z_odr_search)
333 odr_destroy(m_s2z_odr_search);
341 void Yaz_Proxy::set_debug_mode(int mode)
346 int Yaz_Proxy::set_config(const char *config)
349 m_config = new Yaz_ProxyConfig();
350 xfree(m_config_fname);
351 m_config_fname = xstrdup(config);
352 int r = m_config->read_xml(config);
356 m_config->get_generic_info(&m_log_mask, &m_max_clients,
357 &m_max_connect, &m_limit_connect, &period,
359 m_connect.set_period(period);
364 void Yaz_Proxy::set_default_target(const char *target)
366 xfree (m_default_target);
367 m_default_target = 0;
369 m_default_target = (char *) xstrdup (target);
372 void Yaz_Proxy::set_proxy_negotiation (const char *charset, const char *lang,
373 const char *default_charset)
375 yaz_log(YLOG_DEBUG, "%sSet the proxy negotiation: charset to '%s', "
376 "default charset to '%s', language to '%s'", m_session_str,
377 charset?charset:"none",
378 default_charset?default_charset:"none",
380 xfree (m_proxy_negotiation_charset);
381 xfree (m_proxy_negotiation_lang);
382 m_proxy_negotiation_charset = m_proxy_negotiation_lang = 0;
384 m_proxy_negotiation_charset = (char *) xstrdup (charset);
386 m_proxy_negotiation_lang = (char *) xstrdup (lang);
388 m_proxy_negotiation_default_charset =
389 (char *) xstrdup (default_charset);
392 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
395 return m_parent->check_reconfigure();
397 Yaz_ProxyConfig *cfg = m_config;
400 yaz_log(YLOG_LOG, "reconfigure");
402 if (m_config_fname && cfg)
404 yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
405 int r = cfg->read_xml(m_config_fname);
407 yaz_log(YLOG_WARN, "reconfigure failed");
412 cfg->get_generic_info(&m_log_mask, &m_max_clients,
413 &m_max_connect, &m_limit_connect,
414 &period, &m_num_msg_threads);
415 m_connect.set_period(period);
419 yaz_log(YLOG_LOG, "reconfigure");
425 IPDU_Observer *Yaz_Proxy::sessionNotify(IPDU_Observable
426 *the_PDU_Observable, int fd)
430 char session_str[200];
431 const char *peername = the_PDU_Observable->getpeername();
433 peername = "nullpeer";
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;
456 new_proxy->m_num_msg_threads = m_num_msg_threads;
459 // in case we want to watch a particular client..
460 if (!strcmp(peername, "tcp:163.121.19.82")) // NIS GROUP
461 new_proxy->m_log_mask = 255;
464 new_proxy->set_APDU_log(get_APDU_log());
465 if (new_proxy->m_log_mask & PROXY_LOG_APDU_CLIENT)
466 new_proxy->set_APDU_yazlog(1);
468 new_proxy->set_APDU_yazlog(0);
469 strcpy(new_proxy->m_session_str, session_str);
470 new_proxy->m_peername = xstrdup(peername);
471 new_proxy->set_proxy_negotiation(m_proxy_negotiation_charset,
472 m_proxy_negotiation_lang, m_proxy_negotiation_default_charset);
473 // create thread object the first time we get an incoming connection
474 if (!m_my_thread && m_num_msg_threads > 0)
476 yaz_log (YLOG_LOG, "%sStarting message thread management. number=%d",
477 session_str, m_num_msg_threads);
478 m_my_thread = new Msg_Thread(m_socket_observable, m_num_msg_threads);
480 new_proxy->m_my_thread = m_my_thread;
484 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
487 Z_OtherInformationUnit *oi;
489 ent.proto = PROTO_Z3950;
490 ent.oclass = CLASS_USERINFO;
491 ent.value = (oid_value) VAL_COOKIE;
492 assert (oid_ent_to_oid (&ent, oid));
494 if (oid_ent_to_oid (&ent, oid) &&
495 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
496 oi->which == Z_OtherInfo_characterInfo)
497 return oi->information.characterInfo;
500 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
503 Z_OtherInformationUnit *oi;
505 ent.proto = PROTO_Z3950;
506 ent.oclass = CLASS_USERINFO;
507 ent.value = (oid_value) VAL_PROXY;
508 if (oid_ent_to_oid (&ent, oid) &&
509 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
510 oi->which == Z_OtherInfo_characterInfo)
511 return oi->information.characterInfo;
514 const char *Yaz_Proxy::load_balance(const char **url)
516 int zurl_in_use[MAX_ZURL_PLEX];
517 int zurl_in_spare[MAX_ZURL_PLEX];
521 for (i = 0; i<MAX_ZURL_PLEX; i++)
524 zurl_in_spare[i] = 0;
526 for (c = m_parent->m_clientPool; c; c = c->m_next)
528 for (i = 0; url[i]; i++)
529 if (!strcmp(url[i], c->get_hostname()))
532 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
536 int min_use = 100000;
537 int spare_for_min = 0;
539 const char *ret_min = 0;
540 const char *ret_spare = 0;
541 for (i = 0; url[i]; i++)
543 yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
544 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
545 if (min_use > zurl_in_use[i])
548 min_use = zurl_in_use[i];
549 spare_for_min = zurl_in_spare[i];
551 if (max_spare < zurl_in_spare[i])
554 max_spare = zurl_in_spare[i];
560 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
561 const char *proxy_host)
564 Yaz_Proxy *parent = m_parent;
565 Yaz_ProxyClient *c = m_client;
569 const char *url[MAX_ZURL_PLEX];
570 Yaz_ProxyConfig *cfg = check_reconfigure();
573 if (parent && parent->m_debug_mode)
575 // only to be enabled for debugging...
576 if (!strcmp(proxy_host, "stop"))
579 xfree(m_default_target);
580 m_default_target = xstrdup(proxy_host);
582 proxy_host = m_default_target;
583 int client_idletime = -1;
584 const char *cql2rpn_fname = 0;
585 const char *negotiation_charset = 0;
586 const char *negotiation_lang = 0;
587 const char *query_charset = 0;
588 const char *default_client_query_charset = 0;
589 url[0] = m_default_target;
594 cfg->get_target_info(proxy_host, url, &m_bw_max,
595 &m_pdu_max, &m_max_record_retrieve,
597 &m_target_idletime, &client_idletime,
598 &parent->m_max_clients,
599 &m_keepalive_limit_bw,
600 &m_keepalive_limit_pdu,
603 &negotiation_charset,
606 &default_client_query_charset);
608 if (client_idletime != -1)
610 m_client_idletime = client_idletime;
611 timeout(m_client_idletime);
614 // get those FILE descriptors available
615 m_parent->low_socket_close();
617 m_cql2rpn.set_pqf_file(cql2rpn_fname);
618 // reserve them again
619 m_parent->low_socket_open();
621 if (negotiation_charset || negotiation_lang || default_client_query_charset)
623 set_proxy_negotiation(negotiation_charset,
624 negotiation_lang, default_client_query_charset);
626 m_charset_converter->set_target_query_charset(query_charset);
629 yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
632 // we don't handle multiplexing for cookie session, so we just
633 // pick the first one in this case (anonymous users will be able
634 // to use any backend)
635 if (cookie && *cookie)
636 m_proxyTarget = (char*) xstrdup(url[0]);
638 m_proxyTarget = (char*) xstrdup(load_balance(url));
640 if (cookie && *cookie)
641 { // search in sessions with a cookie
642 for (c = parent->m_clientPool; c; c = c->m_next)
645 assert (*c->m_prev == c);
646 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
647 !strcmp(m_proxyTarget, c->get_hostname()))
650 // The following handles "cancel"
651 // If connection is busy (waiting for PDU) and
652 // we have an initRequest we can safely do re-open
653 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
655 yaz_log (YLOG_LOG, "%s REOPEN target=%s", m_session_str,
662 c->m_last_resultCount = 0;
663 c->m_sr_transform = 0;
665 c->m_resultSetStartPoint = 0;
666 c->m_target_idletime = m_target_idletime;
667 if (c->client(m_proxyTarget))
674 c->m_seqno = parent->m_seqno;
675 if (c->m_server && c->m_server != this)
676 c->m_server->m_client = 0;
679 yaz_log (YLOG_DEBUG, "get_client 1 %p %p", this, c);
684 else if (!c && apdu->which == Z_APDU_initRequest )
686 // anonymous sessions without cookie.
687 // if authentication is set it is NOT anonymous se we can't share them.
688 // If charset and lang negotiation is use it is NOT anonymous session too.
689 for (c = parent->m_clientPool; c; c = c->m_next)
692 assert(*c->m_prev == c);
693 if (c->m_server == 0 && c->m_cookie == 0 && c->m_waiting == 0
694 && c->compare_idAuthentication(apdu)
695 && c->compare_charset(apdu)
696 && !strcmp(m_proxyTarget, c->get_hostname()))
699 yaz_log (YLOG_LOG, "%sREUSE %d %s",
700 m_session_str, parent->m_seqno, c->get_hostname());
702 c->m_seqno = parent->m_seqno;
703 assert(c->m_server == 0);
706 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
707 c->set_APDU_yazlog(1);
709 c->set_APDU_yazlog(0);
721 if (apdu->which != Z_APDU_initRequest)
723 yaz_log (YLOG_LOG, "%sno init request as first PDU", m_session_str);
726 // go through list of clients - and find the lowest/oldest one.
727 Yaz_ProxyClient *c_min = 0;
729 int no_of_clients = 0;
730 if (parent->m_clientPool)
731 yaz_log (YLOG_DEBUG, "Existing sessions");
732 for (c = parent->m_clientPool; c; c = c->m_next)
734 yaz_log (YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
735 c->m_waiting, c->get_hostname(),
736 c->m_cookie ? c->m_cookie : "");
738 if (min_seq < 0 || c->m_seqno < min_seq)
740 min_seq = c->m_seqno;
744 if (no_of_clients >= parent->m_max_clients)
747 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
749 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
750 m_session_str, parent->m_max_clients, c->m_seqno);
751 if (c->m_server && c->m_server != this)
752 c->m_server->dec_ref();
756 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
757 m_session_str, parent->m_max_clients,
758 c->m_seqno, parent->m_seqno, c->get_hostname());
762 c->m_cookie = xstrdup(cookie);
763 c->m_seqno = parent->m_seqno;
764 if (c->m_server && c->m_server != this)
766 c->m_server->m_client = 0;
767 c->m_server->dec_ref();
770 c->m_target_idletime = m_target_idletime;
771 c->timeout(m_target_idletime);
773 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
774 c->set_APDU_yazlog(1);
776 c->set_APDU_yazlog(0);
783 yaz_log (YLOG_LOG, "%sNEW %d %s",
784 m_session_str, parent->m_seqno, m_proxyTarget);
785 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
786 c->m_next = parent->m_clientPool;
788 c->m_next->m_prev = &c->m_next;
789 parent->m_clientPool = c;
790 c->m_prev = &parent->m_clientPool;
796 c->m_cookie = xstrdup(cookie);
798 c->m_seqno = parent->m_seqno;
800 c->m_last_resultCount = 0;
803 c->m_sr_transform = 0;
805 c->m_resultSetStartPoint = 0;
807 if (c->client(m_proxyTarget))
812 c->m_target_idletime = m_target_idletime;
815 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
816 c->set_APDU_yazlog(1);
818 c->set_APDU_yazlog(0);
820 c->set_idAuthentication(apdu);
822 yaz_log (YLOG_DEBUG, "get_client 3 %p %p", this, c);
826 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
829 for (i = 0; i<num; i++)
832 Z_DefaultDiagFormat *r;
833 Z_DiagRec *p = pp[i];
834 if (p->which != Z_DiagRec_defaultFormat)
836 yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
840 r = p->u.defaultFormat;
841 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
842 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
843 yaz_log(YLOG_LOG, "%sError unknown diagnostic set", m_session_str);
846 case Z_DefaultDiagFormat_v2Addinfo:
847 yaz_log(YLOG_LOG, "%sError %d %s:%s",
849 *r->condition, diagbib1_str(*r->condition),
852 case Z_DefaultDiagFormat_v3Addinfo:
853 yaz_log(YLOG_LOG, "%sError %d %s:%s",
855 *r->condition, diagbib1_str(*r->condition),
862 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
864 if (!m_stylesheet_xsp || p->num_records <= 0)
866 return 0; /* no XSLT to be done ... */
869 m_stylesheet_offset = 0;
870 m_stylesheet_nprl = p;
871 m_stylesheet_apdu = apdu;
872 m_timeout_mode = timeout_xsl;
878 void Yaz_Proxy::convert_xsl_delay()
881 Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
882 if (npr->which == Z_NamePlusRecord_databaseRecord)
884 Z_External *r = npr->u.databaseRecord;
885 if (r->which == Z_External_octet)
888 fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
890 xmlDocPtr res, doc = xmlParseMemory(
891 (char*) r->u.octet_aligned->buf,
892 r->u.octet_aligned->len);
895 yaz_log(YLOG_LOG, "%sXSLT convert %d",
896 m_session_str, m_stylesheet_offset);
897 res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
904 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
906 m_stylesheet_nprl->records[m_stylesheet_offset]->
908 z_ext_record(odr_encode(), VAL_TEXT_XML,
909 (char*) out_buf, out_len);
918 m_stylesheet_offset++;
919 if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
921 m_timeout_mode = timeout_normal;
922 m_stylesheet_nprl = 0;
924 if (m_stylesheet_xsp)
925 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
927 m_stylesheet_xsp = 0;
928 timeout(m_client_idletime);
929 send_PDU_convert(m_stylesheet_apdu);
935 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
937 if (m_frontend_type != VAL_NONE)
940 for (i = 0; i < p->num_records; i++)
942 Z_NamePlusRecord *npr = p->records[i];
943 if (npr->which == Z_NamePlusRecord_databaseRecord)
945 Z_External *r = npr->u.databaseRecord;
946 if (r->which == Z_External_octet)
949 if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
951 if (!m_usemarcon->m_stage1)
953 m_usemarcon->m_stage1 = new CDetails();
955 m_usemarcon->m_stage1->SetIniFileName(m_usemarcon_ini_stage1);
956 m_usemarcon->m_stage1->SetMarcRecord((char*) r->u.octet_aligned->buf, r->u.octet_aligned->len);
957 int res = m_usemarcon->m_stage1->Start();
962 m_usemarcon->m_stage1->GetMarcRecord(converted, convlen);
963 if (m_usemarcon_ini_stage2 && *m_usemarcon_ini_stage2)
965 if (!m_usemarcon->m_stage2)
967 m_usemarcon->m_stage2 = new CDetails();
969 m_usemarcon->m_stage2->SetIniFileName(m_usemarcon_ini_stage2);
970 m_usemarcon->m_stage2->SetMarcRecord(converted, convlen);
971 res = m_usemarcon->m_stage2->Start();
975 m_usemarcon->m_stage2->GetMarcRecord(converted, convlen);
979 yaz_log(YLOG_LOG, "%sUSEMARCON stage 2 error %d", m_session_str, res);
982 npr->u.databaseRecord =
983 z_ext_record(odr_encode(),
991 yaz_log(YLOG_LOG, "%sUSEMARCON stage 1 error %d", m_session_str, res);
997 npr->u.databaseRecord =
998 z_ext_record(odr_encode(),
1000 (char*) r->u.octet_aligned->buf,
1001 r->u.octet_aligned->len);
1008 void Yaz_Proxy::convert_records_charset(Z_NamePlusRecordList *p,
1009 const char *backend_charset)
1011 int sel = m_charset_converter->get_client_charset_selected();
1012 const char *client_record_charset =
1013 m_charset_converter->get_client_query_charset();
1014 if (sel && backend_charset && client_record_charset &&
1015 strcmp(backend_charset, client_record_charset))
1018 yaz_iconv_t cd = yaz_iconv_open(client_record_charset,
1020 yaz_marc_t mt = yaz_marc_create();
1021 yaz_marc_xml(mt, YAZ_MARC_ISO2709);
1022 yaz_marc_iconv(mt, cd);
1023 for (i = 0; i < p->num_records; i++)
1025 Z_NamePlusRecord *npr = p->records[i];
1026 if (npr->which == Z_NamePlusRecord_databaseRecord)
1028 Z_External *r = npr->u.databaseRecord;
1029 oident *ent = oid_getentbyoid(r->direct_reference);
1030 if (!ent || ent->value == VAL_NONE)
1033 if (ent->value == VAL_SUTRS)
1035 WRBUF w = wrbuf_alloc();
1037 wrbuf_iconv_write(w, cd, (char*) r->u.octet_aligned->buf,
1038 r->u.octet_aligned->len);
1039 npr->u.databaseRecord =
1040 z_ext_record(odr_encode(), ent->value, wrbuf_buf(w),
1044 else if (ent->value == VAL_TEXT_XML)
1048 else if (r->which == Z_External_octet)
1052 if (yaz_marc_decode_buf(mt,
1053 (char*) r->u.octet_aligned->buf,
1054 r->u.octet_aligned->len,
1057 npr->u.databaseRecord =
1058 z_ext_record(odr_encode(), ent->value, result, rlen);
1059 yaz_log(YLOG_LOG, "%sRecoding MARC record",
1066 yaz_iconv_close(cd);
1067 yaz_marc_destroy(mt);
1071 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
1072 const char *backend_charset)
1075 if (!backend_charset)
1076 backend_charset = "MARC-8";
1077 yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
1078 yaz_marc_t mt = yaz_marc_create();
1079 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1080 yaz_marc_iconv(mt, cd);
1081 for (i = 0; i < p->num_records; i++)
1083 Z_NamePlusRecord *npr = p->records[i];
1084 if (npr->which == Z_NamePlusRecord_databaseRecord)
1086 Z_External *r = npr->u.databaseRecord;
1087 if (r->which == Z_External_OPAC)
1089 WRBUF w = wrbuf_alloc();
1091 yaz_opac_decode_wrbuf(mt, r->u.opac, w);
1092 npr->u.databaseRecord = z_ext_record(
1093 odr_encode(), VAL_TEXT_XML,
1094 wrbuf_buf(w), wrbuf_len(w)
1098 else if (r->which == Z_External_octet)
1102 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
1103 r->u.octet_aligned->len,
1106 npr->u.databaseRecord =
1107 z_ext_record(odr_encode(), VAL_TEXT_XML, result, rlen);
1113 yaz_iconv_close(cd);
1114 yaz_marc_destroy(mt);
1117 void Yaz_Proxy::logtime()
1119 #if HAVE_GETTIMEOFDAY
1120 struct timeval *tv = (struct timeval*) m_time_tv;
1124 gettimeofday(&tv1, 0);
1125 long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
1126 (tv1.tv_usec - tv->tv_usec);
1128 yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
1129 diff/1000000, (diff/1000)%1000);
1136 int Yaz_Proxy::send_http_response(int code)
1138 ODR o = odr_encode();
1139 Z_GDU *gdu = z_get_HTTP_Response(o, code);
1140 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1142 hres->version = odr_strdup(o, m_http_version);
1143 if (m_http_keepalive)
1144 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1148 z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate",
1149 "Basic realm=\"YAZ Proxy\"");
1152 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1154 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1158 int r = send_GDU(gdu, &len);
1159 m_bytes_sent += len;
1160 m_bw_stat.add_bytes(len);
1163 recv_GDU_more(true);
1168 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu, int http_code /* = 200 */)
1170 ODR o = odr_encode();
1171 const char *ctype = "text/xml";
1172 Z_GDU *gdu = z_get_HTTP_Response(o, http_code);
1173 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1175 hres->version = odr_strdup(o, m_http_version);
1176 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1177 if (m_http_keepalive)
1178 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1181 if (http_code == 401)
1182 z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate", "Basic realm=\"YAZ Proxy\"");
1184 static Z_SOAP_Handler soap_handlers[2] = {
1186 {"http://www.loc.gov/zing/srw/", 0,
1187 (Z_SOAP_fun) yaz_srw_codec},
1192 Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
1193 soap_package->which = Z_SOAP_generic;
1194 soap_package->u.generic =
1195 (Z_SOAP_Generic *) odr_malloc(o, sizeof(*soap_package->u.generic));
1196 soap_package->u.generic->no = 0;
1197 soap_package->u.generic->ns = soap_handlers[0].ns;
1198 soap_package->u.generic->p = (void *) srw_pdu;
1199 soap_package->ns = m_soap_ns;
1200 z_soap_codec_enc_xsl(o, &soap_package,
1201 &hres->content_buf, &hres->content_len,
1202 soap_handlers, 0, m_s2z_stylesheet);
1203 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1205 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1209 int r = send_GDU(gdu, &len);
1210 m_bytes_sent += len;
1211 m_bw_stat.add_bytes(len);
1214 recv_GDU_more(true);
1219 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
1221 ODR o = odr_encode();
1222 Z_SRW_diagnostic *diagnostic = (Z_SRW_diagnostic *)
1223 odr_malloc(o, sizeof(*diagnostic));
1224 int num_diagnostic = 1;
1225 yaz_mk_std_diagnostic(o, diagnostic, srw_error, add);
1226 return send_srw_search_response(diagnostic, num_diagnostic, srw_error == 3 ? 401 : 200);
1229 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
1230 Z_DefaultDiagFormat *ddf)
1232 int bib1_code = *ddf->condition;
1233 if (bib1_code == 109)
1235 srw_res->num_diagnostics = 1;
1236 srw_res->diagnostics = (Z_SRW_diagnostic *)
1237 odr_malloc(o, sizeof(*srw_res->diagnostics));
1238 yaz_mk_std_diagnostic(o, srw_res->diagnostics,
1239 yaz_diag_bib1_to_srw(*ddf->condition),
1244 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
1246 ODR o = odr_encode();
1247 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1248 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1250 srw_res->numberOfRecords = odr_intdup (o, hits);
1251 if (records && records->which == Z_Records_DBOSD)
1253 srw_res->num_records =
1254 records->u.databaseOrSurDiagnostics->num_records;
1256 srw_res->records = (Z_SRW_record *)
1257 odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
1258 for (i = 0; i < srw_res->num_records; i++)
1260 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
1261 if (npr->which != Z_NamePlusRecord_databaseRecord)
1263 srw_res->records[i].recordSchema = "diagnostic";
1264 srw_res->records[i].recordPacking = m_s2z_packing;
1265 srw_res->records[i].recordData_buf = "67";
1266 srw_res->records[i].recordData_len = 2;
1267 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1270 Z_External *r = npr->u.databaseRecord;
1271 oident *ent = oid_getentbyoid(r->direct_reference);
1272 if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
1274 srw_res->records[i].recordSchema = m_schema;
1275 srw_res->records[i].recordPacking = m_s2z_packing;
1276 srw_res->records[i].recordData_buf = (char*)
1277 r->u.octet_aligned->buf;
1278 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1279 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1283 srw_res->records[i].recordSchema = "diagnostic";
1284 srw_res->records[i].recordPacking = m_s2z_packing;
1285 srw_res->records[i].recordData_buf = "67";
1286 srw_res->records[i].recordData_len = 2;
1287 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1291 if (records && records->which == Z_Records_NSD)
1294 http_code = z_to_srw_diag(odr_encode(), srw_res,
1295 records->u.nonSurrogateDiagnostic);
1297 return send_http_response(http_code);
1299 return send_srw_response(srw_pdu);
1303 int Yaz_Proxy::send_srw_search_response(Z_SRW_diagnostic *diagnostics,
1304 int num_diagnostics, int http_code /* = 200 */)
1306 ODR o = odr_encode();
1307 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1308 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1310 srw_res->num_diagnostics = num_diagnostics;
1311 srw_res->diagnostics = diagnostics;
1312 return send_srw_response(srw_pdu, http_code);
1315 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1316 int num_diagnostics)
1318 Yaz_ProxyConfig *cfg = check_reconfigure();
1322 char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1323 m_s2z_database, &len);
1326 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1327 Z_SRW_explainResponse *er = res->u.explain_response;
1329 er->record.recordData_buf = b;
1330 er->record.recordData_len = len;
1331 er->record.recordPacking = m_s2z_packing;
1332 er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
1334 er->diagnostics = diagnostics;
1335 er->num_diagnostics = num_diagnostics;
1336 return send_srw_response(res);
1339 return send_http_response(404);
1342 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1346 if (apdu->which == Z_APDU_initResponse)
1348 Z_InitResponse *res = apdu->u.initResponse;
1349 if (*res->result == 0)
1351 send_to_srw_client_error(3, 0);
1353 else if (!m_s2z_search_apdu)
1355 send_srw_explain_response(0, 0);
1359 handle_incoming_Z_PDU(m_s2z_search_apdu);
1362 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1364 m_s2z_search_apdu = 0;
1365 Z_SearchResponse *res = apdu->u.searchResponse;
1366 m_s2z_hit_count = *res->resultCount;
1367 if (res->records && res->records->which == Z_Records_NSD)
1369 send_to_srw_client_ok(0, res->records, 1);
1371 else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1374 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1376 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1378 if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1380 *pr->numberOfRecordsRequested =
1381 1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1383 handle_incoming_Z_PDU(m_s2z_present_apdu);
1387 m_s2z_present_apdu = 0;
1388 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1391 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1394 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1396 m_s2z_present_apdu = 0;
1397 Z_PresentResponse *res = apdu->u.presentResponse;
1398 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1404 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1405 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1407 int r = send_Z_PDU(apdu, &len);
1408 m_bytes_sent += len;
1409 m_bw_stat.add_bytes(len);
1416 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1418 int kill_session = 0;
1419 Z_ReferenceId **new_id = get_referenceIdP(apdu);
1422 *new_id = m_referenceId;
1424 if (apdu->which == Z_APDU_searchResponse)
1426 Z_SearchResponse *sr = apdu->u.searchResponse;
1427 Z_Records *p = sr->records;
1428 if (p && p->which == Z_Records_NSD)
1430 Z_DiagRec dr, *dr_p = &dr;
1431 dr.which = Z_DiagRec_defaultFormat;
1432 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1434 *sr->searchStatus = 0;
1435 display_diagrecs(&dr_p, 1);
1439 if (p && p->which == Z_Records_DBOSD)
1443 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1446 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1447 if (m_marcxml_mode == marcxml)
1448 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1451 convert_records_charset(p->u.databaseOrSurDiagnostics,
1453 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1457 if (sr->resultCount)
1459 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1461 if (*sr->resultCount < 0)
1463 m_flag_invalid_session = 1;
1466 *sr->searchStatus = 0;
1468 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1469 *sr->resultCount = 0;
1474 else if (apdu->which == Z_APDU_presentResponse)
1476 Z_PresentResponse *sr = apdu->u.presentResponse;
1477 Z_Records *p = sr->records;
1478 if (p && p->which == Z_Records_NSD)
1480 Z_DiagRec dr, *dr_p = &dr;
1481 dr.which = Z_DiagRec_defaultFormat;
1482 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1483 if (*sr->presentStatus == Z_PresentStatus_success)
1484 *sr->presentStatus = Z_PresentStatus_failure;
1485 display_diagrecs(&dr_p, 1);
1487 if (p && p->which == Z_Records_DBOSD)
1491 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1494 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1495 if (m_marcxml_mode == marcxml)
1496 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1499 convert_records_charset(p->u.databaseOrSurDiagnostics,
1501 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1505 else if (apdu->which == Z_APDU_initResponse)
1507 //Get and check negotiation record
1508 //from init response.
1509 handle_charset_lang_negotiation(apdu);
1511 if (m_initRequest_options)
1514 (Odr_bitmask *)odr_malloc(odr_encode(),
1515 sizeof(Odr_bitmask));
1516 ODR_MASK_ZERO(nopt);
1519 for (i = 0; i<24; i++)
1520 if (ODR_MASK_GET(m_initRequest_options, i) &&
1521 ODR_MASK_GET(apdu->u.initResponse->options, i))
1522 ODR_MASK_SET(nopt, i);
1523 apdu->u.initResponse->options = nopt;
1525 if (m_initRequest_version)
1527 Z_ProtocolVersion *nopt =
1528 (Odr_bitmask *)odr_malloc(odr_encode(),
1529 sizeof(Odr_bitmask));
1530 ODR_MASK_ZERO(nopt);
1533 for (i = 0; i<8; i++)
1534 if (ODR_MASK_GET(m_initRequest_version, i) &&
1535 ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1536 ODR_MASK_SET(nopt, i);
1537 apdu->u.initResponse->protocolVersion = nopt;
1539 apdu->u.initResponse->preferredMessageSize =
1540 odr_intdup(odr_encode(),
1541 m_client->m_initResponse_preferredMessageSize >
1542 m_initRequest_preferredMessageSize ?
1543 m_initRequest_preferredMessageSize :
1544 m_client->m_initResponse_preferredMessageSize);
1545 apdu->u.initResponse->maximumRecordSize =
1546 odr_intdup(odr_encode(),
1547 m_client->m_initResponse_maximumRecordSize >
1548 m_initRequest_maximumRecordSize ?
1549 m_initRequest_maximumRecordSize :
1550 m_client->m_initResponse_maximumRecordSize);
1553 int r = send_PDU_convert(apdu);
1560 m_parent->pre_init();
1565 void Yaz_ProxyClient::set_idAuthentication(Z_APDU *apdu)
1567 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1569 odr_reset(m_idAuthentication_odr);
1570 z_IdAuthentication(m_idAuthentication_odr, &t, 1, 0);
1571 m_idAuthentication_ber_buf =
1572 odr_getbuf(m_idAuthentication_odr,
1573 &m_idAuthentication_ber_size, 0);
1576 bool Yaz_ProxyClient::compare_charset(Z_APDU *apdu)
1581 bool Yaz_ProxyClient::compare_idAuthentication(Z_APDU *apdu)
1583 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1584 ODR odr = odr_createmem(ODR_ENCODE);
1586 z_IdAuthentication(odr, &t, 1, 0);
1588 char *buf = odr_getbuf(odr, &sz, 0);
1589 if (buf && m_idAuthentication_ber_buf
1590 && sz == m_idAuthentication_ber_size
1591 && !memcmp(m_idAuthentication_ber_buf, buf, sz))
1597 if (!buf && !m_idAuthentication_ber_buf)
1602 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1605 const char *apdu_name_tmp = apdu_name(apdu);
1606 int r = send_Z_PDU(apdu, &len);
1607 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1608 yaz_log (YLOG_LOG, "%sSending %s to %s %d bytes",
1610 apdu_name_tmp, get_hostname(), len);
1611 m_bytes_sent += len;
1615 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1617 if (apdu->which == Z_APDU_presentRequest)
1619 Z_PresentRequest *pr = apdu->u.presentRequest;
1620 int toget = *pr->numberOfRecordsRequested;
1621 int start = *pr->resultSetStartPoint;
1623 yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1624 pr->resultSetId, start, toget);
1626 if (*m_parent->m_optimize == '0')
1629 if (!m_client->m_last_resultSetId)
1631 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1632 new_apdu->u.presentResponse->records =
1633 create_nonSurrogateDiagnostics(
1635 YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1637 send_to_client(new_apdu);
1640 if (start < 1 || toget < 0)
1642 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1643 new_apdu->u.presentResponse->records =
1644 create_nonSurrogateDiagnostics(
1646 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1648 send_to_client(new_apdu);
1651 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1653 if (start+toget-1 > m_client->m_last_resultCount)
1655 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1656 new_apdu->u.presentResponse->records =
1657 create_nonSurrogateDiagnostics(
1659 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1661 send_to_client(new_apdu);
1664 Z_NamePlusRecordList *npr;
1666 yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1667 m_session_str, start, toget, yaz_z3950oid_to_str(
1668 pr->preferredRecordSyntax, &oclass));
1670 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1671 pr->preferredRecordSyntax,
1672 pr->recordComposition))
1674 yaz_log (YLOG_LOG, "%sReturned cached records for present request",
1676 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1677 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1679 new_apdu->u.presentResponse->numberOfRecordsReturned
1680 = odr_intdup(odr_encode(), toget);
1682 new_apdu->u.presentResponse->records = (Z_Records*)
1683 odr_malloc(odr_encode(), sizeof(Z_Records));
1684 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1685 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1686 new_apdu->u.presentResponse->nextResultSetPosition =
1687 odr_intdup(odr_encode(), start+toget);
1689 send_to_client(new_apdu);
1695 if (apdu->which != Z_APDU_searchRequest)
1697 Z_SearchRequest *sr = apdu->u.searchRequest;
1698 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1699 Yaz_Z_Databases this_databases;
1701 this_databases.set(sr->num_databaseNames, (const char **)
1704 this_query->set_Z_Query(sr->query);
1706 // Check for non-negative piggyback params.
1707 if (*sr->smallSetUpperBound < 0
1708 || *sr->largeSetLowerBound < 0
1709 || *sr->mediumSetPresentNumber < 0)
1711 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1712 // Not a present request.. But can't find better diagnostic
1713 new_apdu->u.searchResponse->records =
1714 create_nonSurrogateDiagnostics(
1716 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 0);
1717 send_to_client(new_apdu);
1721 char query_str[120];
1722 this_query->print(query_str, sizeof(query_str)-1);
1723 yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1725 if (*m_parent->m_optimize != '0' &&
1726 m_client->m_last_ok && m_client->m_last_query &&
1727 m_client->m_last_query->match(this_query) &&
1728 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1729 m_client->m_last_databases.match(this_databases))
1732 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1733 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1735 Z_NamePlusRecordList *npr;
1736 int toget = *sr->mediumSetPresentNumber;
1737 Z_RecordComposition *comp = 0;
1739 if (toget > m_client->m_last_resultCount)
1740 toget = m_client->m_last_resultCount;
1742 if (sr->mediumSetElementSetNames)
1744 comp = (Z_RecordComposition *)
1745 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1746 comp->which = Z_RecordComp_simple;
1747 comp->u.simple = sr->mediumSetElementSetNames;
1750 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1751 sr->preferredRecordSyntax, comp))
1753 yaz_log (YLOG_LOG, "%sReturned cached records for medium set",
1755 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1756 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1757 new_apdu->u.searchResponse->resultCount =
1758 &m_client->m_last_resultCount;
1760 new_apdu->u.searchResponse->numberOfRecordsReturned
1761 = odr_intdup(odr_encode(), toget);
1763 new_apdu->u.searchResponse->presentStatus =
1764 odr_intdup(odr_encode(), Z_PresentStatus_success);
1765 new_apdu->u.searchResponse->records = (Z_Records*)
1766 odr_malloc(odr_encode(), sizeof(Z_Records));
1767 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1768 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1769 new_apdu->u.searchResponse->nextResultSetPosition =
1770 odr_intdup(odr_encode(), toget+1);
1771 send_to_client(new_apdu);
1777 // send present request (medium size)
1778 yaz_log (YLOG_LOG, "%sOptimizing search for medium set",
1781 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1782 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1783 pr->referenceId = sr->referenceId;
1784 pr->resultSetId = sr->resultSetName;
1785 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1786 *pr->numberOfRecordsRequested = toget;
1787 pr->recordComposition = comp;
1788 m_client->m_sr_transform = 1;
1792 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1793 m_client->m_last_resultCount <= 0)
1795 // large set. Return pseudo-search response immediately
1796 yaz_log (YLOG_LOG, "%sOptimizing search for large set",
1798 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1799 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1800 new_apdu->u.searchResponse->resultCount =
1801 &m_client->m_last_resultCount;
1802 send_to_client(new_apdu);
1807 Z_NamePlusRecordList *npr;
1808 int toget = m_client->m_last_resultCount;
1809 Z_RecordComposition *comp = 0;
1811 // send a present request (small set)
1813 if (sr->smallSetElementSetNames)
1815 comp = (Z_RecordComposition *)
1816 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1817 comp->which = Z_RecordComp_simple;
1818 comp->u.simple = sr->smallSetElementSetNames;
1821 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1822 sr->preferredRecordSyntax, comp))
1824 yaz_log (YLOG_LOG, "%sReturned cached records for small set",
1826 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1827 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1828 new_apdu->u.searchResponse->resultCount =
1829 &m_client->m_last_resultCount;
1831 new_apdu->u.searchResponse->numberOfRecordsReturned
1832 = odr_intdup(odr_encode(), toget);
1834 new_apdu->u.searchResponse->presentStatus =
1835 odr_intdup(odr_encode(), Z_PresentStatus_success);
1836 new_apdu->u.searchResponse->records = (Z_Records*)
1837 odr_malloc(odr_encode(), sizeof(Z_Records));
1838 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1839 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1840 new_apdu->u.searchResponse->nextResultSetPosition =
1841 odr_intdup(odr_encode(), toget+1);
1842 send_to_client(new_apdu);
1847 yaz_log (YLOG_LOG, "%sOptimizing search for small set",
1849 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1850 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1851 pr->referenceId = sr->referenceId;
1852 pr->resultSetId = sr->resultSetName;
1853 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1854 *pr->numberOfRecordsRequested = toget;
1855 pr->recordComposition = comp;
1856 m_client->m_sr_transform = 1;
1861 else // query doesn't match
1863 delete m_client->m_last_query;
1864 m_client->m_last_query = this_query;
1865 m_client->m_last_ok = 0;
1866 m_client->m_cache.clear();
1867 m_client->m_resultSetStartPoint = 0;
1869 xfree (m_client->m_last_resultSetId);
1870 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1872 m_client->m_last_databases.set(sr->num_databaseNames,
1873 (const char **) sr->databaseNames);
1879 void Yaz_Proxy::inc_request_no()
1882 char *cp = m_session_str + strlen(m_session_str)-1;
1885 while (*cp && *cp != ' ')
1888 sprintf(cp+1, "%d ", m_request_no);
1891 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1895 m_bytes_recv += len;
1897 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1898 yaz_log (YLOG_LOG, "%sReceiving %s from client %d bytes",
1899 m_session_str, gdu_name(apdu), len);
1902 // try to make a _bad_ attribute set ID .. Don't enable this in prod.
1903 if (apdu->which == Z_GDU_Z3950
1904 && apdu->u.z3950->which == Z_APDU_searchRequest)
1906 Z_SearchRequest *req = apdu->u.z3950->u.searchRequest;
1907 if (req->query && req->query->which == Z_Query_type_1)
1909 Z_RPNQuery *rpnquery = req->query->u.type_1;
1910 if (rpnquery->attributeSetId)
1912 rpnquery->attributeSetId[0] = -2;
1913 rpnquery->attributeSetId[1] = -1;
1914 yaz_log(YLOG_WARN, "%sBAD FIXUP TEST", m_session_str);
1920 #if HAVE_GETTIMEOFDAY
1921 gettimeofday((struct timeval *) m_time_tv, 0);
1923 m_bw_stat.add_bytes(len);
1924 m_pdu_stat.add_bytes(1);
1926 GDU *gdu = new GDU(apdu);
1928 if (gdu->get() == 0)
1931 yaz_log(YLOG_LOG, "%sUnable to encode package", m_session_str);
1936 m_in_queue.enqueue(gdu);
1937 recv_GDU_more(false);
1940 void Yaz_Proxy::HTTP_Forwarded(Z_GDU *z_gdu)
1942 if (z_gdu->which == Z_GDU_HTTP_Request)
1944 Z_HTTP_Request *hreq = z_gdu->u.HTTP_Request;
1945 const char *x_forwarded_for =
1946 z_HTTP_header_lookup(hreq->headers, "X-Forwarded-For");
1947 if (x_forwarded_for)
1950 m_peername = (char*) xmalloc(strlen(x_forwarded_for)+5);
1951 sprintf(m_peername, "tcp:%s", x_forwarded_for);
1953 yaz_log(YLOG_LOG, "%sHTTP Forwarded from %s", m_session_str,
1955 if (m_log_mask & PROXY_LOG_IP_CLIENT)
1956 sprintf(m_session_str, "%ld:%d %.80s %d ",
1957 (long) time(0), m_session_no, m_peername, m_request_no);
1959 sprintf(m_session_str, "%ld:%d %d ",
1960 (long) time(0), m_session_no, m_request_no);
1965 void Yaz_Proxy::connect_stat(bool &block, int &reduce)
1968 m_parent->m_connect.cleanup(false);
1969 m_parent->m_connect.add_connect(m_peername);
1971 int connect_total = m_parent->m_connect.get_total(m_peername);
1972 int max_connect = m_parent->m_max_connect;
1974 if (max_connect && connect_total > max_connect)
1976 yaz_log(YLOG_LOG, "%sconnect not accepted total=%d max=%d",
1977 m_session_str, connect_total, max_connect);
1982 yaz_log(YLOG_LOG, "%sconnect accepted total=%d", m_session_str,
1985 int limit_connect = m_parent->m_limit_connect;
1987 reduce = connect_total / limit_connect;
1992 void Yaz_Proxy::recv_GDU_reduce(GDU *gdu)
1994 HTTP_Forwarded(gdu->get());
1998 if (m_request_no == 1)
2002 connect_stat(block, reduce);
2006 m_timeout_mode = timeout_busy;
2012 int bw_total = m_bw_stat.get_total();
2013 int pdu_total = m_pdu_stat.get_total();
2014 int search_total = m_search_stat.get_total();
2016 assert(m_timeout_mode == timeout_busy);
2017 assert(m_timeout_gdu == 0);
2020 reduce += search_total / m_search_max;
2022 reduce += (bw_total/m_bw_max);
2025 if (pdu_total > m_pdu_max)
2027 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
2028 reduce = (reduce > nreduce) ? reduce : nreduce;
2034 /* uncomment to force a big reduce */
2035 m_timeout_mode = timeout_reduce;
2036 m_timeout_gdu = gdu;
2037 timeout(3); // call us reduce seconds later
2042 yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d search=%d limit-bw=%d limit-pdu=%d limit-search=%d",
2043 m_session_str, reduce, bw_total, pdu_total, search_total,
2044 m_bw_max, m_pdu_max, m_search_max);
2046 m_timeout_mode = timeout_reduce;
2047 m_timeout_gdu = gdu;
2048 timeout(reduce); // call us reduce seconds later
2051 recv_GDU_normal(gdu);
2054 void Yaz_Proxy::recv_GDU_more(bool normal)
2057 if (normal && m_timeout_mode == timeout_busy)
2058 m_timeout_mode = timeout_normal;
2059 while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
2061 m_timeout_mode = timeout_busy;
2069 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
2072 gdu->move_away_gdu(odr_decode(), &apdu);
2075 if (apdu->which == Z_GDU_Z3950)
2076 handle_incoming_Z_PDU(apdu->u.z3950);
2077 else if (apdu->which == Z_GDU_HTTP_Request)
2078 handle_incoming_HTTP(apdu->u.HTTP_Request);
2081 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
2083 if (m_max_record_retrieve)
2085 if (apdu->which == Z_APDU_presentRequest)
2087 Z_PresentRequest *pr = apdu->u.presentRequest;
2088 if (pr->numberOfRecordsRequested &&
2089 *pr->numberOfRecordsRequested > m_max_record_retrieve)
2090 *pr->numberOfRecordsRequested = m_max_record_retrieve;
2095 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
2097 if (apdu->which == Z_APDU_initRequest)
2099 if (m_initRequest_options &&
2100 !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
2101 (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
2103 // There is no negotiation proposal from
2104 // client's side. OK. The proxy negotiation
2106 Z_InitRequest *initRequest = apdu->u.initRequest;
2107 Z_OtherInformation **otherInfo;
2108 Z_OtherInformationUnit *oi;
2109 get_otherInfoAPDU(apdu, &otherInfo);
2110 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2113 ODR_MASK_SET(initRequest->options,
2114 Z_Options_negotiationModel);
2115 oi->which = Z_OtherInfo_externallyDefinedInfo;
2116 oi->information.externallyDefinedInfo =
2117 yaz_set_proposal_charneg(odr_encode(),
2118 (const char**)&m_proxy_negotiation_charset,
2119 m_proxy_negotiation_charset ? 1:0,
2120 (const char**)&m_proxy_negotiation_lang,
2121 m_proxy_negotiation_lang ? 1:0,
2125 else if (m_initRequest_options &&
2126 ODR_MASK_GET(m_initRequest_options,
2127 Z_Options_negotiationModel) &&
2128 m_charset_converter->get_target_query_charset())
2130 yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
2132 m_charset_converter->get_target_query_charset());
2133 Z_InitRequest *initRequest = apdu->u.initRequest;
2134 Z_CharSetandLanguageNegotiation *negotiation =
2135 yaz_get_charneg_record (initRequest->otherInfo);
2137 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2139 NMEM nmem = nmem_create();
2140 char **charsets = 0;
2141 int num_charsets = 0;
2145 yaz_get_proposal_charneg (nmem, negotiation,
2146 &charsets, &num_charsets,
2147 &langs, &num_langs, &selected);
2149 for (i = 0; i<num_charsets; i++)
2150 yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
2152 for (i = 0; i<num_langs; i++)
2153 yaz_log(YLOG_LOG, "%slang %s", m_session_str,
2156 const char *t_charset =
2157 m_charset_converter->get_target_query_charset();
2158 // sweep through charsets and pick the first supported
2160 for (i = 0; i<num_charsets; i++)
2162 const char *c_charset = charsets[i];
2163 if (!odr_set_charset(odr_decode(), t_charset, c_charset))
2166 if (i != num_charsets)
2168 // got one .. set up ODR for reverse direction
2169 const char *c_charset = charsets[i];
2170 odr_set_charset(odr_encode(), c_charset, t_charset);
2171 m_charset_converter->set_client_query_charset(c_charset);
2172 m_charset_converter->set_client_charset_selected(selected);
2175 ODR_MASK_CLEAR(m_initRequest_options,
2176 Z_Options_negotiationModel);
2177 yaz_del_charneg_record(&initRequest->otherInfo);
2181 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
2185 else if (m_charset_converter->get_target_query_charset() &&
2186 m_proxy_negotiation_default_charset)
2188 m_charset_converter->
2189 set_client_query_charset(m_proxy_negotiation_default_charset);
2192 else if (apdu->which == Z_APDU_initResponse)
2194 Z_InitResponse *initResponse = apdu->u.initResponse;
2195 Z_OtherInformation **otherInfo;
2196 get_otherInfoAPDU(apdu, &otherInfo);
2198 Z_CharSetandLanguageNegotiation *charneg = 0;
2200 if (otherInfo && *otherInfo &&
2201 ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel)
2202 && (charneg = yaz_get_charneg_record(*otherInfo)))
2208 yaz_get_response_charneg(m_referenceId_mem, charneg,
2209 &charset, &lang, &selected);
2211 yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
2212 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
2214 if (m_initRequest_options &&
2215 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
2217 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2220 else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2222 // negotiation-charset, negotiation-lang
2223 // elements of config file in use.
2225 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2228 // clear negotiation option.
2229 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2231 // Delete negotiation (charneg-3) entry.
2232 yaz_del_charneg_record(otherInfo);
2237 if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2239 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2242 else if (m_charset_converter->get_client_query_charset())
2244 Z_OtherInformation **otherInfo;
2245 Z_OtherInformationUnit *oi;
2246 get_otherInfoAPDU(apdu, &otherInfo);
2247 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2250 ODR_MASK_SET(initResponse->options,
2251 Z_Options_negotiationModel);
2252 if (m_initRequest_options)
2253 ODR_MASK_SET(m_initRequest_options,
2254 Z_Options_negotiationModel);
2256 oi->which = Z_OtherInfo_externallyDefinedInfo;
2257 oi->information.externallyDefinedInfo =
2258 yaz_set_response_charneg(
2260 m_charset_converter->get_client_query_charset(),
2262 m_charset_converter->get_client_charset_selected());
2269 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2271 const char *addinfo)
2273 Z_Records *rec = (Z_Records *)
2274 odr_malloc (odr, sizeof(*rec));
2276 odr_malloc (odr, sizeof(*err));
2277 Z_DiagRec *drec = (Z_DiagRec *)
2278 odr_malloc (odr, sizeof(*drec));
2279 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2280 odr_malloc (odr, sizeof(*dr));
2282 rec->which = Z_Records_NSD;
2283 rec->u.nonSurrogateDiagnostic = dr;
2284 dr->diagnosticSetId =
2285 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
2286 dr->condition = err;
2287 dr->which = Z_DefaultDiagFormat_v2Addinfo;
2288 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2292 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2294 if (apdu->which == Z_APDU_searchRequest &&
2295 apdu->u.searchRequest->query &&
2296 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2297 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2299 Z_RPNQuery *rpnquery = 0;
2300 Z_SearchRequest *sr = apdu->u.searchRequest;
2303 yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2304 sr->query->u.type_104->u.cql);
2306 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2307 &rpnquery, odr_encode(),
2310 yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2313 yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2314 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2316 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2317 new_apdu->u.searchResponse->records =
2318 create_nonSurrogateDiagnostics(odr_encode(),
2319 yaz_diag_srw_to_bib1(r),
2321 *new_apdu->u.searchResponse->searchStatus = 0;
2323 send_to_client(new_apdu);
2329 sr->query->which = Z_Query_type_1;
2330 sr->query->u.type_1 = rpnquery;
2337 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2339 if (apdu->which == Z_APDU_searchRequest &&
2340 apdu->u.searchRequest->query)
2342 if (apdu->u.searchRequest->query->which == Z_Query_type_1
2343 || apdu->u.searchRequest->query->which == Z_Query_type_101)
2346 m_charset_converter->set_client_query_charset("UTF-8");
2347 Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2348 m_charset_converter->convert_type_1(rpnquery, odr_encode());
2355 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2357 if (apdu->which == Z_APDU_searchRequest)
2359 Z_SearchRequest *sr = apdu->u.searchRequest;
2363 Yaz_ProxyConfig *cfg = check_reconfigure();
2365 err = cfg->check_query(odr_encode(), m_default_target,
2366 sr->query, &addinfo);
2369 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2371 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2372 new_apdu->u.searchResponse->records =
2373 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2374 *new_apdu->u.searchResponse->searchStatus = 0;
2376 send_to_client(new_apdu);
2384 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2386 if (apdu->which != Z_APDU_initRequest)
2387 return 1; // pass if no init request
2388 Z_InitRequest *req = apdu->u.initRequest;
2390 Yaz_ProxyConfig *cfg = check_reconfigure();
2392 return 1; // pass if no config
2395 if (req->idAuthentication == 0)
2397 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2400 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2402 ret = cfg->client_authentication(
2404 req->idAuthentication->u.idPass->userId,
2405 req->idAuthentication->u.idPass->groupId,
2406 req->idAuthentication->u.idPass->password,
2409 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2411 char user[64], pass[64];
2414 sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2415 ret = cfg->client_authentication(m_default_target, user, 0, pass,
2419 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2424 int Yaz_Proxy::handle_global_authentication(Z_APDU *apdu)
2426 if (apdu->which != Z_APDU_initRequest)
2427 return 1; // pass if no init request
2428 Z_InitRequest *req = apdu->u.initRequest;
2430 Yaz_ProxyConfig *cfg = check_reconfigure();
2432 return 1; // pass if no config
2435 if (req->idAuthentication == 0)
2437 ret = cfg->global_client_authentication(0, 0, 0,
2440 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2442 ret = cfg->global_client_authentication(
2443 req->idAuthentication->u.idPass->userId,
2444 req->idAuthentication->u.idPass->groupId,
2445 req->idAuthentication->u.idPass->password,
2448 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2450 char user[64], pass[64];
2453 sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2454 ret = cfg->global_client_authentication(user, 0, pass,
2458 ret = cfg->global_client_authentication(0, 0, 0, m_peername);
2462 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2464 m_marcxml_mode = none;
2465 if (apdu->which == Z_APDU_searchRequest)
2467 Z_SearchRequest *sr = apdu->u.searchRequest;
2470 Yaz_ProxyConfig *cfg = check_reconfigure();
2472 Z_RecordComposition rc_temp, *rc = 0;
2473 if (sr->smallSetElementSetNames)
2475 rc_temp.which = Z_RecordComp_simple;
2476 rc_temp.u.simple = sr->smallSetElementSetNames;
2480 if (sr->preferredRecordSyntax)
2483 ent = oid_getentbyoid(sr->preferredRecordSyntax);
2484 m_frontend_type = ent->value;
2487 m_frontend_type = VAL_NONE;
2489 char *stylesheet_name = 0;
2491 err = cfg->check_syntax(odr_encode(),
2493 sr->preferredRecordSyntax, rc,
2494 &addinfo, &stylesheet_name, &m_schema,
2495 &m_backend_type, &m_backend_charset,
2496 &m_usemarcon_ini_stage1,
2497 &m_usemarcon_ini_stage2);
2498 if (stylesheet_name)
2500 m_parent->low_socket_close();
2503 if (m_stylesheet_xsp)
2504 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2505 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2508 m_stylesheet_offset = 0;
2509 xfree(stylesheet_name);
2511 m_parent->low_socket_open();
2515 sr->smallSetElementSetNames = 0;
2516 sr->mediumSetElementSetNames = 0;
2517 m_marcxml_mode = marcxml;
2521 sr->preferredRecordSyntax =
2522 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2526 sr->preferredRecordSyntax =
2527 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2532 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2534 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2535 new_apdu->u.searchResponse->records =
2536 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2537 *new_apdu->u.searchResponse->searchStatus = 0;
2539 send_to_client(new_apdu);
2543 else if (m_backend_type)
2545 sr->preferredRecordSyntax =
2546 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2549 else if (apdu->which == Z_APDU_presentRequest)
2551 Z_PresentRequest *pr = apdu->u.presentRequest;
2554 Yaz_ProxyConfig *cfg = check_reconfigure();
2556 if (pr->preferredRecordSyntax)
2559 ent = oid_getentbyoid(pr->preferredRecordSyntax);
2560 m_frontend_type = ent->value;
2563 m_frontend_type = VAL_NONE;
2565 char *stylesheet_name = 0;
2567 err = cfg->check_syntax(odr_encode(), m_default_target,
2568 pr->preferredRecordSyntax,
2569 pr->recordComposition,
2570 &addinfo, &stylesheet_name, &m_schema,
2571 &m_backend_type, &m_backend_charset,
2572 &m_usemarcon_ini_stage1,
2573 &m_usemarcon_ini_stage2
2575 if (stylesheet_name)
2577 m_parent->low_socket_close();
2580 if (m_stylesheet_xsp)
2581 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2582 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2585 m_stylesheet_offset = 0;
2586 xfree(stylesheet_name);
2588 m_parent->low_socket_open();
2592 pr->recordComposition = 0;
2593 m_marcxml_mode = marcxml;
2597 pr->preferredRecordSyntax =
2598 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2602 pr->preferredRecordSyntax =
2603 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2608 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2610 new_apdu->u.presentResponse->referenceId = pr->referenceId;
2611 new_apdu->u.presentResponse->records =
2612 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2613 *new_apdu->u.presentResponse->presentStatus =
2614 Z_PresentStatus_failure;
2616 send_to_client(new_apdu);
2620 else if (m_backend_type)
2622 pr->preferredRecordSyntax =
2623 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2629 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2633 Z_ElementSetNames *esn = (Z_ElementSetNames *)
2634 odr_malloc(o, sizeof(Z_ElementSetNames));
2635 esn->which = Z_ElementSetNames_generic;
2636 esn->u.generic = odr_strdup(o, schema);
2640 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2643 Yaz_ProxyConfig *cfg = check_reconfigure();
2645 t = cfg->get_explain_name(db, backend_db);
2647 if (m_client && m_default_target && t && strcmp(m_default_target, t))
2654 xfree(m_default_target);
2655 m_default_target = xstrdup(t);
2659 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2662 if (strcmp(hreq->method, "GET"))
2664 if (hreq->path[0] != '/')
2666 const char *cp = hreq->path;
2669 if (*cp == '/' && strchr("/.", cp[1]))
2674 Yaz_ProxyConfig *cfg = check_reconfigure();
2676 if (!cfg->get_file_access_info(hreq->path+1))
2679 const char *fname = hreq->path+1;
2680 if (stat(fname, &sbuf))
2682 yaz_log(YLOG_LOG|YLOG_ERRNO, "%sstat failed for %s", m_session_str,
2686 if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2688 yaz_log(YLOG_LOG, "%sNot a regular file %s", m_session_str, fname);
2691 if (sbuf.st_size > (off_t) 1000000)
2693 yaz_log(YLOG_WARN, "%sFile %s too large for transfer", m_session_str,
2698 ODR o = odr_encode();
2700 const char *ctype = cfg->check_mime_type(fname);
2701 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2702 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2704 hres->version = odr_strdup(o, m_http_version);
2705 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2706 if (m_http_keepalive)
2707 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2711 hres->content_len = sbuf.st_size;
2712 hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2713 FILE *f = fopen(fname, "rb");
2716 fread(hres->content_buf, 1, hres->content_len, f);
2723 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2725 yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
2729 send_GDU(gdu, &len);
2730 recv_GDU_more(true);
2734 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2738 odr_destroy(m_s2z_odr_init);
2741 if (m_s2z_odr_search)
2743 odr_destroy(m_s2z_odr_search);
2744 m_s2z_odr_search = 0;
2747 m_http_keepalive = 0;
2749 if (!strcmp(hreq->version, "1.0"))
2751 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2752 if (v && !strcmp(v, "Keep-Alive"))
2753 m_http_keepalive = 1;
2755 m_http_keepalive = 0;
2756 m_http_version = "1.0";
2760 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2761 if (v && !strcmp(v, "close"))
2762 m_http_keepalive = 0;
2764 m_http_keepalive = 1;
2765 m_http_version = "1.1";
2768 const char *a = z_HTTP_header_lookup(hreq->headers, "Authorization");
2769 char authorization_str[255];
2770 *authorization_str = '\0';
2771 if (a && strncasecmp(a, "Basic ", 6) == 0)
2772 base64_decode(a + 6, authorization_str, 254);
2774 Z_SRW_PDU *srw_pdu = 0;
2775 Z_SOAP *soap_package = 0;
2777 Z_SRW_diagnostic *diagnostic = 0;
2778 int num_diagnostic = 0;
2780 yaz_log(YLOG_LOG, "%s%s %s", m_session_str, hreq->method, hreq->path);
2782 if (file_access(hreq))
2786 else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2788 || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2789 &charset, &diagnostic, &num_diagnostic) == 0)
2791 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2792 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2793 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2794 m_s2z_init_apdu = 0;
2795 m_s2z_search_apdu = 0;
2796 m_s2z_present_apdu = 0;
2798 m_s2z_stylesheet = 0;
2800 Z_IdAuthentication *auth = NULL;
2801 if (*authorization_str)
2803 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2804 auth->which = Z_IdAuthentication_idPass;
2805 auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2806 auth->u.idPass->groupId = NULL;
2807 char *p = strchr(authorization_str, ':');
2812 auth->u.idPass->password = odr_strdup(m_s2z_odr_init, p);
2814 auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, authorization_str);
2817 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2820 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2822 const char *backend_db = srw_req->database;
2823 srw_get_client(srw_req->database, &backend_db);
2825 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2826 // recordXPath unsupported.
2827 if (srw_req->recordXPath)
2829 yaz_add_srw_diagnostic(odr_decode(),
2830 &diagnostic, &num_diagnostic,
2834 if (srw_req->sort_type != Z_SRW_sort_type_none)
2836 yaz_add_srw_diagnostic(odr_decode(),
2837 &diagnostic, &num_diagnostic,
2841 if (srw_req->stylesheet)
2843 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2845 // set packing for response records ..
2846 if (srw_req->recordPacking &&
2847 !strcmp(srw_req->recordPacking, "xml"))
2848 m_s2z_packing = Z_SRW_recordPacking_XML;
2850 m_s2z_packing = Z_SRW_recordPacking_string;
2854 Z_SRW_PDU *srw_pdu =
2855 yaz_srw_get(odr_encode(),
2856 Z_SRW_searchRetrieve_response);
2857 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2859 srw_res->diagnostics = diagnostic;
2860 srw_res->num_diagnostics = num_diagnostic;
2861 send_srw_response(srw_pdu);
2865 // prepare search PDU
2866 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2867 Z_APDU_searchRequest);
2868 Z_SearchRequest *z_searchRequest =
2869 m_s2z_search_apdu->u.searchRequest;
2871 z_searchRequest->num_databaseNames = 1;
2872 z_searchRequest->databaseNames = (char**)
2873 odr_malloc(m_s2z_odr_search, sizeof(char *));
2874 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2877 // query transformation
2878 Z_Query *query = (Z_Query *)
2879 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2880 z_searchRequest->query = query;
2882 if (srw_req->query_type == Z_SRW_query_type_cql)
2884 Z_External *ext = (Z_External *)
2885 odr_malloc(m_s2z_odr_search, sizeof(*ext));
2886 ext->direct_reference =
2887 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2888 ext->indirect_reference = 0;
2889 ext->descriptor = 0;
2890 ext->which = Z_External_CQL;
2891 ext->u.cql = srw_req->query.cql;
2893 query->which = Z_Query_type_104;
2894 query->u.type_104 = ext;
2896 else if (srw_req->query_type == Z_SRW_query_type_pqf)
2898 Z_RPNQuery *RPNquery;
2899 YAZ_PQF_Parser pqf_parser;
2901 pqf_parser = yaz_pqf_create ();
2903 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2904 srw_req->query.pqf);
2907 const char *pqf_msg;
2909 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2911 yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
2912 yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2914 send_to_srw_client_error(10, 0);
2917 query->which = Z_Query_type_1;
2918 query->u.type_1 = RPNquery;
2920 yaz_pqf_destroy (pqf_parser);
2924 send_to_srw_client_error(7, "query");
2929 m_s2z_present_apdu = 0;
2931 if (srw_req->maximumRecords)
2932 max = *srw_req->maximumRecords;
2934 if (srw_req->startRecord)
2935 start = *srw_req->startRecord;
2938 // Some backend, such as Voyager doesn't honor piggyback
2939 // So we use present always (0 &&).
2940 if (0 && start <= 1) // Z39.50 piggyback
2942 *z_searchRequest->smallSetUpperBound = max;
2943 *z_searchRequest->mediumSetPresentNumber = max;
2944 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2946 z_searchRequest->preferredRecordSyntax =
2947 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2949 if (srw_req->recordSchema)
2951 z_searchRequest->smallSetElementSetNames =
2952 z_searchRequest->mediumSetElementSetNames =
2953 mk_esn_from_schema(m_s2z_odr_search,
2954 srw_req->recordSchema);
2957 else // Z39.50 present
2959 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2960 Z_APDU_presentRequest);
2961 Z_PresentRequest *z_presentRequest =
2962 m_s2z_present_apdu->u.presentRequest;
2963 *z_presentRequest->resultSetStartPoint = start;
2964 *z_presentRequest->numberOfRecordsRequested = max;
2965 z_presentRequest->preferredRecordSyntax =
2966 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2968 if (srw_req->recordSchema)
2970 z_presentRequest->recordComposition =
2971 (Z_RecordComposition *)
2972 odr_malloc(m_s2z_odr_search,
2973 sizeof(Z_RecordComposition));
2974 z_presentRequest->recordComposition->which =
2975 Z_RecordComp_simple;
2976 z_presentRequest->recordComposition->u.simple =
2977 mk_esn_from_schema(m_s2z_odr_search,
2978 srw_req->recordSchema);
2984 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2985 Z_APDU_initRequest);
2987 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2989 // prevent m_initRequest_apdu memory from being grabbed
2990 // in Yaz_Proxy::handle_incoming_Z_PDU
2991 m_initRequest_apdu = m_s2z_init_apdu;
2992 handle_incoming_Z_PDU(m_s2z_init_apdu);
2997 handle_incoming_Z_PDU(m_s2z_search_apdu);
3001 else if (srw_pdu->which == Z_SRW_explain_request)
3003 Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
3005 const char *backend_db = srw_req->database;
3006 srw_get_client(srw_req->database, &backend_db);
3008 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
3011 if (srw_req->stylesheet)
3013 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
3015 if (srw_req->recordPacking &&
3016 !strcmp(srw_req->recordPacking, "xml"))
3017 m_s2z_packing = Z_SRW_recordPacking_XML;
3019 m_s2z_packing = Z_SRW_recordPacking_string;
3023 send_srw_explain_response(diagnostic, num_diagnostic);
3029 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
3030 Z_APDU_initRequest);
3032 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
3034 // prevent m_initRequest_apdu memory from being grabbed
3035 // in Yaz_Proxy::handle_incoming_Z_PDU
3036 m_initRequest_apdu = m_s2z_init_apdu;
3037 handle_incoming_Z_PDU(m_s2z_init_apdu);
3040 send_srw_explain_response(0, 0);
3043 else if (srw_pdu->which == Z_SRW_scan_request)
3045 m_s2z_database = odr_strdup(m_s2z_odr_init,
3046 srw_pdu->u.scan_request->database);
3048 yaz_add_srw_diagnostic(odr_decode(),
3049 &diagnostic, &num_diagnostic,
3051 Z_SRW_PDU *srw_pdu =
3052 yaz_srw_get(odr_encode(),
3053 Z_SRW_scan_response);
3054 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
3056 srw_res->diagnostics = diagnostic;
3057 srw_res->num_diagnostics = num_diagnostic;
3058 send_srw_response(srw_pdu);
3065 send_to_srw_client_error(4, 0);
3068 send_http_response(400);
3071 void Yaz_Proxy::handle_init(Z_APDU *apdu)
3074 Z_OtherInformation **oi;
3075 get_otherInfoAPDU(apdu, &oi);
3077 if (apdu->u.initRequest->implementationId)
3078 yaz_log(YLOG_LOG, "%simplementationId: %s",
3079 m_session_str, apdu->u.initRequest->implementationId);
3080 if (apdu->u.initRequest->implementationName)
3081 yaz_log(YLOG_LOG, "%simplementationName: %s",
3082 m_session_str, apdu->u.initRequest->implementationName);
3083 if (apdu->u.initRequest->implementationVersion)
3084 yaz_log(YLOG_LOG, "%simplementationVersion: %s",
3085 m_session_str, apdu->u.initRequest->implementationVersion);
3086 if (m_initRequest_apdu == 0)
3088 if (m_initRequest_mem)
3089 nmem_destroy(m_initRequest_mem);
3091 m_initRequest_apdu = apdu;
3092 m_initRequest_mem = odr_extract_mem(odr_decode());
3094 m_initRequest_preferredMessageSize = *apdu->u.initRequest->
3095 preferredMessageSize;
3096 *apdu->u.initRequest->preferredMessageSize = 1024*1024;
3097 m_initRequest_maximumRecordSize = *apdu->u.initRequest->
3099 *apdu->u.initRequest->maximumRecordSize = 1024*1024;
3101 Z_CharSetandLanguageNegotiation *charSetandLangRecord =
3102 yaz_get_charneg_record(*oi);
3104 // Save proposal charsets and langs.
3105 if (ODR_MASK_GET(apdu->u.initRequest->options,
3106 Z_Options_negotiationModel)
3107 && charSetandLangRecord)
3110 yaz_get_proposal_charneg(m_referenceId_mem,
3111 charSetandLangRecord,
3112 &m_initRequest_oi_negotiation_charsets,
3113 &m_initRequest_oi_negotiation_num_charsets,
3114 &m_initRequest_oi_negotiation_langs,
3115 &m_initRequest_oi_negotiation_num_langs,
3116 &m_initRequest_oi_negotiation_selected);
3118 for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
3120 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
3121 m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
3122 m_initRequest_oi_negotiation_charsets[i]:"none");
3124 for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
3126 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
3127 m_session_str, (m_initRequest_oi_negotiation_langs[i])?
3128 m_initRequest_oi_negotiation_langs[i]:"none");
3130 yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
3131 m_session_str, m_initRequest_oi_negotiation_selected);
3133 // save init options for the response..
3134 m_initRequest_options = apdu->u.initRequest->options;
3136 apdu->u.initRequest->options =
3137 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3138 sizeof(Odr_bitmask));
3139 ODR_MASK_ZERO(apdu->u.initRequest->options);
3141 for (i = 0; i<= 24; i++)
3142 ODR_MASK_SET(apdu->u.initRequest->options, i);
3143 // check negotiation option
3144 if (!ODR_MASK_GET(m_initRequest_options,
3145 Z_Options_negotiationModel))
3147 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3148 Z_Options_negotiationModel);
3150 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3151 Z_Options_concurrentOperations);
3153 m_initRequest_version = apdu->u.initRequest->protocolVersion;
3154 apdu->u.initRequest->protocolVersion =
3155 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3156 sizeof(Odr_bitmask));
3157 ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
3159 for (i = 0; i<= 8; i++)
3160 ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
3162 handle_charset_lang_negotiation(apdu);
3163 if (m_client->m_init_flag)
3165 if (handle_init_response_for_invalid_session(apdu))
3167 if (m_client->m_initResponse)
3169 Z_APDU *apdu2 = m_client->m_initResponse;
3170 apdu2->u.initResponse->otherInfo = 0;
3171 if (m_client->m_cookie && *m_client->m_cookie)
3172 set_otherInformationString(apdu2, VAL_COOKIE, 1,
3173 m_client->m_cookie);
3174 apdu2->u.initResponse->referenceId =
3175 apdu->u.initRequest->referenceId;
3176 apdu2->u.initResponse->options = m_client->m_initResponse_options;
3177 apdu2->u.initResponse->protocolVersion =
3178 m_client->m_initResponse_version;
3180 handle_charset_lang_negotiation(apdu2);
3182 if (m_timeout_mode == timeout_busy)
3183 m_timeout_mode = timeout_normal;
3184 send_to_client(apdu2);
3188 m_client->m_init_flag = 1;
3190 if (m_num_msg_threads && m_my_thread)
3192 Auth_Msg *m = new Auth_Msg;
3194 z_APDU(odr_encode(), &apdu, 0, "encode");
3195 char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
3196 m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
3197 memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
3198 odr_reset(odr_encode());
3201 m_my_thread->put(m);
3205 int ret = handle_authentication(apdu);
3206 result_authentication(apdu, ret);
3210 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
3212 Z_ReferenceId **refid = get_referenceIdP(apdu);
3213 nmem_reset(m_referenceId_mem);
3214 if (refid && *refid)
3216 m_referenceId = (Z_ReferenceId *)
3217 nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
3218 m_referenceId->len = m_referenceId->size = (*refid)->len;
3219 m_referenceId->buf = (unsigned char *)
3220 nmem_malloc(m_referenceId_mem, (*refid)->len);
3221 memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
3226 if (!m_client && m_flag_invalid_session)
3228 // Got request for a session that is invalid..
3229 m_apdu_invalid_session = apdu; // save package
3230 m_mem_invalid_session = odr_extract_mem(odr_decode());
3231 apdu = m_initRequest_apdu; // but throw an init to the target
3234 if (apdu->which == Z_APDU_searchRequest)
3235 m_search_stat.add_bytes(1);
3237 // Handle global authentication
3238 if (!handle_global_authentication(apdu))
3241 { // HTTP. Send unauthorized
3242 send_http_response(401);
3247 // Z39.50 just shutdown
3254 // Determine our client.
3255 Z_OtherInformation **oi;
3256 get_otherInfoAPDU(apdu, &oi);
3257 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
3261 { // HTTP. Send not found
3262 send_http_response(404);
3267 // Z39.50 just shutdown
3273 m_client->m_server = this;
3275 if (apdu->which == Z_APDU_initRequest)
3278 handle_incoming_Z_PDU_2(apdu);
3281 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
3283 handle_max_record_retrieve(apdu);
3286 apdu = handle_syntax_validation(apdu);
3289 apdu = handle_query_transformation(apdu);
3292 apdu = handle_target_charset_conversion(apdu);
3295 apdu = handle_query_validation(apdu);
3298 apdu = result_set_optimize(apdu);
3302 m_client->timeout(m_target_idletime); // mark it active even
3303 recv_GDU_more(true);
3304 // though we didn't use it
3308 // delete other info construct completely if 0 elements
3309 Z_OtherInformation **oi;
3310 get_otherInfoAPDU(apdu, &oi);
3311 if (oi && *oi && (*oi)->num_elements == 0)
3314 if (apdu->which == Z_APDU_presentRequest &&
3315 m_client->m_resultSetStartPoint == 0)
3317 Z_PresentRequest *pr = apdu->u.presentRequest;
3318 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3319 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3321 m_client->m_resultSetStartPoint = 0;
3323 if (m_client->send_to_target(apdu) < 0)
3325 m_client->shutdown();
3328 m_client->m_waiting = 1;
3331 void Yaz_Proxy::connectNotify()
3335 void Yaz_Proxy::releaseClient()
3337 xfree(m_proxyTarget);
3339 m_flag_invalid_session = 0;
3340 // only keep if keep_alive flag is set...
3342 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3343 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3344 m_client->m_waiting == 0)
3346 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3348 m_client->get_hostname());
3349 yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3350 m_session_str, m_client->m_pdu_recv,
3351 m_client->m_bytes_sent + m_client->m_bytes_recv,
3352 m_keepalive_limit_bw, m_keepalive_limit_pdu);
3353 assert (m_client->m_waiting != 2);
3354 // Tell client (if any) that no server connection is there..
3355 m_client->m_server = 0;
3360 yaz_log (YLOG_LOG, "%sShutdown (client to proxy) close %s",
3362 m_client->get_hostname());
3363 assert (m_client->m_waiting != 2);
3369 yaz_log (YLOG_LOG, "%sshutdown (client to proxy) bad state",
3375 yaz_log (YLOG_LOG, "%sShutdown (client to proxy)",
3379 m_parent->pre_init();
3382 bool Yaz_Proxy::dec_ref()
3384 m_http_keepalive = 0;
3387 if (m_ref_count > 0)
3396 const char *Yaz_ProxyClient::get_session_str()
3400 return m_server->get_session_str();
3403 void Yaz_ProxyClient::shutdown()
3405 yaz_log (YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
3410 m_waiting = 1; // ensure it's released from Yaz_Proxy::releaseClient
3411 m_server->dec_ref();
3417 void Yaz_Proxy::failNotify()
3420 yaz_log (YLOG_LOG, "%sConnection closed by client", get_session_str());
3424 void Yaz_Proxy::send_response_fail_client(const char *addr)
3428 Z_SRW_diagnostic *diagnostic = 0;
3429 int num_diagnostic = 0;
3431 yaz_add_srw_diagnostic(odr_encode(),
3432 &diagnostic, &num_diagnostic,
3433 YAZ_SRW_SYSTEM_TEMPORARILY_UNAVAILABLE, addr);
3434 if (m_s2z_search_apdu)
3435 send_srw_search_response(diagnostic, num_diagnostic);
3437 send_srw_explain_response(diagnostic, num_diagnostic);
3440 void Yaz_ProxyClient::failNotify()
3443 m_server->inc_request_no();
3444 yaz_log (YLOG_LOG, "%sConnection closed by target %s",
3445 get_session_str(), get_hostname());
3448 m_server->send_response_fail_client(get_hostname());
3452 void Yaz_ProxyClient::connectNotify()
3454 const char *s = get_session_str();
3455 const char *h = get_hostname();
3456 yaz_log (YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
3458 timeout(m_target_idletime);
3463 IPDU_Observer *Yaz_ProxyClient::sessionNotify(IPDU_Observable
3464 *the_PDU_Observable, int fd)
3466 return new Yaz_ProxyClient(the_PDU_Observable, 0);
3469 Yaz_ProxyClient::~Yaz_ProxyClient()
3474 m_next->m_prev = m_prev;
3475 m_waiting = 2; // for debugging purposes only.
3476 odr_destroy(m_init_odr);
3477 odr_destroy(m_idAuthentication_odr);
3478 delete m_last_query;
3479 xfree (m_last_resultSetId);
3483 void Yaz_ProxyClient::pre_init_client()
3485 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
3486 Z_InitRequest *req = apdu->u.initRequest;
3489 for (i = 0; i<= 24; i++)
3490 ODR_MASK_SET(req->options, i);
3491 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3492 Z_Options_negotiationModel);
3493 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3494 Z_Options_concurrentOperations);
3495 for (i = 0; i<= 10; i++)
3496 ODR_MASK_SET(req->protocolVersion, i);
3498 if (send_to_target(apdu) < 0)
3509 void Yaz_Proxy::pre_init()
3512 const char *name = 0;
3513 const char *zurl_in_use[MAX_ZURL_PLEX];
3514 int limit_bw, limit_pdu, limit_req, limit_search;
3515 int target_idletime, client_idletime;
3517 int keepalive_limit_bw, keepalive_limit_pdu;
3519 const char *cql2rpn = 0;
3520 const char *authentication = 0;
3521 const char *negotiation_charset = 0;
3522 const char *negotiation_lang = 0;
3524 Yaz_ProxyConfig *cfg = check_reconfigure();
3528 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
3533 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
3534 &limit_bw, &limit_pdu, &limit_req,
3536 &target_idletime, &client_idletime,
3538 &keepalive_limit_bw,
3539 &keepalive_limit_pdu,
3543 &negotiation_charset,
3551 for (j = 0; zurl_in_use[j]; j++)
3555 int spare_waiting = 0;
3558 for (c = m_clientPool; c; c = c->m_next)
3560 if (!strcmp(zurl_in_use[j], c->get_hostname()))
3562 if (c->m_cookie == 0)
3564 if (c->m_server == 0)
3576 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
3577 "sparew=%d preinit=%d",m_session_str,
3578 name, zurl_in_use[j], in_use, other,
3579 spare, spare_waiting, pre_init);
3580 if (spare + spare_waiting < pre_init)
3582 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
3583 c->m_next = m_clientPool;
3585 c->m_next->m_prev = &c->m_next;
3587 c->m_prev = &m_clientPool;
3589 if (m_log_mask & PROXY_LOG_APDU_SERVER)
3590 c->set_APDU_yazlog(1);
3592 c->set_APDU_yazlog(0);
3594 if (c->client(zurl_in_use[j]))
3602 c->m_target_idletime = target_idletime;
3603 c->m_seqno = m_seqno++;
3610 void Yaz_Proxy::timeoutNotify()
3615 switch(m_timeout_mode)
3617 case timeout_normal:
3621 yaz_log (YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
3624 case timeout_reduce:
3625 timeout(m_client_idletime);
3626 m_timeout_mode = timeout_busy;
3627 gdu = m_timeout_gdu;
3629 recv_GDU_normal(gdu);
3632 assert(m_stylesheet_nprl);
3633 convert_xsl_delay();
3634 recv_GDU_more(true);
3644 void Yaz_Proxy::markInvalid()
3647 m_flag_invalid_session = 1;
3650 void Yaz_ProxyClient::timeoutNotify()
3653 m_server->inc_request_no();
3655 yaz_log (YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
3659 m_server->send_response_fail_client(get_hostname());
3661 Yaz_Proxy *proxy_root = m_root;
3665 proxy_root->pre_init();
3668 Yaz_ProxyClient::Yaz_ProxyClient(IPDU_Observable *the_PDU_Observable,
3669 Yaz_Proxy *parent) :
3670 Z_Assoc (the_PDU_Observable)
3677 m_last_resultSetId = 0;
3678 m_last_resultCount = 0;
3682 m_init_odr = odr_createmem (ODR_DECODE);
3684 m_initResponse_options = 0;
3685 m_initResponse_version = 0;
3686 m_initResponse_preferredMessageSize = 0;
3687 m_initResponse_maximumRecordSize = 0;
3688 m_resultSetStartPoint = 0;
3689 m_bytes_sent = m_bytes_recv = 0;
3693 m_target_idletime = 600;
3695 m_idAuthentication_odr = odr_createmem(ODR_ENCODE);
3696 m_idAuthentication_ber_buf = 0;
3697 m_idAuthentication_ber_size = 0;
3700 const char *Yaz_Proxy::option(const char *name, const char *value)
3702 if (!strcmp (name, "optimize")) {
3705 m_optimize = xstrdup (value);
3712 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
3717 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
3719 if (apdu->which == Z_GDU_Z3950)
3720 recv_Z_PDU(apdu->u.z3950, len);
3721 else if (apdu->which == Z_GDU_HTTP_Response)
3722 recv_HTTP_response(apdu->u.HTTP_Response, len);
3727 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
3729 if (!m_flag_invalid_session)
3731 m_flag_invalid_session = 0;
3732 handle_incoming_Z_PDU(m_apdu_invalid_session);
3733 assert (m_mem_invalid_session);
3734 nmem_destroy(m_mem_invalid_session);
3735 m_mem_invalid_session = 0;
3739 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
3741 m_bytes_recv += len;
3745 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
3746 yaz_log (YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
3747 apdu_name(apdu), get_hostname(), len);
3748 if (apdu->which == Z_APDU_initResponse)
3750 if (!m_server) // if this is a pre init session , check for more
3752 NMEM nmem = odr_extract_mem (odr_decode());
3753 odr_reset (m_init_odr);
3754 nmem_transfer (m_init_odr->mem, nmem);
3755 m_initResponse = apdu;
3756 m_initResponse_options = apdu->u.initResponse->options;
3757 m_initResponse_version = apdu->u.initResponse->protocolVersion;
3758 m_initResponse_preferredMessageSize =
3759 *apdu->u.initResponse->preferredMessageSize;
3760 m_initResponse_maximumRecordSize =
3761 *apdu->u.initResponse->maximumRecordSize;
3763 Z_InitResponse *ir = apdu->u.initResponse;
3765 // apply YAZ Proxy version
3766 char *imv0 = ir->implementationVersion;
3767 char *imv1 = (char*)
3768 odr_malloc(m_init_odr, 20 + (imv0 ? strlen(imv0) : 0));
3773 strcat(imv1, "/" VERSION);
3775 ir->implementationVersion = imv1;
3777 // apply YAZ Proxy implementation name
3778 char *im0 = ir->implementationName;
3780 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
3787 strcat(im1, "(YAZ Proxy)");
3788 ir->implementationName = im1;
3790 nmem_destroy (nmem);
3792 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
3795 if (apdu->which == Z_APDU_searchResponse)
3797 Z_SearchResponse *sr = apdu->u.searchResponse;
3798 m_last_resultCount = *sr->resultCount;
3799 int status = *sr->searchStatus;
3800 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
3804 if (sr->records && sr->records->which == Z_Records_DBOSD)
3806 m_cache.add(odr_decode(),
3807 sr->records->u.databaseOrSurDiagnostics, 1,
3812 if (apdu->which == Z_APDU_presentResponse)
3814 Z_PresentResponse *pr = apdu->u.presentResponse;
3818 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
3819 Z_SearchResponse *sr = new_apdu->u.searchResponse;
3820 sr->referenceId = pr->referenceId;
3821 *sr->resultCount = m_last_resultCount;
3822 sr->records = pr->records;
3823 sr->nextResultSetPosition = pr->nextResultSetPosition;
3824 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
3828 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
3830 m_cache.add(odr_decode(),
3831 pr->records->u.databaseOrSurDiagnostics,
3832 m_resultSetStartPoint, -1);
3833 m_resultSetStartPoint = 0;
3837 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
3839 Yaz_Proxy *server = m_server; // save it. send_to_client may destroy us
3842 server->send_to_client(apdu);
3843 if (apdu->which == Z_APDU_close)
3846 server->recv_GDU_more(true);
3849 void Yaz_Proxy::low_socket_close()
3854 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3855 if (m_lo_fd[i] >= 0)
3856 ::close(m_lo_fd[i]);
3860 void Yaz_Proxy::low_socket_open()
3865 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3866 m_lo_fd[i] = open("/dev/null", O_RDONLY);
3870 int Yaz_Proxy::server(const char *addr)
3872 int r = Z_Assoc::server(addr);
3875 yaz_log(YLOG_LOG, "%sStarted proxy "
3879 " on %s", m_session_str, addr);
3885 void Yaz_Proxy::base64_decode(const char *base64, char *buf, int buf_len)
3887 const char *base64_chars =
3888 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3889 int len = strlen(base64);
3893 for (int pos = 0; pos <= len; pos++)
3895 if (base64[pos] == '=' || buf_pos + 1 >= buf_len)
3898 const char *ch_ptr = strchr(base64_chars, base64[pos]);
3901 char ch = (char) (ch_ptr - base64_chars);
3905 buf[buf_pos] = ch << 2;
3908 buf[buf_pos++] += (ch & 0x30) >> 4;
3909 buf[buf_pos] = (ch & 0x0f) << 4;
3912 buf[buf_pos++] += (ch & 0x3c) >> 2;
3913 buf[buf_pos] = (ch & 0x03) << 6;
3916 buf[buf_pos++] += ch;
3923 buf[buf_pos] = '\0';
3929 * indent-tabs-mode: nil
3931 * vim: shiftwidth=4 tabstop=8 expandtab