1 /* $Id: yaz-proxy.cpp,v 1.68 2006-06-09 09:35:14 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 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1150 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1154 int r = send_GDU(gdu, &len);
1155 m_bytes_sent += len;
1156 m_bw_stat.add_bytes(len);
1159 recv_GDU_more(true);
1164 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu, int http_code /* = 200 */)
1166 ODR o = odr_encode();
1167 const char *ctype = "text/xml";
1168 Z_GDU *gdu = z_get_HTTP_Response(o, http_code);
1169 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1171 hres->version = odr_strdup(o, m_http_version);
1172 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1173 if (m_http_keepalive)
1174 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1177 if (http_code == 401)
1178 z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate", "Basic realm=\"YAZ Proxy\"");
1180 static Z_SOAP_Handler soap_handlers[2] = {
1182 {"http://www.loc.gov/zing/srw/", 0,
1183 (Z_SOAP_fun) yaz_srw_codec},
1188 Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
1189 soap_package->which = Z_SOAP_generic;
1190 soap_package->u.generic =
1191 (Z_SOAP_Generic *) odr_malloc(o, sizeof(*soap_package->u.generic));
1192 soap_package->u.generic->no = 0;
1193 soap_package->u.generic->ns = soap_handlers[0].ns;
1194 soap_package->u.generic->p = (void *) srw_pdu;
1195 soap_package->ns = m_soap_ns;
1196 z_soap_codec_enc_xsl(o, &soap_package,
1197 &hres->content_buf, &hres->content_len,
1198 soap_handlers, 0, m_s2z_stylesheet);
1199 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1201 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1205 int r = send_GDU(gdu, &len);
1206 m_bytes_sent += len;
1207 m_bw_stat.add_bytes(len);
1210 recv_GDU_more(true);
1215 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
1217 ODR o = odr_encode();
1218 Z_SRW_diagnostic *diagnostic = (Z_SRW_diagnostic *)
1219 odr_malloc(o, sizeof(*diagnostic));
1220 int num_diagnostic = 1;
1221 yaz_mk_std_diagnostic(o, diagnostic, srw_error, add);
1222 return send_srw_search_response(diagnostic, num_diagnostic, srw_error == 3 ? 401 : 200);
1225 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
1226 Z_DefaultDiagFormat *ddf)
1228 int bib1_code = *ddf->condition;
1229 if (bib1_code == 109)
1231 srw_res->num_diagnostics = 1;
1232 srw_res->diagnostics = (Z_SRW_diagnostic *)
1233 odr_malloc(o, sizeof(*srw_res->diagnostics));
1234 yaz_mk_std_diagnostic(o, srw_res->diagnostics,
1235 yaz_diag_bib1_to_srw(*ddf->condition),
1240 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
1242 ODR o = odr_encode();
1243 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1244 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1246 srw_res->numberOfRecords = odr_intdup (o, hits);
1247 if (records && records->which == Z_Records_DBOSD)
1249 srw_res->num_records =
1250 records->u.databaseOrSurDiagnostics->num_records;
1252 srw_res->records = (Z_SRW_record *)
1253 odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
1254 for (i = 0; i < srw_res->num_records; i++)
1256 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
1257 if (npr->which != Z_NamePlusRecord_databaseRecord)
1259 srw_res->records[i].recordSchema = "diagnostic";
1260 srw_res->records[i].recordPacking = m_s2z_packing;
1261 srw_res->records[i].recordData_buf = "67";
1262 srw_res->records[i].recordData_len = 2;
1263 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1266 Z_External *r = npr->u.databaseRecord;
1267 oident *ent = oid_getentbyoid(r->direct_reference);
1268 if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
1270 srw_res->records[i].recordSchema = m_schema;
1271 srw_res->records[i].recordPacking = m_s2z_packing;
1272 srw_res->records[i].recordData_buf = (char*)
1273 r->u.octet_aligned->buf;
1274 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1275 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1279 srw_res->records[i].recordSchema = "diagnostic";
1280 srw_res->records[i].recordPacking = m_s2z_packing;
1281 srw_res->records[i].recordData_buf = "67";
1282 srw_res->records[i].recordData_len = 2;
1283 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1287 if (records && records->which == Z_Records_NSD)
1290 http_code = z_to_srw_diag(odr_encode(), srw_res,
1291 records->u.nonSurrogateDiagnostic);
1293 return send_http_response(http_code);
1295 return send_srw_response(srw_pdu);
1299 int Yaz_Proxy::send_srw_search_response(Z_SRW_diagnostic *diagnostics,
1300 int num_diagnostics, int http_code /* = 200 */)
1302 ODR o = odr_encode();
1303 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1304 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1306 srw_res->num_diagnostics = num_diagnostics;
1307 srw_res->diagnostics = diagnostics;
1308 return send_srw_response(srw_pdu, http_code);
1311 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1312 int num_diagnostics)
1314 Yaz_ProxyConfig *cfg = check_reconfigure();
1318 char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1319 m_s2z_database, &len);
1322 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1323 Z_SRW_explainResponse *er = res->u.explain_response;
1325 er->record.recordData_buf = b;
1326 er->record.recordData_len = len;
1327 er->record.recordPacking = m_s2z_packing;
1328 er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
1330 er->diagnostics = diagnostics;
1331 er->num_diagnostics = num_diagnostics;
1332 return send_srw_response(res);
1335 return send_http_response(404);
1338 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1342 if (apdu->which == Z_APDU_initResponse)
1344 Z_InitResponse *res = apdu->u.initResponse;
1345 if (*res->result == 0)
1347 send_to_srw_client_error(3, 0);
1349 else if (!m_s2z_search_apdu)
1351 send_srw_explain_response(0, 0);
1355 handle_incoming_Z_PDU(m_s2z_search_apdu);
1358 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1360 m_s2z_search_apdu = 0;
1361 Z_SearchResponse *res = apdu->u.searchResponse;
1362 m_s2z_hit_count = *res->resultCount;
1363 if (res->records && res->records->which == Z_Records_NSD)
1365 send_to_srw_client_ok(0, res->records, 1);
1367 else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1370 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1372 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1374 if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1376 *pr->numberOfRecordsRequested =
1377 1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1379 handle_incoming_Z_PDU(m_s2z_present_apdu);
1383 m_s2z_present_apdu = 0;
1384 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1387 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1390 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1392 m_s2z_present_apdu = 0;
1393 Z_PresentResponse *res = apdu->u.presentResponse;
1394 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1400 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1401 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1403 int r = send_Z_PDU(apdu, &len);
1404 m_bytes_sent += len;
1405 m_bw_stat.add_bytes(len);
1412 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1414 int kill_session = 0;
1415 Z_ReferenceId **new_id = get_referenceIdP(apdu);
1418 *new_id = m_referenceId;
1420 if (apdu->which == Z_APDU_searchResponse)
1422 Z_SearchResponse *sr = apdu->u.searchResponse;
1423 Z_Records *p = sr->records;
1424 if (p && p->which == Z_Records_NSD)
1426 Z_DiagRec dr, *dr_p = &dr;
1427 dr.which = Z_DiagRec_defaultFormat;
1428 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1430 *sr->searchStatus = 0;
1431 display_diagrecs(&dr_p, 1);
1435 if (p && p->which == Z_Records_DBOSD)
1439 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1442 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1443 if (m_marcxml_mode == marcxml)
1444 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1447 convert_records_charset(p->u.databaseOrSurDiagnostics,
1449 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1453 if (sr->resultCount)
1455 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1457 if (*sr->resultCount < 0)
1459 m_flag_invalid_session = 1;
1462 *sr->searchStatus = 0;
1464 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1465 *sr->resultCount = 0;
1470 else if (apdu->which == Z_APDU_presentResponse)
1472 Z_PresentResponse *sr = apdu->u.presentResponse;
1473 Z_Records *p = sr->records;
1474 if (p && p->which == Z_Records_NSD)
1476 Z_DiagRec dr, *dr_p = &dr;
1477 dr.which = Z_DiagRec_defaultFormat;
1478 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1479 if (*sr->presentStatus == Z_PresentStatus_success)
1480 *sr->presentStatus = Z_PresentStatus_failure;
1481 display_diagrecs(&dr_p, 1);
1483 if (p && p->which == Z_Records_DBOSD)
1487 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1490 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1491 if (m_marcxml_mode == marcxml)
1492 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1495 convert_records_charset(p->u.databaseOrSurDiagnostics,
1497 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1501 else if (apdu->which == Z_APDU_initResponse)
1503 //Get and check negotiation record
1504 //from init response.
1505 handle_charset_lang_negotiation(apdu);
1507 if (m_initRequest_options)
1510 (Odr_bitmask *)odr_malloc(odr_encode(),
1511 sizeof(Odr_bitmask));
1512 ODR_MASK_ZERO(nopt);
1515 for (i = 0; i<24; i++)
1516 if (ODR_MASK_GET(m_initRequest_options, i) &&
1517 ODR_MASK_GET(apdu->u.initResponse->options, i))
1518 ODR_MASK_SET(nopt, i);
1519 apdu->u.initResponse->options = nopt;
1521 if (m_initRequest_version)
1523 Z_ProtocolVersion *nopt =
1524 (Odr_bitmask *)odr_malloc(odr_encode(),
1525 sizeof(Odr_bitmask));
1526 ODR_MASK_ZERO(nopt);
1529 for (i = 0; i<8; i++)
1530 if (ODR_MASK_GET(m_initRequest_version, i) &&
1531 ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1532 ODR_MASK_SET(nopt, i);
1533 apdu->u.initResponse->protocolVersion = nopt;
1535 apdu->u.initResponse->preferredMessageSize =
1536 odr_intdup(odr_encode(),
1537 m_client->m_initResponse_preferredMessageSize >
1538 m_initRequest_preferredMessageSize ?
1539 m_initRequest_preferredMessageSize :
1540 m_client->m_initResponse_preferredMessageSize);
1541 apdu->u.initResponse->maximumRecordSize =
1542 odr_intdup(odr_encode(),
1543 m_client->m_initResponse_maximumRecordSize >
1544 m_initRequest_maximumRecordSize ?
1545 m_initRequest_maximumRecordSize :
1546 m_client->m_initResponse_maximumRecordSize);
1549 int r = send_PDU_convert(apdu);
1556 m_parent->pre_init();
1561 void Yaz_ProxyClient::set_idAuthentication(Z_APDU *apdu)
1563 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1565 odr_reset(m_idAuthentication_odr);
1566 z_IdAuthentication(m_idAuthentication_odr, &t, 1, 0);
1567 m_idAuthentication_ber_buf =
1568 odr_getbuf(m_idAuthentication_odr,
1569 &m_idAuthentication_ber_size, 0);
1572 bool Yaz_ProxyClient::compare_charset(Z_APDU *apdu)
1577 bool Yaz_ProxyClient::compare_idAuthentication(Z_APDU *apdu)
1579 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1580 ODR odr = odr_createmem(ODR_ENCODE);
1582 z_IdAuthentication(odr, &t, 1, 0);
1584 char *buf = odr_getbuf(odr, &sz, 0);
1585 if (buf && m_idAuthentication_ber_buf
1586 && sz == m_idAuthentication_ber_size
1587 && !memcmp(m_idAuthentication_ber_buf, buf, sz))
1593 if (!buf && !m_idAuthentication_ber_buf)
1598 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1601 const char *apdu_name_tmp = apdu_name(apdu);
1602 int r = send_Z_PDU(apdu, &len);
1603 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1604 yaz_log (YLOG_LOG, "%sSending %s to %s %d bytes",
1606 apdu_name_tmp, get_hostname(), len);
1607 m_bytes_sent += len;
1611 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1613 if (apdu->which == Z_APDU_presentRequest)
1615 Z_PresentRequest *pr = apdu->u.presentRequest;
1616 int toget = *pr->numberOfRecordsRequested;
1617 int start = *pr->resultSetStartPoint;
1619 yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1620 pr->resultSetId, start, toget);
1622 if (*m_parent->m_optimize == '0')
1625 if (!m_client->m_last_resultSetId)
1627 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1628 new_apdu->u.presentResponse->records =
1629 create_nonSurrogateDiagnostics(
1631 YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
1633 send_to_client(new_apdu);
1636 if (start < 1 || toget < 0)
1638 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1639 new_apdu->u.presentResponse->records =
1640 create_nonSurrogateDiagnostics(
1642 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1644 send_to_client(new_apdu);
1647 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1649 if (start+toget-1 > m_client->m_last_resultCount)
1651 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1652 new_apdu->u.presentResponse->records =
1653 create_nonSurrogateDiagnostics(
1655 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
1657 send_to_client(new_apdu);
1660 Z_NamePlusRecordList *npr;
1662 yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1663 m_session_str, start, toget, yaz_z3950oid_to_str(
1664 pr->preferredRecordSyntax, &oclass));
1666 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1667 pr->preferredRecordSyntax,
1668 pr->recordComposition))
1670 yaz_log (YLOG_LOG, "%sReturned cached records for present request",
1672 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1673 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1675 new_apdu->u.presentResponse->numberOfRecordsReturned
1676 = odr_intdup(odr_encode(), toget);
1678 new_apdu->u.presentResponse->records = (Z_Records*)
1679 odr_malloc(odr_encode(), sizeof(Z_Records));
1680 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1681 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1682 new_apdu->u.presentResponse->nextResultSetPosition =
1683 odr_intdup(odr_encode(), start+toget);
1685 send_to_client(new_apdu);
1691 if (apdu->which != Z_APDU_searchRequest)
1693 Z_SearchRequest *sr = apdu->u.searchRequest;
1694 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1695 Yaz_Z_Databases this_databases;
1697 this_databases.set(sr->num_databaseNames, (const char **)
1700 this_query->set_Z_Query(sr->query);
1702 // Check for non-negative piggyback params.
1703 if (*sr->smallSetUpperBound < 0
1704 || *sr->largeSetLowerBound < 0
1705 || *sr->mediumSetPresentNumber < 0)
1707 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1708 // Not a present request.. But can't find better diagnostic
1709 new_apdu->u.searchResponse->records =
1710 create_nonSurrogateDiagnostics(
1712 YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE, 0);
1713 send_to_client(new_apdu);
1717 char query_str[120];
1718 this_query->print(query_str, sizeof(query_str)-1);
1719 yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1721 if (*m_parent->m_optimize != '0' &&
1722 m_client->m_last_ok && m_client->m_last_query &&
1723 m_client->m_last_query->match(this_query) &&
1724 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1725 m_client->m_last_databases.match(this_databases))
1728 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1729 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1731 Z_NamePlusRecordList *npr;
1732 int toget = *sr->mediumSetPresentNumber;
1733 Z_RecordComposition *comp = 0;
1735 if (toget > m_client->m_last_resultCount)
1736 toget = m_client->m_last_resultCount;
1738 if (sr->mediumSetElementSetNames)
1740 comp = (Z_RecordComposition *)
1741 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1742 comp->which = Z_RecordComp_simple;
1743 comp->u.simple = sr->mediumSetElementSetNames;
1746 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1747 sr->preferredRecordSyntax, comp))
1749 yaz_log (YLOG_LOG, "%sReturned cached records for medium set",
1751 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1752 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1753 new_apdu->u.searchResponse->resultCount =
1754 &m_client->m_last_resultCount;
1756 new_apdu->u.searchResponse->numberOfRecordsReturned
1757 = odr_intdup(odr_encode(), toget);
1759 new_apdu->u.searchResponse->presentStatus =
1760 odr_intdup(odr_encode(), Z_PresentStatus_success);
1761 new_apdu->u.searchResponse->records = (Z_Records*)
1762 odr_malloc(odr_encode(), sizeof(Z_Records));
1763 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1764 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1765 new_apdu->u.searchResponse->nextResultSetPosition =
1766 odr_intdup(odr_encode(), toget+1);
1767 send_to_client(new_apdu);
1773 // send present request (medium size)
1774 yaz_log (YLOG_LOG, "%sOptimizing search for medium set",
1777 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1778 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1779 pr->referenceId = sr->referenceId;
1780 pr->resultSetId = sr->resultSetName;
1781 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1782 *pr->numberOfRecordsRequested = toget;
1783 pr->recordComposition = comp;
1784 m_client->m_sr_transform = 1;
1788 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1789 m_client->m_last_resultCount <= 0)
1791 // large set. Return pseudo-search response immediately
1792 yaz_log (YLOG_LOG, "%sOptimizing search for large set",
1794 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1795 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1796 new_apdu->u.searchResponse->resultCount =
1797 &m_client->m_last_resultCount;
1798 send_to_client(new_apdu);
1803 Z_NamePlusRecordList *npr;
1804 int toget = m_client->m_last_resultCount;
1805 Z_RecordComposition *comp = 0;
1807 // send a present request (small set)
1809 if (sr->smallSetElementSetNames)
1811 comp = (Z_RecordComposition *)
1812 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1813 comp->which = Z_RecordComp_simple;
1814 comp->u.simple = sr->smallSetElementSetNames;
1817 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1818 sr->preferredRecordSyntax, comp))
1820 yaz_log (YLOG_LOG, "%sReturned cached records for small set",
1822 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1823 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1824 new_apdu->u.searchResponse->resultCount =
1825 &m_client->m_last_resultCount;
1827 new_apdu->u.searchResponse->numberOfRecordsReturned
1828 = odr_intdup(odr_encode(), toget);
1830 new_apdu->u.searchResponse->presentStatus =
1831 odr_intdup(odr_encode(), Z_PresentStatus_success);
1832 new_apdu->u.searchResponse->records = (Z_Records*)
1833 odr_malloc(odr_encode(), sizeof(Z_Records));
1834 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1835 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1836 new_apdu->u.searchResponse->nextResultSetPosition =
1837 odr_intdup(odr_encode(), toget+1);
1838 send_to_client(new_apdu);
1843 yaz_log (YLOG_LOG, "%sOptimizing search for small set",
1845 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1846 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1847 pr->referenceId = sr->referenceId;
1848 pr->resultSetId = sr->resultSetName;
1849 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1850 *pr->numberOfRecordsRequested = toget;
1851 pr->recordComposition = comp;
1852 m_client->m_sr_transform = 1;
1857 else // query doesn't match
1859 delete m_client->m_last_query;
1860 m_client->m_last_query = this_query;
1861 m_client->m_last_ok = 0;
1862 m_client->m_cache.clear();
1863 m_client->m_resultSetStartPoint = 0;
1865 xfree (m_client->m_last_resultSetId);
1866 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1868 m_client->m_last_databases.set(sr->num_databaseNames,
1869 (const char **) sr->databaseNames);
1875 void Yaz_Proxy::inc_request_no()
1878 char *cp = m_session_str + strlen(m_session_str)-1;
1881 while (*cp && *cp != ' ')
1884 sprintf(cp+1, "%d ", m_request_no);
1887 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1891 m_bytes_recv += len;
1893 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1894 yaz_log (YLOG_LOG, "%sReceiving %s from client %d bytes",
1895 m_session_str, gdu_name(apdu), len);
1898 // try to make a _bad_ attribute set ID .. Don't enable this in prod.
1899 if (apdu->which == Z_GDU_Z3950
1900 && apdu->u.z3950->which == Z_APDU_searchRequest)
1902 Z_SearchRequest *req = apdu->u.z3950->u.searchRequest;
1903 if (req->query && req->query->which == Z_Query_type_1)
1905 Z_RPNQuery *rpnquery = req->query->u.type_1;
1906 if (rpnquery->attributeSetId)
1908 rpnquery->attributeSetId[0] = -2;
1909 rpnquery->attributeSetId[1] = -1;
1910 yaz_log(YLOG_WARN, "%sBAD FIXUP TEST", m_session_str);
1916 #if HAVE_GETTIMEOFDAY
1917 gettimeofday((struct timeval *) m_time_tv, 0);
1919 m_bw_stat.add_bytes(len);
1920 m_pdu_stat.add_bytes(1);
1922 GDU *gdu = new GDU(apdu);
1924 if (gdu->get() == 0)
1927 yaz_log(YLOG_LOG, "%sUnable to encode package", m_session_str);
1932 m_in_queue.enqueue(gdu);
1933 recv_GDU_more(false);
1936 void Yaz_Proxy::HTTP_Forwarded(Z_GDU *z_gdu)
1938 if (z_gdu->which == Z_GDU_HTTP_Request)
1940 Z_HTTP_Request *hreq = z_gdu->u.HTTP_Request;
1941 const char *x_forwarded_for =
1942 z_HTTP_header_lookup(hreq->headers, "X-Forwarded-For");
1943 if (x_forwarded_for)
1946 m_peername = (char*) xmalloc(strlen(x_forwarded_for)+5);
1947 sprintf(m_peername, "tcp:%s", x_forwarded_for);
1949 yaz_log(YLOG_LOG, "%sHTTP Forwarded from %s", m_session_str,
1951 if (m_log_mask & PROXY_LOG_IP_CLIENT)
1952 sprintf(m_session_str, "%ld:%d %.80s %d ",
1953 (long) time(0), m_session_no, m_peername, m_request_no);
1955 sprintf(m_session_str, "%ld:%d %d ",
1956 (long) time(0), m_session_no, m_request_no);
1961 void Yaz_Proxy::connect_stat(bool &block, int &reduce)
1964 m_parent->m_connect.cleanup(false);
1965 m_parent->m_connect.add_connect(m_peername);
1967 int connect_total = m_parent->m_connect.get_total(m_peername);
1968 int max_connect = m_parent->m_max_connect;
1970 if (max_connect && connect_total > max_connect)
1972 yaz_log(YLOG_LOG, "%sconnect not accepted total=%d max=%d",
1973 m_session_str, connect_total, max_connect);
1978 yaz_log(YLOG_LOG, "%sconnect accepted total=%d", m_session_str,
1981 int limit_connect = m_parent->m_limit_connect;
1983 reduce = connect_total / limit_connect;
1988 void Yaz_Proxy::recv_GDU_reduce(GDU *gdu)
1990 HTTP_Forwarded(gdu->get());
1994 if (m_request_no == 1)
1998 connect_stat(block, reduce);
2002 m_timeout_mode = timeout_busy;
2008 int bw_total = m_bw_stat.get_total();
2009 int pdu_total = m_pdu_stat.get_total();
2010 int search_total = m_search_stat.get_total();
2012 assert(m_timeout_mode == timeout_busy);
2013 assert(m_timeout_gdu == 0);
2016 reduce += search_total / m_search_max;
2018 reduce += (bw_total/m_bw_max);
2021 if (pdu_total > m_pdu_max)
2023 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
2024 reduce = (reduce > nreduce) ? reduce : nreduce;
2030 /* uncomment to force a big reduce */
2031 m_timeout_mode = timeout_reduce;
2032 m_timeout_gdu = gdu;
2033 timeout(3); // call us reduce seconds later
2038 yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d search=%d limit-bw=%d limit-pdu=%d limit-search=%d",
2039 m_session_str, reduce, bw_total, pdu_total, search_total,
2040 m_bw_max, m_pdu_max, m_search_max);
2042 m_timeout_mode = timeout_reduce;
2043 m_timeout_gdu = gdu;
2044 timeout(reduce); // call us reduce seconds later
2047 recv_GDU_normal(gdu);
2050 void Yaz_Proxy::recv_GDU_more(bool normal)
2053 if (normal && m_timeout_mode == timeout_busy)
2054 m_timeout_mode = timeout_normal;
2055 while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
2057 m_timeout_mode = timeout_busy;
2065 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
2068 gdu->move_away_gdu(odr_decode(), &apdu);
2071 if (apdu->which == Z_GDU_Z3950)
2072 handle_incoming_Z_PDU(apdu->u.z3950);
2073 else if (apdu->which == Z_GDU_HTTP_Request)
2074 handle_incoming_HTTP(apdu->u.HTTP_Request);
2077 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
2079 if (m_max_record_retrieve)
2081 if (apdu->which == Z_APDU_presentRequest)
2083 Z_PresentRequest *pr = apdu->u.presentRequest;
2084 if (pr->numberOfRecordsRequested &&
2085 *pr->numberOfRecordsRequested > m_max_record_retrieve)
2086 *pr->numberOfRecordsRequested = m_max_record_retrieve;
2091 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
2093 if (apdu->which == Z_APDU_initRequest)
2095 if (m_initRequest_options &&
2096 !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
2097 (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
2099 // There is no negotiation proposal from
2100 // client's side. OK. The proxy negotiation
2102 Z_InitRequest *initRequest = apdu->u.initRequest;
2103 Z_OtherInformation **otherInfo;
2104 Z_OtherInformationUnit *oi;
2105 get_otherInfoAPDU(apdu, &otherInfo);
2106 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2109 ODR_MASK_SET(initRequest->options,
2110 Z_Options_negotiationModel);
2111 oi->which = Z_OtherInfo_externallyDefinedInfo;
2112 oi->information.externallyDefinedInfo =
2113 yaz_set_proposal_charneg(odr_encode(),
2114 (const char**)&m_proxy_negotiation_charset,
2115 m_proxy_negotiation_charset ? 1:0,
2116 (const char**)&m_proxy_negotiation_lang,
2117 m_proxy_negotiation_lang ? 1:0,
2121 else if (m_initRequest_options &&
2122 ODR_MASK_GET(m_initRequest_options,
2123 Z_Options_negotiationModel) &&
2124 m_charset_converter->get_target_query_charset())
2126 yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
2128 m_charset_converter->get_target_query_charset());
2129 Z_InitRequest *initRequest = apdu->u.initRequest;
2130 Z_CharSetandLanguageNegotiation *negotiation =
2131 yaz_get_charneg_record (initRequest->otherInfo);
2133 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
2135 NMEM nmem = nmem_create();
2136 char **charsets = 0;
2137 int num_charsets = 0;
2141 yaz_get_proposal_charneg (nmem, negotiation,
2142 &charsets, &num_charsets,
2143 &langs, &num_langs, &selected);
2145 for (i = 0; i<num_charsets; i++)
2146 yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
2148 for (i = 0; i<num_langs; i++)
2149 yaz_log(YLOG_LOG, "%slang %s", m_session_str,
2152 const char *t_charset =
2153 m_charset_converter->get_target_query_charset();
2154 // sweep through charsets and pick the first supported
2156 for (i = 0; i<num_charsets; i++)
2158 const char *c_charset = charsets[i];
2159 if (!odr_set_charset(odr_decode(), t_charset, c_charset))
2162 if (i != num_charsets)
2164 // got one .. set up ODR for reverse direction
2165 const char *c_charset = charsets[i];
2166 odr_set_charset(odr_encode(), c_charset, t_charset);
2167 m_charset_converter->set_client_query_charset(c_charset);
2168 m_charset_converter->set_client_charset_selected(selected);
2171 ODR_MASK_CLEAR(m_initRequest_options,
2172 Z_Options_negotiationModel);
2173 yaz_del_charneg_record(&initRequest->otherInfo);
2177 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
2181 else if (m_charset_converter->get_target_query_charset() &&
2182 m_proxy_negotiation_default_charset)
2184 m_charset_converter->
2185 set_client_query_charset(m_proxy_negotiation_default_charset);
2188 else if (apdu->which == Z_APDU_initResponse)
2190 Z_InitResponse *initResponse = apdu->u.initResponse;
2191 Z_OtherInformation **otherInfo;
2192 get_otherInfoAPDU(apdu, &otherInfo);
2194 Z_CharSetandLanguageNegotiation *charneg = 0;
2196 if (otherInfo && *otherInfo &&
2197 ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel)
2198 && (charneg = yaz_get_charneg_record(*otherInfo)))
2204 yaz_get_response_charneg(m_referenceId_mem, charneg,
2205 &charset, &lang, &selected);
2207 yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
2208 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
2210 if (m_initRequest_options &&
2211 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
2213 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2216 else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2218 // negotiation-charset, negotiation-lang
2219 // elements of config file in use.
2221 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2224 // clear negotiation option.
2225 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2227 // Delete negotiation (charneg-3) entry.
2228 yaz_del_charneg_record(otherInfo);
2233 if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2235 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2238 else if (m_charset_converter->get_client_query_charset())
2240 Z_OtherInformation **otherInfo;
2241 Z_OtherInformationUnit *oi;
2242 get_otherInfoAPDU(apdu, &otherInfo);
2243 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2246 ODR_MASK_SET(initResponse->options,
2247 Z_Options_negotiationModel);
2248 if (m_initRequest_options)
2249 ODR_MASK_SET(m_initRequest_options,
2250 Z_Options_negotiationModel);
2252 oi->which = Z_OtherInfo_externallyDefinedInfo;
2253 oi->information.externallyDefinedInfo =
2254 yaz_set_response_charneg(
2256 m_charset_converter->get_client_query_charset(),
2258 m_charset_converter->get_client_charset_selected());
2265 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2267 const char *addinfo)
2269 Z_Records *rec = (Z_Records *)
2270 odr_malloc (odr, sizeof(*rec));
2272 odr_malloc (odr, sizeof(*err));
2273 Z_DiagRec *drec = (Z_DiagRec *)
2274 odr_malloc (odr, sizeof(*drec));
2275 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2276 odr_malloc (odr, sizeof(*dr));
2278 rec->which = Z_Records_NSD;
2279 rec->u.nonSurrogateDiagnostic = dr;
2280 dr->diagnosticSetId =
2281 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
2282 dr->condition = err;
2283 dr->which = Z_DefaultDiagFormat_v2Addinfo;
2284 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2288 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2290 if (apdu->which == Z_APDU_searchRequest &&
2291 apdu->u.searchRequest->query &&
2292 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2293 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2295 Z_RPNQuery *rpnquery = 0;
2296 Z_SearchRequest *sr = apdu->u.searchRequest;
2299 yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2300 sr->query->u.type_104->u.cql);
2302 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2303 &rpnquery, odr_encode(),
2306 yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2309 yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2310 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2312 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2313 new_apdu->u.searchResponse->records =
2314 create_nonSurrogateDiagnostics(odr_encode(),
2315 yaz_diag_srw_to_bib1(r),
2317 *new_apdu->u.searchResponse->searchStatus = 0;
2319 send_to_client(new_apdu);
2325 sr->query->which = Z_Query_type_1;
2326 sr->query->u.type_1 = rpnquery;
2333 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2335 if (apdu->which == Z_APDU_searchRequest &&
2336 apdu->u.searchRequest->query)
2338 if (apdu->u.searchRequest->query->which == Z_Query_type_1
2339 || apdu->u.searchRequest->query->which == Z_Query_type_101)
2342 m_charset_converter->set_client_query_charset("UTF-8");
2343 Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2344 m_charset_converter->convert_type_1(rpnquery, odr_encode());
2351 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2353 if (apdu->which == Z_APDU_searchRequest)
2355 Z_SearchRequest *sr = apdu->u.searchRequest;
2359 Yaz_ProxyConfig *cfg = check_reconfigure();
2361 err = cfg->check_query(odr_encode(), m_default_target,
2362 sr->query, &addinfo);
2365 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2367 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2368 new_apdu->u.searchResponse->records =
2369 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2370 *new_apdu->u.searchResponse->searchStatus = 0;
2372 send_to_client(new_apdu);
2380 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2382 if (apdu->which != Z_APDU_initRequest)
2383 return 1; // pass if no init request
2384 Z_InitRequest *req = apdu->u.initRequest;
2386 Yaz_ProxyConfig *cfg = check_reconfigure();
2388 return 1; // pass if no config
2391 if (req->idAuthentication == 0)
2393 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2396 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2398 ret = cfg->client_authentication(
2400 req->idAuthentication->u.idPass->userId,
2401 req->idAuthentication->u.idPass->groupId,
2402 req->idAuthentication->u.idPass->password,
2405 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2407 char user[64], pass[64];
2410 sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2411 ret = cfg->client_authentication(m_default_target, user, 0, pass,
2415 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2420 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2422 m_marcxml_mode = none;
2423 if (apdu->which == Z_APDU_searchRequest)
2425 Z_SearchRequest *sr = apdu->u.searchRequest;
2428 Yaz_ProxyConfig *cfg = check_reconfigure();
2430 Z_RecordComposition rc_temp, *rc = 0;
2431 if (sr->smallSetElementSetNames)
2433 rc_temp.which = Z_RecordComp_simple;
2434 rc_temp.u.simple = sr->smallSetElementSetNames;
2438 if (sr->preferredRecordSyntax)
2441 ent = oid_getentbyoid(sr->preferredRecordSyntax);
2442 m_frontend_type = ent->value;
2445 m_frontend_type = VAL_NONE;
2447 char *stylesheet_name = 0;
2449 err = cfg->check_syntax(odr_encode(),
2451 sr->preferredRecordSyntax, rc,
2452 &addinfo, &stylesheet_name, &m_schema,
2453 &m_backend_type, &m_backend_charset,
2454 &m_usemarcon_ini_stage1,
2455 &m_usemarcon_ini_stage2);
2456 if (stylesheet_name)
2458 m_parent->low_socket_close();
2461 if (m_stylesheet_xsp)
2462 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2463 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2466 m_stylesheet_offset = 0;
2467 xfree(stylesheet_name);
2469 m_parent->low_socket_open();
2473 sr->smallSetElementSetNames = 0;
2474 sr->mediumSetElementSetNames = 0;
2475 m_marcxml_mode = marcxml;
2479 sr->preferredRecordSyntax =
2480 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2484 sr->preferredRecordSyntax =
2485 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2490 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2492 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2493 new_apdu->u.searchResponse->records =
2494 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2495 *new_apdu->u.searchResponse->searchStatus = 0;
2497 send_to_client(new_apdu);
2501 else if (m_backend_type)
2503 sr->preferredRecordSyntax =
2504 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2507 else if (apdu->which == Z_APDU_presentRequest)
2509 Z_PresentRequest *pr = apdu->u.presentRequest;
2512 Yaz_ProxyConfig *cfg = check_reconfigure();
2514 if (pr->preferredRecordSyntax)
2517 ent = oid_getentbyoid(pr->preferredRecordSyntax);
2518 m_frontend_type = ent->value;
2521 m_frontend_type = VAL_NONE;
2523 char *stylesheet_name = 0;
2525 err = cfg->check_syntax(odr_encode(), m_default_target,
2526 pr->preferredRecordSyntax,
2527 pr->recordComposition,
2528 &addinfo, &stylesheet_name, &m_schema,
2529 &m_backend_type, &m_backend_charset,
2530 &m_usemarcon_ini_stage1,
2531 &m_usemarcon_ini_stage2
2533 if (stylesheet_name)
2535 m_parent->low_socket_close();
2538 if (m_stylesheet_xsp)
2539 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2540 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2543 m_stylesheet_offset = 0;
2544 xfree(stylesheet_name);
2546 m_parent->low_socket_open();
2550 pr->recordComposition = 0;
2551 m_marcxml_mode = marcxml;
2555 pr->preferredRecordSyntax =
2556 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2560 pr->preferredRecordSyntax =
2561 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2566 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2568 new_apdu->u.presentResponse->referenceId = pr->referenceId;
2569 new_apdu->u.presentResponse->records =
2570 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2571 *new_apdu->u.presentResponse->presentStatus =
2572 Z_PresentStatus_failure;
2574 send_to_client(new_apdu);
2578 else if (m_backend_type)
2580 pr->preferredRecordSyntax =
2581 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2587 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2591 Z_ElementSetNames *esn = (Z_ElementSetNames *)
2592 odr_malloc(o, sizeof(Z_ElementSetNames));
2593 esn->which = Z_ElementSetNames_generic;
2594 esn->u.generic = odr_strdup(o, schema);
2598 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2601 Yaz_ProxyConfig *cfg = check_reconfigure();
2603 t = cfg->get_explain_name(db, backend_db);
2605 if (m_client && m_default_target && t && strcmp(m_default_target, t))
2612 xfree(m_default_target);
2613 m_default_target = xstrdup(t);
2617 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2620 if (strcmp(hreq->method, "GET"))
2622 if (hreq->path[0] != '/')
2624 const char *cp = hreq->path;
2627 if (*cp == '/' && strchr("/.", cp[1]))
2632 Yaz_ProxyConfig *cfg = check_reconfigure();
2634 if (!cfg->get_file_access_info(hreq->path+1))
2637 const char *fname = hreq->path+1;
2638 if (stat(fname, &sbuf))
2640 yaz_log(YLOG_LOG|YLOG_ERRNO, "%sstat failed for %s", m_session_str,
2644 if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2646 yaz_log(YLOG_LOG, "%sNot a regular file %s", m_session_str, fname);
2649 if (sbuf.st_size > (off_t) 1000000)
2651 yaz_log(YLOG_WARN, "%sFile %s too large for transfer", m_session_str,
2656 ODR o = odr_encode();
2658 const char *ctype = cfg->check_mime_type(fname);
2659 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2660 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2662 hres->version = odr_strdup(o, m_http_version);
2663 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2664 if (m_http_keepalive)
2665 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2669 hres->content_len = sbuf.st_size;
2670 hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2671 FILE *f = fopen(fname, "rb");
2674 fread(hres->content_buf, 1, hres->content_len, f);
2681 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2683 yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
2687 send_GDU(gdu, &len);
2688 recv_GDU_more(true);
2692 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2696 odr_destroy(m_s2z_odr_init);
2699 if (m_s2z_odr_search)
2701 odr_destroy(m_s2z_odr_search);
2702 m_s2z_odr_search = 0;
2705 m_http_keepalive = 0;
2707 if (!strcmp(hreq->version, "1.0"))
2709 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2710 if (v && !strcmp(v, "Keep-Alive"))
2711 m_http_keepalive = 1;
2713 m_http_keepalive = 0;
2714 m_http_version = "1.0";
2718 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2719 if (v && !strcmp(v, "close"))
2720 m_http_keepalive = 0;
2722 m_http_keepalive = 1;
2723 m_http_version = "1.1";
2726 const char *a = z_HTTP_header_lookup(hreq->headers, "Authorization");
2727 char authorization_str[255];
2728 *authorization_str = '\0';
2729 if (a && strncasecmp(a, "Basic ", 6) == 0)
2730 base64_decode(a + 6, authorization_str, 254);
2732 Z_SRW_PDU *srw_pdu = 0;
2733 Z_SOAP *soap_package = 0;
2735 Z_SRW_diagnostic *diagnostic = 0;
2736 int num_diagnostic = 0;
2738 yaz_log(YLOG_LOG, "%s%s %s", m_session_str, hreq->method, hreq->path);
2740 if (file_access(hreq))
2744 else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2746 || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2747 &charset, &diagnostic, &num_diagnostic) == 0)
2749 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2750 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2751 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2752 m_s2z_init_apdu = 0;
2753 m_s2z_search_apdu = 0;
2754 m_s2z_present_apdu = 0;
2756 m_s2z_stylesheet = 0;
2758 Z_IdAuthentication *auth = NULL;
2759 if (*authorization_str)
2761 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2762 auth->which = Z_IdAuthentication_idPass;
2763 auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2764 auth->u.idPass->groupId = NULL;
2765 char *p = strchr(authorization_str, ':');
2770 auth->u.idPass->password = odr_strdup(m_s2z_odr_init, p);
2772 auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, authorization_str);
2775 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2778 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2780 const char *backend_db = srw_req->database;
2781 srw_get_client(srw_req->database, &backend_db);
2783 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2784 // recordXPath unsupported.
2785 if (srw_req->recordXPath)
2787 yaz_add_srw_diagnostic(odr_decode(),
2788 &diagnostic, &num_diagnostic,
2792 if (srw_req->sort_type != Z_SRW_sort_type_none)
2794 yaz_add_srw_diagnostic(odr_decode(),
2795 &diagnostic, &num_diagnostic,
2799 if (srw_req->stylesheet)
2801 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2803 // set packing for response records ..
2804 if (srw_req->recordPacking &&
2805 !strcmp(srw_req->recordPacking, "xml"))
2806 m_s2z_packing = Z_SRW_recordPacking_XML;
2808 m_s2z_packing = Z_SRW_recordPacking_string;
2812 Z_SRW_PDU *srw_pdu =
2813 yaz_srw_get(odr_encode(),
2814 Z_SRW_searchRetrieve_response);
2815 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2817 srw_res->diagnostics = diagnostic;
2818 srw_res->num_diagnostics = num_diagnostic;
2819 send_srw_response(srw_pdu);
2823 // prepare search PDU
2824 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2825 Z_APDU_searchRequest);
2826 Z_SearchRequest *z_searchRequest =
2827 m_s2z_search_apdu->u.searchRequest;
2829 z_searchRequest->num_databaseNames = 1;
2830 z_searchRequest->databaseNames = (char**)
2831 odr_malloc(m_s2z_odr_search, sizeof(char *));
2832 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2835 // query transformation
2836 Z_Query *query = (Z_Query *)
2837 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2838 z_searchRequest->query = query;
2840 if (srw_req->query_type == Z_SRW_query_type_cql)
2842 Z_External *ext = (Z_External *)
2843 odr_malloc(m_s2z_odr_search, sizeof(*ext));
2844 ext->direct_reference =
2845 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2846 ext->indirect_reference = 0;
2847 ext->descriptor = 0;
2848 ext->which = Z_External_CQL;
2849 ext->u.cql = srw_req->query.cql;
2851 query->which = Z_Query_type_104;
2852 query->u.type_104 = ext;
2854 else if (srw_req->query_type == Z_SRW_query_type_pqf)
2856 Z_RPNQuery *RPNquery;
2857 YAZ_PQF_Parser pqf_parser;
2859 pqf_parser = yaz_pqf_create ();
2861 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2862 srw_req->query.pqf);
2865 const char *pqf_msg;
2867 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2869 yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
2870 yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2872 send_to_srw_client_error(10, 0);
2875 query->which = Z_Query_type_1;
2876 query->u.type_1 = RPNquery;
2878 yaz_pqf_destroy (pqf_parser);
2882 send_to_srw_client_error(7, "query");
2887 m_s2z_present_apdu = 0;
2889 if (srw_req->maximumRecords)
2890 max = *srw_req->maximumRecords;
2892 if (srw_req->startRecord)
2893 start = *srw_req->startRecord;
2896 // Some backend, such as Voyager doesn't honor piggyback
2897 // So we use present always (0 &&).
2898 if (0 && start <= 1) // Z39.50 piggyback
2900 *z_searchRequest->smallSetUpperBound = max;
2901 *z_searchRequest->mediumSetPresentNumber = max;
2902 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2904 z_searchRequest->preferredRecordSyntax =
2905 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2907 if (srw_req->recordSchema)
2909 z_searchRequest->smallSetElementSetNames =
2910 z_searchRequest->mediumSetElementSetNames =
2911 mk_esn_from_schema(m_s2z_odr_search,
2912 srw_req->recordSchema);
2915 else // Z39.50 present
2917 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2918 Z_APDU_presentRequest);
2919 Z_PresentRequest *z_presentRequest =
2920 m_s2z_present_apdu->u.presentRequest;
2921 *z_presentRequest->resultSetStartPoint = start;
2922 *z_presentRequest->numberOfRecordsRequested = max;
2923 z_presentRequest->preferredRecordSyntax =
2924 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2926 if (srw_req->recordSchema)
2928 z_presentRequest->recordComposition =
2929 (Z_RecordComposition *)
2930 odr_malloc(m_s2z_odr_search,
2931 sizeof(Z_RecordComposition));
2932 z_presentRequest->recordComposition->which =
2933 Z_RecordComp_simple;
2934 z_presentRequest->recordComposition->u.simple =
2935 mk_esn_from_schema(m_s2z_odr_search,
2936 srw_req->recordSchema);
2942 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2943 Z_APDU_initRequest);
2945 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2947 // prevent m_initRequest_apdu memory from being grabbed
2948 // in Yaz_Proxy::handle_incoming_Z_PDU
2949 m_initRequest_apdu = m_s2z_init_apdu;
2950 handle_incoming_Z_PDU(m_s2z_init_apdu);
2955 handle_incoming_Z_PDU(m_s2z_search_apdu);
2959 else if (srw_pdu->which == Z_SRW_explain_request)
2961 Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
2963 const char *backend_db = srw_req->database;
2964 srw_get_client(srw_req->database, &backend_db);
2966 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2969 if (srw_req->stylesheet)
2971 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2973 if (srw_req->recordPacking &&
2974 !strcmp(srw_req->recordPacking, "xml"))
2975 m_s2z_packing = Z_SRW_recordPacking_XML;
2977 m_s2z_packing = Z_SRW_recordPacking_string;
2981 send_srw_explain_response(diagnostic, num_diagnostic);
2987 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2988 Z_APDU_initRequest);
2990 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2992 // prevent m_initRequest_apdu memory from being grabbed
2993 // in Yaz_Proxy::handle_incoming_Z_PDU
2994 m_initRequest_apdu = m_s2z_init_apdu;
2995 handle_incoming_Z_PDU(m_s2z_init_apdu);
2998 send_srw_explain_response(0, 0);
3001 else if (srw_pdu->which == Z_SRW_scan_request)
3003 m_s2z_database = odr_strdup(m_s2z_odr_init,
3004 srw_pdu->u.scan_request->database);
3006 yaz_add_srw_diagnostic(odr_decode(),
3007 &diagnostic, &num_diagnostic,
3009 Z_SRW_PDU *srw_pdu =
3010 yaz_srw_get(odr_encode(),
3011 Z_SRW_scan_response);
3012 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
3014 srw_res->diagnostics = diagnostic;
3015 srw_res->num_diagnostics = num_diagnostic;
3016 send_srw_response(srw_pdu);
3023 send_to_srw_client_error(4, 0);
3026 send_http_response(400);
3029 void Yaz_Proxy::handle_init(Z_APDU *apdu)
3032 Z_OtherInformation **oi;
3033 get_otherInfoAPDU(apdu, &oi);
3035 if (apdu->u.initRequest->implementationId)
3036 yaz_log(YLOG_LOG, "%simplementationId: %s",
3037 m_session_str, apdu->u.initRequest->implementationId);
3038 if (apdu->u.initRequest->implementationName)
3039 yaz_log(YLOG_LOG, "%simplementationName: %s",
3040 m_session_str, apdu->u.initRequest->implementationName);
3041 if (apdu->u.initRequest->implementationVersion)
3042 yaz_log(YLOG_LOG, "%simplementationVersion: %s",
3043 m_session_str, apdu->u.initRequest->implementationVersion);
3044 if (m_initRequest_apdu == 0)
3046 if (m_initRequest_mem)
3047 nmem_destroy(m_initRequest_mem);
3049 m_initRequest_apdu = apdu;
3050 m_initRequest_mem = odr_extract_mem(odr_decode());
3052 m_initRequest_preferredMessageSize = *apdu->u.initRequest->
3053 preferredMessageSize;
3054 *apdu->u.initRequest->preferredMessageSize = 1024*1024;
3055 m_initRequest_maximumRecordSize = *apdu->u.initRequest->
3057 *apdu->u.initRequest->maximumRecordSize = 1024*1024;
3059 Z_CharSetandLanguageNegotiation *charSetandLangRecord =
3060 yaz_get_charneg_record(*oi);
3062 // Save proposal charsets and langs.
3063 if (ODR_MASK_GET(apdu->u.initRequest->options,
3064 Z_Options_negotiationModel)
3065 && charSetandLangRecord)
3068 yaz_get_proposal_charneg(m_referenceId_mem,
3069 charSetandLangRecord,
3070 &m_initRequest_oi_negotiation_charsets,
3071 &m_initRequest_oi_negotiation_num_charsets,
3072 &m_initRequest_oi_negotiation_langs,
3073 &m_initRequest_oi_negotiation_num_langs,
3074 &m_initRequest_oi_negotiation_selected);
3076 for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
3078 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
3079 m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
3080 m_initRequest_oi_negotiation_charsets[i]:"none");
3082 for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
3084 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
3085 m_session_str, (m_initRequest_oi_negotiation_langs[i])?
3086 m_initRequest_oi_negotiation_langs[i]:"none");
3088 yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
3089 m_session_str, m_initRequest_oi_negotiation_selected);
3091 // save init options for the response..
3092 m_initRequest_options = apdu->u.initRequest->options;
3094 apdu->u.initRequest->options =
3095 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3096 sizeof(Odr_bitmask));
3097 ODR_MASK_ZERO(apdu->u.initRequest->options);
3099 for (i = 0; i<= 24; i++)
3100 ODR_MASK_SET(apdu->u.initRequest->options, i);
3101 // check negotiation option
3102 if (!ODR_MASK_GET(m_initRequest_options,
3103 Z_Options_negotiationModel))
3105 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3106 Z_Options_negotiationModel);
3108 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3109 Z_Options_concurrentOperations);
3111 m_initRequest_version = apdu->u.initRequest->protocolVersion;
3112 apdu->u.initRequest->protocolVersion =
3113 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
3114 sizeof(Odr_bitmask));
3115 ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
3117 for (i = 0; i<= 8; i++)
3118 ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
3120 handle_charset_lang_negotiation(apdu);
3121 if (m_client->m_init_flag)
3123 if (handle_init_response_for_invalid_session(apdu))
3125 if (m_client->m_initResponse)
3127 Z_APDU *apdu2 = m_client->m_initResponse;
3128 apdu2->u.initResponse->otherInfo = 0;
3129 if (m_client->m_cookie && *m_client->m_cookie)
3130 set_otherInformationString(apdu2, VAL_COOKIE, 1,
3131 m_client->m_cookie);
3132 apdu2->u.initResponse->referenceId =
3133 apdu->u.initRequest->referenceId;
3134 apdu2->u.initResponse->options = m_client->m_initResponse_options;
3135 apdu2->u.initResponse->protocolVersion =
3136 m_client->m_initResponse_version;
3138 handle_charset_lang_negotiation(apdu2);
3140 if (m_timeout_mode == timeout_busy)
3141 m_timeout_mode = timeout_normal;
3142 send_to_client(apdu2);
3146 m_client->m_init_flag = 1;
3148 if (m_num_msg_threads && m_my_thread)
3150 Auth_Msg *m = new Auth_Msg;
3152 z_APDU(odr_encode(), &apdu, 0, "encode");
3153 char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
3154 m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
3155 memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
3156 odr_reset(odr_encode());
3159 m_my_thread->put(m);
3163 int ret = handle_authentication(apdu);
3164 result_authentication(apdu, ret);
3168 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
3170 Z_ReferenceId **refid = get_referenceIdP(apdu);
3171 nmem_reset(m_referenceId_mem);
3172 if (refid && *refid)
3174 m_referenceId = (Z_ReferenceId *)
3175 nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
3176 m_referenceId->len = m_referenceId->size = (*refid)->len;
3177 m_referenceId->buf = (unsigned char *)
3178 nmem_malloc(m_referenceId_mem, (*refid)->len);
3179 memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
3184 if (!m_client && m_flag_invalid_session)
3186 // Got request for a session that is invalid..
3187 m_apdu_invalid_session = apdu; // save package
3188 m_mem_invalid_session = odr_extract_mem(odr_decode());
3189 apdu = m_initRequest_apdu; // but throw an init to the target
3192 if (apdu->which == Z_APDU_searchRequest)
3193 m_search_stat.add_bytes(1);
3195 // Determine our client.
3196 Z_OtherInformation **oi;
3197 get_otherInfoAPDU(apdu, &oi);
3198 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
3202 { // HTTP. Send not found
3203 send_http_response(404);
3208 // Z39.50 just shutdown
3214 m_client->m_server = this;
3216 if (apdu->which == Z_APDU_initRequest)
3219 handle_incoming_Z_PDU_2(apdu);
3222 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
3224 handle_max_record_retrieve(apdu);
3227 apdu = handle_syntax_validation(apdu);
3230 apdu = handle_query_transformation(apdu);
3233 apdu = handle_target_charset_conversion(apdu);
3236 apdu = handle_query_validation(apdu);
3239 apdu = result_set_optimize(apdu);
3243 m_client->timeout(m_target_idletime); // mark it active even
3244 recv_GDU_more(true);
3245 // though we didn't use it
3249 // delete other info construct completely if 0 elements
3250 Z_OtherInformation **oi;
3251 get_otherInfoAPDU(apdu, &oi);
3252 if (oi && *oi && (*oi)->num_elements == 0)
3255 if (apdu->which == Z_APDU_presentRequest &&
3256 m_client->m_resultSetStartPoint == 0)
3258 Z_PresentRequest *pr = apdu->u.presentRequest;
3259 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3260 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3262 m_client->m_resultSetStartPoint = 0;
3264 if (m_client->send_to_target(apdu) < 0)
3266 m_client->shutdown();
3269 m_client->m_waiting = 1;
3272 void Yaz_Proxy::connectNotify()
3276 void Yaz_Proxy::releaseClient()
3278 xfree(m_proxyTarget);
3280 m_flag_invalid_session = 0;
3281 // only keep if keep_alive flag is set...
3283 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3284 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3285 m_client->m_waiting == 0)
3287 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3289 m_client->get_hostname());
3290 yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3291 m_session_str, m_client->m_pdu_recv,
3292 m_client->m_bytes_sent + m_client->m_bytes_recv,
3293 m_keepalive_limit_bw, m_keepalive_limit_pdu);
3294 assert (m_client->m_waiting != 2);
3295 // Tell client (if any) that no server connection is there..
3296 m_client->m_server = 0;
3301 yaz_log (YLOG_LOG, "%sShutdown (client to proxy) close %s",
3303 m_client->get_hostname());
3304 assert (m_client->m_waiting != 2);
3310 yaz_log (YLOG_LOG, "%sshutdown (client to proxy) bad state",
3316 yaz_log (YLOG_LOG, "%sShutdown (client to proxy)",
3320 m_parent->pre_init();
3323 bool Yaz_Proxy::dec_ref()
3325 m_http_keepalive = 0;
3328 if (m_ref_count > 0)
3337 const char *Yaz_ProxyClient::get_session_str()
3341 return m_server->get_session_str();
3344 void Yaz_ProxyClient::shutdown()
3346 yaz_log (YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
3351 m_waiting = 1; // ensure it's released from Yaz_Proxy::releaseClient
3352 m_server->dec_ref();
3358 void Yaz_Proxy::failNotify()
3361 yaz_log (YLOG_LOG, "%sConnection closed by client", get_session_str());
3365 void Yaz_Proxy::send_response_fail_client(const char *addr)
3369 Z_SRW_diagnostic *diagnostic = 0;
3370 int num_diagnostic = 0;
3372 yaz_add_srw_diagnostic(odr_encode(),
3373 &diagnostic, &num_diagnostic,
3374 YAZ_SRW_SYSTEM_TEMPORARILY_UNAVAILABLE, addr);
3375 if (m_s2z_search_apdu)
3376 send_srw_search_response(diagnostic, num_diagnostic);
3378 send_srw_explain_response(diagnostic, num_diagnostic);
3381 void Yaz_ProxyClient::failNotify()
3384 m_server->inc_request_no();
3385 yaz_log (YLOG_LOG, "%sConnection closed by target %s",
3386 get_session_str(), get_hostname());
3389 m_server->send_response_fail_client(get_hostname());
3393 void Yaz_ProxyClient::connectNotify()
3395 const char *s = get_session_str();
3396 const char *h = get_hostname();
3397 yaz_log (YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
3399 timeout(m_target_idletime);
3404 IPDU_Observer *Yaz_ProxyClient::sessionNotify(IPDU_Observable
3405 *the_PDU_Observable, int fd)
3407 return new Yaz_ProxyClient(the_PDU_Observable, 0);
3410 Yaz_ProxyClient::~Yaz_ProxyClient()
3415 m_next->m_prev = m_prev;
3416 m_waiting = 2; // for debugging purposes only.
3417 odr_destroy(m_init_odr);
3418 odr_destroy(m_idAuthentication_odr);
3419 delete m_last_query;
3420 xfree (m_last_resultSetId);
3424 void Yaz_ProxyClient::pre_init_client()
3426 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
3427 Z_InitRequest *req = apdu->u.initRequest;
3430 for (i = 0; i<= 24; i++)
3431 ODR_MASK_SET(req->options, i);
3432 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3433 Z_Options_negotiationModel);
3434 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3435 Z_Options_concurrentOperations);
3436 for (i = 0; i<= 10; i++)
3437 ODR_MASK_SET(req->protocolVersion, i);
3439 if (send_to_target(apdu) < 0)
3450 void Yaz_Proxy::pre_init()
3453 const char *name = 0;
3454 const char *zurl_in_use[MAX_ZURL_PLEX];
3455 int limit_bw, limit_pdu, limit_req, limit_search;
3456 int target_idletime, client_idletime;
3458 int keepalive_limit_bw, keepalive_limit_pdu;
3460 const char *cql2rpn = 0;
3461 const char *authentication = 0;
3462 const char *negotiation_charset = 0;
3463 const char *negotiation_lang = 0;
3465 Yaz_ProxyConfig *cfg = check_reconfigure();
3469 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
3474 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
3475 &limit_bw, &limit_pdu, &limit_req,
3477 &target_idletime, &client_idletime,
3479 &keepalive_limit_bw,
3480 &keepalive_limit_pdu,
3484 &negotiation_charset,
3492 for (j = 0; zurl_in_use[j]; j++)
3496 int spare_waiting = 0;
3499 for (c = m_clientPool; c; c = c->m_next)
3501 if (!strcmp(zurl_in_use[j], c->get_hostname()))
3503 if (c->m_cookie == 0)
3505 if (c->m_server == 0)
3517 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
3518 "sparew=%d preinit=%d",m_session_str,
3519 name, zurl_in_use[j], in_use, other,
3520 spare, spare_waiting, pre_init);
3521 if (spare + spare_waiting < pre_init)
3523 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
3524 c->m_next = m_clientPool;
3526 c->m_next->m_prev = &c->m_next;
3528 c->m_prev = &m_clientPool;
3530 if (m_log_mask & PROXY_LOG_APDU_SERVER)
3531 c->set_APDU_yazlog(1);
3533 c->set_APDU_yazlog(0);
3535 if (c->client(zurl_in_use[j]))
3543 c->m_target_idletime = target_idletime;
3544 c->m_seqno = m_seqno++;
3551 void Yaz_Proxy::timeoutNotify()
3556 switch(m_timeout_mode)
3558 case timeout_normal:
3562 yaz_log (YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
3565 case timeout_reduce:
3566 timeout(m_client_idletime);
3567 m_timeout_mode = timeout_busy;
3568 gdu = m_timeout_gdu;
3570 recv_GDU_normal(gdu);
3573 assert(m_stylesheet_nprl);
3574 convert_xsl_delay();
3575 recv_GDU_more(true);
3585 void Yaz_Proxy::markInvalid()
3588 m_flag_invalid_session = 1;
3591 void Yaz_ProxyClient::timeoutNotify()
3594 m_server->inc_request_no();
3596 yaz_log (YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
3600 m_server->send_response_fail_client(get_hostname());
3602 Yaz_Proxy *proxy_root = m_root;
3606 proxy_root->pre_init();
3609 Yaz_ProxyClient::Yaz_ProxyClient(IPDU_Observable *the_PDU_Observable,
3610 Yaz_Proxy *parent) :
3611 Z_Assoc (the_PDU_Observable)
3618 m_last_resultSetId = 0;
3619 m_last_resultCount = 0;
3623 m_init_odr = odr_createmem (ODR_DECODE);
3625 m_initResponse_options = 0;
3626 m_initResponse_version = 0;
3627 m_initResponse_preferredMessageSize = 0;
3628 m_initResponse_maximumRecordSize = 0;
3629 m_resultSetStartPoint = 0;
3630 m_bytes_sent = m_bytes_recv = 0;
3634 m_target_idletime = 600;
3636 m_idAuthentication_odr = odr_createmem(ODR_ENCODE);
3637 m_idAuthentication_ber_buf = 0;
3638 m_idAuthentication_ber_size = 0;
3641 const char *Yaz_Proxy::option(const char *name, const char *value)
3643 if (!strcmp (name, "optimize")) {
3646 m_optimize = xstrdup (value);
3653 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
3658 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
3660 if (apdu->which == Z_GDU_Z3950)
3661 recv_Z_PDU(apdu->u.z3950, len);
3662 else if (apdu->which == Z_GDU_HTTP_Response)
3663 recv_HTTP_response(apdu->u.HTTP_Response, len);
3668 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
3670 if (!m_flag_invalid_session)
3672 m_flag_invalid_session = 0;
3673 handle_incoming_Z_PDU(m_apdu_invalid_session);
3674 assert (m_mem_invalid_session);
3675 nmem_destroy(m_mem_invalid_session);
3676 m_mem_invalid_session = 0;
3680 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
3682 m_bytes_recv += len;
3686 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
3687 yaz_log (YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
3688 apdu_name(apdu), get_hostname(), len);
3689 if (apdu->which == Z_APDU_initResponse)
3691 if (!m_server) // if this is a pre init session , check for more
3693 NMEM nmem = odr_extract_mem (odr_decode());
3694 odr_reset (m_init_odr);
3695 nmem_transfer (m_init_odr->mem, nmem);
3696 m_initResponse = apdu;
3697 m_initResponse_options = apdu->u.initResponse->options;
3698 m_initResponse_version = apdu->u.initResponse->protocolVersion;
3699 m_initResponse_preferredMessageSize =
3700 *apdu->u.initResponse->preferredMessageSize;
3701 m_initResponse_maximumRecordSize =
3702 *apdu->u.initResponse->maximumRecordSize;
3704 Z_InitResponse *ir = apdu->u.initResponse;
3706 // apply YAZ Proxy version
3707 char *imv0 = ir->implementationVersion;
3708 char *imv1 = (char*)
3709 odr_malloc(m_init_odr, 20 + (imv0 ? strlen(imv0) : 0));
3714 strcat(imv1, "/" VERSION);
3716 ir->implementationVersion = imv1;
3718 // apply YAZ Proxy implementation name
3719 char *im0 = ir->implementationName;
3721 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
3728 strcat(im1, "(YAZ Proxy)");
3729 ir->implementationName = im1;
3731 nmem_destroy (nmem);
3733 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
3736 if (apdu->which == Z_APDU_searchResponse)
3738 Z_SearchResponse *sr = apdu->u.searchResponse;
3739 m_last_resultCount = *sr->resultCount;
3740 int status = *sr->searchStatus;
3741 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
3745 if (sr->records && sr->records->which == Z_Records_DBOSD)
3747 m_cache.add(odr_decode(),
3748 sr->records->u.databaseOrSurDiagnostics, 1,
3753 if (apdu->which == Z_APDU_presentResponse)
3755 Z_PresentResponse *pr = apdu->u.presentResponse;
3759 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
3760 Z_SearchResponse *sr = new_apdu->u.searchResponse;
3761 sr->referenceId = pr->referenceId;
3762 *sr->resultCount = m_last_resultCount;
3763 sr->records = pr->records;
3764 sr->nextResultSetPosition = pr->nextResultSetPosition;
3765 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
3769 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
3771 m_cache.add(odr_decode(),
3772 pr->records->u.databaseOrSurDiagnostics,
3773 m_resultSetStartPoint, -1);
3774 m_resultSetStartPoint = 0;
3778 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
3780 Yaz_Proxy *server = m_server; // save it. send_to_client may destroy us
3783 server->send_to_client(apdu);
3784 if (apdu->which == Z_APDU_close)
3787 server->recv_GDU_more(true);
3790 void Yaz_Proxy::low_socket_close()
3795 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3796 if (m_lo_fd[i] >= 0)
3797 ::close(m_lo_fd[i]);
3801 void Yaz_Proxy::low_socket_open()
3806 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3807 m_lo_fd[i] = open("/dev/null", O_RDONLY);
3811 int Yaz_Proxy::server(const char *addr)
3813 int r = Z_Assoc::server(addr);
3816 yaz_log(YLOG_LOG, "%sStarted proxy "
3820 " on %s", m_session_str, addr);
3826 void Yaz_Proxy::base64_decode(const char *base64, char *buf, int buf_len)
3828 const char *base64_chars =
3829 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3830 int len = strlen(base64);
3834 for (int pos = 0; pos <= len; pos++)
3836 if (base64[pos] == '=' || buf_pos + 1 >= buf_len)
3839 const char *ch_ptr = strchr(base64_chars, base64[pos]);
3842 char ch = (char) (ch_ptr - base64_chars);
3846 buf[buf_pos] = ch << 2;
3849 buf[buf_pos++] += (ch & 0x30) >> 4;
3850 buf[buf_pos] = (ch & 0x0f) << 4;
3853 buf[buf_pos++] += (ch & 0x3c) >> 2;
3854 buf[buf_pos] = (ch & 0x03) << 6;
3857 buf[buf_pos++] += ch;
3864 buf[buf_pos] = '\0';
3870 * indent-tabs-mode: nil
3872 * vim: shiftwidth=4 tabstop=8 expandtab