1 /* $Id: yaz-proxy.cpp,v 1.42 2006-03-09 00:08:29 adam Exp $
2 Copyright (c) 1998-2005, Index Data.
4 This file is part of the yaz-proxy.
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;
58 #define USE_AUTH_MSG 1
61 class Auth_Msg : public IMsg_Thread {
64 IMsg_Thread *handle();
76 m_nmem = nmem_create();
84 IMsg_Thread *Auth_Msg::handle()
86 yaz_log(YLOG_LOG, "Auth_Msg:handle begin");
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);
100 yaz_log(YLOG_LOG, "Auth_Msg:handle end");
105 void Auth_Msg::result()
107 yaz_log(YLOG_LOG, "Auth_Msg:result proxy ok buf=%p len=%d",
108 m_apdu_buf, m_apdu_len);
109 if (m_proxy->dec_ref(false))
110 yaz_log(YLOG_LOG, "Auth_Msg::proxy deleted meanwhile");
113 yaz_log(YLOG_LOG, "Auth_Msg::proxy still alive");
114 odr_setbuf(m_proxy->odr_decode(), m_apdu_buf, m_apdu_len, 0);
116 int r = z_APDU(m_proxy->odr_decode(), &apdu, 0, 0);
118 yaz_log(YLOG_LOG, "Auth_Msg::result z_APDU OK");
120 yaz_log(YLOG_LOG, "Auth_Msg::result z_APDU failed");
121 m_proxy->result_authentication(apdu, m_ret);
128 void Yaz_Proxy::result_authentication(Z_APDU *apdu, int ret)
130 if (apdu == 0 || ret == 0)
132 Z_APDU *apdu_reject = zget_APDU(odr_encode(), Z_APDU_initResponse);
133 *apdu_reject->u.initResponse->result = 0;
134 send_to_client(apdu_reject);
138 handle_incoming_Z_PDU_2(apdu);
141 static const char *apdu_name(Z_APDU *apdu)
145 case Z_APDU_initRequest:
146 return "initRequest";
147 case Z_APDU_initResponse:
148 return "initResponse";
149 case Z_APDU_searchRequest:
150 return "searchRequest";
151 case Z_APDU_searchResponse:
152 return "searchResponse";
153 case Z_APDU_presentRequest:
154 return "presentRequest";
155 case Z_APDU_presentResponse:
156 return "presentResponse";
157 case Z_APDU_deleteResultSetRequest:
158 return "deleteResultSetRequest";
159 case Z_APDU_deleteResultSetResponse:
160 return "deleteResultSetResponse";
161 case Z_APDU_scanRequest:
162 return "scanRequest";
163 case Z_APDU_scanResponse:
164 return "scanResponse";
165 case Z_APDU_sortRequest:
166 return "sortRequest";
167 case Z_APDU_sortResponse:
168 return "sortResponse";
169 case Z_APDU_extendedServicesRequest:
170 return "extendedServicesRequest";
171 case Z_APDU_extendedServicesResponse:
172 return "extendedServicesResponse";
179 static const char *gdu_name(Z_GDU *gdu)
184 return apdu_name(gdu->u.z3950);
185 case Z_GDU_HTTP_Request:
186 return "HTTP Request";
187 case Z_GDU_HTTP_Response:
188 return "HTTP Response";
190 return "Unknown request/response";
193 Yaz_Proxy::Yaz_Proxy(IPDU_Observable *the_PDU_Observable,
194 ISocketObservable *the_socket_observable,
197 Z_Assoc(the_PDU_Observable), m_bw_stat(60), m_pdu_stat(60)
199 m_PDU_Observable = the_PDU_Observable;
200 m_socket_observable = the_socket_observable;
205 m_keepalive_limit_bw = 500000;
206 m_keepalive_limit_pdu = 1000;
208 m_default_target = 0;
209 m_proxy_negotiation_charset = 0;
210 m_proxy_negotiation_lang = 0;
211 m_charset_converter = new Yaz_CharsetConverter;
215 m_client_idletime = 600;
216 m_target_idletime = 600;
217 m_optimize = xstrdup ("1");
218 strcpy(m_session_str, "0 ");
226 m_timeout_mode = timeout_normal;
228 m_max_record_retrieve = 0;
232 m_flag_invalid_session = 0;
234 m_referenceId_mem = nmem_create();
236 m_marcxml_mode = none;
237 m_stylesheet_xsp = 0;
238 m_stylesheet_nprl = 0;
239 m_stylesheet_apdu = 0;
240 m_s2z_stylesheet = 0;
244 m_backend_charset = 0;
246 m_initRequest_apdu = 0;
247 m_initRequest_mem = 0;
248 m_initRequest_preferredMessageSize = 0;
249 m_initRequest_maximumRecordSize = 0;
250 m_initRequest_options = 0;
251 m_initRequest_version = 0;
252 m_initRequest_oi_negotiation_charsets = 0;
253 m_initRequest_oi_negotiation_num_charsets = 0;
254 m_initRequest_oi_negotiation_langs = 0;
255 m_initRequest_oi_negotiation_num_langs = 0;
256 m_initRequest_oi_negotiation_selected = 0;
257 m_apdu_invalid_session = 0;
258 m_mem_invalid_session = 0;
260 m_s2z_odr_search = 0;
262 m_s2z_search_apdu = 0;
263 m_s2z_present_apdu = 0;
264 m_http_keepalive = 0;
267 m_s2z_packing = Z_SRW_recordPacking_string;
268 #if HAVE_GETTIMEOFDAY
269 m_time_tv = xmalloc(sizeof(struct timeval));
270 struct timeval *tv = (struct timeval *) m_time_tv;
276 m_usemarcon_ini_stage1 = 0;
277 m_usemarcon_ini_stage2 = 0;
278 m_usemarcon = new Yaz_usemarcon();
283 m_main_ptr_dec = false;
287 void Yaz_Proxy::inc_ref()
292 Yaz_Proxy::~Yaz_Proxy()
294 yaz_log(YLOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
295 m_bytes_sent, m_bytes_recv);
296 nmem_destroy(m_initRequest_mem);
297 nmem_destroy(m_mem_invalid_session);
298 nmem_destroy(m_referenceId_mem);
300 xfree(m_proxyTarget);
301 xfree(m_default_target);
302 xfree(m_proxy_negotiation_charset);
303 xfree(m_proxy_negotiation_lang);
304 delete m_charset_converter;
308 if (m_stylesheet_xsp)
309 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
315 xfree (m_backend_type);
316 xfree (m_backend_charset);
317 xfree (m_usemarcon_ini_stage1);
318 xfree (m_usemarcon_ini_stage2);
321 odr_destroy(m_s2z_odr_init);
322 if (m_s2z_odr_search)
323 odr_destroy(m_s2z_odr_search);
331 void Yaz_Proxy::set_debug_mode(int mode)
336 int Yaz_Proxy::set_config(const char *config)
339 m_config = new Yaz_ProxyConfig();
340 xfree(m_config_fname);
341 m_config_fname = xstrdup(config);
342 int r = m_config->read_xml(config);
344 m_config->get_generic_info(&m_log_mask, &m_max_clients);
348 void Yaz_Proxy::set_default_target(const char *target)
350 xfree (m_default_target);
351 m_default_target = 0;
353 m_default_target = (char *) xstrdup (target);
356 void Yaz_Proxy::set_proxy_negotiation (const char *charset, const char *lang)
358 yaz_log(YLOG_LOG, "%sSet the proxy negotiation: charset to '%s', "
359 "language to '%s'", m_session_str, charset?charset:"none",
361 xfree (m_proxy_negotiation_charset);
362 xfree (m_proxy_negotiation_lang);
363 m_proxy_negotiation_charset = m_proxy_negotiation_lang = 0;
365 m_proxy_negotiation_charset = (char *) xstrdup (charset);
367 m_proxy_negotiation_lang = (char *) xstrdup (lang);
370 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
373 return m_parent->check_reconfigure();
375 Yaz_ProxyConfig *cfg = m_config;
378 yaz_log(YLOG_LOG, "reconfigure");
380 if (m_config_fname && cfg)
382 yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
383 int r = cfg->read_xml(m_config_fname);
385 yaz_log(YLOG_WARN, "reconfigure failed");
389 cfg->get_generic_info(&m_log_mask, &m_max_clients);
393 yaz_log(YLOG_LOG, "reconfigure");
399 IPDU_Observer *Yaz_Proxy::sessionNotify(IPDU_Observable
400 *the_PDU_Observable, int fd)
403 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable,
404 m_socket_observable, this);
405 new_proxy->m_config = 0;
406 new_proxy->m_config_fname = 0;
407 new_proxy->timeout(m_client_idletime);
408 new_proxy->m_target_idletime = m_target_idletime;
409 new_proxy->set_default_target(m_default_target);
410 new_proxy->m_max_clients = m_max_clients;
411 new_proxy->m_log_mask = m_log_mask;
412 new_proxy->set_APDU_log(get_APDU_log());
413 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
414 new_proxy->set_APDU_yazlog(1);
416 new_proxy->set_APDU_yazlog(0);
417 sprintf(new_proxy->m_session_str, "%ld:%d ", (long) time(0), m_session_no);
419 new_proxy->m_peername = xstrdup(the_PDU_Observable->getpeername());
420 yaz_log (YLOG_LOG, "%sNew session %s", new_proxy->m_session_str,
421 new_proxy->m_peername);
422 new_proxy->set_proxy_negotiation(m_proxy_negotiation_charset,
423 m_proxy_negotiation_lang);
424 // create thread object the first time we get an incoming connection
426 m_my_thread = new Msg_Thread(m_socket_observable, 1);
427 new_proxy->m_my_thread = m_my_thread;
431 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
434 Z_OtherInformationUnit *oi;
436 ent.proto = PROTO_Z3950;
437 ent.oclass = CLASS_USERINFO;
438 ent.value = (oid_value) VAL_COOKIE;
439 assert (oid_ent_to_oid (&ent, oid));
441 if (oid_ent_to_oid (&ent, oid) &&
442 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
443 oi->which == Z_OtherInfo_characterInfo)
444 return oi->information.characterInfo;
447 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
450 Z_OtherInformationUnit *oi;
452 ent.proto = PROTO_Z3950;
453 ent.oclass = CLASS_USERINFO;
454 ent.value = (oid_value) VAL_PROXY;
455 if (oid_ent_to_oid (&ent, oid) &&
456 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
457 oi->which == Z_OtherInfo_characterInfo)
458 return oi->information.characterInfo;
461 const char *Yaz_Proxy::load_balance(const char **url)
463 int zurl_in_use[MAX_ZURL_PLEX];
464 int zurl_in_spare[MAX_ZURL_PLEX];
468 for (i = 0; i<MAX_ZURL_PLEX; i++)
471 zurl_in_spare[i] = 0;
473 for (c = m_parent->m_clientPool; c; c = c->m_next)
475 for (i = 0; url[i]; i++)
476 if (!strcmp(url[i], c->get_hostname()))
479 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
483 int min_use = 100000;
484 int spare_for_min = 0;
486 const char *ret_min = 0;
487 const char *ret_spare = 0;
488 for (i = 0; url[i]; i++)
490 yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
491 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
492 if (min_use > zurl_in_use[i])
495 min_use = zurl_in_use[i];
496 spare_for_min = zurl_in_spare[i];
498 if (max_spare < zurl_in_spare[i])
501 max_spare = zurl_in_spare[i];
507 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
508 const char *proxy_host)
511 Yaz_Proxy *parent = m_parent;
512 Yaz_ProxyClient *c = m_client;
516 const char *url[MAX_ZURL_PLEX];
517 Yaz_ProxyConfig *cfg = check_reconfigure();
520 if (parent && parent->m_debug_mode)
522 // only to be enabled for debugging...
523 if (!strcmp(proxy_host, "stop"))
526 xfree(m_default_target);
527 m_default_target = xstrdup(proxy_host);
529 proxy_host = m_default_target;
530 int client_idletime = -1;
531 const char *cql2rpn_fname = 0;
532 const char *negotiation_charset = 0;
533 const char *negotiation_lang = 0;
534 const char *query_charset = 0;
535 url[0] = m_default_target;
540 cfg->get_target_info(proxy_host, url, &m_bw_max,
541 &m_pdu_max, &m_max_record_retrieve,
542 &m_search_max, &m_connect_max,
543 &m_target_idletime, &client_idletime,
544 &parent->m_max_clients,
545 &m_keepalive_limit_bw,
546 &m_keepalive_limit_pdu,
549 &negotiation_charset,
553 if (client_idletime != -1)
555 m_client_idletime = client_idletime;
556 timeout(m_client_idletime);
559 m_cql2rpn.set_pqf_file(cql2rpn_fname);
560 if (negotiation_charset || negotiation_lang)
562 set_proxy_negotiation(negotiation_charset,
565 m_charset_converter->set_target_query_charset(query_charset);
568 yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
571 // we don't handle multiplexing for cookie session, so we just
572 // pick the first one in this case (anonymous users will be able
573 // to use any backend)
574 if (cookie && *cookie)
575 m_proxyTarget = (char*) xstrdup(url[0]);
577 m_proxyTarget = (char*) xstrdup(load_balance(url));
579 if (cookie && *cookie)
580 { // search in sessions with a cookie
581 for (c = parent->m_clientPool; c; c = c->m_next)
584 assert (*c->m_prev == c);
585 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
586 !strcmp(m_proxyTarget, c->get_hostname()))
589 // The following handles "cancel"
590 // If connection is busy (waiting for PDU) and
591 // we have an initRequest we can safely do re-open
592 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
594 yaz_log (YLOG_LOG, "%s REOPEN target=%s", m_session_str,
601 c->m_last_resultCount = 0;
602 c->m_sr_transform = 0;
604 c->m_resultSetStartPoint = 0;
605 c->m_target_idletime = m_target_idletime;
606 if (c->client(m_proxyTarget))
613 c->m_seqno = parent->m_seqno;
614 if (c->m_server && c->m_server != this)
615 c->m_server->m_client = 0;
618 yaz_log (YLOG_DEBUG, "get_client 1 %p %p", this, c);
624 apdu->which == Z_APDU_initRequest &&
625 apdu->u.initRequest->idAuthentication == 0 &&
626 !ODR_MASK_GET(apdu->u.initRequest->options, Z_Options_negotiationModel))
628 // anonymous sessions without cookie.
629 // if authentication is set it is NOT anonymous se we can't share them.
630 // If charset and lang negotiation is use it is NOT anonymous session too.
631 for (c = parent->m_clientPool; c; c = c->m_next)
634 assert(*c->m_prev == c);
635 if (c->m_server == 0 && c->m_cookie == 0 &&
637 !strcmp(m_proxyTarget, c->get_hostname()))
640 yaz_log (YLOG_LOG, "%sREUSE %d %s",
641 m_session_str, parent->m_seqno, c->get_hostname());
643 c->m_seqno = parent->m_seqno;
644 assert(c->m_server == 0);
647 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
648 c->set_APDU_yazlog(1);
650 c->set_APDU_yazlog(0);
662 if (apdu->which != Z_APDU_initRequest)
664 yaz_log (YLOG_LOG, "%sno init request as first PDU", m_session_str);
667 Z_InitRequest *initRequest = apdu->u.initRequest;
669 if (initRequest->idAuthentication)
671 // the client uses authentication. We set the keepalive PDU
672 // to 0 so we don't cache it in releaseClient
673 m_keepalive_limit_pdu = 0;
675 // go through list of clients - and find the lowest/oldest one.
676 Yaz_ProxyClient *c_min = 0;
678 int no_of_clients = 0;
679 if (parent->m_clientPool)
680 yaz_log (YLOG_DEBUG, "Existing sessions");
681 for (c = parent->m_clientPool; c; c = c->m_next)
683 yaz_log (YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
684 c->m_waiting, c->get_hostname(),
685 c->m_cookie ? c->m_cookie : "");
687 if (min_seq < 0 || c->m_seqno < min_seq)
689 min_seq = c->m_seqno;
693 if (no_of_clients >= parent->m_max_clients)
696 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
698 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
699 m_session_str, parent->m_max_clients, c->m_seqno);
700 if (c->m_server && c->m_server != this)
701 delete c->m_server; // PROBLEM: m_ref_count!
706 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
707 m_session_str, parent->m_max_clients,
708 c->m_seqno, parent->m_seqno, c->get_hostname());
712 c->m_cookie = xstrdup(cookie);
713 c->m_seqno = parent->m_seqno;
714 if (c->m_server && c->m_server != this)
716 c->m_server->m_client = 0;
717 delete c->m_server; // PROBLEM: m_ref_count!
720 c->m_target_idletime = m_target_idletime;
721 c->timeout(m_target_idletime);
723 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
724 c->set_APDU_yazlog(1);
726 c->set_APDU_yazlog(0);
733 yaz_log (YLOG_LOG, "%sNEW %d %s",
734 m_session_str, parent->m_seqno, m_proxyTarget);
735 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
736 c->m_next = parent->m_clientPool;
738 c->m_next->m_prev = &c->m_next;
739 parent->m_clientPool = c;
740 c->m_prev = &parent->m_clientPool;
746 c->m_cookie = xstrdup(cookie);
748 c->m_seqno = parent->m_seqno;
750 c->m_last_resultCount = 0;
753 c->m_sr_transform = 0;
755 c->m_resultSetStartPoint = 0;
757 if (c->client(m_proxyTarget))
762 c->m_target_idletime = m_target_idletime;
765 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
766 c->set_APDU_yazlog(1);
768 c->set_APDU_yazlog(0);
770 yaz_log (YLOG_DEBUG, "get_client 3 %p %p", this, c);
774 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
777 for (i = 0; i<num; i++)
780 Z_DefaultDiagFormat *r;
781 Z_DiagRec *p = pp[i];
782 if (p->which != Z_DiagRec_defaultFormat)
784 yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
788 r = p->u.defaultFormat;
789 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
790 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
791 yaz_log(YLOG_LOG, "%sError unknown diagnostic set", m_session_str);
794 case Z_DefaultDiagFormat_v2Addinfo:
795 yaz_log(YLOG_LOG, "%sError %d %s:%s",
797 *r->condition, diagbib1_str(*r->condition),
800 case Z_DefaultDiagFormat_v3Addinfo:
801 yaz_log(YLOG_LOG, "%sError %d %s:%s",
803 *r->condition, diagbib1_str(*r->condition),
810 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
812 if (!m_stylesheet_xsp || p->num_records <= 0)
814 return 0; /* no XSLT to be done ... */
817 m_stylesheet_offset = 0;
818 m_stylesheet_nprl = p;
819 m_stylesheet_apdu = apdu;
820 m_timeout_mode = timeout_xsl;
826 void Yaz_Proxy::convert_xsl_delay()
829 Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
830 if (npr->which == Z_NamePlusRecord_databaseRecord)
832 Z_External *r = npr->u.databaseRecord;
833 if (r->which == Z_External_octet)
836 fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
838 xmlDocPtr res, doc = xmlParseMemory(
839 (char*) r->u.octet_aligned->buf,
840 r->u.octet_aligned->len);
843 yaz_log(YLOG_LOG, "%sXSLT convert %d",
844 m_session_str, m_stylesheet_offset);
845 res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
852 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
854 m_stylesheet_nprl->records[m_stylesheet_offset]->
856 z_ext_record(odr_encode(), VAL_TEXT_XML,
857 (char*) out_buf, out_len);
866 m_stylesheet_offset++;
867 if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
869 m_timeout_mode = timeout_normal;
870 m_stylesheet_nprl = 0;
872 if (m_stylesheet_xsp)
873 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
875 m_stylesheet_xsp = 0;
876 timeout(m_client_idletime);
877 send_PDU_convert(m_stylesheet_apdu);
883 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
885 if (m_frontend_type != VAL_NONE)
888 for (i = 0; i < p->num_records; i++)
890 Z_NamePlusRecord *npr = p->records[i];
891 if (npr->which == Z_NamePlusRecord_databaseRecord)
893 Z_External *r = npr->u.databaseRecord;
894 if (r->which == Z_External_octet)
897 if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
899 if (!m_usemarcon->m_stage1)
901 m_usemarcon->m_stage1 = new CDetails();
903 m_usemarcon->m_stage1->SetIniFileName(m_usemarcon_ini_stage1);
904 m_usemarcon->m_stage1->SetMarcRecord((char*) r->u.octet_aligned->buf, r->u.octet_aligned->len);
905 int res = m_usemarcon->m_stage1->Start();
910 m_usemarcon->m_stage1->GetMarcRecord(converted, convlen);
911 if (m_usemarcon_ini_stage2 && *m_usemarcon_ini_stage2)
913 if (!m_usemarcon->m_stage2)
915 m_usemarcon->m_stage2 = new CDetails();
917 m_usemarcon->m_stage2->SetIniFileName(m_usemarcon_ini_stage2);
918 m_usemarcon->m_stage2->SetMarcRecord(converted, convlen);
919 res = m_usemarcon->m_stage2->Start();
923 m_usemarcon->m_stage2->GetMarcRecord(converted, convlen);
927 yaz_log(YLOG_LOG, "%sUSEMARCON stage 2 error %d", m_session_str, res);
930 npr->u.databaseRecord =
931 z_ext_record(odr_encode(),
939 yaz_log(YLOG_LOG, "%sUSEMARCON stage 1 error %d", m_session_str, res);
945 npr->u.databaseRecord =
946 z_ext_record(odr_encode(),
948 (char*) r->u.octet_aligned->buf,
949 r->u.octet_aligned->len);
956 void Yaz_Proxy::convert_records_charset(Z_NamePlusRecordList *p,
957 const char *backend_charset)
959 yaz_log(YLOG_LOG, "%sconvert_to_marc", m_session_str);
960 int sel = m_charset_converter->get_client_charset_selected();
961 const char *client_record_charset =
962 m_charset_converter->get_client_query_charset();
963 if (sel && backend_charset && client_record_charset &&
964 strcmp(backend_charset, client_record_charset))
967 yaz_iconv_t cd = yaz_iconv_open(client_record_charset,
969 yaz_marc_t mt = yaz_marc_create();
970 yaz_marc_xml(mt, YAZ_MARC_ISO2709);
971 yaz_marc_iconv(mt, cd);
972 for (i = 0; i < p->num_records; i++)
974 Z_NamePlusRecord *npr = p->records[i];
975 if (npr->which == Z_NamePlusRecord_databaseRecord)
977 Z_External *r = npr->u.databaseRecord;
978 oident *ent = oid_getentbyoid(r->direct_reference);
979 if (!ent || ent->value == VAL_NONE)
982 if (ent->value == VAL_SUTRS)
984 WRBUF w = wrbuf_alloc();
986 wrbuf_iconv_write(w, cd, (char*) r->u.octet_aligned->buf,
987 r->u.octet_aligned->len);
988 npr->u.databaseRecord =
989 z_ext_record(odr_encode(), ent->value, wrbuf_buf(w),
993 else if (ent->value == VAL_TEXT_XML)
997 else if (r->which == Z_External_octet)
1001 if (yaz_marc_decode_buf(mt,
1002 (char*) r->u.octet_aligned->buf,
1003 r->u.octet_aligned->len,
1006 npr->u.databaseRecord =
1007 z_ext_record(odr_encode(), ent->value, result, rlen);
1008 yaz_log(YLOG_LOG, "%sRecoding MARC record",
1015 yaz_iconv_close(cd);
1016 yaz_marc_destroy(mt);
1020 yaz_log(YLOG_LOG, "%sSkipping marc convert", m_session_str);
1024 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
1025 const char *backend_charset)
1028 if (!backend_charset)
1029 backend_charset = "MARC-8";
1030 yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
1031 yaz_marc_t mt = yaz_marc_create();
1032 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
1033 yaz_marc_iconv(mt, cd);
1034 for (i = 0; i < p->num_records; i++)
1036 Z_NamePlusRecord *npr = p->records[i];
1037 if (npr->which == Z_NamePlusRecord_databaseRecord)
1039 Z_External *r = npr->u.databaseRecord;
1040 if (r->which == Z_External_OPAC)
1042 WRBUF w = wrbuf_alloc();
1044 yaz_opac_decode_wrbuf(mt, r->u.opac, w);
1045 npr->u.databaseRecord = z_ext_record(
1046 odr_encode(), VAL_TEXT_XML,
1047 wrbuf_buf(w), wrbuf_len(w)
1051 else if (r->which == Z_External_octet)
1055 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
1056 r->u.octet_aligned->len,
1059 npr->u.databaseRecord =
1060 z_ext_record(odr_encode(), VAL_TEXT_XML, result, rlen);
1066 yaz_iconv_close(cd);
1067 yaz_marc_destroy(mt);
1070 void Yaz_Proxy::logtime()
1072 #if HAVE_GETTIMEOFDAY
1073 struct timeval *tv = (struct timeval*) m_time_tv;
1077 gettimeofday(&tv1, 0);
1078 long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
1079 (tv1.tv_usec - tv->tv_usec);
1081 yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
1082 diff/1000000, (diff/1000)%1000);
1089 int Yaz_Proxy::send_http_response(int code)
1091 ODR o = odr_encode();
1092 Z_GDU *gdu = z_get_HTTP_Response(o, code);
1093 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1095 hres->version = odr_strdup(o, m_http_version);
1096 if (m_http_keepalive)
1097 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1101 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1103 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1107 int r = send_GDU(gdu, &len);
1108 m_bytes_sent += len;
1109 m_bw_stat.add_bytes(len);
1112 recv_GDU_more(true);
1117 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu)
1119 ODR o = odr_encode();
1120 const char *ctype = "text/xml";
1121 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
1122 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1124 hres->version = odr_strdup(o, m_http_version);
1125 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1126 if (m_http_keepalive)
1127 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1131 static Z_SOAP_Handler soap_handlers[2] = {
1133 {"http://www.loc.gov/zing/srw/", 0,
1134 (Z_SOAP_fun) yaz_srw_codec},
1139 Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
1140 soap_package->which = Z_SOAP_generic;
1141 soap_package->u.generic =
1142 (Z_SOAP_Generic *) odr_malloc(o, sizeof(*soap_package->u.generic));
1143 soap_package->u.generic->no = 0;
1144 soap_package->u.generic->ns = soap_handlers[0].ns;
1145 soap_package->u.generic->p = (void *) srw_pdu;
1146 soap_package->ns = m_soap_ns;
1147 z_soap_codec_enc_xsl(o, &soap_package,
1148 &hres->content_buf, &hres->content_len,
1149 soap_handlers, 0, m_s2z_stylesheet);
1150 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1152 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1156 int r = send_GDU(gdu, &len);
1157 m_bytes_sent += len;
1158 m_bw_stat.add_bytes(len);
1161 recv_GDU_more(true);
1166 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
1168 ODR o = odr_encode();
1169 Z_SRW_diagnostic *diagnostic = (Z_SRW_diagnostic *)
1170 odr_malloc(o, sizeof(*diagnostic));
1171 int num_diagnostic = 1;
1172 yaz_mk_std_diagnostic(o, diagnostic, srw_error, add);
1173 return send_srw_search_response(diagnostic, num_diagnostic);
1176 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
1177 Z_DefaultDiagFormat *ddf)
1179 int bib1_code = *ddf->condition;
1180 if (bib1_code == 109)
1182 srw_res->num_diagnostics = 1;
1183 srw_res->diagnostics = (Z_SRW_diagnostic *)
1184 odr_malloc(o, sizeof(*srw_res->diagnostics));
1185 yaz_mk_std_diagnostic(o, srw_res->diagnostics,
1186 yaz_diag_bib1_to_srw(*ddf->condition),
1191 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
1193 ODR o = odr_encode();
1194 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1195 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1197 srw_res->numberOfRecords = odr_intdup (o, hits);
1198 if (records && records->which == Z_Records_DBOSD)
1200 srw_res->num_records =
1201 records->u.databaseOrSurDiagnostics->num_records;
1203 srw_res->records = (Z_SRW_record *)
1204 odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
1205 for (i = 0; i < srw_res->num_records; i++)
1207 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
1208 if (npr->which != Z_NamePlusRecord_databaseRecord)
1210 srw_res->records[i].recordSchema = "diagnostic";
1211 srw_res->records[i].recordPacking = m_s2z_packing;
1212 srw_res->records[i].recordData_buf = "67";
1213 srw_res->records[i].recordData_len = 2;
1214 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1217 Z_External *r = npr->u.databaseRecord;
1218 oident *ent = oid_getentbyoid(r->direct_reference);
1219 if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
1221 srw_res->records[i].recordSchema = m_schema;
1222 srw_res->records[i].recordPacking = m_s2z_packing;
1223 srw_res->records[i].recordData_buf = (char*)
1224 r->u.octet_aligned->buf;
1225 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1226 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1230 srw_res->records[i].recordSchema = "diagnostic";
1231 srw_res->records[i].recordPacking = m_s2z_packing;
1232 srw_res->records[i].recordData_buf = "67";
1233 srw_res->records[i].recordData_len = 2;
1234 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1238 if (records && records->which == Z_Records_NSD)
1241 http_code = z_to_srw_diag(odr_encode(), srw_res,
1242 records->u.nonSurrogateDiagnostic);
1244 return send_http_response(http_code);
1246 return send_srw_response(srw_pdu);
1250 int Yaz_Proxy::send_srw_search_response(Z_SRW_diagnostic *diagnostics,
1251 int num_diagnostics)
1253 ODR o = odr_encode();
1254 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
1255 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
1257 srw_res->num_diagnostics = num_diagnostics;
1258 srw_res->diagnostics = diagnostics;
1259 return send_srw_response(srw_pdu);
1262 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1263 int num_diagnostics)
1265 Yaz_ProxyConfig *cfg = check_reconfigure();
1269 char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1270 m_s2z_database, &len);
1273 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1274 Z_SRW_explainResponse *er = res->u.explain_response;
1276 er->record.recordData_buf = b;
1277 er->record.recordData_len = len;
1278 er->record.recordPacking = m_s2z_packing;
1279 er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
1281 er->diagnostics = diagnostics;
1282 er->num_diagnostics = num_diagnostics;
1283 return send_srw_response(res);
1286 return send_http_response(404);
1289 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1293 if (apdu->which == Z_APDU_initResponse)
1295 Z_InitResponse *res = apdu->u.initResponse;
1296 if (*res->result == 0)
1298 send_to_srw_client_error(3, 0);
1300 else if (!m_s2z_search_apdu)
1302 send_srw_explain_response(0, 0);
1306 handle_incoming_Z_PDU(m_s2z_search_apdu);
1309 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1311 m_s2z_search_apdu = 0;
1312 Z_SearchResponse *res = apdu->u.searchResponse;
1313 m_s2z_hit_count = *res->resultCount;
1314 if (res->records && res->records->which == Z_Records_NSD)
1316 send_to_srw_client_ok(0, res->records, 1);
1318 else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1321 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1323 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1325 if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1327 *pr->numberOfRecordsRequested =
1328 1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1330 handle_incoming_Z_PDU(m_s2z_present_apdu);
1334 m_s2z_present_apdu = 0;
1335 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1338 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1341 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1343 m_s2z_present_apdu = 0;
1344 Z_PresentResponse *res = apdu->u.presentResponse;
1345 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1351 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1352 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1354 int r = send_Z_PDU(apdu, &len);
1355 m_bytes_sent += len;
1356 m_bw_stat.add_bytes(len);
1363 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1365 int kill_session = 0;
1366 Z_ReferenceId **new_id = get_referenceIdP(apdu);
1369 *new_id = m_referenceId;
1371 if (apdu->which == Z_APDU_searchResponse)
1373 Z_SearchResponse *sr = apdu->u.searchResponse;
1374 Z_Records *p = sr->records;
1375 if (p && p->which == Z_Records_NSD)
1377 Z_DiagRec dr, *dr_p = &dr;
1378 dr.which = Z_DiagRec_defaultFormat;
1379 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1381 *sr->searchStatus = 0;
1382 display_diagrecs(&dr_p, 1);
1386 if (p && p->which == Z_Records_DBOSD)
1390 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1393 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1394 if (m_marcxml_mode == marcxml)
1395 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1398 convert_records_charset(p->u.databaseOrSurDiagnostics,
1400 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1404 if (sr->resultCount)
1406 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1408 if (*sr->resultCount < 0)
1410 m_flag_invalid_session = 1;
1413 *sr->searchStatus = 0;
1415 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1416 *sr->resultCount = 0;
1421 else if (apdu->which == Z_APDU_presentResponse)
1423 Z_PresentResponse *sr = apdu->u.presentResponse;
1424 Z_Records *p = sr->records;
1425 if (p && p->which == Z_Records_NSD)
1427 Z_DiagRec dr, *dr_p = &dr;
1428 dr.which = Z_DiagRec_defaultFormat;
1429 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1430 if (*sr->presentStatus == Z_PresentStatus_success)
1431 *sr->presentStatus = Z_PresentStatus_failure;
1432 display_diagrecs(&dr_p, 1);
1434 if (p && p->which == Z_Records_DBOSD)
1438 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1441 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1442 if (m_marcxml_mode == marcxml)
1443 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1446 convert_records_charset(p->u.databaseOrSurDiagnostics,
1448 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1452 else if (apdu->which == Z_APDU_initResponse)
1454 //Get and check negotiation record
1455 //from init response.
1456 handle_charset_lang_negotiation(apdu);
1458 if (m_initRequest_options)
1461 (Odr_bitmask *)odr_malloc(odr_encode(),
1462 sizeof(Odr_bitmask));
1463 ODR_MASK_ZERO(nopt);
1466 for (i = 0; i<24; i++)
1467 if (ODR_MASK_GET(m_initRequest_options, i) &&
1468 ODR_MASK_GET(apdu->u.initResponse->options, i))
1469 ODR_MASK_SET(nopt, i);
1470 apdu->u.initResponse->options = nopt;
1472 if (m_initRequest_version)
1474 Z_ProtocolVersion *nopt =
1475 (Odr_bitmask *)odr_malloc(odr_encode(),
1476 sizeof(Odr_bitmask));
1477 ODR_MASK_ZERO(nopt);
1480 for (i = 0; i<8; i++)
1481 if (ODR_MASK_GET(m_initRequest_version, i) &&
1482 ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1483 ODR_MASK_SET(nopt, i);
1484 apdu->u.initResponse->protocolVersion = nopt;
1486 apdu->u.initResponse->preferredMessageSize =
1487 odr_intdup(odr_encode(),
1488 m_client->m_initResponse_preferredMessageSize >
1489 m_initRequest_preferredMessageSize ?
1490 m_initRequest_preferredMessageSize :
1491 m_client->m_initResponse_preferredMessageSize);
1492 apdu->u.initResponse->maximumRecordSize =
1493 odr_intdup(odr_encode(),
1494 m_client->m_initResponse_maximumRecordSize >
1495 m_initRequest_maximumRecordSize ?
1496 m_initRequest_maximumRecordSize :
1497 m_client->m_initResponse_maximumRecordSize);
1500 int r = send_PDU_convert(apdu);
1507 m_parent->pre_init();
1512 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1515 const char *apdu_name_tmp = apdu_name(apdu);
1516 int r = send_Z_PDU(apdu, &len);
1517 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1518 yaz_log (YLOG_LOG, "%sSending %s to %s %d bytes",
1520 apdu_name_tmp, get_hostname(), len);
1521 m_bytes_sent += len;
1525 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1527 if (apdu->which == Z_APDU_presentRequest)
1529 Z_PresentRequest *pr = apdu->u.presentRequest;
1530 int toget = *pr->numberOfRecordsRequested;
1531 int start = *pr->resultSetStartPoint;
1533 yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1534 pr->resultSetId, start, toget);
1536 if (*m_parent->m_optimize == '0')
1539 if (!m_client->m_last_resultSetId)
1541 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1542 new_apdu->u.presentResponse->records =
1543 create_nonSurrogateDiagnostics(odr_encode(), 30,
1545 send_to_client(new_apdu);
1548 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1550 if (start+toget-1 > m_client->m_last_resultCount)
1552 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1553 new_apdu->u.presentResponse->records =
1554 create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
1555 send_to_client(new_apdu);
1558 Z_NamePlusRecordList *npr;
1560 yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1561 m_session_str, start, toget, yaz_z3950oid_to_str(
1562 pr->preferredRecordSyntax, &oclass));
1564 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1565 pr->preferredRecordSyntax,
1566 pr->recordComposition))
1568 yaz_log (YLOG_LOG, "%sReturned cached records for present request",
1570 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1571 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1573 new_apdu->u.presentResponse->numberOfRecordsReturned
1574 = odr_intdup(odr_encode(), toget);
1576 new_apdu->u.presentResponse->records = (Z_Records*)
1577 odr_malloc(odr_encode(), sizeof(Z_Records));
1578 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1579 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1580 new_apdu->u.presentResponse->nextResultSetPosition =
1581 odr_intdup(odr_encode(), start+toget);
1583 send_to_client(new_apdu);
1589 if (apdu->which != Z_APDU_searchRequest)
1591 Z_SearchRequest *sr = apdu->u.searchRequest;
1592 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1593 Yaz_Z_Databases this_databases;
1595 this_databases.set(sr->num_databaseNames, (const char **)
1598 this_query->set_Z_Query(sr->query);
1600 char query_str[120];
1601 this_query->print(query_str, sizeof(query_str)-1);
1602 yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1604 if (*m_parent->m_optimize != '0' &&
1605 m_client->m_last_ok && m_client->m_last_query &&
1606 m_client->m_last_query->match(this_query) &&
1607 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1608 m_client->m_last_databases.match(this_databases))
1611 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1612 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1614 Z_NamePlusRecordList *npr;
1615 int toget = *sr->mediumSetPresentNumber;
1616 Z_RecordComposition *comp = 0;
1618 if (toget > m_client->m_last_resultCount)
1619 toget = m_client->m_last_resultCount;
1621 if (sr->mediumSetElementSetNames)
1623 comp = (Z_RecordComposition *)
1624 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1625 comp->which = Z_RecordComp_simple;
1626 comp->u.simple = sr->mediumSetElementSetNames;
1629 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1630 sr->preferredRecordSyntax, comp))
1632 yaz_log (YLOG_LOG, "%sReturned cached records for medium set",
1634 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1635 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1636 new_apdu->u.searchResponse->resultCount =
1637 &m_client->m_last_resultCount;
1639 new_apdu->u.searchResponse->numberOfRecordsReturned
1640 = odr_intdup(odr_encode(), toget);
1642 new_apdu->u.searchResponse->presentStatus =
1643 odr_intdup(odr_encode(), Z_PresentStatus_success);
1644 new_apdu->u.searchResponse->records = (Z_Records*)
1645 odr_malloc(odr_encode(), sizeof(Z_Records));
1646 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1647 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1648 new_apdu->u.searchResponse->nextResultSetPosition =
1649 odr_intdup(odr_encode(), toget+1);
1650 send_to_client(new_apdu);
1656 // send present request (medium size)
1657 yaz_log (YLOG_LOG, "%sOptimizing search for medium set",
1660 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1661 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1662 pr->referenceId = sr->referenceId;
1663 pr->resultSetId = sr->resultSetName;
1664 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1665 *pr->numberOfRecordsRequested = toget;
1666 pr->recordComposition = comp;
1667 m_client->m_sr_transform = 1;
1671 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1672 m_client->m_last_resultCount <= 0)
1674 // large set. Return pseudo-search response immediately
1675 yaz_log (YLOG_LOG, "%sOptimizing search for large set",
1677 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1678 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1679 new_apdu->u.searchResponse->resultCount =
1680 &m_client->m_last_resultCount;
1681 send_to_client(new_apdu);
1686 Z_NamePlusRecordList *npr;
1687 int toget = m_client->m_last_resultCount;
1688 Z_RecordComposition *comp = 0;
1690 // send a present request (small set)
1692 if (sr->smallSetElementSetNames)
1694 comp = (Z_RecordComposition *)
1695 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1696 comp->which = Z_RecordComp_simple;
1697 comp->u.simple = sr->smallSetElementSetNames;
1700 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1701 sr->preferredRecordSyntax, comp))
1703 yaz_log (YLOG_LOG, "%sReturned cached records for small set",
1705 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1706 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1707 new_apdu->u.searchResponse->resultCount =
1708 &m_client->m_last_resultCount;
1710 new_apdu->u.searchResponse->numberOfRecordsReturned
1711 = odr_intdup(odr_encode(), toget);
1713 new_apdu->u.searchResponse->presentStatus =
1714 odr_intdup(odr_encode(), Z_PresentStatus_success);
1715 new_apdu->u.searchResponse->records = (Z_Records*)
1716 odr_malloc(odr_encode(), sizeof(Z_Records));
1717 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1718 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1719 new_apdu->u.searchResponse->nextResultSetPosition =
1720 odr_intdup(odr_encode(), toget+1);
1721 send_to_client(new_apdu);
1726 yaz_log (YLOG_LOG, "%sOptimizing search for small set",
1728 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1729 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1730 pr->referenceId = sr->referenceId;
1731 pr->resultSetId = sr->resultSetName;
1732 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1733 *pr->numberOfRecordsRequested = toget;
1734 pr->recordComposition = comp;
1735 m_client->m_sr_transform = 1;
1740 else // query doesn't match
1742 delete m_client->m_last_query;
1743 m_client->m_last_query = this_query;
1744 m_client->m_last_ok = 0;
1745 m_client->m_cache.clear();
1746 m_client->m_resultSetStartPoint = 0;
1748 xfree (m_client->m_last_resultSetId);
1749 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1751 m_client->m_last_databases.set(sr->num_databaseNames,
1752 (const char **) sr->databaseNames);
1758 void Yaz_Proxy::inc_request_no()
1760 char *cp = strchr(m_session_str, ' ');
1763 sprintf(cp+1, "%d ", m_request_no);
1766 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1770 m_bytes_recv += len;
1772 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1773 yaz_log (YLOG_LOG, "%sReceiving %s from client %d bytes",
1774 m_session_str, gdu_name(apdu), len);
1776 #if HAVE_GETTIMEOFDAY
1777 gettimeofday((struct timeval *) m_time_tv, 0);
1779 m_bw_stat.add_bytes(len);
1780 m_pdu_stat.add_bytes(1);
1782 GDU *gdu = new GDU(apdu);
1783 m_in_queue.enqueue(gdu);
1785 recv_GDU_more(false);
1788 void Yaz_Proxy::recv_GDU_reduce(GDU *gdu)
1790 int bw_total = m_bw_stat.get_total();
1791 int pdu_total = m_pdu_stat.get_total();
1794 assert(m_timeout_mode == timeout_busy);
1795 assert(m_timeout_gdu == 0);
1799 if (bw_total > m_bw_max)
1801 reduce = (bw_total/m_bw_max);
1806 if (pdu_total > m_pdu_max)
1808 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1809 reduce = (reduce > nreduce) ? reduce : nreduce;
1815 /* uncomment to force a big reduce */
1816 m_timeout_mode = timeout_reduce;
1817 m_timeout_gdu = gdu;
1818 timeout(3); // call us reduce seconds later
1823 yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1824 m_session_str, reduce, bw_total, pdu_total,
1825 m_bw_max, m_pdu_max);
1827 m_timeout_mode = timeout_reduce;
1828 m_timeout_gdu = gdu;
1829 timeout(reduce); // call us reduce seconds later
1832 recv_GDU_normal(gdu);
1835 void Yaz_Proxy::recv_GDU_more(bool normal)
1838 if (normal && m_timeout_mode == timeout_busy)
1839 m_timeout_mode = timeout_normal;
1840 while (m_timeout_mode == timeout_normal && (g = m_in_queue.dequeue()))
1842 m_timeout_mode = timeout_busy;
1847 void Yaz_Proxy::recv_GDU_normal(GDU *gdu)
1850 gdu->move_away_gdu(odr_decode(), &apdu);
1853 if (apdu->which == Z_GDU_Z3950)
1854 handle_incoming_Z_PDU(apdu->u.z3950);
1855 else if (apdu->which == Z_GDU_HTTP_Request)
1856 handle_incoming_HTTP(apdu->u.HTTP_Request);
1859 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
1861 if (m_max_record_retrieve)
1863 if (apdu->which == Z_APDU_presentRequest)
1865 Z_PresentRequest *pr = apdu->u.presentRequest;
1866 if (pr->numberOfRecordsRequested &&
1867 *pr->numberOfRecordsRequested > m_max_record_retrieve)
1868 *pr->numberOfRecordsRequested = m_max_record_retrieve;
1873 void Yaz_Proxy::handle_charset_lang_negotiation(Z_APDU *apdu)
1875 if (apdu->which == Z_APDU_initRequest)
1877 yaz_log(YLOG_LOG, "%shandle_charset_lang_negotiation",
1879 if (m_initRequest_options &&
1880 !ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel) &&
1881 (m_proxy_negotiation_charset || m_proxy_negotiation_lang))
1883 // There is no negotiation proposal from
1884 // client's side. OK. The proxy negotiation
1886 Z_InitRequest *initRequest = apdu->u.initRequest;
1887 Z_OtherInformation **otherInfo;
1888 Z_OtherInformationUnit *oi;
1889 get_otherInfoAPDU(apdu, &otherInfo);
1890 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
1893 ODR_MASK_SET(initRequest->options,
1894 Z_Options_negotiationModel);
1895 oi->which = Z_OtherInfo_externallyDefinedInfo;
1896 oi->information.externallyDefinedInfo =
1897 yaz_set_proposal_charneg(odr_encode(),
1898 (const char**)&m_proxy_negotiation_charset,
1899 m_proxy_negotiation_charset ? 1:0,
1900 (const char**)&m_proxy_negotiation_lang,
1901 m_proxy_negotiation_lang ? 1:0,
1905 else if (m_initRequest_options &&
1906 ODR_MASK_GET(m_initRequest_options,
1907 Z_Options_negotiationModel) &&
1908 m_charset_converter->get_target_query_charset())
1910 yaz_log(YLOG_LOG, "%sManaged charset negotiation: charset=%s",
1912 m_charset_converter->get_target_query_charset());
1913 Z_InitRequest *initRequest = apdu->u.initRequest;
1914 Z_CharSetandLanguageNegotiation *negotiation =
1915 yaz_get_charneg_record (initRequest->otherInfo);
1917 negotiation->which == Z_CharSetandLanguageNegotiation_proposal)
1919 NMEM nmem = nmem_create();
1920 char **charsets = 0;
1921 int num_charsets = 0;
1925 yaz_get_proposal_charneg (nmem, negotiation,
1926 &charsets, &num_charsets,
1927 &langs, &num_langs, &selected);
1929 for (i = 0; i<num_charsets; i++)
1930 yaz_log(YLOG_LOG, "%scharset %s", m_session_str,
1932 for (i = 0; i<num_langs; i++)
1933 yaz_log(YLOG_LOG, "%slang %s", m_session_str,
1936 const char *t_charset =
1937 m_charset_converter->get_target_query_charset();
1938 // sweep through charsets and pick the first supported
1940 for (i = 0; i<num_charsets; i++)
1942 const char *c_charset = charsets[i];
1943 if (!odr_set_charset(odr_decode(), t_charset, c_charset))
1946 if (i != num_charsets)
1948 // got one .. set up ODR for reverse direction
1949 const char *c_charset = charsets[i];
1950 odr_set_charset(odr_encode(), c_charset, t_charset);
1951 m_charset_converter->set_client_query_charset(c_charset);
1952 m_charset_converter->set_client_charset_selected(selected);
1955 ODR_MASK_CLEAR(m_initRequest_options,
1956 Z_Options_negotiationModel);
1957 yaz_del_charneg_record(&initRequest->otherInfo);
1961 yaz_log(YLOG_WARN, "%sUnable to decode charset package",
1966 else if (apdu->which == Z_APDU_initResponse)
1968 Z_InitResponse *initResponse = apdu->u.initResponse;
1969 Z_OtherInformation **otherInfo;
1971 if (ODR_MASK_GET(initResponse->options, Z_Options_negotiationModel))
1977 get_otherInfoAPDU(apdu, &otherInfo);
1979 if (!otherInfo && !(*otherInfo))
1982 Z_CharSetandLanguageNegotiation *charneg =
1983 yaz_get_charneg_record(*otherInfo);
1988 yaz_get_response_charneg(m_referenceId_mem, charneg,
1989 &charset, &lang, &selected);
1991 yaz_log(YLOG_LOG, "%sAccepted charset - '%s' and lang - '%s'",
1992 m_session_str, (charset)?charset:"none", (lang)?lang:"none");
1994 if (m_initRequest_options &&
1995 ODR_MASK_GET(m_initRequest_options, Z_Options_negotiationModel))
1997 yaz_log(YLOG_LOG, "%sClient's negotiation record in use",
2000 else if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2002 // negotiation-charset, negotiation-lang
2003 // elements of config file in use.
2005 yaz_log(YLOG_LOG, "%sProxy's negotiation record in use",
2008 // clear negotiation option.
2009 ODR_MASK_CLEAR(initResponse->options, Z_Options_negotiationModel);
2011 // Delete negotiation (charneg-3) entry.
2012 yaz_del_charneg_record(otherInfo);
2017 if (m_proxy_negotiation_charset || m_proxy_negotiation_lang)
2019 yaz_log(YLOG_LOG, "%sTarget did not honor negotiation",
2022 else if (m_charset_converter->get_client_query_charset())
2024 Z_OtherInformation **otherInfo;
2025 Z_OtherInformationUnit *oi;
2026 get_otherInfoAPDU(apdu, &otherInfo);
2027 oi = update_otherInformation(otherInfo, 1, NULL, 0, 0);
2030 ODR_MASK_SET(initResponse->options,
2031 Z_Options_negotiationModel);
2032 if (m_initRequest_options)
2033 ODR_MASK_SET(m_initRequest_options,
2034 Z_Options_negotiationModel);
2036 oi->which = Z_OtherInfo_externallyDefinedInfo;
2037 oi->information.externallyDefinedInfo =
2038 yaz_set_response_charneg(
2040 m_charset_converter->get_client_query_charset(),
2042 m_charset_converter->get_client_charset_selected());
2049 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
2051 const char *addinfo)
2053 Z_Records *rec = (Z_Records *)
2054 odr_malloc (odr, sizeof(*rec));
2056 odr_malloc (odr, sizeof(*err));
2057 Z_DiagRec *drec = (Z_DiagRec *)
2058 odr_malloc (odr, sizeof(*drec));
2059 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
2060 odr_malloc (odr, sizeof(*dr));
2062 rec->which = Z_Records_NSD;
2063 rec->u.nonSurrogateDiagnostic = dr;
2064 dr->diagnosticSetId =
2065 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
2066 dr->condition = err;
2067 dr->which = Z_DefaultDiagFormat_v2Addinfo;
2068 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
2072 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
2074 if (apdu->which == Z_APDU_searchRequest &&
2075 apdu->u.searchRequest->query &&
2076 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
2077 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
2079 Z_RPNQuery *rpnquery = 0;
2080 Z_SearchRequest *sr = apdu->u.searchRequest;
2083 yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
2084 sr->query->u.type_104->u.cql);
2086 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
2087 &rpnquery, odr_encode(),
2090 yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
2093 yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
2094 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2096 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2097 new_apdu->u.searchResponse->records =
2098 create_nonSurrogateDiagnostics(odr_encode(),
2099 yaz_diag_srw_to_bib1(r),
2101 *new_apdu->u.searchResponse->searchStatus = 0;
2103 send_to_client(new_apdu);
2109 sr->query->which = Z_Query_type_1;
2110 sr->query->u.type_1 = rpnquery;
2117 Z_APDU *Yaz_Proxy::handle_target_charset_conversion(Z_APDU *apdu)
2119 if (apdu->which == Z_APDU_searchRequest &&
2120 apdu->u.searchRequest->query)
2122 if (apdu->u.searchRequest->query->which == Z_Query_type_1
2123 || apdu->u.searchRequest->query->which == Z_Query_type_101)
2126 m_charset_converter->set_client_query_charset("UTF-8");
2127 Z_RPNQuery *rpnquery = apdu->u.searchRequest->query->u.type_1;
2128 m_charset_converter->convert_type_1(rpnquery, odr_encode());
2135 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
2137 if (apdu->which == Z_APDU_searchRequest)
2139 Z_SearchRequest *sr = apdu->u.searchRequest;
2143 Yaz_ProxyConfig *cfg = check_reconfigure();
2145 err = cfg->check_query(odr_encode(), m_default_target,
2146 sr->query, &addinfo);
2149 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2151 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2152 new_apdu->u.searchResponse->records =
2153 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2154 *new_apdu->u.searchResponse->searchStatus = 0;
2156 send_to_client(new_apdu);
2164 int Yaz_Proxy::handle_authentication(Z_APDU *apdu)
2166 if (apdu->which != Z_APDU_initRequest)
2167 return 1; // pass if no init request
2168 Z_InitRequest *req = apdu->u.initRequest;
2170 Yaz_ProxyConfig *cfg = check_reconfigure();
2172 return 1; // pass if no config
2175 if (req->idAuthentication == 0)
2177 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2180 else if (req->idAuthentication->which == Z_IdAuthentication_idPass)
2182 ret = cfg->client_authentication(
2184 req->idAuthentication->u.idPass->userId,
2185 req->idAuthentication->u.idPass->groupId,
2186 req->idAuthentication->u.idPass->password,
2189 else if (req->idAuthentication->which == Z_IdAuthentication_open)
2191 char user[64], pass[64];
2194 sscanf(req->idAuthentication->u.open, "%63[^/]/%63s", user, pass);
2195 ret = cfg->client_authentication(m_default_target, user, 0, pass,
2199 ret = cfg->client_authentication(m_default_target, 0, 0, 0,
2202 cfg->target_authentication(m_default_target, odr_encode(), req);
2207 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
2209 m_marcxml_mode = none;
2210 if (apdu->which == Z_APDU_searchRequest)
2212 Z_SearchRequest *sr = apdu->u.searchRequest;
2215 Yaz_ProxyConfig *cfg = check_reconfigure();
2217 Z_RecordComposition rc_temp, *rc = 0;
2218 if (sr->smallSetElementSetNames)
2220 rc_temp.which = Z_RecordComp_simple;
2221 rc_temp.u.simple = sr->smallSetElementSetNames;
2225 if (sr->preferredRecordSyntax)
2228 ent = oid_getentbyoid(sr->preferredRecordSyntax);
2229 m_frontend_type = ent->value;
2232 m_frontend_type = VAL_NONE;
2234 char *stylesheet_name = 0;
2236 err = cfg->check_syntax(odr_encode(),
2238 sr->preferredRecordSyntax, rc,
2239 &addinfo, &stylesheet_name, &m_schema,
2240 &m_backend_type, &m_backend_charset,
2241 &m_usemarcon_ini_stage1,
2242 &m_usemarcon_ini_stage2);
2243 if (stylesheet_name)
2245 m_parent->low_socket_close();
2248 if (m_stylesheet_xsp)
2249 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2250 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2253 m_stylesheet_offset = 0;
2254 xfree(stylesheet_name);
2256 m_parent->low_socket_open();
2260 sr->smallSetElementSetNames = 0;
2261 sr->mediumSetElementSetNames = 0;
2262 m_marcxml_mode = marcxml;
2266 sr->preferredRecordSyntax =
2267 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2271 sr->preferredRecordSyntax =
2272 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2277 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2279 new_apdu->u.searchResponse->referenceId = sr->referenceId;
2280 new_apdu->u.searchResponse->records =
2281 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2282 *new_apdu->u.searchResponse->searchStatus = 0;
2284 send_to_client(new_apdu);
2288 else if (m_backend_type)
2290 sr->preferredRecordSyntax =
2291 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2294 else if (apdu->which == Z_APDU_presentRequest)
2296 Z_PresentRequest *pr = apdu->u.presentRequest;
2299 Yaz_ProxyConfig *cfg = check_reconfigure();
2301 if (pr->preferredRecordSyntax)
2304 ent = oid_getentbyoid(pr->preferredRecordSyntax);
2305 m_frontend_type = ent->value;
2308 m_frontend_type = VAL_NONE;
2310 char *stylesheet_name = 0;
2312 err = cfg->check_syntax(odr_encode(), m_default_target,
2313 pr->preferredRecordSyntax,
2314 pr->recordComposition,
2315 &addinfo, &stylesheet_name, &m_schema,
2316 &m_backend_type, &m_backend_charset,
2317 &m_usemarcon_ini_stage1,
2318 &m_usemarcon_ini_stage2
2320 if (stylesheet_name)
2322 m_parent->low_socket_close();
2325 if (m_stylesheet_xsp)
2326 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
2327 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
2330 m_stylesheet_offset = 0;
2331 xfree(stylesheet_name);
2333 m_parent->low_socket_open();
2337 pr->recordComposition = 0;
2338 m_marcxml_mode = marcxml;
2342 pr->preferredRecordSyntax =
2343 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
2347 pr->preferredRecordSyntax =
2348 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
2353 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
2355 new_apdu->u.presentResponse->referenceId = pr->referenceId;
2356 new_apdu->u.presentResponse->records =
2357 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
2358 *new_apdu->u.presentResponse->presentStatus =
2359 Z_PresentStatus_failure;
2361 send_to_client(new_apdu);
2365 else if (m_backend_type)
2367 pr->preferredRecordSyntax =
2368 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
2374 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
2378 Z_ElementSetNames *esn = (Z_ElementSetNames *)
2379 odr_malloc(o, sizeof(Z_ElementSetNames));
2380 esn->which = Z_ElementSetNames_generic;
2381 esn->u.generic = odr_strdup(o, schema);
2385 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
2388 Yaz_ProxyConfig *cfg = check_reconfigure();
2390 t = cfg->get_explain_name(db, backend_db);
2392 if (m_client && m_default_target && t && strcmp(m_default_target, t))
2399 xfree(m_default_target);
2400 m_default_target = xstrdup(t);
2404 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
2407 if (strcmp(hreq->method, "GET"))
2409 if (hreq->path[0] != '/')
2411 yaz_log(YLOG_WARN, "Bad path: %s", hreq->path);
2414 const char *cp = hreq->path;
2417 if (*cp == '/' && strchr("/.", cp[1]))
2419 yaz_log(YLOG_WARN, "Bad path: %s", hreq->path);
2424 const char *fname = hreq->path+1;
2425 if (stat(fname, &sbuf))
2427 yaz_log(YLOG_WARN|YLOG_ERRNO, "%s: stat failed", fname);
2430 if ((sbuf.st_mode & S_IFMT) != S_IFREG)
2432 yaz_log(YLOG_WARN, "%s: not a regular file", fname);
2435 if (sbuf.st_size > (off_t) 1000000)
2437 yaz_log(YLOG_WARN, "%s: too large for transfer", fname);
2441 ODR o = odr_encode();
2442 Yaz_ProxyConfig *cfg = check_reconfigure();
2443 const char *ctype = cfg->check_mime_type(fname);
2444 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
2445 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
2447 hres->version = odr_strdup(o, m_http_version);
2448 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
2449 if (m_http_keepalive)
2450 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
2454 hres->content_len = sbuf.st_size;
2455 hres->content_buf = (char*) odr_malloc(o, hres->content_len);
2456 FILE *f = fopen(fname, "rb");
2459 fread(hres->content_buf, 1, hres->content_len, f);
2466 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
2468 yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
2472 send_GDU(gdu, &len);
2473 recv_GDU_more(true);
2477 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
2481 odr_destroy(m_s2z_odr_init);
2484 if (m_s2z_odr_search)
2486 odr_destroy(m_s2z_odr_search);
2487 m_s2z_odr_search = 0;
2490 m_http_keepalive = 0;
2492 if (!strcmp(hreq->version, "1.0"))
2494 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2495 if (v && !strcmp(v, "Keep-Alive"))
2496 m_http_keepalive = 1;
2498 m_http_keepalive = 0;
2499 m_http_version = "1.0";
2503 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
2504 if (v && !strcmp(v, "close"))
2505 m_http_keepalive = 0;
2507 m_http_keepalive = 1;
2508 m_http_version = "1.1";
2511 Z_SRW_PDU *srw_pdu = 0;
2512 Z_SOAP *soap_package = 0;
2514 Z_SRW_diagnostic *diagnostic = 0;
2515 int num_diagnostic = 0;
2517 if (file_access(hreq))
2521 else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2523 || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
2524 &charset, &diagnostic, &num_diagnostic) == 0)
2526 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2527 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2528 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2529 m_s2z_init_apdu = 0;
2530 m_s2z_search_apdu = 0;
2531 m_s2z_present_apdu = 0;
2533 m_s2z_stylesheet = 0;
2535 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2537 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2539 const char *backend_db = srw_req->database;
2540 srw_get_client(srw_req->database, &backend_db);
2542 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2543 // recordXPath unsupported.
2544 if (srw_req->recordXPath)
2546 yaz_add_srw_diagnostic(odr_decode(),
2547 &diagnostic, &num_diagnostic,
2551 if (srw_req->sort_type != Z_SRW_sort_type_none)
2553 yaz_add_srw_diagnostic(odr_decode(),
2554 &diagnostic, &num_diagnostic,
2558 if (srw_req->stylesheet)
2560 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2562 // set packing for response records ..
2563 if (srw_req->recordPacking &&
2564 !strcmp(srw_req->recordPacking, "xml"))
2565 m_s2z_packing = Z_SRW_recordPacking_XML;
2567 m_s2z_packing = Z_SRW_recordPacking_string;
2571 Z_SRW_PDU *srw_pdu =
2572 yaz_srw_get(odr_encode(),
2573 Z_SRW_searchRetrieve_response);
2574 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2576 srw_res->diagnostics = diagnostic;
2577 srw_res->num_diagnostics = num_diagnostic;
2578 send_srw_response(srw_pdu);
2582 // prepare search PDU
2583 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2584 Z_APDU_searchRequest);
2585 Z_SearchRequest *z_searchRequest =
2586 m_s2z_search_apdu->u.searchRequest;
2588 z_searchRequest->num_databaseNames = 1;
2589 z_searchRequest->databaseNames = (char**)
2590 odr_malloc(m_s2z_odr_search, sizeof(char *));
2591 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2594 // query transformation
2595 Z_Query *query = (Z_Query *)
2596 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2597 z_searchRequest->query = query;
2599 if (srw_req->query_type == Z_SRW_query_type_cql)
2601 Z_External *ext = (Z_External *)
2602 odr_malloc(m_s2z_odr_search, sizeof(*ext));
2603 ext->direct_reference =
2604 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2605 ext->indirect_reference = 0;
2606 ext->descriptor = 0;
2607 ext->which = Z_External_CQL;
2608 ext->u.cql = srw_req->query.cql;
2610 query->which = Z_Query_type_104;
2611 query->u.type_104 = ext;
2613 else if (srw_req->query_type == Z_SRW_query_type_pqf)
2615 Z_RPNQuery *RPNquery;
2616 YAZ_PQF_Parser pqf_parser;
2618 pqf_parser = yaz_pqf_create ();
2620 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2621 srw_req->query.pqf);
2624 const char *pqf_msg;
2626 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2628 yaz_log(YLOG_LOG, "%*s^\n", ioff+4, "");
2629 yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2631 send_to_srw_client_error(10, 0);
2634 query->which = Z_Query_type_1;
2635 query->u.type_1 = RPNquery;
2637 yaz_pqf_destroy (pqf_parser);
2641 send_to_srw_client_error(7, "query");
2646 m_s2z_present_apdu = 0;
2648 if (srw_req->maximumRecords)
2649 max = *srw_req->maximumRecords;
2651 if (srw_req->startRecord)
2652 start = *srw_req->startRecord;
2655 // Some backend, such as Voyager doesn't honor piggyback
2656 // So we use present always (0 &&).
2657 if (0 && start <= 1) // Z39.50 piggyback
2659 *z_searchRequest->smallSetUpperBound = max;
2660 *z_searchRequest->mediumSetPresentNumber = max;
2661 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2663 z_searchRequest->preferredRecordSyntax =
2664 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2666 if (srw_req->recordSchema)
2668 z_searchRequest->smallSetElementSetNames =
2669 z_searchRequest->mediumSetElementSetNames =
2670 mk_esn_from_schema(m_s2z_odr_search,
2671 srw_req->recordSchema);
2674 else // Z39.50 present
2676 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2677 Z_APDU_presentRequest);
2678 Z_PresentRequest *z_presentRequest =
2679 m_s2z_present_apdu->u.presentRequest;
2680 *z_presentRequest->resultSetStartPoint = start;
2681 *z_presentRequest->numberOfRecordsRequested = max;
2682 z_presentRequest->preferredRecordSyntax =
2683 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2685 if (srw_req->recordSchema)
2687 z_presentRequest->recordComposition =
2688 (Z_RecordComposition *)
2689 odr_malloc(m_s2z_odr_search,
2690 sizeof(Z_RecordComposition));
2691 z_presentRequest->recordComposition->which =
2692 Z_RecordComp_simple;
2693 z_presentRequest->recordComposition->u.simple =
2694 mk_esn_from_schema(m_s2z_odr_search,
2695 srw_req->recordSchema);
2701 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2702 Z_APDU_initRequest);
2704 // prevent m_initRequest_apdu memory from being grabbed
2705 // in Yaz_Proxy::handle_incoming_Z_PDU
2706 m_initRequest_apdu = m_s2z_init_apdu;
2707 handle_incoming_Z_PDU(m_s2z_init_apdu);
2712 handle_incoming_Z_PDU(m_s2z_search_apdu);
2716 else if (srw_pdu->which == Z_SRW_explain_request)
2718 Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
2720 const char *backend_db = srw_req->database;
2721 srw_get_client(srw_req->database, &backend_db);
2723 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2726 if (srw_req->stylesheet)
2728 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2730 if (srw_req->recordPacking &&
2731 !strcmp(srw_req->recordPacking, "xml"))
2732 m_s2z_packing = Z_SRW_recordPacking_XML;
2734 m_s2z_packing = Z_SRW_recordPacking_string;
2738 send_srw_explain_response(diagnostic, num_diagnostic);
2744 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2745 Z_APDU_initRequest);
2747 // prevent m_initRequest_apdu memory from being grabbed
2748 // in Yaz_Proxy::handle_incoming_Z_PDU
2749 m_initRequest_apdu = m_s2z_init_apdu;
2750 handle_incoming_Z_PDU(m_s2z_init_apdu);
2753 send_srw_explain_response(0, 0);
2756 else if (srw_pdu->which == Z_SRW_scan_request)
2758 m_s2z_database = odr_strdup(m_s2z_odr_init,
2759 srw_pdu->u.scan_request->database);
2761 yaz_add_srw_diagnostic(odr_decode(),
2762 &diagnostic, &num_diagnostic,
2764 Z_SRW_PDU *srw_pdu =
2765 yaz_srw_get(odr_encode(),
2766 Z_SRW_scan_response);
2767 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
2769 srw_res->diagnostics = diagnostic;
2770 srw_res->num_diagnostics = num_diagnostic;
2771 send_srw_response(srw_pdu);
2778 send_to_srw_client_error(4, 0);
2781 send_http_response(400);
2784 void Yaz_Proxy::handle_init(Z_APDU *apdu)
2786 Z_OtherInformation **oi;
2787 get_otherInfoAPDU(apdu, &oi);
2789 if (apdu->u.initRequest->implementationId)
2790 yaz_log(YLOG_LOG, "%simplementationId: %s",
2791 m_session_str, apdu->u.initRequest->implementationId);
2792 if (apdu->u.initRequest->implementationName)
2793 yaz_log(YLOG_LOG, "%simplementationName: %s",
2794 m_session_str, apdu->u.initRequest->implementationName);
2795 if (apdu->u.initRequest->implementationVersion)
2796 yaz_log(YLOG_LOG, "%simplementationVersion: %s",
2797 m_session_str, apdu->u.initRequest->implementationVersion);
2798 if (m_initRequest_apdu == 0)
2800 if (m_initRequest_mem)
2801 nmem_destroy(m_initRequest_mem);
2803 m_initRequest_apdu = apdu;
2804 m_initRequest_mem = odr_extract_mem(odr_decode());
2806 m_initRequest_preferredMessageSize = *apdu->u.initRequest->
2807 preferredMessageSize;
2808 *apdu->u.initRequest->preferredMessageSize = 1024*1024;
2809 m_initRequest_maximumRecordSize = *apdu->u.initRequest->
2811 *apdu->u.initRequest->maximumRecordSize = 1024*1024;
2813 Z_CharSetandLanguageNegotiation *charSetandLangRecord =
2814 yaz_get_charneg_record(*oi);
2816 // Save proposal charsets and langs.
2817 if (ODR_MASK_GET(apdu->u.initRequest->options,
2818 Z_Options_negotiationModel)
2819 && charSetandLangRecord)
2822 yaz_get_proposal_charneg(m_referenceId_mem,
2823 charSetandLangRecord,
2824 &m_initRequest_oi_negotiation_charsets,
2825 &m_initRequest_oi_negotiation_num_charsets,
2826 &m_initRequest_oi_negotiation_langs,
2827 &m_initRequest_oi_negotiation_num_langs,
2828 &m_initRequest_oi_negotiation_selected);
2830 for (int i = 0; i<m_initRequest_oi_negotiation_num_charsets; i++)
2832 yaz_log(YLOG_LOG, "%scharacters set proposal: %s",
2833 m_session_str,(m_initRequest_oi_negotiation_charsets[i])?
2834 m_initRequest_oi_negotiation_charsets[i]:"none");
2836 for (int i=0; i<m_initRequest_oi_negotiation_num_langs; i++)
2838 yaz_log(YLOG_LOG, "%slanguages proposal: %s",
2839 m_session_str, (m_initRequest_oi_negotiation_langs[i])?
2840 m_initRequest_oi_negotiation_langs[i]:"none");
2842 yaz_log(YLOG_LOG, "%sselected proposal: %d (boolean)",
2843 m_session_str, m_initRequest_oi_negotiation_selected);
2845 // save init options for the response..
2846 m_initRequest_options = apdu->u.initRequest->options;
2848 apdu->u.initRequest->options =
2849 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2850 sizeof(Odr_bitmask));
2851 ODR_MASK_ZERO(apdu->u.initRequest->options);
2853 for (i = 0; i<= 24; i++)
2854 ODR_MASK_SET(apdu->u.initRequest->options, i);
2855 // check negotiation option
2856 if (!ODR_MASK_GET(m_initRequest_options,
2857 Z_Options_negotiationModel))
2859 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2860 Z_Options_negotiationModel);
2862 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2863 Z_Options_concurrentOperations);
2865 m_initRequest_version = apdu->u.initRequest->protocolVersion;
2866 apdu->u.initRequest->protocolVersion =
2867 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2868 sizeof(Odr_bitmask));
2869 ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
2871 for (i = 0; i<= 8; i++)
2872 ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
2874 if (m_client->m_init_flag)
2876 if (handle_init_response_for_invalid_session(apdu))
2878 if (m_client->m_initResponse)
2880 Z_APDU *apdu2 = m_client->m_initResponse;
2881 apdu2->u.initResponse->otherInfo = 0;
2882 if (m_client->m_cookie && *m_client->m_cookie)
2883 set_otherInformationString(apdu2, VAL_COOKIE, 1,
2884 m_client->m_cookie);
2885 apdu2->u.initResponse->referenceId =
2886 apdu->u.initRequest->referenceId;
2887 apdu2->u.initResponse->options = m_client->m_initResponse_options;
2888 apdu2->u.initResponse->protocolVersion =
2889 m_client->m_initResponse_version;
2891 send_to_client(apdu2);
2892 m_timeout_mode = timeout_normal;
2896 m_client->m_init_flag = 1;
2899 yaz_log(YLOG_LOG, "%suse_auth_msg", m_session_str);
2900 Auth_Msg *m = new Auth_Msg;
2902 z_APDU(odr_encode(), &apdu, 0, "encode");
2903 char *apdu_buf = odr_getbuf(odr_encode(), &m->m_apdu_len, 0);
2904 m->m_apdu_buf = (char*) nmem_malloc(m->m_nmem, m->m_apdu_len);
2905 memcpy(m->m_apdu_buf, apdu_buf, m->m_apdu_len);
2906 odr_reset(odr_encode());
2909 m_my_thread->put(m);
2911 int ret = handle_authentication(apdu);
2912 result_authentication(apdu, ret);
2916 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
2918 Z_ReferenceId **refid = get_referenceIdP(apdu);
2919 nmem_reset(m_referenceId_mem);
2920 if (refid && *refid)
2922 m_referenceId = (Z_ReferenceId *)
2923 nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
2924 m_referenceId->len = m_referenceId->size = (*refid)->len;
2925 m_referenceId->buf = (unsigned char *)
2926 nmem_malloc(m_referenceId_mem, (*refid)->len);
2927 memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
2932 if (!m_client && m_flag_invalid_session)
2934 // Got request for a session that is invalid..
2935 m_apdu_invalid_session = apdu; // save package
2936 m_mem_invalid_session = odr_extract_mem(odr_decode());
2937 apdu = m_initRequest_apdu; // but throw an init to the target
2940 // Determine our client.
2941 Z_OtherInformation **oi;
2942 get_otherInfoAPDU(apdu, &oi);
2943 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
2947 { // HTTP. Send not found
2948 send_http_response(404);
2953 // Z39.50 just shutdown
2959 m_client->m_server = this;
2961 if (apdu->which == Z_APDU_initRequest)
2964 handle_incoming_Z_PDU_2(apdu);
2967 void Yaz_Proxy::handle_incoming_Z_PDU_2(Z_APDU *apdu)
2969 handle_max_record_retrieve(apdu);
2972 apdu = handle_syntax_validation(apdu);
2975 apdu = handle_query_transformation(apdu);
2978 apdu = handle_target_charset_conversion(apdu);
2981 apdu = handle_query_validation(apdu);
2984 apdu = result_set_optimize(apdu);
2988 m_client->timeout(m_target_idletime); // mark it active even
2989 recv_GDU_more(true);
2990 // though we didn't use it
2993 // Add otherInformation entry in APDU if
2994 // negotiation is in use.
2996 handle_charset_lang_negotiation(apdu);
2998 // delete other info construct completely if 0 elements
2999 Z_OtherInformation **oi;
3000 get_otherInfoAPDU(apdu, &oi);
3001 if (oi && *oi && (*oi)->num_elements == 0)
3004 if (apdu->which == Z_APDU_presentRequest &&
3005 m_client->m_resultSetStartPoint == 0)
3007 Z_PresentRequest *pr = apdu->u.presentRequest;
3008 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
3009 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
3011 m_client->m_resultSetStartPoint = 0;
3013 if (m_client->send_to_target(apdu) < 0)
3015 m_client->shutdown();
3018 m_client->m_waiting = 1;
3021 void Yaz_Proxy::connectNotify()
3025 void Yaz_Proxy::releaseClient()
3027 xfree(m_proxyTarget);
3029 m_flag_invalid_session = 0;
3030 // only keep if keep_alive flag is set...
3032 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
3033 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
3034 m_client->m_waiting == 0)
3036 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
3038 m_client->get_hostname());
3039 yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
3040 m_session_str, m_client->m_pdu_recv,
3041 m_client->m_bytes_sent + m_client->m_bytes_recv,
3042 m_keepalive_limit_bw, m_keepalive_limit_pdu);
3043 assert (m_client->m_waiting != 2);
3044 // Tell client (if any) that no server connection is there..
3045 m_client->m_server = 0;
3050 yaz_log (YLOG_LOG, "%sShutdown (client to proxy) close %s",
3052 m_client->get_hostname());
3053 assert (m_client->m_waiting != 2);
3059 yaz_log (YLOG_LOG, "%sshutdown (client to proxy) bad state",
3065 yaz_log (YLOG_LOG, "%sShutdown (client to proxy)",
3069 m_parent->pre_init();
3072 bool Yaz_Proxy::dec_ref(bool main_ptr)
3074 yaz_log(YLOG_LOG, "%sdec_ref count=%d", m_session_str, m_ref_count);
3076 assert(m_ref_count > 0);
3081 m_main_ptr_dec = true;
3084 m_http_keepalive = 0;
3087 if (m_ref_count > 0)
3096 const char *Yaz_ProxyClient::get_session_str()
3100 return m_server->get_session_str();
3103 void Yaz_ProxyClient::shutdown()
3105 yaz_log (YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
3110 m_waiting = 1; // ensure it's released from Proxy in releaseClient
3111 m_server->dec_ref(true);
3117 void Yaz_Proxy::failNotify()
3120 yaz_log (YLOG_LOG, "%sConnection closed by client",
3125 void Yaz_Proxy::send_response_fail_client(const char *addr)
3127 yaz_log(YLOG_LOG, "%ssend_close_response", get_session_str());
3130 Z_SRW_diagnostic *diagnostic = 0;
3131 int num_diagnostic = 0;
3133 yaz_add_srw_diagnostic(odr_encode(),
3134 &diagnostic, &num_diagnostic,
3135 YAZ_SRW_SYSTEM_TEMPORARILY_UNAVAILABLE, addr);
3136 if (m_s2z_search_apdu)
3137 send_srw_search_response(diagnostic, num_diagnostic);
3139 send_srw_explain_response(diagnostic, num_diagnostic);
3142 void Yaz_ProxyClient::failNotify()
3145 m_server->inc_request_no();
3146 yaz_log (YLOG_LOG, "%sConnection closed by target %s",
3147 get_session_str(), get_hostname());
3150 m_server->send_response_fail_client(get_hostname());
3154 void Yaz_ProxyClient::connectNotify()
3156 const char *s = get_session_str();
3157 const char *h = get_hostname();
3158 yaz_log (YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
3160 timeout(m_target_idletime);
3165 IPDU_Observer *Yaz_ProxyClient::sessionNotify(IPDU_Observable
3166 *the_PDU_Observable, int fd)
3168 return new Yaz_ProxyClient(the_PDU_Observable, 0);
3171 Yaz_ProxyClient::~Yaz_ProxyClient()
3176 m_next->m_prev = m_prev;
3177 m_waiting = 2; // for debugging purposes only.
3178 odr_destroy(m_init_odr);
3179 delete m_last_query;
3180 xfree (m_last_resultSetId);
3184 void Yaz_ProxyClient::pre_init_client()
3186 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
3187 Z_InitRequest *req = apdu->u.initRequest;
3190 for (i = 0; i<= 24; i++)
3191 ODR_MASK_SET(req->options, i);
3192 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3193 Z_Options_negotiationModel);
3194 ODR_MASK_CLEAR(apdu->u.initRequest->options,
3195 Z_Options_concurrentOperations);
3196 for (i = 0; i<= 10; i++)
3197 ODR_MASK_SET(req->protocolVersion, i);
3199 if (send_to_target(apdu) < 0)
3210 void Yaz_Proxy::pre_init()
3213 const char *name = 0;
3214 const char *zurl_in_use[MAX_ZURL_PLEX];
3215 int limit_bw, limit_pdu, limit_req, limit_search, limit_connect;
3216 int target_idletime, client_idletime;
3218 int keepalive_limit_bw, keepalive_limit_pdu;
3220 const char *cql2rpn = 0;
3221 const char *authentication = 0;
3222 const char *negotiation_charset = 0;
3223 const char *negotiation_lang = 0;
3225 Yaz_ProxyConfig *cfg = check_reconfigure();
3229 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
3234 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
3235 &limit_bw, &limit_pdu, &limit_req,
3236 &limit_search, &limit_connect,
3237 &target_idletime, &client_idletime,
3239 &keepalive_limit_bw,
3240 &keepalive_limit_pdu,
3244 &negotiation_charset,
3251 for (j = 0; zurl_in_use[j]; j++)
3255 int spare_waiting = 0;
3258 for (c = m_clientPool; c; c = c->m_next)
3260 if (!strcmp(zurl_in_use[j], c->get_hostname()))
3262 if (c->m_cookie == 0)
3264 if (c->m_server == 0)
3276 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
3277 "sparew=%d preinit=%d",m_session_str,
3278 name, zurl_in_use[j], in_use, other,
3279 spare, spare_waiting, pre_init);
3280 if (spare + spare_waiting < pre_init)
3282 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
3283 c->m_next = m_clientPool;
3285 c->m_next->m_prev = &c->m_next;
3287 c->m_prev = &m_clientPool;
3289 if (m_log_mask & PROXY_LOG_APDU_SERVER)
3290 c->set_APDU_yazlog(1);
3292 c->set_APDU_yazlog(0);
3294 if (c->client(zurl_in_use[j]))
3302 c->m_target_idletime = target_idletime;
3303 c->m_seqno = m_seqno++;
3310 void Yaz_Proxy::timeoutNotify()
3315 switch(m_timeout_mode)
3317 case timeout_normal:
3321 yaz_log (YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
3324 case timeout_reduce:
3325 timeout(m_client_idletime);
3326 m_timeout_mode = timeout_busy;
3327 gdu = m_timeout_gdu;
3329 recv_GDU_normal(gdu);
3332 assert(m_stylesheet_nprl);
3333 convert_xsl_delay();
3334 recv_GDU_more(true);
3344 void Yaz_Proxy::markInvalid()
3347 m_flag_invalid_session = 1;
3350 void Yaz_ProxyClient::timeoutNotify()
3353 m_server->inc_request_no();
3355 yaz_log (YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
3359 m_server->send_response_fail_client(get_hostname());
3365 Yaz_ProxyClient::Yaz_ProxyClient(IPDU_Observable *the_PDU_Observable,
3366 Yaz_Proxy *parent) :
3367 Z_Assoc (the_PDU_Observable)
3374 m_last_resultSetId = 0;
3375 m_last_resultCount = 0;
3379 m_init_odr = odr_createmem (ODR_DECODE);
3381 m_initResponse_options = 0;
3382 m_initResponse_version = 0;
3383 m_initResponse_preferredMessageSize = 0;
3384 m_initResponse_maximumRecordSize = 0;
3385 m_resultSetStartPoint = 0;
3386 m_bytes_sent = m_bytes_recv = 0;
3390 m_target_idletime = 600;
3394 const char *Yaz_Proxy::option(const char *name, const char *value)
3396 if (!strcmp (name, "optimize")) {
3399 m_optimize = xstrdup (value);
3406 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
3411 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
3413 if (apdu->which == Z_GDU_Z3950)
3414 recv_Z_PDU(apdu->u.z3950, len);
3415 else if (apdu->which == Z_GDU_HTTP_Response)
3416 recv_HTTP_response(apdu->u.HTTP_Response, len);
3421 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
3423 if (!m_flag_invalid_session)
3425 m_flag_invalid_session = 0;
3426 handle_incoming_Z_PDU(m_apdu_invalid_session);
3427 assert (m_mem_invalid_session);
3428 nmem_destroy(m_mem_invalid_session);
3429 m_mem_invalid_session = 0;
3433 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
3435 m_bytes_recv += len;
3439 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
3440 yaz_log (YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
3441 apdu_name(apdu), get_hostname(), len);
3442 if (apdu->which == Z_APDU_initResponse)
3444 if (!m_server) // if this is a pre init session , check for more
3446 NMEM nmem = odr_extract_mem (odr_decode());
3447 odr_reset (m_init_odr);
3448 nmem_transfer (m_init_odr->mem, nmem);
3449 m_initResponse = apdu;
3450 m_initResponse_options = apdu->u.initResponse->options;
3451 m_initResponse_version = apdu->u.initResponse->protocolVersion;
3452 m_initResponse_preferredMessageSize =
3453 *apdu->u.initResponse->preferredMessageSize;
3454 m_initResponse_maximumRecordSize =
3455 *apdu->u.initResponse->maximumRecordSize;
3457 Z_InitResponse *ir = apdu->u.initResponse;
3458 char *im0 = ir->implementationName;
3461 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
3468 strcat(im1, "(YAZ Proxy)");
3469 ir->implementationName = im1;
3471 nmem_destroy (nmem);
3473 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
3476 if (apdu->which == Z_APDU_searchResponse)
3478 Z_SearchResponse *sr = apdu->u.searchResponse;
3479 m_last_resultCount = *sr->resultCount;
3480 int status = *sr->searchStatus;
3481 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
3485 if (sr->records && sr->records->which == Z_Records_DBOSD)
3487 m_cache.add(odr_decode(),
3488 sr->records->u.databaseOrSurDiagnostics, 1,
3493 if (apdu->which == Z_APDU_presentResponse)
3495 Z_PresentResponse *pr = apdu->u.presentResponse;
3499 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
3500 Z_SearchResponse *sr = new_apdu->u.searchResponse;
3501 sr->referenceId = pr->referenceId;
3502 *sr->resultCount = m_last_resultCount;
3503 sr->records = pr->records;
3504 sr->nextResultSetPosition = pr->nextResultSetPosition;
3505 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
3509 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
3511 m_cache.add(odr_decode(),
3512 pr->records->u.databaseOrSurDiagnostics,
3513 m_resultSetStartPoint, -1);
3514 m_resultSetStartPoint = 0;
3518 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
3520 Yaz_Proxy *server = m_server; // save it. send_to_client may destroy us
3523 server->send_to_client(apdu);
3524 if (apdu->which == Z_APDU_close)
3527 server->recv_GDU_more(true);
3530 void Yaz_Proxy::low_socket_close()
3535 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3536 if (m_lo_fd[i] >= 0)
3537 ::close(m_lo_fd[i]);
3541 void Yaz_Proxy::low_socket_open()
3546 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
3547 m_lo_fd[i] = open("/dev/null", O_RDONLY);
3551 int Yaz_Proxy::server(const char *addr)
3553 int r = Z_Assoc::server(addr);
3556 yaz_log(YLOG_LOG, "%sStarted proxy "
3560 " on %s", m_session_str, addr);
3569 * indent-tabs-mode: nil
3571 * vim: shiftwidth=4 tabstop=8 expandtab