1 /* $Id: yaz-proxy.cpp,v 1.47 2006-03-30 14:16:34 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
63 #define USE_AUTH_MSG 0
67 class YAZ_EXPORT Auth_Msg : public IMsg_Thread {
70 IMsg_Thread *handle();
82 m_nmem = nmem_create();
90 IMsg_Thread *Auth_Msg::handle()
92 ODR decode = odr_createmem(ODR_DECODE);
95 odr_setbuf(decode, m_apdu_buf, m_apdu_len, 0);
96 int r = z_APDU(decode, &apdu, 0, 0);
99 yaz_log(YLOG_WARN, "decode failed in Auth_Msg::handle");
103 m_ret = m_proxy->handle_authentication(apdu);
109 void Auth_Msg::result()
111 if (m_proxy->dec_ref(false))
113 yaz_log(YLOG_LOG, "Auth_Msg::proxy deleted meanwhile");
117 odr_setbuf(m_proxy->odr_decode(), m_apdu_buf, m_apdu_len, 0);
119 int r = z_APDU(m_proxy->odr_decode(), &apdu, 0, 0);
121 yaz_log(YLOG_LOG, "Auth_Msg::result z_APDU failed");
122 m_proxy->result_authentication(apdu, m_ret);
129 void Yaz_Proxy::result_authentication(Z_APDU *apdu, int ret)
131 if (apdu == 0 || ret == 0)
133 Z_APDU *apdu_reject = zget_APDU(odr_encode(), Z_APDU_initResponse);
134 *apdu_reject->u.initResponse->result = 0;
135 send_to_client(apdu_reject);
140 if (apdu->which == Z_APDU_initRequest)
142 Yaz_ProxyConfig *cfg = check_reconfigure();
144 cfg->target_authentication(m_default_target, odr_encode(),
145 apdu->u.initRequest);
147 handle_incoming_Z_PDU_2(apdu);
151 static const char *apdu_name(Z_APDU *apdu)
155 case Z_APDU_initRequest:
156 return "initRequest";
157 case Z_APDU_initResponse:
158 return "initResponse";
159 case Z_APDU_searchRequest:
160 return "searchRequest";
161 case Z_APDU_searchResponse:
162 return "searchResponse";
163 case Z_APDU_presentRequest:
164 return "presentRequest";
165 case Z_APDU_presentResponse:
166 return "presentResponse";
167 case Z_APDU_deleteResultSetRequest:
168 return "deleteResultSetRequest";
169 case Z_APDU_deleteResultSetResponse:
170 return "deleteResultSetResponse";
171 case Z_APDU_scanRequest:
172 return "scanRequest";
173 case Z_APDU_scanResponse:
174 return "scanResponse";
175 case Z_APDU_sortRequest:
176 return "sortRequest";
177 case Z_APDU_sortResponse:
178 return "sortResponse";
179 case Z_APDU_extendedServicesRequest:
180 return "extendedServicesRequest";
181 case Z_APDU_extendedServicesResponse:
182 return "extendedServicesResponse";
189 static const char *gdu_name(Z_GDU *gdu)
194 return apdu_name(gdu->u.z3950);
195 case Z_GDU_HTTP_Request:
196 return "HTTP Request";
197 case Z_GDU_HTTP_Response:
198 return "HTTP Response";
200 return "Unknown request/response";
203 Yaz_Proxy::Yaz_Proxy(IPDU_Observable *the_PDU_Observable,
204 ISocketObservable *the_socket_observable,
207 Z_Assoc(the_PDU_Observable), m_bw_stat(60), m_pdu_stat(60)
209 m_PDU_Observable = the_PDU_Observable;
210 m_socket_observable = the_socket_observable;
215 m_keepalive_limit_bw = 500000;
216 m_keepalive_limit_pdu = 1000;
218 m_default_target = 0;
219 m_proxy_negotiation_charset = 0;
220 m_proxy_negotiation_lang = 0;
221 m_proxy_negotiation_default_charset = 0;
222 m_charset_converter = new Yaz_CharsetConverter;
226 m_client_idletime = 600;
227 m_target_idletime = 600;
228 m_optimize = xstrdup ("1");
229 strcpy(m_session_str, "0 ");
237 m_timeout_mode = timeout_normal;
239 m_max_record_retrieve = 0;
243 m_flag_invalid_session = 0;
245 m_referenceId_mem = nmem_create();
247 m_marcxml_mode = none;
248 m_stylesheet_xsp = 0;
249 m_stylesheet_nprl = 0;
250 m_stylesheet_apdu = 0;
251 m_s2z_stylesheet = 0;
255 m_backend_charset = 0;
257 m_initRequest_apdu = 0;
258 m_initRequest_mem = 0;
259 m_initRequest_preferredMessageSize = 0;
260 m_initRequest_maximumRecordSize = 0;
261 m_initRequest_options = 0;
262 m_initRequest_version = 0;
263 m_initRequest_oi_negotiation_charsets = 0;
264 m_initRequest_oi_negotiation_num_charsets = 0;
265 m_initRequest_oi_negotiation_langs = 0;
266 m_initRequest_oi_negotiation_num_langs = 0;
267 m_initRequest_oi_negotiation_selected = 0;
268 m_apdu_invalid_session = 0;
269 m_mem_invalid_session = 0;
271 m_s2z_odr_search = 0;
273 m_s2z_search_apdu = 0;
274 m_s2z_present_apdu = 0;
275 m_http_keepalive = 0;
278 m_s2z_packing = Z_SRW_recordPacking_string;
279 #if HAVE_GETTIMEOFDAY
280 m_time_tv = xmalloc(sizeof(struct timeval));
281 struct timeval *tv = (struct timeval *) m_time_tv;
287 m_usemarcon_ini_stage1 = 0;
288 m_usemarcon_ini_stage2 = 0;
289 m_usemarcon = new Yaz_usemarcon();
294 m_main_ptr_dec = false;
298 void Yaz_Proxy::inc_ref()
303 Yaz_Proxy::~Yaz_Proxy()
305 yaz_log(YLOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
306 m_bytes_sent, m_bytes_recv);
307 nmem_destroy(m_initRequest_mem);
308 nmem_destroy(m_mem_invalid_session);
309 nmem_destroy(m_referenceId_mem);
311 xfree(m_proxyTarget);
312 xfree(m_default_target);
313 xfree(m_proxy_negotiation_charset);
314 xfree(m_proxy_negotiation_lang);
315 xfree(m_proxy_negotiation_default_charset);
316 delete m_charset_converter;
320 if (m_stylesheet_xsp)
321 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
327 xfree (m_backend_type);
328 xfree (m_backend_charset);
329 xfree (m_usemarcon_ini_stage1);
330 xfree (m_usemarcon_ini_stage2);
333 odr_destroy(m_s2z_odr_init);
334 if (m_s2z_odr_search)
335 odr_destroy(m_s2z_odr_search);
343 void Yaz_Proxy::set_debug_mode(int mode)
348 int Yaz_Proxy::set_config(const char *config)
351 m_config = new Yaz_ProxyConfig();
352 xfree(m_config_fname);
353 m_config_fname = xstrdup(config);
354 int r = m_config->read_xml(config);
356 m_config->get_generic_info(&m_log_mask, &m_max_clients,
361 void Yaz_Proxy::set_default_target(const char *target)
363 xfree (m_default_target);
364 m_default_target = 0;
366 m_default_target = (char *) xstrdup (target);
369 void Yaz_Proxy::set_proxy_negotiation (const char *charset, const char *lang,
370 const char *default_charset)
372 yaz_log(YLOG_LOG, "%sSet the proxy negotiation: charset to '%s', "
373 "default charset to '%s', language to '%s'", m_session_str,
374 charset?charset:"none",
375 default_charset?default_charset:"none",
377 xfree (m_proxy_negotiation_charset);
378 xfree (m_proxy_negotiation_lang);
379 m_proxy_negotiation_charset = m_proxy_negotiation_lang = 0;
381 m_proxy_negotiation_charset = (char *) xstrdup (charset);
383 m_proxy_negotiation_lang = (char *) xstrdup (lang);
385 m_proxy_negotiation_default_charset =
386 (char *) xstrdup (default_charset);
389 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
392 return m_parent->check_reconfigure();
394 Yaz_ProxyConfig *cfg = m_config;
397 yaz_log(YLOG_LOG, "reconfigure");
399 if (m_config_fname && cfg)
401 yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
402 int r = cfg->read_xml(m_config_fname);
404 yaz_log(YLOG_WARN, "reconfigure failed");
408 cfg->get_generic_info(&m_log_mask, &m_max_clients,
413 yaz_log(YLOG_LOG, "reconfigure");
419 IPDU_Observer *Yaz_Proxy::sessionNotify(IPDU_Observable
420 *the_PDU_Observable, int fd)
424 char session_str[200];
425 sprintf(session_str, "%ld:%d ", (long) time(0), m_session_no);
428 const char *peername = the_PDU_Observable->getpeername();
429 yaz_log (YLOG_LOG, "%sNew session %s", session_str, peername);
431 m_connect.cleanup(false);
432 m_connect.add_connect(peername);
434 int connect_total = m_connect.get_total(peername);
435 int connect_max = m_connect_max;
436 if (connect_max && connect_total > connect_max)
438 yaz_log(YLOG_LOG, "%sconnect not accepted total=%d max=%d",
439 session_str, connect_total, connect_max);
442 yaz_log(YLOG_LOG, "%sconnect accepted total=%d", session_str,
445 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable,
446 m_socket_observable, this);
447 new_proxy->m_config = 0;
448 new_proxy->m_config_fname = 0;
449 new_proxy->timeout(m_client_idletime);
450 new_proxy->m_target_idletime = m_target_idletime;
451 new_proxy->set_default_target(m_default_target);
452 new_proxy->m_max_clients = m_max_clients;
453 new_proxy->m_log_mask = m_log_mask;
454 new_proxy->set_APDU_log(get_APDU_log());
455 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
456 new_proxy->set_APDU_yazlog(1);
458 new_proxy->set_APDU_yazlog(0);
459 strcpy(new_proxy->m_session_str, session_str);
460 new_proxy->m_peername = xstrdup(peername);
461 new_proxy->set_proxy_negotiation(m_proxy_negotiation_charset,
462 m_proxy_negotiation_lang, m_proxy_negotiation_default_charset);
463 // create thread object the first time we get an incoming connection
465 m_my_thread = new Msg_Thread(m_socket_observable, 1);
466 new_proxy->m_my_thread = m_my_thread;
470 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
473 Z_OtherInformationUnit *oi;
475 ent.proto = PROTO_Z3950;
476 ent.oclass = CLASS_USERINFO;
477 ent.value = (oid_value) VAL_COOKIE;
478 assert (oid_ent_to_oid (&ent, oid));
480 if (oid_ent_to_oid (&ent, oid) &&
481 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
482 oi->which == Z_OtherInfo_characterInfo)
483 return oi->information.characterInfo;
486 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
489 Z_OtherInformationUnit *oi;
491 ent.proto = PROTO_Z3950;
492 ent.oclass = CLASS_USERINFO;
493 ent.value = (oid_value) VAL_PROXY;
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 const char *Yaz_Proxy::load_balance(const char **url)
502 int zurl_in_use[MAX_ZURL_PLEX];
503 int zurl_in_spare[MAX_ZURL_PLEX];
507 for (i = 0; i<MAX_ZURL_PLEX; i++)
510 zurl_in_spare[i] = 0;
512 for (c = m_parent->m_clientPool; c; c = c->m_next)
514 for (i = 0; url[i]; i++)
515 if (!strcmp(url[i], c->get_hostname()))
518 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
522 int min_use = 100000;
523 int spare_for_min = 0;
525 const char *ret_min = 0;
526 const char *ret_spare = 0;
527 for (i = 0; url[i]; i++)
529 yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
530 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
531 if (min_use > zurl_in_use[i])
534 min_use = zurl_in_use[i];
535 spare_for_min = zurl_in_spare[i];
537 if (max_spare < zurl_in_spare[i])
540 max_spare = zurl_in_spare[i];
546 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
547 const char *proxy_host)
550 Yaz_Proxy *parent = m_parent;
551 Yaz_ProxyClient *c = m_client;
555 const char *url[MAX_ZURL_PLEX];
556 Yaz_ProxyConfig *cfg = check_reconfigure();
559 if (parent && parent->m_debug_mode)
561 // only to be enabled for debugging...
562 if (!strcmp(proxy_host, "stop"))
565 xfree(m_default_target);
566 m_default_target = xstrdup(proxy_host);
568 proxy_host = m_default_target;
569 int client_idletime = -1;
570 const char *cql2rpn_fname = 0;
571 const char *negotiation_charset = 0;
572 const char *negotiation_lang = 0;
573 const char *query_charset = 0;
574 const char *default_client_query_charset = 0;
575 url[0] = m_default_target;
580 cfg->get_target_info(proxy_host, url, &m_bw_max,
581 &m_pdu_max, &m_max_record_retrieve,
583 &m_target_idletime, &client_idletime,
584 &parent->m_max_clients,
585 &m_keepalive_limit_bw,
586 &m_keepalive_limit_pdu,
589 &negotiation_charset,
592 &default_client_query_charset);
594 if (client_idletime != -1)
596 m_client_idletime = client_idletime;
597 timeout(m_client_idletime);
600 m_cql2rpn.set_pqf_file(cql2rpn_fname);
601 if (negotiation_charset || negotiation_lang || default_client_query_charset)
603 set_proxy_negotiation(negotiation_charset,
604 negotiation_lang, default_client_query_charset);
606 m_charset_converter->set_target_query_charset(query_charset);
609 yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
612 // we don't handle multiplexing for cookie session, so we just
613 // pick the first one in this case (anonymous users will be able
614 // to use any backend)
615 if (cookie && *cookie)
616 m_proxyTarget = (char*) xstrdup(url[0]);
618 m_proxyTarget = (char*) xstrdup(load_balance(url));
620 if (cookie && *cookie)
621 { // search in sessions with a cookie
622 for (c = parent->m_clientPool; c; c = c->m_next)
625 assert (*c->m_prev == c);
626 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
627 !strcmp(m_proxyTarget, c->get_hostname()))
630 // The following handles "cancel"
631 // If connection is busy (waiting for PDU) and
632 // we have an initRequest we can safely do re-open
633 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
635 yaz_log (YLOG_LOG, "%s REOPEN target=%s", m_session_str,
642 c->m_last_resultCount = 0;
643 c->m_sr_transform = 0;
645 c->m_resultSetStartPoint = 0;
646 c->m_target_idletime = m_target_idletime;
647 if (c->client(m_proxyTarget))
654 c->m_seqno = parent->m_seqno;
655 if (c->m_server && c->m_server != this)
656 c->m_server->m_client = 0;
659 yaz_log (YLOG_DEBUG, "get_client 1 %p %p", this, c);
664 else if (!c && apdu->which == Z_APDU_initRequest )
666 // anonymous sessions without cookie.
667 // if authentication is set it is NOT anonymous se we can't share them.
668 // If charset and lang negotiation is use it is NOT anonymous session too.
669 for (c = parent->m_clientPool; c; c = c->m_next)
672 assert(*c->m_prev == c);
673 if (c->m_server == 0 && c->m_cookie == 0 && c->m_waiting == 0
674 && c->compare_idAuthentication(apdu)
675 && c->compare_charset(apdu)
676 && !strcmp(m_proxyTarget, c->get_hostname()))
679 yaz_log (YLOG_LOG, "%sREUSE %d %s",
680 m_session_str, parent->m_seqno, c->get_hostname());
682 c->m_seqno = parent->m_seqno;
683 assert(c->m_server == 0);
686 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
687 c->set_APDU_yazlog(1);
689 c->set_APDU_yazlog(0);
701 if (apdu->which != Z_APDU_initRequest)
703 yaz_log (YLOG_LOG, "%sno init request as first PDU", m_session_str);
706 // go through list of clients - and find the lowest/oldest one.
707 Yaz_ProxyClient *c_min = 0;
709 int no_of_clients = 0;
710 if (parent->m_clientPool)
711 yaz_log (YLOG_DEBUG, "Existing sessions");
712 for (c = parent->m_clientPool; c; c = c->m_next)
714 yaz_log (YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
715 c->m_waiting, c->get_hostname(),
716 c->m_cookie ? c->m_cookie : "");
718 if (min_seq < 0 || c->m_seqno < min_seq)
720 min_seq = c->m_seqno;
724 if (no_of_clients >= parent->m_max_clients)
727 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
729 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
730 m_session_str, parent->m_max_clients, c->m_seqno);
731 if (c->m_server && c->m_server != this)
732 delete c->m_server; // PROBLEM: m_ref_count!
737 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
738 m_session_str, parent->m_max_clients,
739 c->m_seqno, parent->m_seqno, c->get_hostname());
743 c->m_cookie = xstrdup(cookie);
744 c->m_seqno = parent->m_seqno;
745 if (c->m_server && c->m_server != this)
747 c->m_server->m_client = 0;
748 delete c->m_server; // PROBLEM: m_ref_count!
751 c->m_target_idletime = m_target_idletime;
752 c->timeout(m_target_idletime);
754 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
755 c->set_APDU_yazlog(1);
757 c->set_APDU_yazlog(0);
764 yaz_log (YLOG_LOG, "%sNEW %d %s",
765 m_session_str, parent->m_seqno, m_proxyTarget);
766 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
767 c->m_next = parent->m_clientPool;
769 c->m_next->m_prev = &c->m_next;
770 parent->m_clientPool = c;
771 c->m_prev = &parent->m_clientPool;
777 c->m_cookie = xstrdup(cookie);
779 c->m_seqno = parent->m_seqno;
781 c->m_last_resultCount = 0;
784 c->m_sr_transform = 0;
786 c->m_resultSetStartPoint = 0;
788 if (c->client(m_proxyTarget))
793 c->m_target_idletime = m_target_idletime;
796 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
797 c->set_APDU_yazlog(1);
799 c->set_APDU_yazlog(0);
801 c->set_idAuthentication(apdu);
803 yaz_log (YLOG_DEBUG, "get_client 3 %p %p", this, c);
807 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
810 for (i = 0; i<num; i++)
813 Z_DefaultDiagFormat *r;
814 Z_DiagRec *p = pp[i];
815 if (p->which != Z_DiagRec_defaultFormat)
817 yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
821 r = p->u.defaultFormat;
822 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
823 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
824 yaz_log(YLOG_LOG, "%sError unknown diagnostic set", m_session_str);
827 case Z_DefaultDiagFormat_v2Addinfo:
828 yaz_log(YLOG_LOG, "%sError %d %s:%s",
830 *r->condition, diagbib1_str(*r->condition),
833 case Z_DefaultDiagFormat_v3Addinfo:
834 yaz_log(YLOG_LOG, "%sError %d %s:%s",
836 *r->condition, diagbib1_str(*r->condition),
843 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
845 if (!m_stylesheet_xsp || p->num_records <= 0)
847 return 0; /* no XSLT to be done ... */
850 m_stylesheet_offset = 0;
851 m_stylesheet_nprl = p;
852 m_stylesheet_apdu = apdu;
853 m_timeout_mode = timeout_xsl;
859 void Yaz_Proxy::convert_xsl_delay()
862 Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
863 if (npr->which == Z_NamePlusRecord_databaseRecord)
865 Z_External *r = npr->u.databaseRecord;
866 if (r->which == Z_External_octet)
869 fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
871 xmlDocPtr res, doc = xmlParseMemory(
872 (char*) r->u.octet_aligned->buf,
873 r->u.octet_aligned->len);
876 yaz_log(YLOG_LOG, "%sXSLT convert %d",
877 m_session_str, m_stylesheet_offset);
878 res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
885 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
887 m_stylesheet_nprl->records[m_stylesheet_offset]->
889 z_ext_record(odr_encode(), VAL_TEXT_XML,
890 (char*) out_buf, out_len);
899 m_stylesheet_offset++;
900 if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
902 m_timeout_mode = timeout_normal;
903 m_stylesheet_nprl = 0;
905 if (m_stylesheet_xsp)
906 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
908 m_stylesheet_xsp = 0;
909 timeout(m_client_idletime);
910 send_PDU_convert(m_stylesheet_apdu);
916 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
918 if (m_frontend_type != VAL_NONE)
921 for (i = 0; i < p->num_records; i++)
923 Z_NamePlusRecord *npr = p->records[i];
924 if (npr->which == Z_NamePlusRecord_databaseRecord)
926 Z_External *r = npr->u.databaseRecord;
927 if (r->which == Z_External_octet)
930 if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
932 if (!m_usemarcon->m_stage1)
934 m_usemarcon->m_stage1 = new CDetails();
936 m_usemarcon->m_stage1->SetIniFileName(m_usemarcon_ini_stage1);
937 m_usemarcon->m_stage1->SetMarcRecord((char*) r->u.octet_aligned->buf, r->u.octet_aligned->len);
938 int res = m_usemarcon->m_stage1->Start();
943 m_usemarcon->m_stage1->GetMarcRecord(converted, convlen);
944 if (m_usemarcon_ini_stage2 && *m_usemarcon_ini_stage2)
946 if (!m_usemarcon->m_stage2)
948 m_usemarcon->m_stage2 = new CDetails();
950 m_usemarcon->m_stage2->SetIniFileName(m_usemarcon_ini_stage2);
951 m_usemarcon->m_stage2->SetMarcRecord(converted, convlen);
952 res = m_usemarcon->m_stage2->Start();
956 m_usemarcon->m_stage2->GetMarcRecord(converted, convlen);
960 yaz_log(YLOG_LOG, "%sUSEMARCON stage 2 error %d", m_session_str, res);
963 npr->u.databaseRecord =
964 z_ext_record(odr_encode(),
972 yaz_log(YLOG_LOG, "%sUSEMARCON stage 1 error %d", m_session_str, res);
978 npr->u.databaseRecord =
979 z_ext_record(odr_encode(),
981 (char*) r->u.octet_aligned->buf,
982 r->u.octet_aligned->len);
989 void Yaz_Proxy::convert_records_charset(Z_NamePlusRecordList *p,
990 const char *backend_charset)
992 yaz_log(YLOG_LOG, "%sconvert_to_marc", m_session_str);
993 int sel = m_charset_converter->get_client_charset_selected();
994 const char *client_record_charset =
995 m_charset_converter->get_client_query_charset();
996 if (sel && backend_charset && client_record_charset &&
997 strcmp(backend_charset, client_record_charset))
1000 yaz_iconv_t cd = yaz_iconv_open(client_record_charset,
1002 yaz_marc_t mt = yaz_marc_create();
1003 yaz_marc_xml(mt, YAZ_MARC_ISO2709);
1004 yaz_marc_iconv(mt, cd);
1005 for (i = 0; i < p->num_records; i++)
1007 Z_NamePlusRecord *npr = p->records[i];
1008 if (npr->which == Z_NamePlusRecord_databaseRecord)
1010 Z_External *r = npr->u.databaseRecord;
1011 oident *ent = oid_getentbyoid(r->direct_reference);
1012 if (!ent || ent->value == VAL_NONE)
1015 if (ent->value == VAL_SUTRS)
1017 WRBUF w = wrbuf_alloc();
1019 wrbuf_iconv_write(w, cd, (char*) r->u.octet_aligned->buf,
1020 r->u.octet_aligned->len);
1021 npr->u.databaseRecord =
1022 z_ext_record(odr_encode(), ent->value, wrbuf_buf(w),
1026 else if (ent->value == VAL_TEXT_XML)
1030 else if (r->which == Z_External_octet)
1034 if (yaz_marc_decode_buf(mt,
1035 (char*) r->u.octet_aligned->buf,
1036 r->u.octet_aligned->len,
1039 npr->u.databaseRecord =
1040 z_ext_record(odr_encode(), ent->value, result, rlen);
1041 yaz_log(YLOG_LOG, "%sRecoding MARC record",
1048 yaz_iconv_close(cd);
1049 yaz_marc_destroy(mt);
1053 yaz_log(YLOG_LOG, "%sSkipping marc convert", m_session_str);
1057 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
1058 const char *backend_charset)
1061 if (!backend_charset)
1062 backend_charset = "MARC-8";
1063 yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
1064 yaz_marc_t mt = yaz_marc_create();
1065 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1066 yaz_marc_iconv(mt, cd);
1067 for (i = 0; i < p->num_records; i++)
1069 Z_NamePlusRecord *npr = p->records[i];
1070 if (npr->which == Z_NamePlusRecord_databaseRecord)
1072 Z_External *r = npr->u.databaseRecord;
1073 if (r->which == Z_External_OPAC)
1075 WRBUF w = wrbuf_alloc();
1077 yaz_opac_decode_wrbuf(mt, r->u.opac, w);
1078 npr->u.databaseRecord = z_ext_record(
1079 odr_encode(), VAL_TEXT_XML,
1080 wrbuf_buf(w), wrbuf_len(w)
1084 else if (r->which == Z_External_octet)
1088 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
1089 r->u.octet_aligned->len,
1092 npr->u.databaseRecord =
1093 z_ext_record(odr_encode(), VAL_TEXT_XML, result, rlen);
1099 yaz_iconv_close(cd);
1100 yaz_marc_destroy(mt);
1103 void Yaz_Proxy::logtime()
1105 #if HAVE_GETTIMEOFDAY
1106 struct timeval *tv = (struct timeval*) m_time_tv;
1110 gettimeofday(&tv1, 0);
1111 long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
1112 (tv1.tv_usec - tv->tv_usec);
1114 yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
1115 diff/1000000, (diff/1000)%1000);
1122 int Yaz_Proxy::send_http_response(int code)
1124 ODR o = odr_encode();
1125 Z_GDU *gdu = z_get_HTTP_Response(o, code);
1126 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1128 hres->version = odr_strdup(o, m_http_version);
1129 if (m_http_keepalive)
1130 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1134 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1136 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1140 int r = send_GDU(gdu, &len);
1141 m_bytes_sent += len;
1142 m_bw_stat.add_bytes(len);
1145 recv_GDU_more(true);
1150 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu, int http_code /* = 200 */)
1152 ODR o = odr_encode();
1153 const char *ctype = "text/xml";
1154 Z_GDU *gdu = z_get_HTTP_Response(o, http_code);
1155 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1157 hres->version = odr_strdup(o, m_http_version);
1158 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1159 if (m_http_keepalive)
1160 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1163 if (http_code == 401)
1164 z_HTTP_header_add(o, &hres->headers, "WWW-Authenticate", "Basic realm=\"YAZ Proxy\"");
1166 static Z_SOAP_Handler soap_handlers[2] = {
1168 {"http://www.loc.gov/zing/srw/", 0,
1169 (Z_SOAP_fun) yaz_srw_codec},
1174 Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
1175 soap_package->which = Z_SOAP_generic;
1176 soap_package->u.generic =
1177 (Z_SOAP_Generic *) odr_malloc(o, sizeof(*soap_package->u.generic));
1178 soap_package->u.generic->no = 0;
1179 soap_package->u.generic->ns = soap_handlers[0].ns;
1180 soap_package->u.generic->p = (void *) srw_pdu;
1181 soap_package->ns = m_soap_ns;
1182 z_soap_codec_enc_xsl(o, &soap_package,
1183 &hres->content_buf, &hres->content_len,
1184 soap_handlers, 0, m_s2z_stylesheet);
1185 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1187 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1191 int r = send_GDU(gdu, &len);
1192 m_bytes_sent += len;
1193 m_bw_stat.add_bytes(len);
1196 recv_GDU_more(true);
1201 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
1203 ODR o = odr_encode();
1204 Z_SRW_diagnostic *diagnostic = (Z_SRW_diagnostic *)
1205 odr_malloc(o, sizeof(*diagnostic));
1206 int num_diagnostic = 1;
1207 yaz_mk_std_diagnostic(o, diagnostic, srw_error, add);
1208 return send_srw_search_response(diagnostic, num_diagnostic, srw_error == 3 ? 401 : 200);
1211 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
1212 Z_DefaultDiagFormat *ddf)
1214 int bib1_code = *ddf->condition;
1215 if (bib1_code == 109)
1217 srw_res->num_diagnostics = 1;
1218 srw_res->diagnostics = (Z_SRW_diagnostic *)
1219 odr_malloc(o, sizeof(*srw_res->diagnostics));
1220 yaz_mk_std_diagnostic(o, srw_res->diagnostics,
1221 yaz_diag_bib1_to_srw(*ddf->condition),
1226 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
1228 ODR o = odr_encode();
1229 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1230 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1232 srw_res->numberOfRecords = odr_intdup (o, hits);
1233 if (records && records->which == Z_Records_DBOSD)
1235 srw_res->num_records =
1236 records->u.databaseOrSurDiagnostics->num_records;
1238 srw_res->records = (Z_SRW_record *)
1239 odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
1240 for (i = 0; i < srw_res->num_records; i++)
1242 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
1243 if (npr->which != Z_NamePlusRecord_databaseRecord)
1245 srw_res->records[i].recordSchema = "diagnostic";
1246 srw_res->records[i].recordPacking = m_s2z_packing;
1247 srw_res->records[i].recordData_buf = "67";
1248 srw_res->records[i].recordData_len = 2;
1249 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1252 Z_External *r = npr->u.databaseRecord;
1253 oident *ent = oid_getentbyoid(r->direct_reference);
1254 if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
1256 srw_res->records[i].recordSchema = m_schema;
1257 srw_res->records[i].recordPacking = m_s2z_packing;
1258 srw_res->records[i].recordData_buf = (char*)
1259 r->u.octet_aligned->buf;
1260 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1261 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1265 srw_res->records[i].recordSchema = "diagnostic";
1266 srw_res->records[i].recordPacking = m_s2z_packing;
1267 srw_res->records[i].recordData_buf = "67";
1268 srw_res->records[i].recordData_len = 2;
1269 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1273 if (records && records->which == Z_Records_NSD)
1276 http_code = z_to_srw_diag(odr_encode(), srw_res,
1277 records->u.nonSurrogateDiagnostic);
1279 return send_http_response(http_code);
1281 return send_srw_response(srw_pdu);
1285 int Yaz_Proxy::send_srw_search_response(Z_SRW_diagnostic *diagnostics,
1286 int num_diagnostics, int http_code /* = 200 */)
1288 ODR o = odr_encode();
1289 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1290 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1292 srw_res->num_diagnostics = num_diagnostics;
1293 srw_res->diagnostics = diagnostics;
1294 return send_srw_response(srw_pdu, http_code);
1297 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1298 int num_diagnostics)
1300 Yaz_ProxyConfig *cfg = check_reconfigure();
1304 char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1305 m_s2z_database, &len);
1308 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1309 Z_SRW_explainResponse *er = res->u.explain_response;
1311 er->record.recordData_buf = b;
1312 er->record.recordData_len = len;
1313 er->record.recordPacking = m_s2z_packing;
1314 er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
1316 er->diagnostics = diagnostics;
1317 er->num_diagnostics = num_diagnostics;
1318 return send_srw_response(res);
1321 return send_http_response(404);
1324 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1328 if (apdu->which == Z_APDU_initResponse)
1330 Z_InitResponse *res = apdu->u.initResponse;
1331 if (*res->result == 0)
1333 send_to_srw_client_error(3, 0);
1335 else if (!m_s2z_search_apdu)
1337 send_srw_explain_response(0, 0);
1341 handle_incoming_Z_PDU(m_s2z_search_apdu);
1344 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1346 m_s2z_search_apdu = 0;
1347 Z_SearchResponse *res = apdu->u.searchResponse;
1348 m_s2z_hit_count = *res->resultCount;
1349 if (res->records && res->records->which == Z_Records_NSD)
1351 send_to_srw_client_ok(0, res->records, 1);
1353 else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1356 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1358 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1360 if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1362 *pr->numberOfRecordsRequested =
1363 1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1365 handle_incoming_Z_PDU(m_s2z_present_apdu);
1369 m_s2z_present_apdu = 0;
1370 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1373 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1376 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1378 m_s2z_present_apdu = 0;
1379 Z_PresentResponse *res = apdu->u.presentResponse;
1380 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1386 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1387 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1389 int r = send_Z_PDU(apdu, &len);
1390 m_bytes_sent += len;
1391 m_bw_stat.add_bytes(len);
1398 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1400 int kill_session = 0;
1401 Z_ReferenceId **new_id = get_referenceIdP(apdu);
1404 *new_id = m_referenceId;
1406 if (apdu->which == Z_APDU_searchResponse)
1408 Z_SearchResponse *sr = apdu->u.searchResponse;
1409 Z_Records *p = sr->records;
1410 if (p && p->which == Z_Records_NSD)
1412 Z_DiagRec dr, *dr_p = &dr;
1413 dr.which = Z_DiagRec_defaultFormat;
1414 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1416 *sr->searchStatus = 0;
1417 display_diagrecs(&dr_p, 1);
1421 if (p && p->which == Z_Records_DBOSD)
1425 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1428 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1429 if (m_marcxml_mode == marcxml)
1430 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1433 convert_records_charset(p->u.databaseOrSurDiagnostics,
1435 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1439 if (sr->resultCount)
1441 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1443 if (*sr->resultCount < 0)
1445 m_flag_invalid_session = 1;
1448 *sr->searchStatus = 0;
1450 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1451 *sr->resultCount = 0;
1456 else if (apdu->which == Z_APDU_presentResponse)
1458 Z_PresentResponse *sr = apdu->u.presentResponse;
1459 Z_Records *p = sr->records;
1460 if (p && p->which == Z_Records_NSD)
1462 Z_DiagRec dr, *dr_p = &dr;
1463 dr.which = Z_DiagRec_defaultFormat;
1464 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1465 if (*sr->presentStatus == Z_PresentStatus_success)
1466 *sr->presentStatus = Z_PresentStatus_failure;
1467 display_diagrecs(&dr_p, 1);
1469 if (p && p->which == Z_Records_DBOSD)
1473 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1476 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1477 if (m_marcxml_mode == marcxml)
1478 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1481 convert_records_charset(p->u.databaseOrSurDiagnostics,
1483 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1487 else if (apdu->which == Z_APDU_initResponse)
1489 //Get and check negotiation record
1490 //from init response.
1491 handle_charset_lang_negotiation(apdu);
1493 if (m_initRequest_options)
1496 (Odr_bitmask *)odr_malloc(odr_encode(),
1497 sizeof(Odr_bitmask));
1498 ODR_MASK_ZERO(nopt);
1501 for (i = 0; i<24; i++)
1502 if (ODR_MASK_GET(m_initRequest_options, i) &&
1503 ODR_MASK_GET(apdu->u.initResponse->options, i))
1504 ODR_MASK_SET(nopt, i);
1505 apdu->u.initResponse->options = nopt;
1507 if (m_initRequest_version)
1509 Z_ProtocolVersion *nopt =
1510 (Odr_bitmask *)odr_malloc(odr_encode(),
1511 sizeof(Odr_bitmask));
1512 ODR_MASK_ZERO(nopt);
1515 for (i = 0; i<8; i++)
1516 if (ODR_MASK_GET(m_initRequest_version, i) &&
1517 ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1518 ODR_MASK_SET(nopt, i);
1519 apdu->u.initResponse->protocolVersion = nopt;
1521 apdu->u.initResponse->preferredMessageSize =
1522 odr_intdup(odr_encode(),
1523 m_client->m_initResponse_preferredMessageSize >
1524 m_initRequest_preferredMessageSize ?
1525 m_initRequest_preferredMessageSize :
1526 m_client->m_initResponse_preferredMessageSize);
1527 apdu->u.initResponse->maximumRecordSize =
1528 odr_intdup(odr_encode(),
1529 m_client->m_initResponse_maximumRecordSize >
1530 m_initRequest_maximumRecordSize ?
1531 m_initRequest_maximumRecordSize :
1532 m_client->m_initResponse_maximumRecordSize);
1535 int r = send_PDU_convert(apdu);
1542 m_parent->pre_init();
1547 void Yaz_ProxyClient::set_idAuthentication(Z_APDU *apdu)
1549 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1551 odr_reset(m_idAuthentication_odr);
1552 z_IdAuthentication(m_idAuthentication_odr, &t, 1, 0);
1553 m_idAuthentication_ber_buf =
1554 odr_getbuf(m_idAuthentication_odr,
1555 &m_idAuthentication_ber_size, 0);
1558 bool Yaz_ProxyClient::compare_charset(Z_APDU *apdu)
1563 bool Yaz_ProxyClient::compare_idAuthentication(Z_APDU *apdu)
1565 Z_IdAuthentication *t = apdu->u.initRequest->idAuthentication;
1566 ODR odr = odr_createmem(ODR_ENCODE);
1568 z_IdAuthentication(odr, &t, 1, 0);
1570 char *buf = odr_getbuf(odr, &sz, 0);
1571 if (buf && m_idAuthentication_ber_buf
1572 && sz == m_idAuthentication_ber_size
1573 && !memcmp(m_idAuthentication_ber_buf, buf, sz))
1579 if (!buf && !m_idAuthentication_ber_buf)
1584 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1587 const char *apdu_name_tmp = apdu_name(apdu);
1588 int r = send_Z_PDU(apdu, &len);
1589 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1590 yaz_log (YLOG_LOG, "%sSending %s to %s %d bytes",
1592 apdu_name_tmp, get_hostname(), len);
1593 m_bytes_sent += len;
1597 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1599 if (apdu->which == Z_APDU_presentRequest)
1601 Z_PresentRequest *pr = apdu->u.presentRequest;
1602 int toget = *pr->numberOfRecordsRequested;
1603 int start = *pr->resultSetStartPoint;
1605 yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1606 pr->resultSetId, start, toget);
1608 if (*m_parent->m_optimize == '0')
1611 if (!m_client->m_last_resultSetId)
1613 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1614 new_apdu->u.presentResponse->records =
1615 create_nonSurrogateDiagnostics(odr_encode(), 30,
1617 send_to_client(new_apdu);
1620 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1622 if (start+toget-1 > m_client->m_last_resultCount)
1624 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1625 new_apdu->u.presentResponse->records =
1626 create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
1627 send_to_client(new_apdu);
1630 Z_NamePlusRecordList *npr;
1632 yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1633 m_session_str, start, toget, yaz_z3950oid_to_str(
1634 pr->preferredRecordSyntax, &oclass));
1636 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1637 pr->preferredRecordSyntax,
1638 pr->recordComposition))
1640 yaz_log (YLOG_LOG, "%sReturned cached records for present request",
1642 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1643 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1645 new_apdu->u.presentResponse->numberOfRecordsReturned
1646 = odr_intdup(odr_encode(), toget);
1648 new_apdu->u.presentResponse->records = (Z_Records*)
1649 odr_malloc(odr_encode(), sizeof(Z_Records));
1650 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1651 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1652 new_apdu->u.presentResponse->nextResultSetPosition =
1653 odr_intdup(odr_encode(), start+toget);
1655 send_to_client(new_apdu);
1661 if (apdu->which != Z_APDU_searchRequest)
1663 Z_SearchRequest *sr = apdu->u.searchRequest;
1664 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1665 Yaz_Z_Databases this_databases;
1667 this_databases.set(sr->num_databaseNames, (const char **)
1670 this_query->set_Z_Query(sr->query);
1672 char query_str[120];
1673 this_query->print(query_str, sizeof(query_str)-1);
1674 yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1676 if (*m_parent->m_optimize != '0' &&
1677 m_client->m_last_ok && m_client->m_last_query &&
1678 m_client->m_last_query->match(this_query) &&
1679 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1680 m_client->m_last_databases.match(this_databases))
1683 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1684 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1686 Z_NamePlusRecordList *npr;
1687 int toget = *sr->mediumSetPresentNumber;
1688 Z_RecordComposition *comp = 0;
1690 if (toget > m_client->m_last_resultCount)
1691 toget = m_client->m_last_resultCount;
1693 if (sr->mediumSetElementSetNames)
1695 comp = (Z_RecordComposition *)
1696 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1697 comp->which = Z_RecordComp_simple;
1698 comp->u.simple = sr->mediumSetElementSetNames;
1701 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1702 sr->preferredRecordSyntax, comp))
1704 yaz_log (YLOG_LOG, "%sReturned cached records for medium set",
1706 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1707 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1708 new_apdu->u.searchResponse->resultCount =
1709 &m_client->m_last_resultCount;
1711 new_apdu->u.searchResponse->numberOfRecordsReturned
1712 = odr_intdup(odr_encode(), toget);
1714 new_apdu->u.searchResponse->presentStatus =
1715 odr_intdup(odr_encode(), Z_PresentStatus_success);
1716 new_apdu->u.searchResponse->records = (Z_Records*)
1717 odr_malloc(odr_encode(), sizeof(Z_Records));
1718 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1719 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1720 new_apdu->u.searchResponse->nextResultSetPosition =
1721 odr_intdup(odr_encode(), toget+1);
1722 send_to_client(new_apdu);
1728 // send present request (medium size)
1729 yaz_log (YLOG_LOG, "%sOptimizing search for medium set",
1732 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1733 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1734 pr->referenceId = sr->referenceId;
1735 pr->resultSetId = sr->resultSetName;
1736 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1737 *pr->numberOfRecordsRequested = toget;
1738 pr->recordComposition = comp;
1739 m_client->m_sr_transform = 1;
1743 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1744 m_client->m_last_resultCount <= 0)
1746 // large set. Return pseudo-search response immediately
1747 yaz_log (YLOG_LOG, "%sOptimizing search for large set",
1749 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1750 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1751 new_apdu->u.searchResponse->resultCount =
1752 &m_client->m_last_resultCount;
1753 send_to_client(new_apdu);
1758 Z_NamePlusRecordList *npr;
1759 int toget = m_client->m_last_resultCount;
1760 Z_RecordComposition *comp = 0;
1762 // send a present request (small set)
1764 if (sr->smallSetElementSetNames)
1766 comp = (Z_RecordComposition *)
1767 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1768 comp->which = Z_RecordComp_simple;
1769 comp->u.simple = sr->smallSetElementSetNames;
1772 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1773 sr->preferredRecordSyntax, comp))
1775 yaz_log (YLOG_LOG, "%sReturned cached records for small set",
1777 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1778 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1779 new_apdu->u.searchResponse->resultCount =
1780 &m_client->m_last_resultCount;
1782 new_apdu->u.searchResponse->numberOfRecordsReturned
1783 = odr_intdup(odr_encode(), toget);
1785 new_apdu->u.searchResponse->presentStatus =
1786 odr_intdup(odr_encode(), Z_PresentStatus_success);
1787 new_apdu->u.searchResponse->records = (Z_Records*)
1788 odr_malloc(odr_encode(), sizeof(Z_Records));
1789 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1790 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1791 new_apdu->u.searchResponse->nextResultSetPosition =
1792 odr_intdup(odr_encode(), toget+1);
1793 send_to_client(new_apdu);
1798 yaz_log (YLOG_LOG, "%sOptimizing search for small set",
1800 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1801 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1802 pr->referenceId = sr->referenceId;
1803 pr->resultSetId = sr->resultSetName;
1804 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1805 *pr->numberOfRecordsRequested = toget;
1806 pr->recordComposition = comp;
1807 m_client->m_sr_transform = 1;
1812 else // query doesn't match
1814 delete m_client->m_last_query;
1815 m_client->m_last_query = this_query;
1816 m_client->m_last_ok = 0;
1817 m_client->m_cache.clear();
1818 m_client->m_resultSetStartPoint = 0;
1820 xfree (m_client->m_last_resultSetId);
1821 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1823 m_client->m_last_databases.set(sr->num_databaseNames,
1824 (const char **) sr->databaseNames);
1830 void Yaz_Proxy::inc_request_no()
1832 char *cp = strchr(m_session_str, ' ');
1835 sprintf(cp+1, "%d ", m_request_no);
1838 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1842 m_bytes_recv += len;
1844 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1845 yaz_log (YLOG_LOG, "%sReceiving %s from client %d bytes",
1846 m_session_str, gdu_name(apdu), len);
1848 #if HAVE_GETTIMEOFDAY
1849 gettimeofday((struct timeval *) m_time_tv, 0);
1851 m_bw_stat.add_bytes(len);
1852 m_pdu_stat.add_bytes(1);
1854 GDU *gdu = new GDU(apdu);
1855 m_in_queue.enqueue(gdu);
1857 recv_GDU_more(false);
1860 void Yaz_Proxy::recv_GDU_reduce(GDU *gdu)
1864 int bw_total = m_bw_stat.get_total();
1865 int pdu_total = m_pdu_stat.get_total();
1867 assert(m_timeout_mode == timeout_busy);
1868 assert(m_timeout_gdu == 0);
1872 if (bw_total > m_bw_max)
1874 reduce = (bw_total/m_bw_max);
1879 if (pdu_total > m_pdu_max)
1881 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1882 reduce = (reduce > nreduce) ? reduce : nreduce;
1888 /* uncomment to force a big reduce */
1889 m_timeout_mode = timeout_reduce;
1890 m_timeout_gdu = gdu;
1891 timeout(3); // call us reduce seconds later
1896 yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1897 m_session_str, reduce, bw_total, pdu_total,
1898 m_bw_max, m_pdu_max);
1900 m_timeout_mode = timeout_reduce;
1901 m_timeout_gdu = gdu;
1902 timeout(reduce); // call us reduce seconds later
1905 recv_GDU_normal(gdu);
1908 void Yaz_Proxy::recv_GDU_more(bool normal)
1911 if (normal && m_timeout_mode == timeout_busy)
1912 m_timeout_mode = timeout_normal;
1913 while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
1915 m_timeout_mode = timeout_busy;
1920 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
1923 gdu->move_away_gdu(odr_decode(), &apdu);
1926 if (apdu->which == Z_GDU_Z3950)
1927 handle_incoming_Z_PDU(apdu->u.z3950);
1928 else if (apdu->which == Z_GDU_HTTP_Request)
1929 handle_incoming_HTTP(apdu->u.HTTP_Request);
1932 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
1934 if (m_max_record_retrieve)
1936 if (apdu->which == Z_APDU_presentRequest)
1938 Z_PresentRequest *pr = apdu->u.presentRequest;
1939 if (pr->numberOfRecordsRequested &&
1940 *pr->numberOfRecordsRequested > m_max_record_retrieve)
1941 *pr->numberOfRecordsRequested = m_max_record_retrieve;
1946 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
1948 if (apdu->which == Z_APDU_initRequest)
1950 if (m_initRequest_options &&
1951 !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
1952 (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
1954 // There is no negotiation proposal from
1955 // client's side. OK. The proxy negotiation
1957 Z_InitRequest *initRequest = apdu->u.initRequest;
1958 Z_OtherInformation **otherInfo;
1959 Z_OtherInformationUnit *oi;
1960 get_otherInfoAPDU(apdu, &otherInfo);
1961 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
1964 ODR_MASK_SET(initRequest->options,
1965 Z_Options_negotiationModel);
1966 oi->which = Z_OtherInfo_externallyDefinedInfo;
1967 oi->information.externallyDefinedInfo =
1968 yaz_set_proposal_charneg(odr_encode(),
1969 (const char**)&m_proxy_negotiation_charset,
1970 m_proxy_negotiation_charset ? 1:0,
1971 (const char**)&m_proxy_negotiation_lang,
1972 m_proxy_negotiation_lang ? 1:0,
1976 else if (m_initRequest_options &&
1977 ODR_MASK_GET(m_initRequest_options,
1978 Z_Options_negotiationModel) &&
1979 m_charset_converter->get_target_query_charset())
1981 yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
1983 m_charset_converter->get_target_query_charset());
1984 Z_InitRequest *initRequest = apdu->u.initRequest;
1985 Z_CharSetandLanguageNegotiation *negotiation =
1986 yaz_get_charneg_record (initRequest->otherInfo);
1988 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1990 NMEM nmem = nmem_create();
1991 char **charsets = 0;
1992 int num_charsets = 0;
1996 yaz_get_proposal_charneg (nmem, negotiation,
1997 &charsets, &num_charsets,
1998 &langs, &num_langs, &selected);
2000 for (i = 0; i<num_charsets; i++)
2001 yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
2003 for (i = 0; i<num_langs; i++)
2004 yaz_log(YLOG_LOG, "%slang %s", m_session_str,
2007 const char *t_charset =
2008 m_charset_converter->get_target_query_charset();
2009 // sweep through charsets and pick the first supported
2011 for (i = 0; i<num_charsets; i++)
2013 const char *c_charset = charsets[i];
2014 if (!odr_set_charset(odr_decode(), t_charset, c_charset))
2017 if (i != num_charsets)
2019 // got one .. set up ODR for reverse direction
2020 const char *c_charset = charsets[i];
2021 odr_set_charset(odr_encode(), c_charset, t_charset);
2022 m_charset_converter->set_client_query_charset(c_charset);
2023 m_charset_converter->set_client_charset_selected(selected);
2026 ODR_MASK_CLEAR(m_initRequest_options,
2027 Z_Options_negotiationModel);
2028 yaz_del_charneg_record(&initRequest->otherInfo);
2032 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
2036 else if (m_charset_converter->get_target_query_charset() &&
2037 m_proxy_negotiation_default_charset)
2039 m_charset_converter->
2040 set_client_query_charset(m_proxy_negotiation_default_charset);
2043 else if (apdu->which == Z_APDU_initResponse)
2045 Z_InitResponse *initResponse = apdu->u.initResponse;
2046 Z_OtherInformation **otherInfo;
2047 get_otherInfoAPDU(apdu, &otherInfo);
2049 Z_CharSetandLanguageNegotiation *charneg = 0;
2051 if (otherInfo && *otherInfo &&
2052 ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel)
2053 && (charneg = yaz_get_charneg_record(*otherInfo)))
2059 yaz_get_response_charneg(m_referenceId_mem, charneg,
2060 &charset, &lang, &selected);
2062 yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
2063 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
2065 if (m_initRequest_options &&
2066 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
2068 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2071 else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2073 // negotiation-charset, negotiation-lang
2074 // elements of config file in use.
2076 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2079 // clear negotiation option.
2080 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2082 // Delete negotiation (charneg-3) entry.
2083 yaz_del_charneg_record(otherInfo);
2088 if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2090 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2093 else if (m_charset_converter->get_client_query_charset())
2095 Z_OtherInformation **otherInfo;
2096 Z_OtherInformationUnit *oi;
2097 get_otherInfoAPDU(apdu, &otherInfo);
2098 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2101 ODR_MASK_SET(initResponse->options,
2102 Z_Options_negotiationModel);
2103 if (m_initRequest_options)
2104 ODR_MASK_SET(m_initRequest_options,
2105 Z_Options_negotiationModel);
2107 oi->which = Z_OtherInfo_externallyDefinedInfo;
2108 oi->information.externallyDefinedInfo =
2109 yaz_set_response_charneg(
2111 m_charset_converter->get_client_query_charset(),
2113 m_charset_converter->get_client_charset_selected());
2120 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2122 const char *addinfo)
2124 Z_Records *rec = (Z_Records *)
2125 odr_malloc (odr, sizeof(*rec));
2127 odr_malloc (odr, sizeof(*err));
2128 Z_DiagRec *drec = (Z_DiagRec *)
2129 odr_malloc (odr, sizeof(*drec));
2130 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2131 odr_malloc (odr, sizeof(*dr));
2133 rec->which = Z_Records_NSD;
2134 rec->u.nonSurrogateDiagnostic = dr;
2135 dr->diagnosticSetId =
2136 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
2137 dr->condition = err;
2138 dr->which = Z_DefaultDiagFormat_v2Addinfo;
2139 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2143 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2145 if (apdu->which == Z_APDU_searchRequest &&
2146 apdu->u.searchRequest->query &&
2147 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2148 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2150 Z_RPNQuery *rpnquery = 0;
2151 Z_SearchRequest *sr = apdu->u.searchRequest;
2154 yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2155 sr->query->u.type_104->u.cql);
2157 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2158 &rpnquery, odr_encode(),
2161 yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2164 yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2165 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2167 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2168 new_apdu->u.searchResponse->records =
2169 create_nonSurrogateDiagnostics(odr_encode(),
2170 yaz_diag_srw_to_bib1(r),
2172 *new_apdu->u.searchResponse->searchStatus = 0;
2174 send_to_client(new_apdu);
2180 sr->query->which = Z_Query_type_1;
2181 sr->query->u.type_1 = rpnquery;
2188 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2190 if (apdu->which == Z_APDU_searchRequest &&
2191 apdu->u.searchRequest->query)
2193 if (apdu->u.searchRequest->query->which == Z_Query_type_1
2194 || apdu->u.searchRequest->query->which == Z_Query_type_101)
2197 m_charset_converter->set_client_query_charset("UTF-8");
2198 Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2199 m_charset_converter->convert_type_1(rpnquery, odr_encode());
2206 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2208 if (apdu->which == Z_APDU_searchRequest)
2210 Z_SearchRequest *sr = apdu->u.searchRequest;
2214 Yaz_ProxyConfig *cfg = check_reconfigure();
2216 err = cfg->check_query(odr_encode(), m_default_target,
2217 sr->query, &addinfo);
2220 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2222 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2223 new_apdu->u.searchResponse->records =
2224 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2225 *new_apdu->u.searchResponse->searchStatus = 0;
2227 send_to_client(new_apdu);
2235 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2237 if (apdu->which != Z_APDU_initRequest)
2238 return 1; // pass if no init request
2239 Z_InitRequest *req = apdu->u.initRequest;
2241 Yaz_ProxyConfig *cfg = check_reconfigure();
2243 return 1; // pass if no config
2246 if (req->idAuthentication == 0)
2248 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2251 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2253 ret = cfg->client_authentication(
2255 req->idAuthentication->u.idPass->userId,
2256 req->idAuthentication->u.idPass->groupId,
2257 req->idAuthentication->u.idPass->password,
2260 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2262 char user[64], pass[64];
2265 sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2266 ret = cfg->client_authentication(m_default_target, user, 0, pass,
2270 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2275 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2277 m_marcxml_mode = none;
2278 if (apdu->which == Z_APDU_searchRequest)
2280 Z_SearchRequest *sr = apdu->u.searchRequest;
2283 Yaz_ProxyConfig *cfg = check_reconfigure();
2285 Z_RecordComposition rc_temp, *rc = 0;
2286 if (sr->smallSetElementSetNames)
2288 rc_temp.which = Z_RecordComp_simple;
2289 rc_temp.u.simple = sr->smallSetElementSetNames;
2293 if (sr->preferredRecordSyntax)
2296 ent = oid_getentbyoid(sr->preferredRecordSyntax);
2297 m_frontend_type = ent->value;
2300 m_frontend_type = VAL_NONE;
2302 char *stylesheet_name = 0;
2304 err = cfg->check_syntax(odr_encode(),
2306 sr->preferredRecordSyntax, rc,
2307 &addinfo, &stylesheet_name, &m_schema,
2308 &m_backend_type, &m_backend_charset,
2309 &m_usemarcon_ini_stage1,
2310 &m_usemarcon_ini_stage2);
2311 if (stylesheet_name)
2313 m_parent->low_socket_close();
2316 if (m_stylesheet_xsp)
2317 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2318 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2321 m_stylesheet_offset = 0;
2322 xfree(stylesheet_name);
2324 m_parent->low_socket_open();
2328 sr->smallSetElementSetNames = 0;
2329 sr->mediumSetElementSetNames = 0;
2330 m_marcxml_mode = marcxml;
2334 sr->preferredRecordSyntax =
2335 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2339 sr->preferredRecordSyntax =
2340 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2345 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2347 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2348 new_apdu->u.searchResponse->records =
2349 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2350 *new_apdu->u.searchResponse->searchStatus = 0;
2352 send_to_client(new_apdu);
2356 else if (m_backend_type)
2358 sr->preferredRecordSyntax =
2359 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2362 else if (apdu->which == Z_APDU_presentRequest)
2364 Z_PresentRequest *pr = apdu->u.presentRequest;
2367 Yaz_ProxyConfig *cfg = check_reconfigure();
2369 if (pr->preferredRecordSyntax)
2372 ent = oid_getentbyoid(pr->preferredRecordSyntax);
2373 m_frontend_type = ent->value;
2376 m_frontend_type = VAL_NONE;
2378 char *stylesheet_name = 0;
2380 err = cfg->check_syntax(odr_encode(), m_default_target,
2381 pr->preferredRecordSyntax,
2382 pr->recordComposition,
2383 &addinfo, &stylesheet_name, &m_schema,
2384 &m_backend_type, &m_backend_charset,
2385 &m_usemarcon_ini_stage1,
2386 &m_usemarcon_ini_stage2
2388 if (stylesheet_name)
2390 m_parent->low_socket_close();
2393 if (m_stylesheet_xsp)
2394 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2395 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2398 m_stylesheet_offset = 0;
2399 xfree(stylesheet_name);
2401 m_parent->low_socket_open();
2405 pr->recordComposition = 0;
2406 m_marcxml_mode = marcxml;
2410 pr->preferredRecordSyntax =
2411 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2415 pr->preferredRecordSyntax =
2416 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2421 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2423 new_apdu->u.presentResponse->referenceId = pr->referenceId;
2424 new_apdu->u.presentResponse->records =
2425 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2426 *new_apdu->u.presentResponse->presentStatus =
2427 Z_PresentStatus_failure;
2429 send_to_client(new_apdu);
2433 else if (m_backend_type)
2435 pr->preferredRecordSyntax =
2436 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2442 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2446 Z_ElementSetNames *esn = (Z_ElementSetNames *)
2447 odr_malloc(o, sizeof(Z_ElementSetNames));
2448 esn->which = Z_ElementSetNames_generic;
2449 esn->u.generic = odr_strdup(o, schema);
2453 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2456 Yaz_ProxyConfig *cfg = check_reconfigure();
2458 t = cfg->get_explain_name(db, backend_db);
2460 if (m_client && m_default_target && t && strcmp(m_default_target, t))
2467 xfree(m_default_target);
2468 m_default_target = xstrdup(t);
2472 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2475 if (strcmp(hreq->method, "GET"))
2477 if (hreq->path[0] != '/')
2479 yaz_log(YLOG_WARN, "Bad path: %s", hreq->path);
2482 const char *cp = hreq->path;
2485 if (*cp == '/' && strchr("/.", cp[1]))
2487 yaz_log(YLOG_WARN, "Bad path: %s", hreq->path);
2492 const char *fname = hreq->path+1;
2493 if (stat(fname, &sbuf))
2495 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s: stat failed", fname);
2498 if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2500 yaz_log(YLOG_WARN, "%s: not a regular file", fname);
2503 if (sbuf.st_size > (off_t) 1000000)
2505 yaz_log(YLOG_WARN, "%s: too large for transfer", fname);
2509 ODR o = odr_encode();
2510 Yaz_ProxyConfig *cfg = check_reconfigure();
2511 const char *ctype = cfg->check_mime_type(fname);
2512 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2513 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2515 hres->version = odr_strdup(o, m_http_version);
2516 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2517 if (m_http_keepalive)
2518 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2522 hres->content_len = sbuf.st_size;
2523 hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2524 FILE *f = fopen(fname, "rb");
2527 fread(hres->content_buf, 1, hres->content_len, f);
2534 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2536 yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
2540 send_GDU(gdu, &len);
2541 recv_GDU_more(true);
2545 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2549 odr_destroy(m_s2z_odr_init);
2552 if (m_s2z_odr_search)
2554 odr_destroy(m_s2z_odr_search);
2555 m_s2z_odr_search = 0;
2558 m_http_keepalive = 0;
2560 if (!strcmp(hreq->version, "1.0"))
2562 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2563 if (v && !strcmp(v, "Keep-Alive"))
2564 m_http_keepalive = 1;
2566 m_http_keepalive = 0;
2567 m_http_version = "1.0";
2571 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2572 if (v && !strcmp(v, "close"))
2573 m_http_keepalive = 0;
2575 m_http_keepalive = 1;
2576 m_http_version = "1.1";
2579 const char *a = z_HTTP_header_lookup(hreq->headers, "Authorization");
2580 char authorization_str[255];
2581 *authorization_str = '\0';
2582 if (a && strncasecmp(a, "Basic ", 6) == 0)
2583 base64_decode(a + 6, authorization_str, 254);
2585 Z_SRW_PDU *srw_pdu = 0;
2586 Z_SOAP *soap_package = 0;
2588 Z_SRW_diagnostic *diagnostic = 0;
2589 int num_diagnostic = 0;
2591 if (file_access(hreq))
2595 else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2597 || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2598 &charset, &diagnostic, &num_diagnostic) == 0)
2600 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2601 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2602 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2603 m_s2z_init_apdu = 0;
2604 m_s2z_search_apdu = 0;
2605 m_s2z_present_apdu = 0;
2607 m_s2z_stylesheet = 0;
2609 Z_IdAuthentication *auth = NULL;
2610 if (*authorization_str)
2612 auth = (Z_IdAuthentication *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdAuthentication));
2613 auth->which = Z_IdAuthentication_idPass;
2614 auth->u.idPass = (Z_IdPass *) odr_malloc(m_s2z_odr_init, sizeof(Z_IdPass));
2615 auth->u.idPass->groupId = NULL;
2616 char *p = strchr(authorization_str, ':');
2621 auth->u.idPass->password = odr_strdup(m_s2z_odr_init, p);
2623 auth->u.idPass->userId = odr_strdup(m_s2z_odr_init, authorization_str);
2626 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2628 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2630 const char *backend_db = srw_req->database;
2631 srw_get_client(srw_req->database, &backend_db);
2633 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2634 // recordXPath unsupported.
2635 if (srw_req->recordXPath)
2637 yaz_add_srw_diagnostic(odr_decode(),
2638 &diagnostic, &num_diagnostic,
2642 if (srw_req->sort_type != Z_SRW_sort_type_none)
2644 yaz_add_srw_diagnostic(odr_decode(),
2645 &diagnostic, &num_diagnostic,
2649 if (srw_req->stylesheet)
2651 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2653 // set packing for response records ..
2654 if (srw_req->recordPacking &&
2655 !strcmp(srw_req->recordPacking, "xml"))
2656 m_s2z_packing = Z_SRW_recordPacking_XML;
2658 m_s2z_packing = Z_SRW_recordPacking_string;
2662 Z_SRW_PDU *srw_pdu =
2663 yaz_srw_get(odr_encode(),
2664 Z_SRW_searchRetrieve_response);
2665 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2667 srw_res->diagnostics = diagnostic;
2668 srw_res->num_diagnostics = num_diagnostic;
2669 send_srw_response(srw_pdu);
2673 // prepare search PDU
2674 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2675 Z_APDU_searchRequest);
2676 Z_SearchRequest *z_searchRequest =
2677 m_s2z_search_apdu->u.searchRequest;
2679 z_searchRequest->num_databaseNames = 1;
2680 z_searchRequest->databaseNames = (char**)
2681 odr_malloc(m_s2z_odr_search, sizeof(char *));
2682 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2685 // query transformation
2686 Z_Query *query = (Z_Query *)
2687 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2688 z_searchRequest->query = query;
2690 if (srw_req->query_type == Z_SRW_query_type_cql)
2692 Z_External *ext = (Z_External *)
2693 odr_malloc(m_s2z_odr_search, sizeof(*ext));
2694 ext->direct_reference =
2695 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2696 ext->indirect_reference = 0;
2697 ext->descriptor = 0;
2698 ext->which = Z_External_CQL;
2699 ext->u.cql = srw_req->query.cql;
2701 query->which = Z_Query_type_104;
2702 query->u.type_104 = ext;
2704 else if (srw_req->query_type == Z_SRW_query_type_pqf)
2706 Z_RPNQuery *RPNquery;
2707 YAZ_PQF_Parser pqf_parser;
2709 pqf_parser = yaz_pqf_create ();
2711 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2712 srw_req->query.pqf);
2715 const char *pqf_msg;
2717 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2719 yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
2720 yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2722 send_to_srw_client_error(10, 0);
2725 query->which = Z_Query_type_1;
2726 query->u.type_1 = RPNquery;
2728 yaz_pqf_destroy (pqf_parser);
2732 send_to_srw_client_error(7, "query");
2737 m_s2z_present_apdu = 0;
2739 if (srw_req->maximumRecords)
2740 max = *srw_req->maximumRecords;
2742 if (srw_req->startRecord)
2743 start = *srw_req->startRecord;
2746 // Some backend, such as Voyager doesn't honor piggyback
2747 // So we use present always (0 &&).
2748 if (0 && start <= 1) // Z39.50 piggyback
2750 *z_searchRequest->smallSetUpperBound = max;
2751 *z_searchRequest->mediumSetPresentNumber = max;
2752 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2754 z_searchRequest->preferredRecordSyntax =
2755 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2757 if (srw_req->recordSchema)
2759 z_searchRequest->smallSetElementSetNames =
2760 z_searchRequest->mediumSetElementSetNames =
2761 mk_esn_from_schema(m_s2z_odr_search,
2762 srw_req->recordSchema);
2765 else // Z39.50 present
2767 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2768 Z_APDU_presentRequest);
2769 Z_PresentRequest *z_presentRequest =
2770 m_s2z_present_apdu->u.presentRequest;
2771 *z_presentRequest->resultSetStartPoint = start;
2772 *z_presentRequest->numberOfRecordsRequested = max;
2773 z_presentRequest->preferredRecordSyntax =
2774 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2776 if (srw_req->recordSchema)
2778 z_presentRequest->recordComposition =
2779 (Z_RecordComposition *)
2780 odr_malloc(m_s2z_odr_search,
2781 sizeof(Z_RecordComposition));
2782 z_presentRequest->recordComposition->which =
2783 Z_RecordComp_simple;
2784 z_presentRequest->recordComposition->u.simple =
2785 mk_esn_from_schema(m_s2z_odr_search,
2786 srw_req->recordSchema);
2792 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2793 Z_APDU_initRequest);
2795 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2797 // prevent m_initRequest_apdu memory from being grabbed
2798 // in Yaz_Proxy::handle_incoming_Z_PDU
2799 m_initRequest_apdu = m_s2z_init_apdu;
2800 handle_incoming_Z_PDU(m_s2z_init_apdu);
2805 handle_incoming_Z_PDU(m_s2z_search_apdu);
2809 else if (srw_pdu->which == Z_SRW_explain_request)
2811 Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
2813 const char *backend_db = srw_req->database;
2814 srw_get_client(srw_req->database, &backend_db);
2816 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2819 if (srw_req->stylesheet)
2821 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2823 if (srw_req->recordPacking &&
2824 !strcmp(srw_req->recordPacking, "xml"))
2825 m_s2z_packing = Z_SRW_recordPacking_XML;
2827 m_s2z_packing = Z_SRW_recordPacking_string;
2831 send_srw_explain_response(diagnostic, num_diagnostic);
2837 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2838 Z_APDU_initRequest);
2840 m_s2z_init_apdu->u.initRequest->idAuthentication = auth;
2842 // prevent m_initRequest_apdu memory from being grabbed
2843 // in Yaz_Proxy::handle_incoming_Z_PDU
2844 m_initRequest_apdu = m_s2z_init_apdu;
2845 handle_incoming_Z_PDU(m_s2z_init_apdu);
2848 send_srw_explain_response(0, 0);
2851 else if (srw_pdu->which == Z_SRW_scan_request)
2853 m_s2z_database = odr_strdup(m_s2z_odr_init,
2854 srw_pdu->u.scan_request->database);
2856 yaz_add_srw_diagnostic(odr_decode(),
2857 &diagnostic, &num_diagnostic,
2859 Z_SRW_PDU *srw_pdu =
2860 yaz_srw_get(odr_encode(),
2861 Z_SRW_scan_response);
2862 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
2864 srw_res->diagnostics = diagnostic;
2865 srw_res->num_diagnostics = num_diagnostic;
2866 send_srw_response(srw_pdu);
2873 send_to_srw_client_error(4, 0);
2876 send_http_response(400);
2879 void Yaz_Proxy::handle_init(Z_APDU *apdu)
2882 Z_OtherInformation **oi;
2883 get_otherInfoAPDU(apdu, &oi);
2885 if (apdu->u.initRequest->implementationId)
2886 yaz_log(YLOG_LOG, "%simplementationId: %s",
2887 m_session_str, apdu->u.initRequest->implementationId);
2888 if (apdu->u.initRequest->implementationName)
2889 yaz_log(YLOG_LOG, "%simplementationName: %s",
2890 m_session_str, apdu->u.initRequest->implementationName);
2891 if (apdu->u.initRequest->implementationVersion)
2892 yaz_log(YLOG_LOG, "%simplementationVersion: %s",
2893 m_session_str, apdu->u.initRequest->implementationVersion);
2894 if (m_initRequest_apdu == 0)
2896 if (m_initRequest_mem)
2897 nmem_destroy(m_initRequest_mem);
2899 m_initRequest_apdu = apdu;
2900 m_initRequest_mem = odr_extract_mem(odr_decode());
2902 m_initRequest_preferredMessageSize = *apdu->u.initRequest->
2903 preferredMessageSize;
2904 *apdu->u.initRequest->preferredMessageSize = 1024*1024;
2905 m_initRequest_maximumRecordSize = *apdu->u.initRequest->
2907 *apdu->u.initRequest->maximumRecordSize = 1024*1024;
2909 Z_CharSetandLanguageNegotiation *charSetandLangRecord =
2910 yaz_get_charneg_record(*oi);
2912 // Save proposal charsets and langs.
2913 if (ODR_MASK_GET(apdu->u.initRequest->options,
2914 Z_Options_negotiationModel)
2915 && charSetandLangRecord)
2918 yaz_get_proposal_charneg(m_referenceId_mem,
2919 charSetandLangRecord,
2920 &m_initRequest_oi_negotiation_charsets,
2921 &m_initRequest_oi_negotiation_num_charsets,
2922 &m_initRequest_oi_negotiation_langs,
2923 &m_initRequest_oi_negotiation_num_langs,
2924 &m_initRequest_oi_negotiation_selected);
2926 for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
2928 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
2929 m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
2930 m_initRequest_oi_negotiation_charsets[i]:"none");
2932 for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
2934 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
2935 m_session_str, (m_initRequest_oi_negotiation_langs[i])?
2936 m_initRequest_oi_negotiation_langs[i]:"none");
2938 yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
2939 m_session_str, m_initRequest_oi_negotiation_selected);
2941 // save init options for the response..
2942 m_initRequest_options = apdu->u.initRequest->options;
2944 apdu->u.initRequest->options =
2945 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2946 sizeof(Odr_bitmask));
2947 ODR_MASK_ZERO(apdu->u.initRequest->options);
2949 for (i = 0; i<= 24; i++)
2950 ODR_MASK_SET(apdu->u.initRequest->options, i);
2951 // check negotiation option
2952 if (!ODR_MASK_GET(m_initRequest_options,
2953 Z_Options_negotiationModel))
2955 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2956 Z_Options_negotiationModel);
2958 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2959 Z_Options_concurrentOperations);
2961 m_initRequest_version = apdu->u.initRequest->protocolVersion;
2962 apdu->u.initRequest->protocolVersion =
2963 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2964 sizeof(Odr_bitmask));
2965 ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
2967 for (i = 0; i<= 8; i++)
2968 ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
2970 handle_charset_lang_negotiation(apdu);
2971 if (m_client->m_init_flag)
2973 if (handle_init_response_for_invalid_session(apdu))
2975 if (m_client->m_initResponse)
2977 Z_APDU *apdu2 = m_client->m_initResponse;
2978 apdu2->u.initResponse->otherInfo = 0;
2979 if (m_client->m_cookie && *m_client->m_cookie)
2980 set_otherInformationString(apdu2, VAL_COOKIE, 1,
2981 m_client->m_cookie);
2982 apdu2->u.initResponse->referenceId =
2983 apdu->u.initRequest->referenceId;
2984 apdu2->u.initResponse->options = m_client->m_initResponse_options;
2985 apdu2->u.initResponse->protocolVersion =
2986 m_client->m_initResponse_version;
2988 handle_charset_lang_negotiation(apdu2);
2990 send_to_client(apdu2);
2991 m_timeout_mode = timeout_normal;
2995 m_client->m_init_flag = 1;
2998 Auth_Msg *m = new Auth_Msg;
3000 z_APDU(odr_encode(), &apdu, 0, "encode");
3001 char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
3002 m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
3003 memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
3004 odr_reset(odr_encode());
3007 m_my_thread->put(m);
3009 int ret = handle_authentication(apdu);
3010 result_authentication(apdu, ret);
3014 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
3016 Z_ReferenceId **refid = get_referenceIdP(apdu);
3017 nmem_reset(m_referenceId_mem);
3018 if (refid && *refid)
3020 m_referenceId = (Z_ReferenceId *)
3021 nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
3022 m_referenceId->len = m_referenceId->size = (*refid)->len;
3023 m_referenceId->buf = (unsigned char *)
3024 nmem_malloc(m_referenceId_mem, (*refid)->len);
3025 memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
3030 if (!m_client && m_flag_invalid_session)
3032 // Got request for a session that is invalid..
3033 m_apdu_invalid_session = apdu; // save package
3034 m_mem_invalid_session = odr_extract_mem(odr_decode());
3035 apdu = m_initRequest_apdu; // but throw an init to the target
3038 // Determine our client.
3039 Z_OtherInformation **oi;
3040 get_otherInfoAPDU(apdu, &oi);
3041 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
3045 { // HTTP. Send not found
3046 send_http_response(404);
3051 // Z39.50 just shutdown
3057 m_client->m_server = this;
3059 if (apdu->which == Z_APDU_initRequest)
3062 handle_incoming_Z_PDU_2(apdu);
3065 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
3067 handle_max_record_retrieve(apdu);
3070 apdu = handle_syntax_validation(apdu);
3073 apdu = handle_query_transformation(apdu);
3076 apdu = handle_target_charset_conversion(apdu);
3079 apdu = handle_query_validation(apdu);
3082 apdu = result_set_optimize(apdu);
3086 m_client->timeout(m_target_idletime); // mark it active even
3087 recv_GDU_more(true);
3088 // though we didn't use it
3092 // delete other info construct completely if 0 elements
3093 Z_OtherInformation **oi;
3094 get_otherInfoAPDU(apdu, &oi);
3095 if (oi && *oi && (*oi)->num_elements == 0)
3098 if (apdu->which == Z_APDU_presentRequest &&
3099 m_client->m_resultSetStartPoint == 0)
3101 Z_PresentRequest *pr = apdu->u.presentRequest;
3102 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3103 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3105 m_client->m_resultSetStartPoint = 0;
3107 if (m_client->send_to_target(apdu) < 0)
3109 m_client->shutdown();
3112 m_client->m_waiting = 1;
3115 void Yaz_Proxy::connectNotify()
3119 void Yaz_Proxy::releaseClient()
3121 xfree(m_proxyTarget);
3123 m_flag_invalid_session = 0;
3124 // only keep if keep_alive flag is set...
3126 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3127 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3128 m_client->m_waiting == 0)
3130 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3132 m_client->get_hostname());
3133 yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3134 m_session_str, m_client->m_pdu_recv,
3135 m_client->m_bytes_sent + m_client->m_bytes_recv,
3136 m_keepalive_limit_bw, m_keepalive_limit_pdu);
3137 assert (m_client->m_waiting != 2);
3138 // Tell client (if any) that no server connection is there..
3139 m_client->m_server = 0;
3144 yaz_log (YLOG_LOG, "%sShutdown (client to proxy) close %s",
3146 m_client->get_hostname());
3147 assert (m_client->m_waiting != 2);
3153 yaz_log (YLOG_LOG, "%sshutdown (client to proxy) bad state",
3159 yaz_log (YLOG_LOG, "%sShutdown (client to proxy)",
3163 m_parent->pre_init();
3166 bool Yaz_Proxy::dec_ref(bool main_ptr)
3168 assert(m_ref_count > 0);
3173 m_main_ptr_dec = true;
3176 m_http_keepalive = 0;
3179 if (m_ref_count > 0)
3188 const char *Yaz_ProxyClient::get_session_str()
3192 return m_server->get_session_str();
3195 void Yaz_ProxyClient::shutdown()
3197 yaz_log (YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
3202 m_waiting = 1; // ensure it's released from Proxy in releaseClient
3203 m_server->dec_ref(true);
3209 void Yaz_Proxy::failNotify()
3212 yaz_log (YLOG_LOG, "%sConnection closed by client",
3217 void Yaz_Proxy::send_response_fail_client(const char *addr)
3221 Z_SRW_diagnostic *diagnostic = 0;
3222 int num_diagnostic = 0;
3224 yaz_add_srw_diagnostic(odr_encode(),
3225 &diagnostic, &num_diagnostic,
3226 YAZ_SRW_SYSTEM_TEMPORARILY_UNAVAILABLE, addr);
3227 if (m_s2z_search_apdu)
3228 send_srw_search_response(diagnostic, num_diagnostic);
3230 send_srw_explain_response(diagnostic, num_diagnostic);
3233 void Yaz_ProxyClient::failNotify()
3236 m_server->inc_request_no();
3237 yaz_log (YLOG_LOG, "%sConnection closed by target %s",
3238 get_session_str(), get_hostname());
3241 m_server->send_response_fail_client(get_hostname());
3245 void Yaz_ProxyClient::connectNotify()
3247 const char *s = get_session_str();
3248 const char *h = get_hostname();
3249 yaz_log (YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
3251 timeout(m_target_idletime);
3256 IPDU_Observer *Yaz_ProxyClient::sessionNotify(IPDU_Observable
3257 *the_PDU_Observable, int fd)
3259 return new Yaz_ProxyClient(the_PDU_Observable, 0);
3262 Yaz_ProxyClient::~Yaz_ProxyClient()
3267 m_next->m_prev = m_prev;
3268 m_waiting = 2; // for debugging purposes only.
3269 odr_destroy(m_init_odr);
3270 odr_destroy(m_idAuthentication_odr);
3271 delete m_last_query;
3272 xfree (m_last_resultSetId);
3276 void Yaz_ProxyClient::pre_init_client()
3278 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
3279 Z_InitRequest *req = apdu->u.initRequest;
3282 for (i = 0; i<= 24; i++)
3283 ODR_MASK_SET(req->options, i);
3284 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3285 Z_Options_negotiationModel);
3286 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3287 Z_Options_concurrentOperations);
3288 for (i = 0; i<= 10; i++)
3289 ODR_MASK_SET(req->protocolVersion, i);
3291 if (send_to_target(apdu) < 0)
3302 void Yaz_Proxy::pre_init()
3305 const char *name = 0;
3306 const char *zurl_in_use[MAX_ZURL_PLEX];
3307 int limit_bw, limit_pdu, limit_req, limit_search;
3308 int target_idletime, client_idletime;
3310 int keepalive_limit_bw, keepalive_limit_pdu;
3312 const char *cql2rpn = 0;
3313 const char *authentication = 0;
3314 const char *negotiation_charset = 0;
3315 const char *negotiation_lang = 0;
3317 Yaz_ProxyConfig *cfg = check_reconfigure();
3321 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
3326 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
3327 &limit_bw, &limit_pdu, &limit_req,
3329 &target_idletime, &client_idletime,
3331 &keepalive_limit_bw,
3332 &keepalive_limit_pdu,
3336 &negotiation_charset,
3344 for (j = 0; zurl_in_use[j]; j++)
3348 int spare_waiting = 0;
3351 for (c = m_clientPool; c; c = c->m_next)
3353 if (!strcmp(zurl_in_use[j], c->get_hostname()))
3355 if (c->m_cookie == 0)
3357 if (c->m_server == 0)
3369 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
3370 "sparew=%d preinit=%d",m_session_str,
3371 name, zurl_in_use[j], in_use, other,
3372 spare, spare_waiting, pre_init);
3373 if (spare + spare_waiting < pre_init)
3375 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
3376 c->m_next = m_clientPool;
3378 c->m_next->m_prev = &c->m_next;
3380 c->m_prev = &m_clientPool;
3382 if (m_log_mask & PROXY_LOG_APDU_SERVER)
3383 c->set_APDU_yazlog(1);
3385 c->set_APDU_yazlog(0);
3387 if (c->client(zurl_in_use[j]))
3395 c->m_target_idletime = target_idletime;
3396 c->m_seqno = m_seqno++;
3403 void Yaz_Proxy::timeoutNotify()
3408 switch(m_timeout_mode)
3410 case timeout_normal:
3414 yaz_log (YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
3417 case timeout_reduce:
3418 timeout(m_client_idletime);
3419 m_timeout_mode = timeout_busy;
3420 gdu = m_timeout_gdu;
3422 recv_GDU_normal(gdu);
3425 assert(m_stylesheet_nprl);
3426 convert_xsl_delay();
3427 recv_GDU_more(true);
3437 void Yaz_Proxy::markInvalid()
3440 m_flag_invalid_session = 1;
3443 void Yaz_ProxyClient::timeoutNotify()
3446 m_server->inc_request_no();
3448 yaz_log (YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
3452 m_server->send_response_fail_client(get_hostname());
3458 Yaz_ProxyClient::Yaz_ProxyClient(IPDU_Observable *the_PDU_Observable,
3459 Yaz_Proxy *parent) :
3460 Z_Assoc (the_PDU_Observable)
3467 m_last_resultSetId = 0;
3468 m_last_resultCount = 0;
3472 m_init_odr = odr_createmem (ODR_DECODE);
3474 m_initResponse_options = 0;
3475 m_initResponse_version = 0;
3476 m_initResponse_preferredMessageSize = 0;
3477 m_initResponse_maximumRecordSize = 0;
3478 m_resultSetStartPoint = 0;
3479 m_bytes_sent = m_bytes_recv = 0;
3483 m_target_idletime = 600;
3485 m_idAuthentication_odr = odr_createmem(ODR_ENCODE);
3486 m_idAuthentication_ber_buf = 0;
3487 m_idAuthentication_ber_size = 0;
3490 const char *Yaz_Proxy::option(const char *name, const char *value)
3492 if (!strcmp (name, "optimize")) {
3495 m_optimize = xstrdup (value);
3502 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
3507 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
3509 if (apdu->which == Z_GDU_Z3950)
3510 recv_Z_PDU(apdu->u.z3950, len);
3511 else if (apdu->which == Z_GDU_HTTP_Response)
3512 recv_HTTP_response(apdu->u.HTTP_Response, len);
3517 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
3519 if (!m_flag_invalid_session)
3521 m_flag_invalid_session = 0;
3522 handle_incoming_Z_PDU(m_apdu_invalid_session);
3523 assert (m_mem_invalid_session);
3524 nmem_destroy(m_mem_invalid_session);
3525 m_mem_invalid_session = 0;
3529 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
3531 m_bytes_recv += len;
3535 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
3536 yaz_log (YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
3537 apdu_name(apdu), get_hostname(), len);
3538 if (apdu->which == Z_APDU_initResponse)
3540 if (!m_server) // if this is a pre init session , check for more
3542 NMEM nmem = odr_extract_mem (odr_decode());
3543 odr_reset (m_init_odr);
3544 nmem_transfer (m_init_odr->mem, nmem);
3545 m_initResponse = apdu;
3546 m_initResponse_options = apdu->u.initResponse->options;
3547 m_initResponse_version = apdu->u.initResponse->protocolVersion;
3548 m_initResponse_preferredMessageSize =
3549 *apdu->u.initResponse->preferredMessageSize;
3550 m_initResponse_maximumRecordSize =
3551 *apdu->u.initResponse->maximumRecordSize;
3553 Z_InitResponse *ir = apdu->u.initResponse;
3554 char *im0 = ir->implementationName;
3557 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
3564 strcat(im1, "(YAZ Proxy)");
3565 ir->implementationName = im1;
3567 nmem_destroy (nmem);
3569 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
3572 if (apdu->which == Z_APDU_searchResponse)
3574 Z_SearchResponse *sr = apdu->u.searchResponse;
3575 m_last_resultCount = *sr->resultCount;
3576 int status = *sr->searchStatus;
3577 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
3581 if (sr->records && sr->records->which == Z_Records_DBOSD)
3583 m_cache.add(odr_decode(),
3584 sr->records->u.databaseOrSurDiagnostics, 1,
3589 if (apdu->which == Z_APDU_presentResponse)
3591 Z_PresentResponse *pr = apdu->u.presentResponse;
3595 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
3596 Z_SearchResponse *sr = new_apdu->u.searchResponse;
3597 sr->referenceId = pr->referenceId;
3598 *sr->resultCount = m_last_resultCount;
3599 sr->records = pr->records;
3600 sr->nextResultSetPosition = pr->nextResultSetPosition;
3601 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
3605 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
3607 m_cache.add(odr_decode(),
3608 pr->records->u.databaseOrSurDiagnostics,
3609 m_resultSetStartPoint, -1);
3610 m_resultSetStartPoint = 0;
3614 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
3616 Yaz_Proxy *server = m_server; // save it. send_to_client may destroy us
3619 server->send_to_client(apdu);
3620 if (apdu->which == Z_APDU_close)
3623 server->recv_GDU_more(true);
3626 void Yaz_Proxy::low_socket_close()
3631 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3632 if (m_lo_fd[i] >= 0)
3633 ::close(m_lo_fd[i]);
3637 void Yaz_Proxy::low_socket_open()
3642 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3643 m_lo_fd[i] = open("/dev/null", O_RDONLY);
3647 int Yaz_Proxy::server(const char *addr)
3649 int r = Z_Assoc::server(addr);
3652 yaz_log(YLOG_LOG, "%sStarted proxy "
3656 " on %s", m_session_str, addr);
3662 void Yaz_Proxy::base64_decode(const char *base64, char *buf, int buf_len)
3664 const char *base64_chars =
3665 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3666 int len = strlen(base64);
3670 for (int pos = 0; pos <= len; pos++)
3672 if (base64[pos] == '=' || buf_pos + 1 >= buf_len)
3675 const char *ch_ptr = strchr(base64_chars, base64[pos]);
3678 char ch = (char) (ch_ptr - base64_chars);
3682 buf[buf_pos] = ch << 2;
3685 buf[buf_pos++] += (ch & 0x30) >> 4;
3686 buf[buf_pos] = (ch & 0x0f) << 4;
3689 buf[buf_pos++] += (ch & 0x3c) >> 2;
3690 buf[buf_pos] = (ch & 0x03) << 6;
3693 buf[buf_pos++] += ch;
3700 buf[buf_pos] = '\0';
3706 * indent-tabs-mode: nil
3708 * vim: shiftwidth=4 tabstop=8 expandtab