1 /* $Id: yaz-proxy.cpp,v 1.14 2004-12-13 20:52:33 adam Exp $
2 Copyright (c) 1998-2004, 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
33 #include <sys/types.h>
37 #include <yaz/marcdisp.h>
38 #include <yaz/yaz-iconv.h>
40 #include <yaz/diagbib1.h>
42 #include <yaz/pquery.h>
43 #include <yaz/otherinfo.h>
45 static const char *apdu_name(Z_APDU *apdu)
49 case Z_APDU_initRequest:
51 case Z_APDU_initResponse:
52 return "initResponse";
53 case Z_APDU_searchRequest:
54 return "searchRequest";
55 case Z_APDU_searchResponse:
56 return "searchResponse";
57 case Z_APDU_presentRequest:
58 return "presentRequest";
59 case Z_APDU_presentResponse:
60 return "presentResponse";
61 case Z_APDU_deleteResultSetRequest:
62 return "deleteResultSetRequest";
63 case Z_APDU_deleteResultSetResponse:
64 return "deleteResultSetResponse";
65 case Z_APDU_scanRequest:
67 case Z_APDU_scanResponse:
68 return "scanResponse";
69 case Z_APDU_sortRequest:
71 case Z_APDU_sortResponse:
72 return "sortResponse";
73 case Z_APDU_extendedServicesRequest:
74 return "extendedServicesRequest";
75 case Z_APDU_extendedServicesResponse:
76 return "extendedServicesResponse";
83 static const char *gdu_name(Z_GDU *gdu)
88 return apdu_name(gdu->u.z3950);
89 case Z_GDU_HTTP_Request:
90 return "HTTP Request";
91 case Z_GDU_HTTP_Response:
92 return "HTTP Response";
94 return "Unknown request/response";
97 Yaz_Proxy::Yaz_Proxy(IYaz_PDU_Observable *the_PDU_Observable,
99 Yaz_Z_Assoc(the_PDU_Observable), m_bw_stat(60), m_pdu_stat(60)
101 m_PDU_Observable = the_PDU_Observable;
106 m_keepalive_limit_bw = 500000;
107 m_keepalive_limit_pdu = 1000;
109 m_default_target = 0;
110 m_proxy_authentication = 0;
114 m_client_idletime = 600;
115 m_target_idletime = 600;
116 m_optimize = xstrdup ("1");
117 strcpy(m_session_str, "0 ");
124 m_max_record_retrieve = 0;
128 m_invalid_session = 0;
130 m_referenceId_mem = nmem_create();
133 m_stylesheet_xsp = 0;
134 m_stylesheet_nprl = 0;
135 m_s2z_stylesheet = 0;
139 m_backend_charset = 0;
141 m_initRequest_apdu = 0;
142 m_initRequest_mem = 0;
143 m_initRequest_preferredMessageSize = 0;
144 m_initRequest_maximumRecordSize = 0;
145 m_initRequest_options = 0;
146 m_initRequest_version = 0;
147 m_apdu_invalid_session = 0;
148 m_mem_invalid_session = 0;
150 m_s2z_odr_search = 0;
152 m_s2z_search_apdu = 0;
153 m_s2z_present_apdu = 0;
154 m_http_keepalive = 0;
157 m_s2z_packing = Z_SRW_recordPacking_string;
158 #if HAVE_GETTIMEOFDAY
159 m_time_tv = xmalloc(sizeof(struct timeval));
160 struct timeval *tv = (struct timeval *) m_time_tv;
166 m_usemarcon_ini_stage1 = 0;
167 m_usemarcon_ini_stage2 = 0;
168 m_usemarcon = new Yaz_usemarcon();
173 Yaz_Proxy::~Yaz_Proxy()
175 yaz_log(YLOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
176 m_bytes_sent, m_bytes_recv);
177 nmem_destroy(m_initRequest_mem);
178 nmem_destroy(m_mem_invalid_session);
179 nmem_destroy(m_referenceId_mem);
181 xfree(m_proxyTarget);
182 xfree(m_default_target);
183 xfree(m_proxy_authentication);
187 if (m_stylesheet_xsp)
188 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
193 xfree (m_backend_type);
194 xfree (m_backend_charset);
195 xfree (m_usemarcon_ini_stage1);
196 xfree (m_usemarcon_ini_stage2);
199 odr_destroy(m_s2z_odr_init);
200 if (m_s2z_odr_search)
201 odr_destroy(m_s2z_odr_search);
207 int Yaz_Proxy::set_config(const char *config)
210 m_config = new Yaz_ProxyConfig();
211 xfree(m_config_fname);
212 m_config_fname = xstrdup(config);
213 int r = m_config->read_xml(config);
215 m_config->get_generic_info(&m_log_mask, &m_max_clients);
219 void Yaz_Proxy::set_default_target(const char *target)
221 xfree (m_default_target);
222 m_default_target = 0;
224 m_default_target = (char *) xstrdup (target);
227 void Yaz_Proxy::set_proxy_authentication (const char *auth)
229 xfree (m_proxy_authentication);
230 m_proxy_authentication = 0;
232 m_proxy_authentication = (char *) xstrdup (auth);
235 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
238 return m_parent->check_reconfigure();
240 Yaz_ProxyConfig *cfg = m_config;
243 yaz_log(YLOG_LOG, "reconfigure");
245 if (m_config_fname && cfg)
247 yaz_log(YLOG_LOG, "reconfigure config %s", m_config_fname);
248 int r = cfg->read_xml(m_config_fname);
250 yaz_log(YLOG_WARN, "reconfigure failed");
254 cfg->get_generic_info(&m_log_mask, &m_max_clients);
258 yaz_log(YLOG_LOG, "reconfigure");
264 IYaz_PDU_Observer *Yaz_Proxy::sessionNotify(IYaz_PDU_Observable
265 *the_PDU_Observable, int fd)
268 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable, this);
269 new_proxy->m_config = 0;
270 new_proxy->m_config_fname = 0;
271 new_proxy->timeout(m_client_idletime);
272 new_proxy->m_target_idletime = m_target_idletime;
273 new_proxy->set_default_target(m_default_target);
274 new_proxy->m_max_clients = m_max_clients;
275 new_proxy->m_log_mask = m_log_mask;
276 new_proxy->set_APDU_log(get_APDU_log());
277 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
278 new_proxy->set_APDU_yazlog(1);
280 new_proxy->set_APDU_yazlog(0);
281 new_proxy->set_proxy_authentication(m_proxy_authentication);
282 sprintf(new_proxy->m_session_str, "%ld:%d ", (long) time(0), m_session_no);
284 yaz_log (YLOG_LOG, "%sNew session %s", new_proxy->m_session_str,
285 the_PDU_Observable->getpeername());
289 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
292 Z_OtherInformationUnit *oi;
294 ent.proto = PROTO_Z3950;
295 ent.oclass = CLASS_USERINFO;
296 ent.value = (oid_value) VAL_COOKIE;
297 assert (oid_ent_to_oid (&ent, oid));
299 if (oid_ent_to_oid (&ent, oid) &&
300 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
301 oi->which == Z_OtherInfo_characterInfo)
302 return oi->information.characterInfo;
306 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
309 Z_OtherInformationUnit *oi;
311 ent.proto = PROTO_Z3950;
312 ent.oclass = CLASS_USERINFO;
313 ent.value = (oid_value) VAL_PROXY;
314 if (oid_ent_to_oid (&ent, oid) &&
315 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
316 oi->which == Z_OtherInfo_characterInfo)
317 return oi->information.characterInfo;
321 const char *Yaz_Proxy::load_balance(const char **url)
323 int zurl_in_use[MAX_ZURL_PLEX];
324 int zurl_in_spare[MAX_ZURL_PLEX];
328 for (i = 0; i<MAX_ZURL_PLEX; i++)
331 zurl_in_spare[i] = 0;
333 for (c = m_parent->m_clientPool; c; c = c->m_next)
335 for (i = 0; url[i]; i++)
336 if (!strcmp(url[i], c->get_hostname()))
339 if (c->m_cookie == 0 && c->m_server == 0 && c->m_waiting == 0)
343 int min_use = 100000;
344 int spare_for_min = 0;
346 const char *ret_min = 0;
347 const char *ret_spare = 0;
348 for (i = 0; url[i]; i++)
350 yaz_log(YLOG_DEBUG, "%szurl=%s use=%d spare=%d",
351 m_session_str, url[i], zurl_in_use[i], zurl_in_spare[i]);
352 if (min_use > zurl_in_use[i])
355 min_use = zurl_in_use[i];
356 spare_for_min = zurl_in_spare[i];
358 if (max_spare < zurl_in_spare[i])
361 max_spare = zurl_in_spare[i];
364 // use the one with minimum connections if spare is > 3
365 if (spare_for_min > 3)
367 // use one with most spares (if any)
373 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu, const char *cookie,
374 const char *proxy_host)
377 Yaz_Proxy *parent = m_parent;
378 Yaz_ProxyClient *c = m_client;
382 const char *url[MAX_ZURL_PLEX];
383 Yaz_ProxyConfig *cfg = check_reconfigure();
387 /* only to be enabled for debugging... */
388 if (!strcmp(proxy_host, "stop"))
391 xfree(m_default_target);
392 m_default_target = xstrdup(proxy_host);
394 proxy_host = m_default_target;
395 int client_idletime = -1;
396 const char *cql2rpn_fname = 0;
397 const char *authentication = 0;
398 url[0] = m_default_target;
403 cfg->get_target_info(proxy_host, url, &m_bw_max,
404 &m_pdu_max, &m_max_record_retrieve,
405 &m_target_idletime, &client_idletime,
406 &parent->m_max_clients,
407 &m_keepalive_limit_bw,
408 &m_keepalive_limit_pdu,
413 if (client_idletime != -1)
415 m_client_idletime = client_idletime;
416 timeout(m_client_idletime);
419 m_cql2rpn.set_pqf_file(cql2rpn_fname);
421 set_proxy_authentication(authentication);
424 yaz_log(YLOG_LOG, "%sNo default target", m_session_str);
427 // we don't handle multiplexing for cookie session, so we just
428 // pick the first one in this case (anonymous users will be able
429 // to use any backend)
430 if (cookie && *cookie)
431 m_proxyTarget = (char*) xstrdup(url[0]);
433 m_proxyTarget = (char*) xstrdup(load_balance(url));
435 if (cookie && *cookie)
436 { // search in sessions with a cookie
437 for (c = parent->m_clientPool; c; c = c->m_next)
440 assert (*c->m_prev == c);
441 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
442 !strcmp(m_proxyTarget, c->get_hostname()))
445 // The following handles "cancel"
446 // If connection is busy (waiting for PDU) and
447 // we have an initRequest we can safely do re-open
448 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
450 yaz_log (YLOG_LOG, "%s REOPEN target=%s", m_session_str,
457 c->m_last_resultCount = 0;
458 c->m_sr_transform = 0;
460 c->m_resultSetStartPoint = 0;
461 c->m_target_idletime = m_target_idletime;
462 if (c->client(m_proxyTarget))
469 c->m_seqno = parent->m_seqno;
470 if (c->m_server && c->m_server != this)
471 c->m_server->m_client = 0;
474 yaz_log (YLOG_DEBUG, "get_client 1 %p %p", this, c);
479 else if (!c && apdu->which == Z_APDU_initRequest
480 && apdu->u.initRequest->idAuthentication == 0)
482 // anonymous sessions without cookie.
483 // if authentication is set it is NOT anonymous se we can't share them.
484 for (c = parent->m_clientPool; c; c = c->m_next)
487 assert(*c->m_prev == c);
488 if (c->m_server == 0 && c->m_cookie == 0 &&
490 !strcmp(m_proxyTarget, c->get_hostname()))
493 yaz_log (YLOG_LOG, "%sREUSE %d %s",
494 m_session_str, parent->m_seqno, c->get_hostname());
496 c->m_seqno = parent->m_seqno;
497 assert(c->m_server == 0);
500 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
501 c->set_APDU_yazlog(1);
503 c->set_APDU_yazlog(0);
515 if (apdu->which != Z_APDU_initRequest)
517 yaz_log (YLOG_LOG, "%sno init request as first PDU", m_session_str);
520 Z_InitRequest *initRequest = apdu->u.initRequest;
522 if (!initRequest->idAuthentication)
524 if (m_proxy_authentication)
526 initRequest->idAuthentication =
527 (Z_IdAuthentication *)
528 odr_malloc (odr_encode(),
529 sizeof(*initRequest->idAuthentication));
530 initRequest->idAuthentication->which =
531 Z_IdAuthentication_open;
532 initRequest->idAuthentication->u.open =
533 odr_strdup (odr_encode(), m_proxy_authentication);
538 // the client use authentication. We set the keepalive PDU
539 // to 0 so we don't cache it in releaseClient
540 m_keepalive_limit_pdu = 0;
542 // go through list of clients - and find the lowest/oldest one.
543 Yaz_ProxyClient *c_min = 0;
545 int no_of_clients = 0;
546 if (parent->m_clientPool)
547 yaz_log (YLOG_DEBUG, "Existing sessions");
548 for (c = parent->m_clientPool; c; c = c->m_next)
550 yaz_log (YLOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
551 c->m_waiting, c->get_hostname(),
552 c->m_cookie ? c->m_cookie : "");
554 if (min_seq < 0 || c->m_seqno < min_seq)
556 min_seq = c->m_seqno;
560 if (no_of_clients >= parent->m_max_clients)
563 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
565 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Destroy %d",
566 m_session_str, parent->m_max_clients, c->m_seqno);
567 if (c->m_server && c->m_server != this)
573 yaz_log (YLOG_LOG, "%sMAXCLIENTS %d Reuse %d %d %s",
574 m_session_str, parent->m_max_clients,
575 c->m_seqno, parent->m_seqno, c->get_hostname());
579 c->m_cookie = xstrdup(cookie);
580 c->m_seqno = parent->m_seqno;
581 if (c->m_server && c->m_server != this)
583 c->m_server->m_client = 0;
587 c->m_target_idletime = m_target_idletime;
588 c->timeout(m_target_idletime);
590 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
591 c->set_APDU_yazlog(1);
593 c->set_APDU_yazlog(0);
600 yaz_log (YLOG_LOG, "%sNEW %d %s",
601 m_session_str, parent->m_seqno, m_proxyTarget);
602 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
603 c->m_next = parent->m_clientPool;
605 c->m_next->m_prev = &c->m_next;
606 parent->m_clientPool = c;
607 c->m_prev = &parent->m_clientPool;
613 c->m_cookie = xstrdup(cookie);
615 c->m_seqno = parent->m_seqno;
617 c->m_last_resultCount = 0;
620 c->m_sr_transform = 0;
622 c->m_resultSetStartPoint = 0;
624 if (c->client(m_proxyTarget))
629 c->m_target_idletime = m_target_idletime;
632 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
633 c->set_APDU_yazlog(1);
635 c->set_APDU_yazlog(0);
637 yaz_log (YLOG_DEBUG, "get_client 3 %p %p", this, c);
641 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
644 for (i = 0; i<num; i++)
647 Z_DefaultDiagFormat *r;
648 Z_DiagRec *p = pp[i];
649 if (p->which != Z_DiagRec_defaultFormat)
651 yaz_log(YLOG_LOG, "%sError no diagnostics", m_session_str);
655 r = p->u.defaultFormat;
656 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
657 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
658 yaz_log(YLOG_LOG, "%sError unknown diagnostic set", m_session_str);
661 case Z_DefaultDiagFormat_v2Addinfo:
662 yaz_log(YLOG_LOG, "%sError %d %s:%s",
664 *r->condition, diagbib1_str(*r->condition),
667 case Z_DefaultDiagFormat_v3Addinfo:
668 yaz_log(YLOG_LOG, "%sError %d %s:%s",
670 *r->condition, diagbib1_str(*r->condition),
677 int Yaz_Proxy::convert_xsl(Z_NamePlusRecordList *p, Z_APDU *apdu)
679 if (!m_stylesheet_xsp || p->num_records <= 0)
680 return 0; /* no XSLT to be done ... */
682 m_stylesheet_offset = 0;
683 m_stylesheet_nprl = p;
684 m_stylesheet_apdu = apdu;
689 void Yaz_Proxy::convert_xsl_delay()
691 Z_NamePlusRecord *npr = m_stylesheet_nprl->records[m_stylesheet_offset];
693 if (npr->which == Z_NamePlusRecord_databaseRecord)
695 Z_External *r = npr->u.databaseRecord;
696 if (r->which == Z_External_octet)
699 fwrite((char*) r->u.octet_aligned->buf, 1, r->u.octet_aligned->len, stdout);
701 xmlDocPtr res, doc = xmlParseMemory(
702 (char*) r->u.octet_aligned->buf,
703 r->u.octet_aligned->len);
706 yaz_log(YLOG_LOG, "%sXSLT convert %d",
707 m_session_str, m_stylesheet_offset);
708 res = xsltApplyStylesheet((xsltStylesheetPtr) m_stylesheet_xsp,
715 xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1);
717 m_stylesheet_nprl->records[m_stylesheet_offset]->
719 z_ext_record(odr_encode(), VAL_TEXT_XML,
720 (char*) out_buf, out_len);
729 m_stylesheet_offset++;
730 if (m_stylesheet_offset == m_stylesheet_nprl->num_records)
732 m_stylesheet_nprl = 0;
734 if (m_stylesheet_xsp)
735 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
737 m_stylesheet_xsp = 0;
738 timeout(m_client_idletime);
739 send_PDU_convert(m_stylesheet_apdu);
745 void Yaz_Proxy::convert_to_frontend_type(Z_NamePlusRecordList *p)
747 if (m_frontend_type != VAL_NONE)
750 for (i = 0; i < p->num_records; i++)
752 Z_NamePlusRecord *npr = p->records[i];
753 if (npr->which == Z_NamePlusRecord_databaseRecord)
755 Z_External *r = npr->u.databaseRecord;
756 if (r->which == Z_External_octet)
759 if (m_usemarcon_ini_stage1 && *m_usemarcon_ini_stage1)
761 if (!m_usemarcon->m_stage1)
763 m_usemarcon->m_stage1 = new CDetails();
765 m_usemarcon->m_stage1->SetIniFileName(m_usemarcon_ini_stage1);
766 m_usemarcon->m_stage1->SetMarcRecord((char*) r->u.octet_aligned->buf, r->u.octet_aligned->len);
767 int res = m_usemarcon->m_stage1->Start();
772 m_usemarcon->m_stage1->GetMarcRecord(converted, convlen);
773 if (m_usemarcon_ini_stage2 && *m_usemarcon_ini_stage2)
775 if (!m_usemarcon->m_stage2)
777 m_usemarcon->m_stage2 = new CDetails();
779 m_usemarcon->m_stage2->SetIniFileName(m_usemarcon_ini_stage2);
780 m_usemarcon->m_stage2->SetMarcRecord(converted, convlen);
781 res = m_usemarcon->m_stage2->Start();
785 m_usemarcon->m_stage2->GetMarcRecord(converted, convlen);
789 yaz_log(YLOG_LOG, "%sUSEMARCON stage 2 error %d", m_session_str, res);
792 npr->u.databaseRecord =
793 z_ext_record(odr_encode(),
801 yaz_log(YLOG_LOG, "%sUSEMARCON stage 1 error %d", m_session_str, res);
806 npr->u.databaseRecord =
807 z_ext_record(odr_encode(),
809 (char*) r->u.octet_aligned->buf,
810 r->u.octet_aligned->len);
817 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p,
818 const char *backend_charset)
822 if (!backend_charset)
823 backend_charset = "MARC-8";
824 yaz_iconv_t cd = yaz_iconv_open("UTF-8", backend_charset);
825 yaz_marc_t mt = yaz_marc_create();
826 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
827 yaz_marc_iconv(mt, cd);
828 for (i = 0; i < p->num_records; i++)
830 Z_NamePlusRecord *npr = p->records[i];
831 if (npr->which == Z_NamePlusRecord_databaseRecord)
833 Z_External *r = npr->u.databaseRecord;
834 if (r->which == Z_External_octet)
838 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
839 r->u.octet_aligned->len,
842 npr->u.databaseRecord = z_ext_record(odr_encode(),
851 yaz_marc_destroy(mt);
854 void Yaz_Proxy::logtime()
856 #if HAVE_GETTIMEOFDAY
857 struct timeval *tv = (struct timeval*) m_time_tv;
861 gettimeofday(&tv1, 0);
862 long diff = (tv1.tv_sec - tv->tv_sec)*1000000 +
863 (tv1.tv_usec - tv->tv_usec);
865 yaz_log(YLOG_LOG, "%sElapsed %ld.%03ld", m_session_str,
866 diff/1000000, (diff/1000)%1000);
873 int Yaz_Proxy::send_http_response(int code)
875 ODR o = odr_encode();
876 Z_GDU *gdu = z_get_HTTP_Response(o, code);
877 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
879 hres->version = odr_strdup(o, m_http_version);
880 if (m_http_keepalive)
881 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
885 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
887 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
891 int r = send_GDU(gdu, &len);
893 m_bw_stat.add_bytes(len);
898 int Yaz_Proxy::send_srw_response(Z_SRW_PDU *srw_pdu)
900 ODR o = odr_encode();
901 const char *ctype = "text/xml";
902 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
903 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
905 hres->version = odr_strdup(o, m_http_version);
906 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
907 if (m_http_keepalive)
908 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
912 static Z_SOAP_Handler soap_handlers[2] = {
914 {"http://www.loc.gov/zing/srw/", 0,
915 (Z_SOAP_fun) yaz_srw_codec},
920 Z_SOAP *soap_package = (Z_SOAP*) odr_malloc(o, sizeof(Z_SOAP));
921 soap_package->which = Z_SOAP_generic;
922 soap_package->u.generic =
923 (Z_SOAP_Generic *) odr_malloc(o, sizeof(*soap_package->u.generic));
924 soap_package->u.generic->no = 0;
925 soap_package->u.generic->ns = soap_handlers[0].ns;
926 soap_package->u.generic->p = (void *) srw_pdu;
927 soap_package->ns = m_soap_ns;
928 z_soap_codec_enc_xsl(o, &soap_package,
929 &hres->content_buf, &hres->content_len,
930 soap_handlers, 0, m_s2z_stylesheet);
931 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
933 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
937 int r = send_GDU(gdu, &len);
939 m_bw_stat.add_bytes(len);
944 int Yaz_Proxy::send_to_srw_client_error(int srw_error, const char *add)
946 ODR o = odr_encode();
947 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
948 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
950 srw_res->num_diagnostics = 1;
951 srw_res->diagnostics = (Z_SRW_diagnostic *)
952 odr_malloc(o, sizeof(*srw_res->diagnostics));
953 yaz_mk_std_diagnostic(o, srw_res->diagnostics, srw_error, add);
954 return send_srw_response(srw_pdu);
957 int Yaz_Proxy::z_to_srw_diag(ODR o, Z_SRW_searchRetrieveResponse *srw_res,
958 Z_DefaultDiagFormat *ddf)
960 int bib1_code = *ddf->condition;
961 if (bib1_code == 109)
963 srw_res->num_diagnostics = 1;
964 srw_res->diagnostics = (Z_SRW_diagnostic *)
965 odr_malloc(o, sizeof(*srw_res->diagnostics));
966 yaz_mk_std_diagnostic(o, srw_res->diagnostics,
967 yaz_diag_bib1_to_srw(*ddf->condition),
972 int Yaz_Proxy::send_to_srw_client_ok(int hits, Z_Records *records, int start)
974 ODR o = odr_encode();
975 Z_SRW_PDU *srw_pdu = yaz_srw_get(o, Z_SRW_searchRetrieve_response);
976 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
978 srw_res->numberOfRecords = odr_intdup (o, hits);
979 if (records && records->which == Z_Records_DBOSD)
981 srw_res->num_records =
982 records->u.databaseOrSurDiagnostics->num_records;
984 srw_res->records = (Z_SRW_record *)
985 odr_malloc(o, srw_res->num_records * sizeof(Z_SRW_record));
986 for (i = 0; i < srw_res->num_records; i++)
988 Z_NamePlusRecord *npr = records->u.databaseOrSurDiagnostics->records[i];
989 if (npr->which != Z_NamePlusRecord_databaseRecord)
991 srw_res->records[i].recordSchema = "diagnostic";
992 srw_res->records[i].recordPacking = m_s2z_packing;
993 srw_res->records[i].recordData_buf = "67";
994 srw_res->records[i].recordData_len = 2;
995 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
998 Z_External *r = npr->u.databaseRecord;
999 oident *ent = oid_getentbyoid(r->direct_reference);
1000 if (r->which == Z_External_octet && ent->value == VAL_TEXT_XML)
1002 srw_res->records[i].recordSchema = m_schema;
1003 srw_res->records[i].recordPacking = m_s2z_packing;
1004 srw_res->records[i].recordData_buf = (char*)
1005 r->u.octet_aligned->buf;
1006 srw_res->records[i].recordData_len = r->u.octet_aligned->len;
1007 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1011 srw_res->records[i].recordSchema = "diagnostic";
1012 srw_res->records[i].recordPacking = m_s2z_packing;
1013 srw_res->records[i].recordData_buf = "67";
1014 srw_res->records[i].recordData_len = 2;
1015 srw_res->records[i].recordPosition = odr_intdup(o, i+start);
1019 if (records && records->which == Z_Records_NSD)
1022 http_code = z_to_srw_diag(odr_encode(), srw_res,
1023 records->u.nonSurrogateDiagnostic);
1025 return send_http_response(http_code);
1027 return send_srw_response(srw_pdu);
1031 int Yaz_Proxy::send_srw_explain_response(Z_SRW_diagnostic *diagnostics,
1032 int num_diagnostics)
1034 Yaz_ProxyConfig *cfg = check_reconfigure();
1038 char *b = cfg->get_explain_doc(odr_encode(), 0 /* target */,
1039 m_s2z_database, &len);
1042 Z_SRW_PDU *res = yaz_srw_get(odr_encode(), Z_SRW_explain_response);
1043 Z_SRW_explainResponse *er = res->u.explain_response;
1045 er->record.recordData_buf = b;
1046 er->record.recordData_len = len;
1047 er->record.recordPacking = m_s2z_packing;
1048 er->record.recordSchema = "http://explain.z3950.org/dtd/2.0/";
1050 er->diagnostics = diagnostics;
1051 er->num_diagnostics = num_diagnostics;
1052 return send_srw_response(res);
1055 return send_http_response(404);
1058 int Yaz_Proxy::send_PDU_convert(Z_APDU *apdu)
1062 if (apdu->which == Z_APDU_initResponse)
1064 Z_InitResponse *res = apdu->u.initResponse;
1065 if (*res->result == 0)
1067 send_to_srw_client_error(3, 0);
1069 else if (!m_s2z_search_apdu)
1071 send_srw_explain_response(0, 0);
1075 handle_incoming_Z_PDU(m_s2z_search_apdu);
1078 else if (m_s2z_search_apdu && apdu->which == Z_APDU_searchResponse)
1080 m_s2z_search_apdu = 0;
1081 Z_SearchResponse *res = apdu->u.searchResponse;
1082 m_s2z_hit_count = *res->resultCount;
1083 if (res->records && res->records->which == Z_Records_NSD)
1085 send_to_srw_client_ok(0, res->records, 1);
1087 else if (m_s2z_present_apdu && m_s2z_hit_count > 0)
1090 Z_PresentRequest *pr = m_s2z_present_apdu->u.presentRequest;
1092 if (*pr->resultSetStartPoint <= m_s2z_hit_count)
1094 if (*pr->numberOfRecordsRequested+ *pr->resultSetStartPoint
1096 *pr->numberOfRecordsRequested =
1097 1 + m_s2z_hit_count - *pr->resultSetStartPoint;
1099 handle_incoming_Z_PDU(m_s2z_present_apdu);
1103 m_s2z_present_apdu = 0;
1104 send_to_srw_client_ok(m_s2z_hit_count, res->records, 1);
1107 else if (m_s2z_present_apdu && apdu->which == Z_APDU_presentResponse)
1110 *m_s2z_present_apdu->u.presentRequest->resultSetStartPoint;
1112 m_s2z_present_apdu = 0;
1113 Z_PresentResponse *res = apdu->u.presentResponse;
1114 send_to_srw_client_ok(m_s2z_hit_count, res->records, start);
1120 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1121 yaz_log (YLOG_LOG, "%sSending %s to client", m_session_str,
1123 int r = send_Z_PDU(apdu, &len);
1124 m_bytes_sent += len;
1125 m_bw_stat.add_bytes(len);
1132 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
1134 int kill_session = 0;
1135 Z_ReferenceId **new_id = get_referenceIdP(apdu);
1138 *new_id = m_referenceId;
1140 if (apdu->which == Z_APDU_searchResponse)
1142 Z_SearchResponse *sr = apdu->u.searchResponse;
1143 Z_Records *p = sr->records;
1144 if (p && p->which == Z_Records_NSD)
1146 Z_DiagRec dr, *dr_p = &dr;
1147 dr.which = Z_DiagRec_defaultFormat;
1148 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1150 *sr->searchStatus = 0;
1151 display_diagrecs(&dr_p, 1);
1155 if (p && p->which == Z_Records_DBOSD)
1159 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1162 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1164 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1166 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1170 if (sr->resultCount)
1172 yaz_log(YLOG_LOG, "%s%d hits", m_session_str,
1174 if (*sr->resultCount < 0)
1176 m_invalid_session = 1;
1179 *sr->searchStatus = 0;
1181 create_nonSurrogateDiagnostics(odr_encode(), 2, 0);
1182 *sr->resultCount = 0;
1187 else if (apdu->which == Z_APDU_presentResponse)
1189 Z_PresentResponse *sr = apdu->u.presentResponse;
1190 Z_Records *p = sr->records;
1191 if (p && p->which == Z_Records_NSD)
1193 Z_DiagRec dr, *dr_p = &dr;
1194 dr.which = Z_DiagRec_defaultFormat;
1195 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1196 if (*sr->presentStatus == Z_PresentStatus_success)
1197 *sr->presentStatus = Z_PresentStatus_failure;
1198 display_diagrecs(&dr_p, 1);
1200 if (p && p->which == Z_Records_DBOSD)
1204 || m_usemarcon_ini_stage1 || m_usemarcon_ini_stage2
1207 convert_to_frontend_type(p->u.databaseOrSurDiagnostics);
1209 convert_to_marcxml(p->u.databaseOrSurDiagnostics,
1211 if (convert_xsl(p->u.databaseOrSurDiagnostics, apdu))
1215 else if (apdu->which == Z_APDU_initResponse)
1217 if (m_initRequest_options)
1220 (Odr_bitmask *)odr_malloc(odr_encode(),
1221 sizeof(Odr_bitmask));
1222 ODR_MASK_ZERO(nopt);
1225 for (i = 0; i<24; i++)
1226 if (ODR_MASK_GET(m_initRequest_options, i) &&
1227 ODR_MASK_GET(apdu->u.initResponse->options, i))
1228 ODR_MASK_SET(nopt, i);
1229 apdu->u.initResponse->options = nopt;
1231 if (m_initRequest_version)
1233 Z_ProtocolVersion *nopt =
1234 (Odr_bitmask *)odr_malloc(odr_encode(),
1235 sizeof(Odr_bitmask));
1236 ODR_MASK_ZERO(nopt);
1239 for (i = 0; i<8; i++)
1240 if (ODR_MASK_GET(m_initRequest_version, i) &&
1241 ODR_MASK_GET(apdu->u.initResponse->protocolVersion, i))
1242 ODR_MASK_SET(nopt, i);
1243 apdu->u.initResponse->protocolVersion = nopt;
1245 apdu->u.initResponse->preferredMessageSize =
1246 odr_intdup(odr_encode(),
1247 m_client->m_initResponse_preferredMessageSize >
1248 m_initRequest_preferredMessageSize ?
1249 m_initRequest_preferredMessageSize :
1250 m_client->m_initResponse_preferredMessageSize);
1251 apdu->u.initResponse->maximumRecordSize =
1252 odr_intdup(odr_encode(),
1253 m_client->m_initResponse_maximumRecordSize >
1254 m_initRequest_maximumRecordSize ?
1255 m_initRequest_maximumRecordSize :
1256 m_client->m_initResponse_maximumRecordSize);
1258 int r = send_PDU_convert(apdu);
1265 m_parent->pre_init();
1270 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
1273 const char *apdu_name_tmp = apdu_name(apdu);
1274 int r = send_Z_PDU(apdu, &len);
1275 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1276 yaz_log (YLOG_LOG, "%sSending %s to %s %d bytes",
1278 apdu_name_tmp, get_hostname(), len);
1279 m_bytes_sent += len;
1283 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
1285 if (apdu->which == Z_APDU_presentRequest)
1287 Z_PresentRequest *pr = apdu->u.presentRequest;
1288 int toget = *pr->numberOfRecordsRequested;
1289 int start = *pr->resultSetStartPoint;
1291 yaz_log(YLOG_LOG, "%sPresent %s %d+%d", m_session_str,
1292 pr->resultSetId, start, toget);
1294 if (*m_parent->m_optimize == '0')
1297 if (!m_client->m_last_resultSetId)
1299 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1300 new_apdu->u.presentResponse->records =
1301 create_nonSurrogateDiagnostics(odr_encode(), 30,
1303 send_to_client(new_apdu);
1306 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
1308 if (start+toget-1 > m_client->m_last_resultCount)
1310 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1311 new_apdu->u.presentResponse->records =
1312 create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
1313 send_to_client(new_apdu);
1316 Z_NamePlusRecordList *npr;
1318 yaz_log(YLOG_LOG, "%sCache lookup %d+%d syntax=%s",
1319 m_session_str, start, toget, yaz_z3950oid_to_str(
1320 pr->preferredRecordSyntax, &oclass));
1322 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
1323 pr->preferredRecordSyntax,
1324 pr->recordComposition))
1326 yaz_log (YLOG_LOG, "%sReturned cached records for present request",
1328 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1329 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1331 new_apdu->u.presentResponse->numberOfRecordsReturned
1332 = odr_intdup(odr_encode(), toget);
1334 new_apdu->u.presentResponse->records = (Z_Records*)
1335 odr_malloc(odr_encode(), sizeof(Z_Records));
1336 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
1337 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
1338 new_apdu->u.presentResponse->nextResultSetPosition =
1339 odr_intdup(odr_encode(), start+toget);
1341 send_to_client(new_apdu);
1347 if (apdu->which != Z_APDU_searchRequest)
1349 Z_SearchRequest *sr = apdu->u.searchRequest;
1350 Yaz_Z_Query *this_query = new Yaz_Z_Query;
1351 Yaz_Z_Databases this_databases;
1353 this_databases.set(sr->num_databaseNames, (const char **)
1356 this_query->set_Z_Query(sr->query);
1358 char query_str[120];
1359 this_query->print(query_str, sizeof(query_str)-1);
1360 yaz_log(YLOG_LOG, "%sSearch %s", m_session_str, query_str);
1362 if (*m_parent->m_optimize != '0' &&
1363 m_client->m_last_ok && m_client->m_last_query &&
1364 m_client->m_last_query->match(this_query) &&
1365 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
1366 m_client->m_last_databases.match(this_databases))
1369 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
1370 m_client->m_last_resultCount < *sr->largeSetLowerBound)
1372 Z_NamePlusRecordList *npr;
1373 int toget = *sr->mediumSetPresentNumber;
1374 Z_RecordComposition *comp = 0;
1376 if (toget > m_client->m_last_resultCount)
1377 toget = m_client->m_last_resultCount;
1379 if (sr->mediumSetElementSetNames)
1381 comp = (Z_RecordComposition *)
1382 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1383 comp->which = Z_RecordComp_simple;
1384 comp->u.simple = sr->mediumSetElementSetNames;
1387 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1388 sr->preferredRecordSyntax, comp))
1390 yaz_log (YLOG_LOG, "%sReturned cached records for medium set",
1392 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1393 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1394 new_apdu->u.searchResponse->resultCount =
1395 &m_client->m_last_resultCount;
1397 new_apdu->u.searchResponse->numberOfRecordsReturned
1398 = odr_intdup(odr_encode(), toget);
1400 new_apdu->u.searchResponse->presentStatus =
1401 odr_intdup(odr_encode(), Z_PresentStatus_success);
1402 new_apdu->u.searchResponse->records = (Z_Records*)
1403 odr_malloc(odr_encode(), sizeof(Z_Records));
1404 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1405 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1406 new_apdu->u.searchResponse->nextResultSetPosition =
1407 odr_intdup(odr_encode(), toget+1);
1408 send_to_client(new_apdu);
1414 // send present request (medium size)
1415 yaz_log (YLOG_LOG, "%sOptimizing search for medium set",
1418 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1419 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1420 pr->referenceId = sr->referenceId;
1421 pr->resultSetId = sr->resultSetName;
1422 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1423 *pr->numberOfRecordsRequested = toget;
1424 pr->recordComposition = comp;
1425 m_client->m_sr_transform = 1;
1429 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
1430 m_client->m_last_resultCount <= 0)
1432 // large set. Return pseudo-search response immediately
1433 yaz_log (YLOG_LOG, "%sOptimizing search for large set",
1435 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1436 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1437 new_apdu->u.searchResponse->resultCount =
1438 &m_client->m_last_resultCount;
1439 send_to_client(new_apdu);
1444 Z_NamePlusRecordList *npr;
1445 int toget = m_client->m_last_resultCount;
1446 Z_RecordComposition *comp = 0;
1448 // send a present request (small set)
1450 if (sr->smallSetElementSetNames)
1452 comp = (Z_RecordComposition *)
1453 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
1454 comp->which = Z_RecordComp_simple;
1455 comp->u.simple = sr->smallSetElementSetNames;
1458 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
1459 sr->preferredRecordSyntax, comp))
1461 yaz_log (YLOG_LOG, "%sReturned cached records for small set",
1463 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1464 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1465 new_apdu->u.searchResponse->resultCount =
1466 &m_client->m_last_resultCount;
1468 new_apdu->u.searchResponse->numberOfRecordsReturned
1469 = odr_intdup(odr_encode(), toget);
1471 new_apdu->u.searchResponse->presentStatus =
1472 odr_intdup(odr_encode(), Z_PresentStatus_success);
1473 new_apdu->u.searchResponse->records = (Z_Records*)
1474 odr_malloc(odr_encode(), sizeof(Z_Records));
1475 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
1476 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
1477 new_apdu->u.searchResponse->nextResultSetPosition =
1478 odr_intdup(odr_encode(), toget+1);
1479 send_to_client(new_apdu);
1484 yaz_log (YLOG_LOG, "%sOptimizing search for small set",
1486 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
1487 Z_PresentRequest *pr = new_apdu->u.presentRequest;
1488 pr->referenceId = sr->referenceId;
1489 pr->resultSetId = sr->resultSetName;
1490 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
1491 *pr->numberOfRecordsRequested = toget;
1492 pr->recordComposition = comp;
1493 m_client->m_sr_transform = 1;
1498 else // query doesn't match
1500 delete m_client->m_last_query;
1501 m_client->m_last_query = this_query;
1502 m_client->m_last_ok = 0;
1503 m_client->m_cache.clear();
1504 m_client->m_resultSetStartPoint = 0;
1506 xfree (m_client->m_last_resultSetId);
1507 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
1509 m_client->m_last_databases.set(sr->num_databaseNames,
1510 (const char **) sr->databaseNames);
1516 void Yaz_Proxy::inc_request_no()
1518 char *cp = strchr(m_session_str, ' ');
1521 sprintf(cp+1, "%d ", m_request_no);
1524 void Yaz_Proxy::recv_GDU(Z_GDU *apdu, int len)
1528 m_bytes_recv += len;
1530 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1531 yaz_log (YLOG_LOG, "%sReceiving %s from client %d bytes",
1532 m_session_str, gdu_name(apdu), len);
1534 if (m_bw_hold_PDU) // double incoming PDU. shutdown now.
1537 m_bw_stat.add_bytes(len);
1538 m_pdu_stat.add_bytes(1);
1540 #if HAVE_GETTIMEOFDAY
1541 gettimeofday((struct timeval *) m_time_tv, 0);
1544 int bw_total = m_bw_stat.get_total();
1545 int pdu_total = m_pdu_stat.get_total();
1550 if (bw_total > m_bw_max)
1552 reduce = (bw_total/m_bw_max);
1557 if (pdu_total > m_pdu_max)
1559 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
1560 reduce = (reduce > nreduce) ? reduce : nreduce;
1566 yaz_log(YLOG_LOG, "%sdelay=%d bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1567 m_session_str, reduce, bw_total, pdu_total,
1568 m_bw_max, m_pdu_max);
1570 m_bw_hold_PDU = apdu; // save PDU and signal "on hold"
1571 timeout(reduce); // call us reduce seconds later
1573 else if (apdu->which == Z_GDU_Z3950)
1574 handle_incoming_Z_PDU(apdu->u.z3950);
1575 else if (apdu->which == Z_GDU_HTTP_Request)
1576 handle_incoming_HTTP(apdu->u.HTTP_Request);
1579 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
1581 if (m_max_record_retrieve)
1583 if (apdu->which == Z_APDU_presentRequest)
1585 Z_PresentRequest *pr = apdu->u.presentRequest;
1586 if (pr->numberOfRecordsRequested &&
1587 *pr->numberOfRecordsRequested > m_max_record_retrieve)
1588 *pr->numberOfRecordsRequested = m_max_record_retrieve;
1593 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
1595 const char *addinfo)
1597 Z_Records *rec = (Z_Records *)
1598 odr_malloc (odr, sizeof(*rec));
1600 odr_malloc (odr, sizeof(*err));
1601 Z_DiagRec *drec = (Z_DiagRec *)
1602 odr_malloc (odr, sizeof(*drec));
1603 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
1604 odr_malloc (odr, sizeof(*dr));
1606 rec->which = Z_Records_NSD;
1607 rec->u.nonSurrogateDiagnostic = dr;
1608 dr->diagnosticSetId =
1609 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
1610 dr->condition = err;
1611 dr->which = Z_DefaultDiagFormat_v2Addinfo;
1612 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
1616 Z_APDU *Yaz_Proxy::handle_query_transformation(Z_APDU *apdu)
1618 if (apdu->which == Z_APDU_searchRequest &&
1619 apdu->u.searchRequest->query &&
1620 apdu->u.searchRequest->query->which == Z_Query_type_104 &&
1621 apdu->u.searchRequest->query->u.type_104->which == Z_External_CQL)
1623 Z_RPNQuery *rpnquery = 0;
1624 Z_SearchRequest *sr = apdu->u.searchRequest;
1627 yaz_log(YLOG_LOG, "%sCQL: %s", m_session_str,
1628 sr->query->u.type_104->u.cql);
1630 int r = m_cql2rpn.query_transform(sr->query->u.type_104->u.cql,
1631 &rpnquery, odr_encode(),
1634 yaz_log(YLOG_LOG, "%sNo CQL to RPN table", m_session_str);
1637 yaz_log(YLOG_LOG, "%sCQL Conversion error %d", m_session_str, r);
1638 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1640 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1641 new_apdu->u.searchResponse->records =
1642 create_nonSurrogateDiagnostics(odr_encode(),
1643 yaz_diag_srw_to_bib1(r),
1645 *new_apdu->u.searchResponse->searchStatus = 0;
1647 send_to_client(new_apdu);
1653 sr->query->which = Z_Query_type_1;
1654 sr->query->u.type_1 = rpnquery;
1661 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
1663 if (apdu->which == Z_APDU_searchRequest)
1665 Z_SearchRequest *sr = apdu->u.searchRequest;
1669 Yaz_ProxyConfig *cfg = check_reconfigure();
1671 err = cfg->check_query(odr_encode(), m_default_target,
1672 sr->query, &addinfo);
1675 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1677 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1678 new_apdu->u.searchResponse->records =
1679 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1680 *new_apdu->u.searchResponse->searchStatus = 0;
1682 send_to_client(new_apdu);
1690 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
1693 if (apdu->which == Z_APDU_searchRequest)
1695 Z_SearchRequest *sr = apdu->u.searchRequest;
1698 Yaz_ProxyConfig *cfg = check_reconfigure();
1700 Z_RecordComposition rc_temp, *rc = 0;
1701 if (sr->smallSetElementSetNames)
1703 rc_temp.which = Z_RecordComp_simple;
1704 rc_temp.u.simple = sr->smallSetElementSetNames;
1708 if (sr->preferredRecordSyntax)
1711 ent = oid_getentbyoid(sr->preferredRecordSyntax);
1712 m_frontend_type = ent->value;
1715 m_frontend_type = VAL_NONE;
1717 char *stylesheet_name = 0;
1719 err = cfg->check_syntax(odr_encode(),
1721 sr->preferredRecordSyntax, rc,
1722 &addinfo, &stylesheet_name, &m_schema,
1723 &m_backend_type, &m_backend_charset,
1724 &m_usemarcon_ini_stage1,
1725 &m_usemarcon_ini_stage2);
1726 if (stylesheet_name)
1728 m_parent->low_socket_close();
1731 if (m_stylesheet_xsp)
1732 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
1733 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
1736 m_stylesheet_offset = 0;
1737 xfree(stylesheet_name);
1739 m_parent->low_socket_open();
1743 sr->smallSetElementSetNames = 0;
1744 sr->mediumSetElementSetNames = 0;
1748 sr->preferredRecordSyntax =
1749 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
1753 sr->preferredRecordSyntax =
1754 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
1760 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1762 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1763 new_apdu->u.searchResponse->records =
1764 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1765 *new_apdu->u.searchResponse->searchStatus = 0;
1767 send_to_client(new_apdu);
1771 else if (m_backend_type)
1773 sr->preferredRecordSyntax =
1774 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
1777 else if (apdu->which == Z_APDU_presentRequest)
1779 Z_PresentRequest *pr = apdu->u.presentRequest;
1782 Yaz_ProxyConfig *cfg = check_reconfigure();
1784 if (pr->preferredRecordSyntax)
1787 ent = oid_getentbyoid(pr->preferredRecordSyntax);
1788 m_frontend_type = ent->value;
1791 m_frontend_type = VAL_NONE;
1793 char *stylesheet_name = 0;
1795 err = cfg->check_syntax(odr_encode(), m_default_target,
1796 pr->preferredRecordSyntax,
1797 pr->recordComposition,
1798 &addinfo, &stylesheet_name, &m_schema,
1799 &m_backend_type, &m_backend_charset,
1800 &m_usemarcon_ini_stage1,
1801 &m_usemarcon_ini_stage2
1803 if (stylesheet_name)
1805 m_parent->low_socket_close();
1808 if (m_stylesheet_xsp)
1809 xsltFreeStylesheet((xsltStylesheetPtr) m_stylesheet_xsp);
1810 m_stylesheet_xsp = xsltParseStylesheetFile((const xmlChar*)
1813 m_stylesheet_offset = 0;
1814 xfree(stylesheet_name);
1816 m_parent->low_socket_open();
1820 pr->recordComposition = 0;
1824 pr->preferredRecordSyntax =
1825 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN,
1829 pr->preferredRecordSyntax =
1830 yaz_oidval_to_z3950oid(odr_encode(), CLASS_RECSYN,
1836 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1838 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1839 new_apdu->u.presentResponse->records =
1840 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1841 *new_apdu->u.presentResponse->presentStatus =
1842 Z_PresentStatus_failure;
1844 send_to_client(new_apdu);
1848 else if (m_backend_type)
1850 pr->preferredRecordSyntax =
1851 yaz_str_to_z3950oid(odr_encode(), CLASS_RECSYN, m_backend_type);
1857 Z_ElementSetNames *Yaz_Proxy::mk_esn_from_schema(ODR o, const char *schema)
1861 Z_ElementSetNames *esn = (Z_ElementSetNames *)
1862 odr_malloc(o, sizeof(Z_ElementSetNames));
1863 esn->which = Z_ElementSetNames_generic;
1864 esn->u.generic = odr_strdup(o, schema);
1868 void Yaz_Proxy::srw_get_client(const char *db, const char **backend_db)
1871 Yaz_ProxyConfig *cfg = check_reconfigure();
1873 t = cfg->get_explain_name(db, backend_db);
1875 if (m_client && m_default_target && t && strcmp(m_default_target, t))
1882 xfree(m_default_target);
1883 m_default_target = xstrdup(t);
1887 int Yaz_Proxy::file_access(Z_HTTP_Request *hreq)
1889 yaz_log(YLOG_LOG, "file_access");
1890 if (strcmp(hreq->method, "GET"))
1893 if (hreq->path[0] != '/')
1895 yaz_log(YLOG_WARN, "Path != /");
1898 const char *cp = hreq->path;
1901 if (*cp == '/' && strchr("/.", cp[1]))
1905 const char *fname = hreq->path+1;
1906 if (stat(fname, &sbuf))
1908 yaz_log(YLOG_WARN, "stat %s failed", fname);
1911 if ((sbuf.st_mode & S_IFMT) != S_IFREG)
1913 if (sbuf.st_size > (off_t) 1000000)
1916 ODR o = odr_encode();
1917 Yaz_ProxyConfig *cfg = check_reconfigure();
1918 const char *ctype = cfg->check_mime_type(fname);
1919 Z_GDU *gdu = z_get_HTTP_Response(o, 200);
1920 Z_HTTP_Response *hres = gdu->u.HTTP_Response;
1922 hres->version = odr_strdup(o, m_http_version);
1923 z_HTTP_header_add(o, &hres->headers, "Content-Type", ctype);
1924 if (m_http_keepalive)
1925 z_HTTP_header_add(o, &hres->headers, "Connection", "Keep-Alive");
1929 hres->content_len = sbuf.st_size;
1930 hres->content_buf = (char*) odr_malloc(o, hres->content_len);
1931 FILE *f = fopen(fname, "rb");
1934 fread(hres->content_buf, 1, hres->content_len, f);
1941 if (m_log_mask & PROXY_LOG_REQ_CLIENT)
1943 yaz_log (YLOG_LOG, "%sSending file %s to client", m_session_str,
1947 send_GDU(gdu, &len);
1951 void Yaz_Proxy::handle_incoming_HTTP(Z_HTTP_Request *hreq)
1955 odr_destroy(m_s2z_odr_init);
1958 if (m_s2z_odr_search)
1960 odr_destroy(m_s2z_odr_search);
1961 m_s2z_odr_search = 0;
1964 m_http_keepalive = 0;
1966 if (!strcmp(hreq->version, "1.0"))
1968 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1969 if (v && !strcmp(v, "Keep-Alive"))
1970 m_http_keepalive = 1;
1972 m_http_keepalive = 0;
1973 m_http_version = "1.0";
1977 const char *v = z_HTTP_header_lookup(hreq->headers, "Connection");
1978 if (v && !strcmp(v, "close"))
1979 m_http_keepalive = 0;
1981 m_http_keepalive = 1;
1982 m_http_version = "1.1";
1985 Z_SRW_PDU *srw_pdu = 0;
1986 Z_SOAP *soap_package = 0;
1988 Z_SRW_diagnostic *diagnostic = 0;
1989 int num_diagnostic = 0;
1991 if (file_access(hreq))
1995 else if (yaz_srw_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
1997 || yaz_sru_decode(hreq, &srw_pdu, &soap_package, odr_decode(),
1998 &charset, &diagnostic, &num_diagnostic) == 0)
2000 m_s2z_odr_init = odr_createmem(ODR_ENCODE);
2001 m_s2z_odr_search = odr_createmem(ODR_ENCODE);
2002 m_soap_ns = odr_strdup(m_s2z_odr_search, soap_package->ns);
2003 m_s2z_init_apdu = 0;
2004 m_s2z_search_apdu = 0;
2005 m_s2z_present_apdu = 0;
2007 m_s2z_stylesheet = 0;
2009 if (srw_pdu->which == Z_SRW_searchRetrieve_request)
2011 Z_SRW_searchRetrieveRequest *srw_req = srw_pdu->u.request;
2013 const char *backend_db = srw_req->database;
2014 srw_get_client(srw_req->database, &backend_db);
2016 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2017 // recordXPath unsupported.
2018 if (srw_req->recordXPath)
2020 yaz_add_srw_diagnostic(odr_decode(),
2021 &diagnostic, &num_diagnostic,
2025 if (srw_req->sort_type != Z_SRW_sort_type_none)
2027 yaz_add_srw_diagnostic(odr_decode(),
2028 &diagnostic, &num_diagnostic,
2032 if (srw_req->stylesheet)
2034 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2036 // set packing for response records ..
2037 if (srw_req->recordPacking &&
2038 !strcmp(srw_req->recordPacking, "xml"))
2039 m_s2z_packing = Z_SRW_recordPacking_XML;
2041 m_s2z_packing = Z_SRW_recordPacking_string;
2045 Z_SRW_PDU *srw_pdu =
2046 yaz_srw_get(odr_encode(),
2047 Z_SRW_searchRetrieve_response);
2048 Z_SRW_searchRetrieveResponse *srw_res = srw_pdu->u.response;
2050 srw_res->diagnostics = diagnostic;
2051 srw_res->num_diagnostics = num_diagnostic;
2052 send_srw_response(srw_pdu);
2056 // prepare search PDU
2057 m_s2z_search_apdu = zget_APDU(m_s2z_odr_search,
2058 Z_APDU_searchRequest);
2059 Z_SearchRequest *z_searchRequest =
2060 m_s2z_search_apdu->u.searchRequest;
2062 z_searchRequest->num_databaseNames = 1;
2063 z_searchRequest->databaseNames = (char**)
2064 odr_malloc(m_s2z_odr_search, sizeof(char *));
2065 z_searchRequest->databaseNames[0] = odr_strdup(m_s2z_odr_search,
2068 // query transformation
2069 Z_Query *query = (Z_Query *)
2070 odr_malloc(m_s2z_odr_search, sizeof(Z_Query));
2071 z_searchRequest->query = query;
2073 if (srw_req->query_type == Z_SRW_query_type_cql)
2075 Z_External *ext = (Z_External *)
2076 odr_malloc(m_s2z_odr_search, sizeof(*ext));
2077 ext->direct_reference =
2078 odr_getoidbystr(m_s2z_odr_search, "1.2.840.10003.16.2");
2079 ext->indirect_reference = 0;
2080 ext->descriptor = 0;
2081 ext->which = Z_External_CQL;
2082 ext->u.cql = srw_req->query.cql;
2084 query->which = Z_Query_type_104;
2085 query->u.type_104 = ext;
2087 else if (srw_req->query_type == Z_SRW_query_type_pqf)
2089 Z_RPNQuery *RPNquery;
2090 YAZ_PQF_Parser pqf_parser;
2092 pqf_parser = yaz_pqf_create ();
2094 RPNquery = yaz_pqf_parse (pqf_parser, m_s2z_odr_search,
2095 srw_req->query.pqf);
2098 const char *pqf_msg;
2100 int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2101 yaz_log(YLOG_LOG, "%*s^\n", off+4, "");
2102 yaz_log(YLOG_LOG, "Bad PQF: %s (code %d)\n", pqf_msg, code);
2104 send_to_srw_client_error(10, 0);
2107 query->which = Z_Query_type_1;
2108 query->u.type_1 = RPNquery;
2110 yaz_pqf_destroy (pqf_parser);
2114 send_to_srw_client_error(7, "query");
2119 m_s2z_present_apdu = 0;
2121 if (srw_req->maximumRecords)
2122 max = *srw_req->maximumRecords;
2124 if (srw_req->startRecord)
2125 start = *srw_req->startRecord;
2128 // Some backend, such as Voyager doesn't honor piggyback
2129 // So we use present always (0 &&).
2130 if (0 && start <= 1) // Z39.50 piggyback
2132 *z_searchRequest->smallSetUpperBound = max;
2133 *z_searchRequest->mediumSetPresentNumber = max;
2134 *z_searchRequest->largeSetLowerBound = 2000000000; // 2e9
2136 z_searchRequest->preferredRecordSyntax =
2137 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2139 if (srw_req->recordSchema)
2141 z_searchRequest->smallSetElementSetNames =
2142 z_searchRequest->mediumSetElementSetNames =
2143 mk_esn_from_schema(m_s2z_odr_search,
2144 srw_req->recordSchema);
2147 else // Z39.50 present
2149 m_s2z_present_apdu = zget_APDU(m_s2z_odr_search,
2150 Z_APDU_presentRequest);
2151 Z_PresentRequest *z_presentRequest =
2152 m_s2z_present_apdu->u.presentRequest;
2153 *z_presentRequest->resultSetStartPoint = start;
2154 *z_presentRequest->numberOfRecordsRequested = max;
2155 z_presentRequest->preferredRecordSyntax =
2156 yaz_oidval_to_z3950oid(m_s2z_odr_search, CLASS_RECSYN,
2158 if (srw_req->recordSchema)
2160 z_presentRequest->recordComposition =
2161 (Z_RecordComposition *)
2162 odr_malloc(m_s2z_odr_search,
2163 sizeof(Z_RecordComposition));
2164 z_presentRequest->recordComposition->which =
2165 Z_RecordComp_simple;
2166 z_presentRequest->recordComposition->u.simple =
2167 mk_esn_from_schema(m_s2z_odr_search,
2168 srw_req->recordSchema);
2174 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2175 Z_APDU_initRequest);
2177 // prevent m_initRequest_apdu memory from being grabbed
2178 // in Yaz_Proxy::handle_incoming_Z_PDU
2179 m_initRequest_apdu = m_s2z_init_apdu;
2180 handle_incoming_Z_PDU(m_s2z_init_apdu);
2185 handle_incoming_Z_PDU(m_s2z_search_apdu);
2189 else if (srw_pdu->which == Z_SRW_explain_request)
2191 Z_SRW_explainRequest *srw_req = srw_pdu->u.explain_request;
2193 const char *backend_db = srw_req->database;
2194 srw_get_client(srw_req->database, &backend_db);
2196 m_s2z_database = odr_strdup(m_s2z_odr_init, srw_req->database);
2199 if (srw_req->stylesheet)
2201 odr_strdup(m_s2z_odr_init, srw_req->stylesheet);
2203 if (srw_req->recordPacking &&
2204 !strcmp(srw_req->recordPacking, "xml"))
2205 m_s2z_packing = Z_SRW_recordPacking_XML;
2207 m_s2z_packing = Z_SRW_recordPacking_string;
2211 send_srw_explain_response(diagnostic, num_diagnostic);
2217 m_s2z_init_apdu = zget_APDU(m_s2z_odr_init,
2218 Z_APDU_initRequest);
2220 // prevent m_initRequest_apdu memory from being grabbed
2221 // in Yaz_Proxy::handle_incoming_Z_PDU
2222 m_initRequest_apdu = m_s2z_init_apdu;
2223 handle_incoming_Z_PDU(m_s2z_init_apdu);
2226 send_srw_explain_response(0, 0);
2229 else if (srw_pdu->which == Z_SRW_scan_request)
2231 m_s2z_database = odr_strdup(m_s2z_odr_init,
2232 srw_pdu->u.scan_request->database);
2234 yaz_add_srw_diagnostic(odr_decode(),
2235 &diagnostic, &num_diagnostic,
2237 Z_SRW_PDU *srw_pdu =
2238 yaz_srw_get(odr_encode(),
2239 Z_SRW_scan_response);
2240 Z_SRW_scanResponse *srw_res = srw_pdu->u.scan_response;
2242 srw_res->diagnostics = diagnostic;
2243 srw_res->num_diagnostics = num_diagnostic;
2244 send_srw_response(srw_pdu);
2251 send_to_srw_client_error(4, 0);
2254 send_http_response(400);
2257 void Yaz_Proxy::handle_incoming_Z_PDU(Z_APDU *apdu)
2259 Z_ReferenceId **refid = get_referenceIdP(apdu);
2260 nmem_reset(m_referenceId_mem);
2261 if (refid && *refid)
2263 m_referenceId = (Z_ReferenceId *)
2264 nmem_malloc(m_referenceId_mem, sizeof(*m_referenceId));
2265 m_referenceId->len = m_referenceId->size = (*refid)->len;
2266 m_referenceId->buf = (unsigned char *)
2267 nmem_malloc(m_referenceId_mem, (*refid)->len);
2268 memcpy(m_referenceId->buf, (*refid)->buf, (*refid)->len);
2273 if (!m_client && m_invalid_session)
2275 m_apdu_invalid_session = apdu;
2276 m_mem_invalid_session = odr_extract_mem(odr_decode());
2277 apdu = m_initRequest_apdu;
2280 // Determine our client.
2281 Z_OtherInformation **oi;
2282 get_otherInfoAPDU(apdu, &oi);
2283 m_client = get_client(apdu, get_cookie(oi), get_proxy(oi));
2288 send_http_response(404);
2297 m_client->m_server = this;
2299 if (apdu->which == Z_APDU_initRequest)
2301 if (apdu->u.initRequest->implementationId)
2302 yaz_log(YLOG_LOG, "%simplementationId: %s",
2303 m_session_str, apdu->u.initRequest->implementationId);
2304 if (apdu->u.initRequest->implementationName)
2305 yaz_log(YLOG_LOG, "%simplementationName: %s",
2306 m_session_str, apdu->u.initRequest->implementationName);
2307 if (apdu->u.initRequest->implementationVersion)
2308 yaz_log(YLOG_LOG, "%simplementationVersion: %s",
2309 m_session_str, apdu->u.initRequest->implementationVersion);
2310 if (m_initRequest_apdu == 0)
2312 if (m_initRequest_mem)
2313 nmem_destroy(m_initRequest_mem);
2314 m_initRequest_apdu = apdu;
2315 m_initRequest_mem = odr_extract_mem(odr_decode());
2317 m_initRequest_preferredMessageSize = *apdu->u.initRequest->
2318 preferredMessageSize;
2319 *apdu->u.initRequest->preferredMessageSize = 1024*1024;
2320 m_initRequest_maximumRecordSize = *apdu->u.initRequest->
2322 *apdu->u.initRequest->maximumRecordSize = 1024*1024;
2324 // save init options for the response..
2325 m_initRequest_options = apdu->u.initRequest->options;
2327 apdu->u.initRequest->options =
2328 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2329 sizeof(Odr_bitmask));
2330 ODR_MASK_ZERO(apdu->u.initRequest->options);
2332 for (i = 0; i<= 24; i++)
2333 ODR_MASK_SET(apdu->u.initRequest->options, i);
2334 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2335 Z_Options_negotiationModel);
2336 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2337 Z_Options_concurrentOperations);
2340 m_initRequest_version = apdu->u.initRequest->protocolVersion;
2341 apdu->u.initRequest->protocolVersion =
2342 (Odr_bitmask *)nmem_malloc(m_initRequest_mem,
2343 sizeof(Odr_bitmask));
2344 ODR_MASK_ZERO(apdu->u.initRequest->protocolVersion);
2346 for (i = 0; i<= 8; i++)
2347 ODR_MASK_SET(apdu->u.initRequest->protocolVersion, i);
2349 if (m_client->m_init_flag)
2351 if (handle_init_response_for_invalid_session(apdu))
2353 if (m_client->m_initResponse)
2355 Z_APDU *apdu2 = m_client->m_initResponse;
2356 apdu2->u.initResponse->otherInfo = 0;
2357 if (m_client->m_cookie && *m_client->m_cookie)
2358 set_otherInformationString(apdu2, VAL_COOKIE, 1,
2359 m_client->m_cookie);
2360 apdu2->u.initResponse->referenceId =
2361 apdu->u.initRequest->referenceId;
2362 apdu2->u.initResponse->options = m_client->m_initResponse_options;
2363 apdu2->u.initResponse->protocolVersion =
2364 m_client->m_initResponse_version;
2366 send_to_client(apdu2);
2370 m_client->m_init_flag = 1;
2372 handle_max_record_retrieve(apdu);
2375 apdu = handle_syntax_validation(apdu);
2378 apdu = handle_query_transformation(apdu);
2381 apdu = handle_query_validation(apdu);
2384 apdu = result_set_optimize(apdu);
2387 m_client->timeout(m_target_idletime); // mark it active even
2388 // though we didn't use it
2392 // delete other info construct completely if 0 elements
2393 get_otherInfoAPDU(apdu, &oi);
2394 if (*oi && (*oi)->num_elements == 0)
2397 if (apdu->which == Z_APDU_presentRequest &&
2398 m_client->m_resultSetStartPoint == 0)
2400 Z_PresentRequest *pr = apdu->u.presentRequest;
2401 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
2402 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
2404 m_client->m_resultSetStartPoint = 0;
2406 if (m_client->send_to_target(apdu) < 0)
2413 m_client->m_waiting = 1;
2416 void Yaz_Proxy::connectNotify()
2420 void Yaz_Proxy::releaseClient()
2422 xfree(m_proxyTarget);
2424 m_invalid_session = 0;
2425 // only keep if keep_alive flag is set...
2427 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
2428 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
2429 m_client->m_waiting == 0)
2431 yaz_log(YLOG_LOG, "%sShutdown (client to proxy) keepalive %s",
2433 m_client->get_hostname());
2434 yaz_log(YLOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
2435 m_session_str, m_client->m_pdu_recv,
2436 m_client->m_bytes_sent + m_client->m_bytes_recv,
2437 m_keepalive_limit_bw, m_keepalive_limit_pdu);
2438 assert (m_client->m_waiting != 2);
2439 // Tell client (if any) that no server connection is there..
2440 m_client->m_server = 0;
2445 yaz_log (YLOG_LOG, "%sShutdown (client to proxy) close %s",
2447 m_client->get_hostname());
2448 assert (m_client->m_waiting != 2);
2454 yaz_log (YLOG_LOG, "%sshutdown (client to proxy) bad state",
2460 yaz_log (YLOG_LOG, "%sShutdown (client to proxy)",
2464 m_parent->pre_init();
2467 void Yaz_Proxy::shutdown()
2473 const char *Yaz_ProxyClient::get_session_str()
2477 return m_server->get_session_str();
2480 void Yaz_ProxyClient::shutdown()
2482 yaz_log (YLOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
2488 void Yaz_Proxy::failNotify()
2491 yaz_log (YLOG_LOG, "%sConnection closed by client",
2496 void Yaz_ProxyClient::failNotify()
2499 m_server->inc_request_no();
2500 yaz_log (YLOG_LOG, "%sConnection closed by target %s",
2501 get_session_str(), get_hostname());
2505 void Yaz_ProxyClient::connectNotify()
2507 const char *s = get_session_str();
2508 const char *h = get_hostname();
2509 yaz_log (YLOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
2511 timeout(m_target_idletime);
2516 IYaz_PDU_Observer *Yaz_ProxyClient::sessionNotify(IYaz_PDU_Observable
2517 *the_PDU_Observable, int fd)
2519 return new Yaz_ProxyClient(the_PDU_Observable, 0);
2522 Yaz_ProxyClient::~Yaz_ProxyClient()
2527 m_next->m_prev = m_prev;
2528 m_waiting = 2; // for debugging purposes only.
2529 odr_destroy(m_init_odr);
2530 delete m_last_query;
2531 xfree (m_last_resultSetId);
2535 void Yaz_ProxyClient::pre_init_client()
2537 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
2538 Z_InitRequest *req = apdu->u.initRequest;
2541 for (i = 0; i<= 24; i++)
2542 ODR_MASK_SET(req->options, i);
2543 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2544 Z_Options_negotiationModel);
2545 ODR_MASK_CLEAR(apdu->u.initRequest->options,
2546 Z_Options_concurrentOperations);
2547 for (i = 0; i<= 10; i++)
2548 ODR_MASK_SET(req->protocolVersion, i);
2550 if (send_to_target(apdu) < 0)
2561 void Yaz_Proxy::pre_init()
2564 const char *name = 0;
2565 const char *zurl_in_use[MAX_ZURL_PLEX];
2566 int limit_bw, limit_pdu, limit_req;
2567 int target_idletime, client_idletime;
2569 int keepalive_limit_bw, keepalive_limit_pdu;
2571 const char *cql2rpn = 0;
2572 const char *authentication = 0;
2574 Yaz_ProxyConfig *cfg = check_reconfigure();
2578 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
2583 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
2584 &limit_bw, &limit_pdu, &limit_req,
2585 &target_idletime, &client_idletime,
2587 &keepalive_limit_bw,
2588 &keepalive_limit_pdu,
2591 &authentication) ; i++)
2596 for (j = 0; zurl_in_use[j]; j++)
2600 int spare_waiting = 0;
2603 for (c = m_clientPool; c; c = c->m_next)
2605 if (!strcmp(zurl_in_use[j], c->get_hostname()))
2607 if (c->m_cookie == 0)
2609 if (c->m_server == 0)
2621 yaz_log(YLOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
2622 "sparew=%d preinit=%d",m_session_str,
2623 name, zurl_in_use[j], in_use, other,
2624 spare, spare_waiting, pre_init);
2625 if (spare + spare_waiting < pre_init)
2627 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
2628 c->m_next = m_clientPool;
2630 c->m_next->m_prev = &c->m_next;
2632 c->m_prev = &m_clientPool;
2634 if (m_log_mask & PROXY_LOG_APDU_SERVER)
2635 c->set_APDU_yazlog(1);
2637 c->set_APDU_yazlog(0);
2639 if (c->client(zurl_in_use[j]))
2647 c->m_target_idletime = target_idletime;
2648 c->m_seqno = m_seqno++;
2655 void Yaz_Proxy::timeoutNotify()
2661 timeout(m_client_idletime);
2662 Z_GDU *apdu = m_bw_hold_PDU;
2665 if (apdu->which == Z_GDU_Z3950)
2666 handle_incoming_Z_PDU(apdu->u.z3950);
2667 else if (apdu->which == Z_GDU_HTTP_Request)
2668 handle_incoming_HTTP(apdu->u.HTTP_Request);
2670 else if (m_stylesheet_nprl)
2671 convert_xsl_delay();
2676 yaz_log (YLOG_LOG, "%sTimeout (client to proxy)", m_session_str);
2687 void Yaz_Proxy::markInvalid()
2690 m_invalid_session = 1;
2693 void Yaz_ProxyClient::timeoutNotify()
2696 m_server->inc_request_no();
2698 yaz_log (YLOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
2702 if (m_server && m_init_flag)
2704 // target timed out in a session that was properly initialized
2705 // server object stay alive but we mark it as invalid so it
2706 // gets initialized again
2707 m_server->markInvalid();
2713 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable,
2714 Yaz_Proxy *parent) :
2715 Yaz_Z_Assoc (the_PDU_Observable)
2722 m_last_resultSetId = 0;
2723 m_last_resultCount = 0;
2727 m_init_odr = odr_createmem (ODR_DECODE);
2729 m_initResponse_options = 0;
2730 m_initResponse_version = 0;
2731 m_initResponse_preferredMessageSize = 0;
2732 m_initResponse_maximumRecordSize = 0;
2733 m_resultSetStartPoint = 0;
2734 m_bytes_sent = m_bytes_recv = 0;
2738 m_target_idletime = 600;
2742 const char *Yaz_Proxy::option(const char *name, const char *value)
2744 if (!strcmp (name, "optimize")) {
2747 m_optimize = xstrdup (value);
2754 void Yaz_ProxyClient::recv_HTTP_response(Z_HTTP_Response *apdu, int len)
2759 void Yaz_ProxyClient::recv_GDU(Z_GDU *apdu, int len)
2761 if (apdu->which == Z_GDU_Z3950)
2762 recv_Z_PDU(apdu->u.z3950, len);
2763 else if (apdu->which == Z_GDU_HTTP_Response)
2764 recv_HTTP_response(apdu->u.HTTP_Response, len);
2769 int Yaz_Proxy::handle_init_response_for_invalid_session(Z_APDU *apdu)
2771 if (!m_invalid_session)
2773 m_invalid_session = 0;
2774 handle_incoming_Z_PDU(m_apdu_invalid_session);
2775 assert (m_mem_invalid_session);
2776 nmem_destroy(m_mem_invalid_session);
2777 m_mem_invalid_session = 0;
2781 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
2783 m_bytes_recv += len;
2787 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
2788 yaz_log (YLOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
2789 apdu_name(apdu), get_hostname(), len);
2790 if (apdu->which == Z_APDU_initResponse)
2792 if (!m_server) // if this is a pre init session , check for more
2794 NMEM nmem = odr_extract_mem (odr_decode());
2795 odr_reset (m_init_odr);
2796 nmem_transfer (m_init_odr->mem, nmem);
2797 m_initResponse = apdu;
2798 m_initResponse_options = apdu->u.initResponse->options;
2799 m_initResponse_version = apdu->u.initResponse->protocolVersion;
2800 m_initResponse_preferredMessageSize =
2801 *apdu->u.initResponse->preferredMessageSize;
2802 m_initResponse_maximumRecordSize =
2803 *apdu->u.initResponse->maximumRecordSize;
2805 Z_InitResponse *ir = apdu->u.initResponse;
2806 char *im0 = ir->implementationName;
2809 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
2816 strcat(im1, "(YAZ Proxy)");
2817 ir->implementationName = im1;
2819 nmem_destroy (nmem);
2821 if (m_server && m_server->handle_init_response_for_invalid_session(apdu))
2824 if (apdu->which == Z_APDU_searchResponse)
2826 Z_SearchResponse *sr = apdu->u.searchResponse;
2827 m_last_resultCount = *sr->resultCount;
2828 int status = *sr->searchStatus;
2829 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
2833 if (sr->records && sr->records->which == Z_Records_DBOSD)
2835 m_cache.add(odr_decode(),
2836 sr->records->u.databaseOrSurDiagnostics, 1,
2841 if (apdu->which == Z_APDU_presentResponse)
2843 Z_PresentResponse *pr = apdu->u.presentResponse;
2847 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
2848 Z_SearchResponse *sr = new_apdu->u.searchResponse;
2849 sr->referenceId = pr->referenceId;
2850 *sr->resultCount = m_last_resultCount;
2851 sr->records = pr->records;
2852 sr->nextResultSetPosition = pr->nextResultSetPosition;
2853 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
2857 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
2859 m_cache.add(odr_decode(),
2860 pr->records->u.databaseOrSurDiagnostics,
2861 m_resultSetStartPoint, -1);
2862 m_resultSetStartPoint = 0;
2866 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
2869 m_server->send_to_client(apdu);
2871 if (apdu->which == Z_APDU_close)
2877 void Yaz_Proxy::low_socket_close()
2882 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
2883 if (m_lo_fd[i] >= 0)
2884 ::close(m_lo_fd[i]);
2888 void Yaz_Proxy::low_socket_open()
2893 for (i = 0; i<NO_SPARE_SOLARIS_FD; i++)
2894 m_lo_fd[i] = open("/dev/null", O_RDONLY);
2898 int Yaz_Proxy::server(const char *addr)
2900 int r = Yaz_Z_Assoc::server(addr);
2903 yaz_log(YLOG_LOG, "%sStarted proxy "
2907 " on %s", m_session_str, addr);