2 * Copyright (c) 1998-2003, Index Data.
3 * See the file LICENSE for details.
5 * $Id: yaz-proxy.cpp,v 1.62 2003-10-16 16:10:43 adam Exp $
11 #include <yaz/marcdisp.h>
12 #include <yaz/yaz-iconv.h>
14 #include <yaz/diagbib1.h>
15 #include <yaz++/proxy.h>
17 static const char *apdu_name(Z_APDU *apdu)
21 case Z_APDU_initRequest:
23 case Z_APDU_initResponse:
24 return "initResponse";
25 case Z_APDU_searchRequest:
26 return "searchRequest";
27 case Z_APDU_searchResponse:
28 return "searchResponse";
29 case Z_APDU_presentRequest:
30 return "presentRequest";
31 case Z_APDU_presentResponse:
32 return "presentResponse";
33 case Z_APDU_deleteResultSetRequest:
34 return "deleteResultSetRequest";
35 case Z_APDU_deleteResultSetResponse:
36 return "deleteResultSetResponse";
37 case Z_APDU_scanRequest:
39 case Z_APDU_scanResponse:
40 return "scanResponse";
41 case Z_APDU_sortRequest:
43 case Z_APDU_sortResponse:
44 return "sortResponse";
45 case Z_APDU_extendedServicesRequest:
46 return "extendedServicesRequest";
47 case Z_APDU_extendedServicesResponse:
48 return "extendedServicesResponse";
55 Yaz_Proxy::Yaz_Proxy(IYaz_PDU_Observable *the_PDU_Observable,
57 Yaz_Z_Assoc(the_PDU_Observable), m_bw_stat(60), m_pdu_stat(60)
59 m_PDU_Observable = the_PDU_Observable;
64 m_keepalive_limit_bw = 500000;
65 m_keepalive_limit_pdu = 1000;
68 m_proxy_authentication = 0;
72 m_client_idletime = 600;
73 m_target_idletime = 600;
74 m_optimize = xstrdup ("1");
75 strcpy(m_session_str, "0");
77 m_bytes_sent = m_bytes_recv = 0;
81 m_max_record_retrieve = 0;
85 m_invalid_session = 0;
90 Yaz_Proxy::~Yaz_Proxy()
92 yaz_log(LOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
93 m_bytes_sent, m_bytes_recv);
94 xfree (m_proxyTarget);
95 xfree (m_default_target);
96 xfree (m_proxy_authentication);
101 int Yaz_Proxy::set_config(const char *config)
104 m_config = new Yaz_ProxyConfig();
105 xfree(m_config_fname);
106 m_config_fname = xstrdup(config);
107 int r = m_config->read_xml(config);
109 m_config->get_generic_info(&m_log_mask, &m_max_clients);
113 void Yaz_Proxy::set_default_target(const char *target)
115 xfree (m_default_target);
116 m_default_target = 0;
118 m_default_target = (char *) xstrdup (target);
121 void Yaz_Proxy::set_proxy_authentication (const char *auth)
123 xfree (m_proxy_authentication);
124 m_proxy_authentication = 0;
126 m_proxy_authentication = (char *) xstrdup (auth);
129 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
132 return m_parent->check_reconfigure();
134 Yaz_ProxyConfig *cfg = m_config;
137 yaz_log(LOG_LOG, "reconfigure");
139 if (m_config_fname && cfg)
141 yaz_log(LOG_LOG, "reconfigure config %s", m_config_fname);
142 int r = cfg->read_xml(m_config_fname);
144 yaz_log(LOG_WARN, "reconfigure failed");
148 cfg->get_generic_info(&m_log_mask, &m_max_clients);
152 yaz_log(LOG_LOG, "reconfigure");
158 IYaz_PDU_Observer *Yaz_Proxy::sessionNotify(IYaz_PDU_Observable
159 *the_PDU_Observable, int fd)
162 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable, this);
163 new_proxy->m_config = 0;
164 new_proxy->m_config_fname = 0;
165 new_proxy->timeout(m_client_idletime);
166 new_proxy->m_target_idletime = m_target_idletime;
167 new_proxy->set_default_target(m_default_target);
168 new_proxy->m_max_clients = m_max_clients;
169 new_proxy->m_log_mask = m_log_mask;
170 new_proxy->set_APDU_log(get_APDU_log());
171 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
172 new_proxy->set_APDU_yazlog(1);
174 new_proxy->set_APDU_yazlog(0);
175 new_proxy->set_proxy_authentication(m_proxy_authentication);
176 sprintf(new_proxy->m_session_str, "%ld:%d ", (long) time(0), m_session_no);
178 yaz_log (LOG_LOG, "%sNew session %s", new_proxy->m_session_str,
179 the_PDU_Observable->getpeername());
183 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
186 Z_OtherInformationUnit *oi;
188 ent.proto = PROTO_Z3950;
189 ent.oclass = CLASS_USERINFO;
190 ent.value = (oid_value) VAL_COOKIE;
191 assert (oid_ent_to_oid (&ent, oid));
193 if (oid_ent_to_oid (&ent, oid) &&
194 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
195 oi->which == Z_OtherInfo_characterInfo)
196 return oi->information.characterInfo;
200 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
203 Z_OtherInformationUnit *oi;
205 ent.proto = PROTO_Z3950;
206 ent.oclass = CLASS_USERINFO;
207 ent.value = (oid_value) VAL_PROXY;
208 if (oid_ent_to_oid (&ent, oid) &&
209 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
210 oi->which == Z_OtherInfo_characterInfo)
211 return oi->information.characterInfo;
215 const char *Yaz_Proxy::load_balance(const char **url)
217 int zurl_in_use[MAX_ZURL_PLEX];
221 for (i = 0; i<MAX_ZURL_PLEX; i++)
223 for (c = m_parent->m_clientPool; c; c = c->m_next)
225 for (i = 0; url[i]; i++)
226 if (!strcmp(url[i], c->get_hostname()))
231 for (i = 0; url[i]; i++)
233 yaz_log(LOG_DEBUG, "%szurl=%s use=%d",
234 m_session_str, url[i], zurl_in_use[i]);
235 if (min > zurl_in_use[i])
238 min = zurl_in_use[i];
244 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu)
247 Yaz_Proxy *parent = m_parent;
248 Z_OtherInformation **oi;
249 Yaz_ProxyClient *c = m_client;
251 get_otherInfoAPDU(apdu, &oi);
252 char *cookie = get_cookie(oi);
256 const char *url[MAX_ZURL_PLEX];
257 const char *proxy_host = get_proxy(oi);
258 Yaz_ProxyConfig *cfg = check_reconfigure();
261 xfree(m_default_target);
262 m_default_target = xstrdup(proxy_host);
263 proxy_host = m_default_target;
265 int client_idletime = -1;
266 url[0] = m_default_target;
271 cfg->get_target_info(proxy_host, url, &m_bw_max,
272 &m_pdu_max, &m_max_record_retrieve,
273 &m_target_idletime, &client_idletime,
274 &parent->m_max_clients,
275 &m_keepalive_limit_bw,
276 &m_keepalive_limit_pdu,
279 if (client_idletime != -1)
281 m_client_idletime = client_idletime;
282 timeout(m_client_idletime);
286 yaz_log(LOG_LOG, "%sNo default target", m_session_str);
289 // we don't handle multiplexing for cookie session, so we just
290 // pick the first one in this case (anonymous users will be able
291 // to use any backend)
292 if (cookie && *cookie)
293 m_proxyTarget = (char*) xstrdup(url[0]);
295 m_proxyTarget = (char*) xstrdup(load_balance(url));
297 if (cookie && *cookie)
298 { // search in sessions with a cookie
299 for (c = parent->m_clientPool; c; c = c->m_next)
302 assert (*c->m_prev == c);
303 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
304 !strcmp(m_proxyTarget, c->get_hostname()))
307 // The following handles "cancel"
308 // If connection is busy (waiting for PDU) and
309 // we have an initRequest we can safely do re-open
310 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
312 yaz_log (LOG_LOG, "%s REOPEN target=%s", m_session_str,
319 c->m_last_resultCount = 0;
320 c->m_sr_transform = 0;
322 c->m_resultSetStartPoint = 0;
323 c->m_target_idletime = m_target_idletime;
324 if (c->client(m_proxyTarget))
331 c->m_seqno = parent->m_seqno;
332 if (c->m_server && c->m_server != this)
333 c->m_server->m_client = 0;
336 yaz_log (LOG_DEBUG, "get_client 1 %p %p", this, c);
343 // don't have a client session yet. Search in session w/o cookie
344 for (c = parent->m_clientPool; c; c = c->m_next)
347 assert (*c->m_prev == c);
348 if (c->m_server == 0 && c->m_cookie == 0 &&
350 !strcmp(m_proxyTarget, c->get_hostname()))
353 yaz_log (LOG_LOG, "%sREUSE %d %d %s",
355 c->m_seqno, parent->m_seqno, c->get_hostname());
357 c->m_seqno = parent->m_seqno;
358 assert(c->m_server == 0);
361 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
362 c->set_APDU_yazlog(1);
364 c->set_APDU_yazlog(0);
376 if (apdu->which != Z_APDU_initRequest)
378 yaz_log (LOG_LOG, "no first INIT!");
381 Z_InitRequest *initRequest = apdu->u.initRequest;
383 if (!initRequest->idAuthentication)
385 if (m_proxy_authentication)
387 initRequest->idAuthentication =
388 (Z_IdAuthentication *)
389 odr_malloc (odr_encode(),
390 sizeof(*initRequest->idAuthentication));
391 initRequest->idAuthentication->which =
392 Z_IdAuthentication_open;
393 initRequest->idAuthentication->u.open =
394 odr_strdup (odr_encode(), m_proxy_authentication);
398 // go through list of clients - and find the lowest/oldest one.
399 Yaz_ProxyClient *c_min = 0;
401 int no_of_clients = 0;
402 if (parent->m_clientPool)
403 yaz_log (LOG_DEBUG, "Existing sessions");
404 for (c = parent->m_clientPool; c; c = c->m_next)
406 yaz_log (LOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
407 c->m_waiting, c->get_hostname(),
408 c->m_cookie ? c->m_cookie : "");
410 if (min_seq < 0 || c->m_seqno < min_seq)
412 min_seq = c->m_seqno;
416 if (no_of_clients >= parent->m_max_clients)
419 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
421 yaz_log (LOG_LOG, "%sMAXCLIENTS Destroy %d",
422 m_session_str, c->m_seqno);
423 if (c->m_server && c->m_server != this)
429 yaz_log (LOG_LOG, "%sMAXCLIENTS Reuse %d %d %s",
431 c->m_seqno, parent->m_seqno, c->get_hostname());
435 c->m_cookie = xstrdup(cookie);
436 c->m_seqno = parent->m_seqno;
437 if (c->m_server && c->m_server != this)
439 c->m_server->m_client = 0;
443 c->m_target_idletime = m_target_idletime;
444 c->timeout(m_target_idletime);
446 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
447 c->set_APDU_yazlog(1);
449 c->set_APDU_yazlog(0);
456 yaz_log (LOG_LOG, "%sNEW %d %s",
457 m_session_str, parent->m_seqno, m_proxyTarget);
458 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
459 c->m_next = parent->m_clientPool;
461 c->m_next->m_prev = &c->m_next;
462 parent->m_clientPool = c;
463 c->m_prev = &parent->m_clientPool;
469 c->m_cookie = xstrdup(cookie);
471 c->m_seqno = parent->m_seqno;
473 c->m_last_resultCount = 0;
476 c->m_sr_transform = 0;
478 c->m_resultSetStartPoint = 0;
480 if (c->client(m_proxyTarget))
485 c->m_target_idletime = m_target_idletime;
488 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
489 c->set_APDU_yazlog(1);
491 c->set_APDU_yazlog(0);
493 yaz_log (LOG_DEBUG, "get_client 3 %p %p", this, c);
497 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
500 for (i = 0; i<num; i++)
503 Z_DefaultDiagFormat *r;
504 Z_DiagRec *p = pp[i];
505 if (p->which != Z_DiagRec_defaultFormat)
507 yaz_log(LOG_LOG, "%sError no diagnostics", m_session_str);
511 r = p->u.defaultFormat;
512 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
513 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
514 yaz_log(LOG_LOG, "%sError unknown diagnostic set", m_session_str);
517 case Z_DefaultDiagFormat_v2Addinfo:
518 yaz_log(LOG_LOG, "%sError %d %s:%s",
520 *r->condition, diagbib1_str(*r->condition),
523 case Z_DefaultDiagFormat_v3Addinfo:
524 yaz_log(LOG_LOG, "%sError %d %s:%s",
526 *r->condition, diagbib1_str(*r->condition),
533 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p)
537 yaz_marc_t mt = yaz_marc_create();
538 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
539 for (i = 0; i < p->num_records; i++)
541 Z_NamePlusRecord *npr = p->records[i];
542 if (npr->which == Z_NamePlusRecord_databaseRecord)
544 Z_External *r = npr->u.databaseRecord;
545 if (r->which == Z_External_octet)
549 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
550 r->u.octet_aligned->len,
553 yaz_iconv_t cd = yaz_iconv_open("UTF-8", "MARC-8");
554 WRBUF wrbuf = wrbuf_alloc();
557 size_t inbytesleft = rlen;
558 const char *inp = result;
559 while (cd && inbytesleft)
561 size_t outbytesleft = sizeof(outbuf);
565 r = yaz_iconv (cd, (char**) &inp,
567 &outp, &outbytesleft);
568 if (r == (size_t) (-1))
570 int e = yaz_iconv_error(cd);
571 if (e != YAZ_ICONV_E2BIG)
573 yaz_log(LOG_WARN, "conversion failure");
577 wrbuf_write(wrbuf, outbuf, outp - outbuf);
582 npr->u.databaseRecord = z_ext_record(odr_encode(),
586 wrbuf_free(wrbuf, 1);
591 yaz_marc_destroy(mt);
594 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
597 if (apdu->which == Z_APDU_searchResponse)
599 Z_SearchResponse *sr = apdu->u.searchResponse;
600 Z_Records *p = sr->records;
601 if (p && p->which == Z_Records_NSD)
603 Z_DiagRec dr, *dr_p = &dr;
604 dr.which = Z_DiagRec_defaultFormat;
605 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
607 display_diagrecs(&dr_p, 1);
611 if (m_marcxml_flag && p && p->which == Z_Records_DBOSD)
612 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
615 yaz_log(LOG_LOG, "%s%d hits", m_session_str,
617 if (*sr->resultCount < 0)
618 m_invalid_session = 1;
622 else if (apdu->which == Z_APDU_presentResponse)
624 Z_PresentResponse *sr = apdu->u.presentResponse;
625 Z_Records *p = sr->records;
626 if (p && p->which == Z_Records_NSD)
628 Z_DiagRec dr, *dr_p = &dr;
629 dr.which = Z_DiagRec_defaultFormat;
630 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
632 display_diagrecs(&dr_p, 1);
634 if (m_marcxml_flag && p && p->which == Z_Records_DBOSD)
635 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
637 int r = send_Z_PDU(apdu, &len);
638 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
639 yaz_log (LOG_DEBUG, "%sSending %s to client %d bytes", m_session_str,
640 apdu_name(apdu), len);
642 m_bw_stat.add_bytes(len);
646 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
649 int r = send_Z_PDU(apdu, &len);
650 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
651 yaz_log (LOG_LOG, "%sSending %s to %s %d bytes",
653 apdu_name(apdu), get_hostname(), len);
658 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
660 if (apdu->which == Z_APDU_presentRequest)
662 Z_PresentRequest *pr = apdu->u.presentRequest;
663 Z_NamePlusRecordList *npr;
664 int toget = *pr->numberOfRecordsRequested;
665 int start = *pr->resultSetStartPoint;
667 yaz_log(LOG_LOG, "%sPresent %s %d+%d", m_session_str,
668 pr->resultSetId, start, toget);
670 if (*m_parent->m_optimize == '0')
673 if (!m_client->m_last_resultSetId)
675 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
676 new_apdu->u.presentResponse->records =
677 create_nonSurrogateDiagnostics(odr_encode(), 30,
679 send_to_client(new_apdu);
682 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
684 if (start+toget-1 > m_client->m_last_resultCount)
686 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
687 new_apdu->u.presentResponse->records =
688 create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
689 send_to_client(new_apdu);
692 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
693 pr->preferredRecordSyntax,
694 pr->recordComposition))
696 yaz_log (LOG_LOG, "%sReturned cached records for present request",
698 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
699 new_apdu->u.presentResponse->referenceId = pr->referenceId;
701 new_apdu->u.presentResponse->numberOfRecordsReturned
702 = odr_intdup(odr_encode(), toget);
704 new_apdu->u.presentResponse->records = (Z_Records*)
705 odr_malloc(odr_encode(), sizeof(Z_Records));
706 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
707 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
708 new_apdu->u.presentResponse->nextResultSetPosition =
709 odr_intdup(odr_encode(), start+toget);
711 send_to_client(new_apdu);
717 if (apdu->which != Z_APDU_searchRequest)
719 Z_SearchRequest *sr = apdu->u.searchRequest;
720 Yaz_Z_Query *this_query = new Yaz_Z_Query;
721 Yaz_Z_Databases this_databases;
723 this_databases.set(sr->num_databaseNames, (const char **)
726 this_query->set_Z_Query(sr->query);
729 this_query->print(query_str, sizeof(query_str)-1);
730 yaz_log(LOG_LOG, "%sSearch %s", m_session_str, query_str);
732 if (*m_parent->m_optimize != '0' &&
733 m_client->m_last_ok && m_client->m_last_query &&
734 m_client->m_last_query->match(this_query) &&
735 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
736 m_client->m_last_databases.match(this_databases))
739 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
740 m_client->m_last_resultCount < *sr->largeSetLowerBound)
742 Z_NamePlusRecordList *npr;
743 int toget = *sr->mediumSetPresentNumber;
744 Z_RecordComposition *comp = 0;
746 if (toget > m_client->m_last_resultCount)
747 toget = m_client->m_last_resultCount;
749 if (sr->mediumSetElementSetNames)
751 comp = (Z_RecordComposition *)
752 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
753 comp->which = Z_RecordComp_simple;
754 comp->u.simple = sr->mediumSetElementSetNames;
757 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
758 sr->preferredRecordSyntax, comp))
760 yaz_log (LOG_LOG, "%sReturned cached records for medium set",
762 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
763 new_apdu->u.searchResponse->referenceId = sr->referenceId;
764 new_apdu->u.searchResponse->resultCount =
765 &m_client->m_last_resultCount;
767 new_apdu->u.searchResponse->numberOfRecordsReturned
768 = odr_intdup(odr_encode(), toget);
770 new_apdu->u.searchResponse->presentStatus =
771 odr_intdup(odr_encode(), Z_PresentStatus_success);
772 new_apdu->u.searchResponse->records = (Z_Records*)
773 odr_malloc(odr_encode(), sizeof(Z_Records));
774 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
775 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
776 new_apdu->u.searchResponse->nextResultSetPosition =
777 odr_intdup(odr_encode(), toget+1);
778 send_to_client(new_apdu);
784 // send present request (medium size)
785 yaz_log (LOG_LOG, "%sOptimizing search for medium set",
788 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
789 Z_PresentRequest *pr = new_apdu->u.presentRequest;
790 pr->referenceId = sr->referenceId;
791 pr->resultSetId = sr->resultSetName;
792 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
793 *pr->numberOfRecordsRequested = toget;
794 pr->recordComposition = comp;
795 m_client->m_sr_transform = 1;
799 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
800 m_client->m_last_resultCount <= 0)
802 // large set. Return pseudo-search response immediately
803 yaz_log (LOG_LOG, "%sOptimizing search for large set",
805 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
806 new_apdu->u.searchResponse->referenceId = sr->referenceId;
807 new_apdu->u.searchResponse->resultCount =
808 &m_client->m_last_resultCount;
809 send_to_client(new_apdu);
814 Z_NamePlusRecordList *npr;
815 int toget = m_client->m_last_resultCount;
816 Z_RecordComposition *comp = 0;
818 // send a present request (small set)
820 if (sr->smallSetElementSetNames)
822 comp = (Z_RecordComposition *)
823 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
824 comp->which = Z_RecordComp_simple;
825 comp->u.simple = sr->smallSetElementSetNames;
828 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
829 sr->preferredRecordSyntax, comp))
831 yaz_log (LOG_LOG, "%sReturned cached records for small set",
833 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
834 new_apdu->u.searchResponse->referenceId = sr->referenceId;
835 new_apdu->u.searchResponse->resultCount =
836 &m_client->m_last_resultCount;
838 new_apdu->u.searchResponse->numberOfRecordsReturned
839 = odr_intdup(odr_encode(), toget);
841 new_apdu->u.searchResponse->presentStatus =
842 odr_intdup(odr_encode(), Z_PresentStatus_success);
843 new_apdu->u.searchResponse->records = (Z_Records*)
844 odr_malloc(odr_encode(), sizeof(Z_Records));
845 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
846 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
847 new_apdu->u.searchResponse->nextResultSetPosition =
848 odr_intdup(odr_encode(), toget+1);
849 send_to_client(new_apdu);
854 yaz_log (LOG_LOG, "%sOptimizing search for small set",
856 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
857 Z_PresentRequest *pr = new_apdu->u.presentRequest;
858 pr->referenceId = sr->referenceId;
859 pr->resultSetId = sr->resultSetName;
860 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
861 *pr->numberOfRecordsRequested = toget;
862 pr->recordComposition = comp;
863 m_client->m_sr_transform = 1;
868 else // query doesn't match
870 delete m_client->m_last_query;
871 m_client->m_last_query = this_query;
872 m_client->m_last_ok = 0;
873 m_client->m_cache.clear();
874 m_client->m_resultSetStartPoint = 0;
876 xfree (m_client->m_last_resultSetId);
877 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
879 m_client->m_last_databases.set(sr->num_databaseNames,
880 (const char **) sr->databaseNames);
886 void Yaz_Proxy::recv_Z_PDU(Z_APDU *apdu, int len)
888 char *cp = strchr(m_session_str, ' ');
891 sprintf(cp+1, "%d ", m_request_no);
896 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
897 yaz_log (LOG_DEBUG, "%sReceiving %s from client %d bytes",
898 m_session_str, apdu_name(apdu), len);
900 if (m_bw_hold_PDU) // double incoming PDU. shutdown now.
903 m_bw_stat.add_bytes(len);
904 m_pdu_stat.add_bytes(1);
906 int bw_total = m_bw_stat.get_total();
907 int pdu_total = m_pdu_stat.get_total();
909 yaz_log(LOG_LOG, "%sstat bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
910 m_session_str, bw_total, pdu_total, m_bw_max, m_pdu_max);
913 if (bw_total > m_bw_max)
915 reduce = (bw_total/m_bw_max);
920 if (pdu_total > m_pdu_max)
922 int nreduce = (60/m_pdu_max);
923 reduce = (reduce > nreduce) ? reduce : nreduce;
928 yaz_log(LOG_LOG, "%sLimit delay=%d", m_session_str, reduce);
929 m_bw_hold_PDU = apdu; // save PDU and signal "on hold"
930 timeout(reduce); // call us reduce seconds later
933 recv_Z_PDU_0(apdu); // all fine. Proceed receive PDU as usual
936 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
938 if (m_max_record_retrieve)
940 if (apdu->which == Z_APDU_presentRequest)
942 Z_PresentRequest *pr = apdu->u.presentRequest;
943 if (pr->numberOfRecordsRequested &&
944 *pr->numberOfRecordsRequested > m_max_record_retrieve)
945 *pr->numberOfRecordsRequested = m_max_record_retrieve;
950 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
954 Z_Records *rec = (Z_Records *)
955 odr_malloc (odr, sizeof(*rec));
957 odr_malloc (odr, sizeof(*err));
958 Z_DiagRec *drec = (Z_DiagRec *)
959 odr_malloc (odr, sizeof(*drec));
960 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
961 odr_malloc (odr, sizeof(*dr));
963 rec->which = Z_Records_NSD;
964 rec->u.nonSurrogateDiagnostic = dr;
965 dr->diagnosticSetId =
966 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
968 dr->which = Z_DefaultDiagFormat_v2Addinfo;
969 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
973 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
975 if (apdu->which == Z_APDU_searchRequest)
977 Z_SearchRequest *sr = apdu->u.searchRequest;
981 Yaz_ProxyConfig *cfg = check_reconfigure();
983 err = cfg->check_query(odr_encode(), m_default_target,
984 sr->query, &addinfo);
987 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
989 new_apdu->u.searchResponse->referenceId = sr->referenceId;
990 new_apdu->u.searchResponse->records =
991 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
992 *new_apdu->u.searchResponse->searchStatus = 0;
994 send_to_client(new_apdu);
1002 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
1005 if (apdu->which == Z_APDU_searchRequest)
1007 Z_SearchRequest *sr = apdu->u.searchRequest;
1008 if (*sr->smallSetUpperBound > 0 || *sr->mediumSetPresentNumber > 0)
1012 Yaz_ProxyConfig *cfg = check_reconfigure();
1015 err = cfg->check_syntax(odr_encode(),
1017 sr->preferredRecordSyntax,
1021 sr->preferredRecordSyntax =
1022 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN,
1028 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1030 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1031 new_apdu->u.searchResponse->records =
1032 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1033 *new_apdu->u.searchResponse->searchStatus = 0;
1035 send_to_client(new_apdu);
1041 else if (apdu->which == Z_APDU_presentRequest)
1043 Z_PresentRequest *pr = apdu->u.presentRequest;
1046 Yaz_ProxyConfig *cfg = check_reconfigure();
1049 err = cfg->check_syntax(odr_encode(), m_default_target,
1050 pr->preferredRecordSyntax,
1054 pr->preferredRecordSyntax =
1055 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN,
1061 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1063 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1064 new_apdu->u.presentResponse->records =
1065 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1066 *new_apdu->u.presentResponse->presentStatus =
1067 Z_PresentStatus_failure;
1069 send_to_client(new_apdu);
1077 void Yaz_Proxy::recv_Z_PDU_0(Z_APDU *apdu)
1079 // Determine our client.
1080 m_client = get_client(apdu);
1086 m_client->m_server = this;
1088 if (apdu->which == Z_APDU_initRequest)
1090 if (apdu->u.initRequest->implementationId)
1091 yaz_log(LOG_LOG, "%simplementationId: %s",
1092 m_session_str, apdu->u.initRequest->implementationId);
1093 if (apdu->u.initRequest->implementationName)
1094 yaz_log(LOG_LOG, "%simplementationName: %s",
1095 m_session_str, apdu->u.initRequest->implementationName);
1096 if (apdu->u.initRequest->implementationVersion)
1097 yaz_log(LOG_LOG, "%simplementationVersion: %s",
1098 m_session_str, apdu->u.initRequest->implementationVersion);
1099 if (m_client->m_init_flag)
1101 Z_APDU *apdu = m_client->m_initResponse;
1102 apdu->u.initResponse->otherInfo = 0;
1103 if (m_client->m_cookie && *m_client->m_cookie)
1104 set_otherInformationString(apdu, VAL_COOKIE, 1,
1105 m_client->m_cookie);
1106 send_to_client(apdu);
1109 m_client->m_init_flag = 1;
1111 handle_max_record_retrieve(apdu);
1114 apdu = handle_syntax_validation(apdu);
1117 apdu = handle_query_validation(apdu);
1120 apdu = result_set_optimize(apdu);
1123 m_client->timeout(m_target_idletime); // mark it active even
1124 // though we didn't use it
1128 // delete other info part from PDU before sending to target
1129 Z_OtherInformation **oi;
1130 get_otherInfoAPDU(apdu, &oi);
1134 if (apdu->which == Z_APDU_presentRequest &&
1135 m_client->m_resultSetStartPoint == 0)
1137 Z_PresentRequest *pr = apdu->u.presentRequest;
1138 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
1139 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
1141 m_client->m_resultSetStartPoint = 0;
1143 if (m_client->send_to_target(apdu) < 0)
1150 m_client->m_waiting = 1;
1153 void Yaz_Proxy::connectNotify()
1157 void Yaz_Proxy::shutdown()
1159 // only keep if keep_alive flag is set...
1161 !m_invalid_session &&
1162 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
1163 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
1164 m_client->m_waiting == 0)
1166 yaz_log(LOG_LOG, "%sShutdown (client to proxy) keepalive %s",
1168 m_client->get_hostname());
1169 yaz_log(LOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1170 m_session_str, m_client->m_pdu_recv,
1171 m_client->m_bytes_sent + m_client->m_bytes_recv,
1172 m_keepalive_limit_bw, m_keepalive_limit_pdu);
1173 assert (m_client->m_waiting != 2);
1174 // Tell client (if any) that no server connection is there..
1175 m_client->m_server = 0;
1179 yaz_log (LOG_LOG, "%sShutdown (client to proxy) close %s",
1181 m_client->get_hostname());
1182 assert (m_client->m_waiting != 2);
1187 yaz_log (LOG_LOG, "%sshutdown (client to proxy) bad state",
1193 yaz_log (LOG_LOG, "%sShutdown (client to proxy)",
1197 m_parent->pre_init();
1201 const char *Yaz_ProxyClient::get_session_str()
1205 return m_server->get_session_str();
1208 void Yaz_ProxyClient::shutdown()
1210 yaz_log (LOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
1216 void Yaz_Proxy::failNotify()
1218 yaz_log (LOG_LOG, "%sConnection closed by client",
1223 void Yaz_ProxyClient::failNotify()
1225 yaz_log (LOG_LOG, "%sConnection closed by target %s",
1226 get_session_str(), get_hostname());
1230 void Yaz_ProxyClient::connectNotify()
1232 const char *s = get_session_str();
1233 const char *h = get_hostname();
1234 yaz_log (LOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
1236 timeout(m_target_idletime);
1241 IYaz_PDU_Observer *Yaz_ProxyClient::sessionNotify(IYaz_PDU_Observable
1242 *the_PDU_Observable, int fd)
1244 return new Yaz_ProxyClient(the_PDU_Observable, 0);
1247 Yaz_ProxyClient::~Yaz_ProxyClient()
1252 m_next->m_prev = m_prev;
1253 m_waiting = 2; // for debugging purposes only.
1254 odr_destroy(m_init_odr);
1255 delete m_last_query;
1256 xfree (m_last_resultSetId);
1260 void Yaz_ProxyClient::pre_init_client()
1262 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
1263 Z_InitRequest *req = apdu->u.initRequest;
1265 ODR_MASK_SET(req->options, Z_Options_search);
1266 ODR_MASK_SET(req->options, Z_Options_present);
1267 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
1268 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
1269 ODR_MASK_SET(req->options, Z_Options_scan);
1270 ODR_MASK_SET(req->options, Z_Options_sort);
1271 ODR_MASK_SET(req->options, Z_Options_extendedServices);
1272 ODR_MASK_SET(req->options, Z_Options_delSet);
1274 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
1275 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
1276 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
1278 if (send_to_target(apdu) < 0)
1289 void Yaz_Proxy::pre_init()
1292 const char *name = 0;
1293 const char *zurl_in_use[MAX_ZURL_PLEX];
1294 int limit_bw, limit_pdu, limit_req;
1295 int target_idletime, client_idletime;
1297 int keepalive_limit_bw, keepalive_limit_pdu;
1300 Yaz_ProxyConfig *cfg = check_reconfigure();
1304 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
1309 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
1310 &limit_bw, &limit_pdu, &limit_req,
1311 &target_idletime, &client_idletime,
1313 &keepalive_limit_bw,
1314 &keepalive_limit_pdu,
1320 for (j = 0; zurl_in_use[j]; j++)
1324 for (c = m_clientPool; c; c = c->m_next)
1326 if (!strcmp(zurl_in_use[j], c->get_hostname())
1327 && c->m_server == 0 && c->m_cookie == 0)
1330 yaz_log(LOG_LOG, "%s pre-init %s %s spare=%d pre_init=%d",
1332 name, zurl_in_use[j], spare, pre_init);
1333 if (spare < pre_init)
1335 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
1336 c->m_next = m_clientPool;
1338 c->m_next->m_prev = &c->m_next;
1340 c->m_prev = &m_clientPool;
1342 if (m_log_mask & PROXY_LOG_APDU_SERVER)
1343 c->set_APDU_yazlog(1);
1345 c->set_APDU_yazlog(0);
1347 if (c->client(zurl_in_use[j]))
1355 c->m_target_idletime = target_idletime;
1356 c->m_seqno = m_seqno++;
1363 void Yaz_Proxy::timeoutNotify()
1369 timeout(m_client_idletime);
1370 Z_APDU *apdu = m_bw_hold_PDU;
1376 yaz_log (LOG_LOG, "%sTimeout (client to proxy)", m_session_str);
1387 void Yaz_ProxyClient::timeoutNotify()
1389 yaz_log (LOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
1396 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable,
1397 Yaz_Proxy *parent) :
1398 Yaz_Z_Assoc (the_PDU_Observable)
1405 m_last_resultSetId = 0;
1406 m_last_resultCount = 0;
1410 m_init_odr = odr_createmem (ODR_DECODE);
1412 m_resultSetStartPoint = 0;
1413 m_bytes_sent = m_bytes_recv = 0;
1417 m_target_idletime = 600;
1421 const char *Yaz_Proxy::option(const char *name, const char *value)
1423 if (!strcmp (name, "optimize")) {
1426 m_optimize = xstrdup (value);
1433 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
1435 m_bytes_recv += len;
1438 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1439 yaz_log (LOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
1440 apdu_name(apdu), get_hostname(), len);
1441 if (apdu->which == Z_APDU_initResponse)
1443 if (!m_server) // if this is a pre init session , check for more
1445 NMEM nmem = odr_extract_mem (odr_decode());
1446 odr_reset (m_init_odr);
1447 nmem_transfer (m_init_odr->mem, nmem);
1448 m_initResponse = apdu;
1450 Z_InitResponse *ir = apdu->u.initResponse;
1451 char *im0 = ir->implementationName;
1454 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
1461 strcat(im1, "(YAZ Proxy)");
1462 ir->implementationName = im1;
1464 nmem_destroy (nmem);
1466 if (apdu->which == Z_APDU_searchResponse)
1468 Z_SearchResponse *sr = apdu->u.searchResponse;
1469 m_last_resultCount = *sr->resultCount;
1470 int status = *sr->searchStatus;
1471 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
1475 if (sr->records && sr->records->which == Z_Records_DBOSD)
1477 m_cache.add(odr_decode(),
1478 sr->records->u.databaseOrSurDiagnostics, 1,
1483 if (apdu->which == Z_APDU_presentResponse)
1485 Z_PresentResponse *pr = apdu->u.presentResponse;
1489 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1490 Z_SearchResponse *sr = new_apdu->u.searchResponse;
1491 sr->referenceId = pr->referenceId;
1492 *sr->resultCount = m_last_resultCount;
1493 sr->records = pr->records;
1494 sr->nextResultSetPosition = pr->nextResultSetPosition;
1495 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
1499 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
1501 m_cache.add(odr_decode(),
1502 pr->records->u.databaseOrSurDiagnostics,
1503 m_resultSetStartPoint, -1);
1504 m_resultSetStartPoint = 0;
1508 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
1511 m_server->send_to_client(apdu);
1513 if (apdu->which == Z_APDU_close)
1519 void Yaz_Proxy::server(const char *addr)
1521 Yaz_Z_Assoc::server(addr);