2 * Copyright (c) 1998-2003, Index Data.
3 * See the file LICENSE for details.
5 * $Id: yaz-proxy.cpp,v 1.60 2003-10-16 08:28:10 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;
71 m_client_idletime = 600;
72 m_target_idletime = 600;
73 m_optimize = xstrdup ("1");
74 strcpy(m_session_str, "x");
76 m_bytes_sent = m_bytes_recv = 0;
80 m_max_record_retrieve = 0;
84 m_invalid_session = 0;
89 Yaz_Proxy::~Yaz_Proxy()
91 yaz_log(LOG_LOG, "%sClosed %d/%d sent/recv bytes total", m_session_str,
92 m_bytes_sent, m_bytes_recv);
93 xfree (m_proxyTarget);
94 xfree (m_default_target);
95 xfree (m_proxy_authentication);
100 int Yaz_Proxy::set_config(const char *config)
103 m_config = new Yaz_ProxyConfig();
104 xfree(m_config_fname);
105 m_config_fname = xstrdup(config);
106 int r = m_config->read_xml(config);
110 void Yaz_Proxy::set_default_target(const char *target)
112 xfree (m_default_target);
113 m_default_target = 0;
115 m_default_target = (char *) xstrdup (target);
118 void Yaz_Proxy::set_proxy_authentication (const char *auth)
120 xfree (m_proxy_authentication);
121 m_proxy_authentication = 0;
123 m_proxy_authentication = (char *) xstrdup (auth);
126 Yaz_ProxyConfig *Yaz_Proxy::check_reconfigure()
129 return m_parent->check_reconfigure();
131 Yaz_ProxyConfig *cfg = m_config;
134 yaz_log(LOG_LOG, "reconfigure");
136 if (m_config_fname && cfg)
138 yaz_log(LOG_LOG, "reconfigure config %s", m_config_fname);
139 int r = cfg->read_xml(m_config_fname);
141 yaz_log(LOG_WARN, "reconfigure failed");
144 yaz_log(LOG_LOG, "reconfigure");
150 IYaz_PDU_Observer *Yaz_Proxy::sessionNotify(IYaz_PDU_Observable
151 *the_PDU_Observable, int fd)
154 Yaz_Proxy *new_proxy = new Yaz_Proxy(the_PDU_Observable, this);
155 new_proxy->m_config = 0;
156 new_proxy->m_config_fname = 0;
157 new_proxy->timeout(m_client_idletime);
158 new_proxy->m_target_idletime = m_target_idletime;
159 new_proxy->set_default_target(m_default_target);
160 new_proxy->set_APDU_log(get_APDU_log());
161 new_proxy->set_proxy_authentication(m_proxy_authentication);
162 sprintf(new_proxy->m_session_str, "%ld:%d ", (long) time(0), m_session_no);
164 yaz_log (LOG_LOG, "%sNew session %s", new_proxy->m_session_str,
165 the_PDU_Observable->getpeername());
169 char *Yaz_Proxy::get_cookie(Z_OtherInformation **otherInfo)
172 Z_OtherInformationUnit *oi;
174 ent.proto = PROTO_Z3950;
175 ent.oclass = CLASS_USERINFO;
176 ent.value = (oid_value) VAL_COOKIE;
177 assert (oid_ent_to_oid (&ent, oid));
179 if (oid_ent_to_oid (&ent, oid) &&
180 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
181 oi->which == Z_OtherInfo_characterInfo)
182 return oi->information.characterInfo;
186 char *Yaz_Proxy::get_proxy(Z_OtherInformation **otherInfo)
189 Z_OtherInformationUnit *oi;
191 ent.proto = PROTO_Z3950;
192 ent.oclass = CLASS_USERINFO;
193 ent.value = (oid_value) VAL_PROXY;
194 if (oid_ent_to_oid (&ent, oid) &&
195 (oi = update_otherInformation(otherInfo, 0, oid, 1, 1)) &&
196 oi->which == Z_OtherInfo_characterInfo)
197 return oi->information.characterInfo;
201 const char *Yaz_Proxy::load_balance(const char **url)
203 int zurl_in_use[MAX_ZURL_PLEX];
207 for (i = 0; i<MAX_ZURL_PLEX; i++)
209 for (c = m_parent->m_clientPool; c; c = c->m_next)
211 for (i = 0; url[i]; i++)
212 if (!strcmp(url[i], c->get_hostname()))
217 for (i = 0; url[i]; i++)
219 yaz_log(LOG_DEBUG, "%szurl=%s use=%d",
220 m_session_str, url[i], zurl_in_use[i]);
221 if (min > zurl_in_use[i])
224 min = zurl_in_use[i];
230 Yaz_ProxyClient *Yaz_Proxy::get_client(Z_APDU *apdu)
233 Yaz_Proxy *parent = m_parent;
234 Z_OtherInformation **oi;
235 Yaz_ProxyClient *c = m_client;
237 get_otherInfoAPDU(apdu, &oi);
238 char *cookie = get_cookie(oi);
242 const char *url[MAX_ZURL_PLEX];
243 const char *proxy_host = get_proxy(oi);
244 Yaz_ProxyConfig *cfg = check_reconfigure();
247 xfree(m_default_target);
248 m_default_target = xstrdup(proxy_host);
249 proxy_host = m_default_target;
251 int client_idletime = -1;
253 url[0] = m_default_target;
256 cfg->get_target_info(proxy_host, url, &m_bw_max,
257 &m_pdu_max, &m_max_record_retrieve,
258 &m_target_idletime, &client_idletime,
259 &parent->m_max_clients,
260 &m_keepalive_limit_bw,
261 &m_keepalive_limit_pdu,
263 if (client_idletime != -1)
265 m_client_idletime = client_idletime;
266 timeout(m_client_idletime);
270 yaz_log(LOG_LOG, "%sNo default target", m_session_str);
273 // we don't handle multiplexing for cookie session, so we just
274 // pick the first one in this case (anonymous users will be able
275 // to use any backend)
276 if (cookie && *cookie)
277 m_proxyTarget = (char*) xstrdup(url[0]);
279 m_proxyTarget = (char*) xstrdup(load_balance(url));
281 if (cookie && *cookie)
283 Yaz_ProxyClient *cc = 0;
285 for (c = parent->m_clientPool; c; c = c->m_next)
288 assert (*c->m_prev == c);
289 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
290 !strcmp(m_proxyTarget, c->get_hostname()))
299 // The following handles "cancel"
300 // If connection is busy (waiting for PDU) and
301 // we have an initRequest we can safely do re-open
302 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
304 yaz_log (LOG_LOG, "%s REOPEN target=%s", m_session_str,
311 c->m_last_resultCount = 0;
312 c->m_sr_transform = 0;
314 c->m_resultSetStartPoint = 0;
315 c->m_target_idletime = m_target_idletime;
316 if (c->client(m_proxyTarget))
323 c->m_seqno = parent->m_seqno;
324 if (c->m_server && c->m_server != this)
325 c->m_server->m_client = 0;
328 yaz_log (LOG_DEBUG, "get_client 1 %p %p", this, c);
334 Yaz_ProxyClient *cc = 0;
336 for (c = parent->m_clientPool; c; c = c->m_next)
339 assert (*c->m_prev == c);
340 if (c->m_server == 0 && c->m_cookie == 0 &&
342 !strcmp(m_proxyTarget, c->get_hostname()))
352 yaz_log (LOG_LOG, "%sREUSE %d %d %s",
354 c->m_seqno, parent->m_seqno, c->get_hostname());
356 c->m_seqno = parent->m_seqno;
357 assert(c->m_server == 0);
369 if (apdu->which != Z_APDU_initRequest)
371 yaz_log (LOG_LOG, "no first INIT!");
374 Z_InitRequest *initRequest = apdu->u.initRequest;
376 if (!initRequest->idAuthentication)
378 if (m_proxy_authentication)
380 initRequest->idAuthentication =
381 (Z_IdAuthentication *)
382 odr_malloc (odr_encode(),
383 sizeof(*initRequest->idAuthentication));
384 initRequest->idAuthentication->which =
385 Z_IdAuthentication_open;
386 initRequest->idAuthentication->u.open =
387 odr_strdup (odr_encode(), m_proxy_authentication);
391 // go through list of clients - and find the lowest/oldest one.
392 Yaz_ProxyClient *c_min = 0;
394 int no_of_clients = 0;
395 if (parent->m_clientPool)
396 yaz_log (LOG_DEBUG, "Existing sessions");
397 for (c = parent->m_clientPool; c; c = c->m_next)
399 yaz_log (LOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
400 c->m_waiting, c->get_hostname(),
401 c->m_cookie ? c->m_cookie : "");
403 if (min_seq < 0 || c->m_seqno < min_seq)
405 min_seq = c->m_seqno;
409 if (no_of_clients >= parent->m_max_clients)
412 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
414 yaz_log (LOG_LOG, "%sMAXCLIENTS Destroy %d",
415 m_session_str, c->m_seqno);
416 if (c->m_server && c->m_server != this)
422 yaz_log (LOG_LOG, "%sMAXCLIENTS Reuse %d %d %s",
424 c->m_seqno, parent->m_seqno, c->get_hostname());
428 c->m_cookie = xstrdup(cookie);
429 c->m_seqno = parent->m_seqno;
430 if (c->m_server && c->m_server != this)
432 c->m_server->m_client = 0;
436 c->m_target_idletime = m_target_idletime;
437 c->timeout(m_target_idletime);
443 yaz_log (LOG_LOG, "%sNEW %d %s",
444 m_session_str, parent->m_seqno, m_proxyTarget);
445 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
446 c->m_next = parent->m_clientPool;
448 c->m_next->m_prev = &c->m_next;
449 parent->m_clientPool = c;
450 c->m_prev = &parent->m_clientPool;
456 c->m_cookie = xstrdup(cookie);
458 c->m_seqno = parent->m_seqno;
460 c->m_last_resultCount = 0;
463 c->m_sr_transform = 0;
465 c->m_resultSetStartPoint = 0;
467 if (c->client(m_proxyTarget))
472 c->m_target_idletime = m_target_idletime;
476 yaz_log (LOG_DEBUG, "get_client 3 %p %p", this, c);
480 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
483 for (i = 0; i<num; i++)
486 Z_DefaultDiagFormat *r;
487 Z_DiagRec *p = pp[i];
488 if (p->which != Z_DiagRec_defaultFormat)
490 yaz_log(LOG_LOG, "%sError no diagnostics", m_session_str);
494 r = p->u.defaultFormat;
495 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
496 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
497 yaz_log(LOG_LOG, "%sError unknown diagnostic set", m_session_str);
500 case Z_DefaultDiagFormat_v2Addinfo:
501 yaz_log(LOG_LOG, "%sError %d %s:%s",
503 *r->condition, diagbib1_str(*r->condition),
506 case Z_DefaultDiagFormat_v3Addinfo:
507 yaz_log(LOG_LOG, "%sError %d %s:%s",
509 *r->condition, diagbib1_str(*r->condition),
516 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p)
520 yaz_marc_t mt = yaz_marc_create();
521 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
522 for (i = 0; i < p->num_records; i++)
524 Z_NamePlusRecord *npr = p->records[i];
525 if (npr->which == Z_NamePlusRecord_databaseRecord)
527 Z_External *r = npr->u.databaseRecord;
528 if (r->which == Z_External_octet)
532 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
533 r->u.octet_aligned->len,
536 yaz_iconv_t cd = yaz_iconv_open("UTF-8", "MARC-8");
537 WRBUF wrbuf = wrbuf_alloc();
540 size_t inbytesleft = rlen;
541 const char *inp = result;
542 while (cd && inbytesleft)
544 size_t outbytesleft = sizeof(outbuf);
548 r = yaz_iconv (cd, (char**) &inp,
550 &outp, &outbytesleft);
551 if (r == (size_t) (-1))
553 int e = yaz_iconv_error(cd);
554 if (e != YAZ_ICONV_E2BIG)
556 yaz_log(LOG_WARN, "conversion failure");
560 wrbuf_write(wrbuf, outbuf, outp - outbuf);
565 npr->u.databaseRecord = z_ext_record(odr_encode(),
569 wrbuf_free(wrbuf, 1);
574 yaz_marc_destroy(mt);
577 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
580 if (apdu->which == Z_APDU_searchResponse)
582 Z_SearchResponse *sr = apdu->u.searchResponse;
583 Z_Records *p = sr->records;
584 if (p && p->which == Z_Records_NSD)
586 Z_DiagRec dr, *dr_p = &dr;
587 dr.which = Z_DiagRec_defaultFormat;
588 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
590 display_diagrecs(&dr_p, 1);
594 if (m_marcxml_flag && p && p->which == Z_Records_DBOSD)
595 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
598 yaz_log(LOG_LOG, "%s%d hits", m_session_str,
600 if (*sr->resultCount < 0)
601 m_invalid_session = 1;
605 else if (apdu->which == Z_APDU_presentResponse)
607 Z_PresentResponse *sr = apdu->u.presentResponse;
608 Z_Records *p = sr->records;
609 if (p && p->which == Z_Records_NSD)
611 Z_DiagRec dr, *dr_p = &dr;
612 dr.which = Z_DiagRec_defaultFormat;
613 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
615 display_diagrecs(&dr_p, 1);
617 if (m_marcxml_flag && p && p->which == Z_Records_DBOSD)
618 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
620 int r = send_Z_PDU(apdu, &len);
621 yaz_log (LOG_DEBUG, "%sSending %s to client %d bytes", m_session_str,
622 apdu_name(apdu), len);
624 m_bw_stat.add_bytes(len);
628 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
631 int r = send_Z_PDU(apdu, &len);
632 yaz_log (LOG_LOG, "%sSending %s to %s %d bytes",
634 apdu_name(apdu), get_hostname(), len);
639 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
641 if (apdu->which == Z_APDU_presentRequest)
643 Z_PresentRequest *pr = apdu->u.presentRequest;
644 Z_NamePlusRecordList *npr;
645 int toget = *pr->numberOfRecordsRequested;
646 int start = *pr->resultSetStartPoint;
648 yaz_log(LOG_LOG, "%sPresent %s %d+%d", m_session_str,
649 pr->resultSetId, start, toget);
651 if (*m_parent->m_optimize == '0')
654 if (!m_client->m_last_resultSetId)
656 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
657 new_apdu->u.presentResponse->records =
658 create_nonSurrogateDiagnostics(odr_encode(), 30,
660 send_to_client(new_apdu);
663 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
665 if (start+toget-1 > m_client->m_last_resultCount)
667 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
668 new_apdu->u.presentResponse->records =
669 create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
670 send_to_client(new_apdu);
673 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
674 pr->preferredRecordSyntax,
675 pr->recordComposition))
677 yaz_log (LOG_LOG, "%sReturned cached records for present request",
679 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
680 new_apdu->u.presentResponse->referenceId = pr->referenceId;
682 new_apdu->u.presentResponse->numberOfRecordsReturned
683 = odr_intdup(odr_encode(), toget);
685 new_apdu->u.presentResponse->records = (Z_Records*)
686 odr_malloc(odr_encode(), sizeof(Z_Records));
687 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
688 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
689 new_apdu->u.presentResponse->nextResultSetPosition =
690 odr_intdup(odr_encode(), start+toget);
692 send_to_client(new_apdu);
698 if (apdu->which != Z_APDU_searchRequest)
700 Z_SearchRequest *sr = apdu->u.searchRequest;
701 Yaz_Z_Query *this_query = new Yaz_Z_Query;
702 Yaz_Z_Databases this_databases;
704 this_databases.set(sr->num_databaseNames, (const char **)
707 this_query->set_Z_Query(sr->query);
710 this_query->print(query_str, sizeof(query_str)-1);
711 yaz_log(LOG_LOG, "%sSearch %s", m_session_str, query_str);
713 if (*m_parent->m_optimize != '0' &&
714 m_client->m_last_ok && m_client->m_last_query &&
715 m_client->m_last_query->match(this_query) &&
716 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
717 m_client->m_last_databases.match(this_databases))
720 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
721 m_client->m_last_resultCount < *sr->largeSetLowerBound)
723 Z_NamePlusRecordList *npr;
724 int toget = *sr->mediumSetPresentNumber;
725 Z_RecordComposition *comp = 0;
727 if (toget > m_client->m_last_resultCount)
728 toget = m_client->m_last_resultCount;
730 if (sr->mediumSetElementSetNames)
732 comp = (Z_RecordComposition *)
733 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
734 comp->which = Z_RecordComp_simple;
735 comp->u.simple = sr->mediumSetElementSetNames;
738 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
739 sr->preferredRecordSyntax, comp))
741 yaz_log (LOG_LOG, "%sReturned cached records for medium set",
743 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
744 new_apdu->u.searchResponse->referenceId = sr->referenceId;
745 new_apdu->u.searchResponse->resultCount =
746 &m_client->m_last_resultCount;
748 new_apdu->u.searchResponse->numberOfRecordsReturned
749 = odr_intdup(odr_encode(), toget);
751 new_apdu->u.searchResponse->presentStatus =
752 odr_intdup(odr_encode(), Z_PresentStatus_success);
753 new_apdu->u.searchResponse->records = (Z_Records*)
754 odr_malloc(odr_encode(), sizeof(Z_Records));
755 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
756 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
757 new_apdu->u.searchResponse->nextResultSetPosition =
758 odr_intdup(odr_encode(), toget+1);
759 send_to_client(new_apdu);
765 // send present request (medium size)
766 yaz_log (LOG_LOG, "%sOptimizing search for medium set",
769 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
770 Z_PresentRequest *pr = new_apdu->u.presentRequest;
771 pr->referenceId = sr->referenceId;
772 pr->resultSetId = sr->resultSetName;
773 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
774 *pr->numberOfRecordsRequested = toget;
775 pr->recordComposition = comp;
776 m_client->m_sr_transform = 1;
780 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
781 m_client->m_last_resultCount <= 0)
783 // large set. Return pseudo-search response immediately
784 yaz_log (LOG_LOG, "%sOptimizing search for large set",
786 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
787 new_apdu->u.searchResponse->referenceId = sr->referenceId;
788 new_apdu->u.searchResponse->resultCount =
789 &m_client->m_last_resultCount;
790 send_to_client(new_apdu);
795 Z_NamePlusRecordList *npr;
796 int toget = m_client->m_last_resultCount;
797 Z_RecordComposition *comp = 0;
799 // send a present request (small set)
801 if (sr->smallSetElementSetNames)
803 comp = (Z_RecordComposition *)
804 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
805 comp->which = Z_RecordComp_simple;
806 comp->u.simple = sr->smallSetElementSetNames;
809 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
810 sr->preferredRecordSyntax, comp))
812 yaz_log (LOG_LOG, "%sReturned cached records for small set",
814 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
815 new_apdu->u.searchResponse->referenceId = sr->referenceId;
816 new_apdu->u.searchResponse->resultCount =
817 &m_client->m_last_resultCount;
819 new_apdu->u.searchResponse->numberOfRecordsReturned
820 = odr_intdup(odr_encode(), toget);
822 new_apdu->u.searchResponse->presentStatus =
823 odr_intdup(odr_encode(), Z_PresentStatus_success);
824 new_apdu->u.searchResponse->records = (Z_Records*)
825 odr_malloc(odr_encode(), sizeof(Z_Records));
826 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
827 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
828 new_apdu->u.searchResponse->nextResultSetPosition =
829 odr_intdup(odr_encode(), toget+1);
830 send_to_client(new_apdu);
835 yaz_log (LOG_LOG, "%sOptimizing search for small set",
837 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
838 Z_PresentRequest *pr = new_apdu->u.presentRequest;
839 pr->referenceId = sr->referenceId;
840 pr->resultSetId = sr->resultSetName;
841 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
842 *pr->numberOfRecordsRequested = toget;
843 pr->recordComposition = comp;
844 m_client->m_sr_transform = 1;
849 else // query doesn't match
851 delete m_client->m_last_query;
852 m_client->m_last_query = this_query;
853 m_client->m_last_ok = 0;
854 m_client->m_cache.clear();
855 m_client->m_resultSetStartPoint = 0;
857 xfree (m_client->m_last_resultSetId);
858 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
860 m_client->m_last_databases.set(sr->num_databaseNames,
861 (const char **) sr->databaseNames);
867 void Yaz_Proxy::recv_Z_PDU(Z_APDU *apdu, int len)
869 char *cp = strchr(m_session_str, ' ');
872 sprintf(cp+1, "%d ", m_request_no);
877 yaz_log (LOG_DEBUG, "%sReceiving %s from client %d bytes", m_session_str,
878 apdu_name(apdu), len);
880 if (m_bw_hold_PDU) // double incoming PDU. shutdown now.
883 m_bw_stat.add_bytes(len);
884 m_pdu_stat.add_bytes(1);
886 int bw_total = m_bw_stat.get_total();
887 int pdu_total = m_pdu_stat.get_total();
889 yaz_log(LOG_LOG, "%sstat bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
890 m_session_str, bw_total, pdu_total, m_bw_max, m_pdu_max);
893 if (bw_total > m_bw_max)
895 reduce = (bw_total/m_bw_max);
900 if (pdu_total > m_pdu_max)
902 int nreduce = (60/m_pdu_max);
903 reduce = (reduce > nreduce) ? reduce : nreduce;
908 yaz_log(LOG_LOG, "%sLimit delay=%d", m_session_str, reduce);
909 m_bw_hold_PDU = apdu; // save PDU and signal "on hold"
910 timeout(reduce); // call us reduce seconds later
913 recv_Z_PDU_0(apdu); // all fine. Proceed receive PDU as usual
916 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
918 if (m_max_record_retrieve)
920 if (apdu->which == Z_APDU_presentRequest)
922 Z_PresentRequest *pr = apdu->u.presentRequest;
923 if (pr->numberOfRecordsRequested &&
924 *pr->numberOfRecordsRequested > m_max_record_retrieve)
925 *pr->numberOfRecordsRequested = m_max_record_retrieve;
930 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
934 Z_Records *rec = (Z_Records *)
935 odr_malloc (odr, sizeof(*rec));
937 odr_malloc (odr, sizeof(*err));
938 Z_DiagRec *drec = (Z_DiagRec *)
939 odr_malloc (odr, sizeof(*drec));
940 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
941 odr_malloc (odr, sizeof(*dr));
943 rec->which = Z_Records_NSD;
944 rec->u.nonSurrogateDiagnostic = dr;
945 dr->diagnosticSetId =
946 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
948 dr->which = Z_DefaultDiagFormat_v2Addinfo;
949 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
953 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
955 if (apdu->which == Z_APDU_searchRequest)
957 Z_SearchRequest *sr = apdu->u.searchRequest;
961 Yaz_ProxyConfig *cfg = check_reconfigure();
963 err = cfg->check_query(odr_encode(), m_default_target,
964 sr->query, &addinfo);
967 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
969 new_apdu->u.searchResponse->referenceId = sr->referenceId;
970 new_apdu->u.searchResponse->records =
971 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
972 *new_apdu->u.searchResponse->searchStatus = 0;
974 send_to_client(new_apdu);
982 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
985 if (apdu->which == Z_APDU_searchRequest)
987 Z_SearchRequest *sr = apdu->u.searchRequest;
988 if (*sr->smallSetUpperBound > 0 || *sr->mediumSetPresentNumber > 0)
992 Yaz_ProxyConfig *cfg = check_reconfigure();
995 err = cfg->check_syntax(odr_encode(),
997 sr->preferredRecordSyntax,
1001 sr->preferredRecordSyntax =
1002 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN,
1008 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1010 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1011 new_apdu->u.searchResponse->records =
1012 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1013 *new_apdu->u.searchResponse->searchStatus = 0;
1015 send_to_client(new_apdu);
1021 else if (apdu->which == Z_APDU_presentRequest)
1023 Z_PresentRequest *pr = apdu->u.presentRequest;
1026 Yaz_ProxyConfig *cfg = check_reconfigure();
1029 err = cfg->check_syntax(odr_encode(), m_default_target,
1030 pr->preferredRecordSyntax,
1034 pr->preferredRecordSyntax =
1035 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN,
1041 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1043 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1044 new_apdu->u.presentResponse->records =
1045 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1046 *new_apdu->u.presentResponse->presentStatus =
1047 Z_PresentStatus_failure;
1049 send_to_client(new_apdu);
1057 void Yaz_Proxy::recv_Z_PDU_0(Z_APDU *apdu)
1059 // Determine our client.
1060 m_client = get_client(apdu);
1066 m_client->m_server = this;
1068 if (apdu->which == Z_APDU_initRequest)
1070 if (apdu->u.initRequest->implementationId)
1071 yaz_log(LOG_LOG, "%simplementationId: %s",
1072 m_session_str, apdu->u.initRequest->implementationId);
1073 if (apdu->u.initRequest->implementationName)
1074 yaz_log(LOG_LOG, "%simplementationName: %s",
1075 m_session_str, apdu->u.initRequest->implementationName);
1076 if (apdu->u.initRequest->implementationVersion)
1077 yaz_log(LOG_LOG, "%simplementationVersion: %s",
1078 m_session_str, apdu->u.initRequest->implementationVersion);
1079 if (m_client->m_init_flag)
1081 Z_APDU *apdu = m_client->m_initResponse;
1082 apdu->u.initResponse->otherInfo = 0;
1083 if (m_client->m_cookie && *m_client->m_cookie)
1084 set_otherInformationString(apdu, VAL_COOKIE, 1,
1085 m_client->m_cookie);
1086 send_to_client(apdu);
1089 m_client->m_init_flag = 1;
1091 handle_max_record_retrieve(apdu);
1094 apdu = handle_syntax_validation(apdu);
1097 apdu = handle_query_validation(apdu);
1100 apdu = result_set_optimize(apdu);
1103 m_client->timeout(m_target_idletime); // mark it active even
1104 // though we didn't use it
1108 // delete other info part from PDU before sending to target
1109 Z_OtherInformation **oi;
1110 get_otherInfoAPDU(apdu, &oi);
1114 if (apdu->which == Z_APDU_presentRequest &&
1115 m_client->m_resultSetStartPoint == 0)
1117 Z_PresentRequest *pr = apdu->u.presentRequest;
1118 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
1119 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
1121 m_client->m_resultSetStartPoint = 0;
1123 if (m_client->send_to_target(apdu) < 0)
1130 m_client->m_waiting = 1;
1133 void Yaz_Proxy::connectNotify()
1137 void Yaz_Proxy::shutdown()
1139 // only keep if keep_alive flag is set...
1141 !m_invalid_session &&
1142 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
1143 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
1144 m_client->m_waiting == 0)
1146 yaz_log(LOG_LOG, "%sShutdown (client to proxy) keepalive %s",
1148 m_client->get_hostname());
1149 yaz_log(LOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1150 m_session_str, m_client->m_pdu_recv,
1151 m_client->m_bytes_sent + m_client->m_bytes_recv,
1152 m_keepalive_limit_bw, m_keepalive_limit_pdu);
1153 assert (m_client->m_waiting != 2);
1154 // Tell client (if any) that no server connection is there..
1155 m_client->m_server = 0;
1159 yaz_log (LOG_LOG, "%sShutdown (client to proxy) close %s",
1161 m_client->get_hostname());
1162 assert (m_client->m_waiting != 2);
1167 yaz_log (LOG_LOG, "%sshutdown (client to proxy) bad state",
1173 yaz_log (LOG_LOG, "%sShutdown (client to proxy)",
1177 m_parent->pre_init();
1181 const char *Yaz_ProxyClient::get_session_str()
1185 return m_server->get_session_str();
1188 void Yaz_ProxyClient::shutdown()
1190 yaz_log (LOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
1196 void Yaz_Proxy::failNotify()
1198 yaz_log (LOG_LOG, "%sConnection closed by client",
1203 void Yaz_ProxyClient::failNotify()
1205 yaz_log (LOG_LOG, "%sConnection closed by target %s",
1206 get_session_str(), get_hostname());
1210 void Yaz_ProxyClient::connectNotify()
1212 const char *s = get_session_str();
1213 const char *h = get_hostname();
1214 yaz_log (LOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
1216 timeout(m_target_idletime);
1221 IYaz_PDU_Observer *Yaz_ProxyClient::sessionNotify(IYaz_PDU_Observable
1222 *the_PDU_Observable, int fd)
1224 return new Yaz_ProxyClient(the_PDU_Observable, 0);
1227 Yaz_ProxyClient::~Yaz_ProxyClient()
1232 m_next->m_prev = m_prev;
1233 m_waiting = 2; // for debugging purposes only.
1234 odr_destroy(m_init_odr);
1235 delete m_last_query;
1236 xfree (m_last_resultSetId);
1240 void Yaz_ProxyClient::pre_init_client()
1242 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
1243 Z_InitRequest *req = apdu->u.initRequest;
1245 ODR_MASK_SET(req->options, Z_Options_search);
1246 ODR_MASK_SET(req->options, Z_Options_present);
1247 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
1248 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
1249 ODR_MASK_SET(req->options, Z_Options_scan);
1250 ODR_MASK_SET(req->options, Z_Options_sort);
1251 ODR_MASK_SET(req->options, Z_Options_extendedServices);
1252 ODR_MASK_SET(req->options, Z_Options_delSet);
1254 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
1255 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
1256 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
1258 if (send_to_target(apdu) < 0)
1269 void Yaz_Proxy::pre_init()
1272 const char *name = 0;
1273 const char *zurl_in_use[MAX_ZURL_PLEX];
1274 int limit_bw, limit_pdu, limit_req;
1275 int target_idletime, client_idletime;
1277 int keepalive_limit_bw, keepalive_limit_pdu;
1280 Yaz_ProxyConfig *cfg = check_reconfigure();
1282 yaz_log(LOG_LOG, "pre_init");
1284 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
1285 &limit_bw, &limit_pdu, &limit_req,
1286 &target_idletime, &client_idletime,
1288 &keepalive_limit_bw,
1289 &keepalive_limit_pdu,
1295 for (j = 0; zurl_in_use[j]; j++)
1299 for (c = m_clientPool; c; c = c->m_next)
1301 if (!strcmp(zurl_in_use[j], c->get_hostname())
1302 && c->m_server == 0 && c->m_cookie == 0)
1305 yaz_log(LOG_LOG, "pre_init %s %s spare=%d pre_init=%d",
1306 name, zurl_in_use[j], spare, pre_init);
1307 if (spare < pre_init)
1309 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
1310 c->m_next = m_clientPool;
1312 c->m_next->m_prev = &c->m_next;
1314 c->m_prev = &m_clientPool;
1316 if (c->client(zurl_in_use[j]))
1324 c->m_target_idletime = target_idletime;
1325 yaz_log(LOG_LOG, "pre_init name=%s zurl=%s timeout=%d", name,
1326 zurl_in_use[j], target_idletime);
1327 c->m_seqno = m_seqno++;
1334 void Yaz_Proxy::timeoutNotify()
1340 timeout(m_client_idletime);
1341 Z_APDU *apdu = m_bw_hold_PDU;
1347 yaz_log (LOG_LOG, "%sTimeout (client to proxy)", m_session_str);
1358 void Yaz_ProxyClient::timeoutNotify()
1360 yaz_log (LOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
1367 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable,
1368 Yaz_Proxy *parent) :
1369 Yaz_Z_Assoc (the_PDU_Observable)
1376 m_last_resultSetId = 0;
1377 m_last_resultCount = 0;
1381 m_init_odr = odr_createmem (ODR_DECODE);
1383 m_resultSetStartPoint = 0;
1384 m_bytes_sent = m_bytes_recv = 0;
1388 m_target_idletime = 600;
1392 const char *Yaz_Proxy::option(const char *name, const char *value)
1394 if (!strcmp (name, "optimize")) {
1397 m_optimize = xstrdup (value);
1404 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
1406 m_bytes_recv += len;
1409 yaz_log (LOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
1410 apdu_name(apdu), get_hostname(), len);
1411 if (apdu->which == Z_APDU_initResponse)
1413 if (!m_server) // if this is a pre init session , check for more
1415 NMEM nmem = odr_extract_mem (odr_decode());
1416 odr_reset (m_init_odr);
1417 nmem_transfer (m_init_odr->mem, nmem);
1418 m_initResponse = apdu;
1420 Z_InitResponse *ir = apdu->u.initResponse;
1421 char *im0 = ir->implementationName;
1424 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
1431 strcat(im1, "(YAZ Proxy)");
1432 ir->implementationName = im1;
1434 nmem_destroy (nmem);
1436 if (apdu->which == Z_APDU_searchResponse)
1438 Z_SearchResponse *sr = apdu->u.searchResponse;
1439 m_last_resultCount = *sr->resultCount;
1440 int status = *sr->searchStatus;
1441 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
1445 if (sr->records && sr->records->which == Z_Records_DBOSD)
1447 m_cache.add(odr_decode(),
1448 sr->records->u.databaseOrSurDiagnostics, 1,
1453 if (apdu->which == Z_APDU_presentResponse)
1455 Z_PresentResponse *pr = apdu->u.presentResponse;
1459 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1460 Z_SearchResponse *sr = new_apdu->u.searchResponse;
1461 sr->referenceId = pr->referenceId;
1462 *sr->resultCount = m_last_resultCount;
1463 sr->records = pr->records;
1464 sr->nextResultSetPosition = pr->nextResultSetPosition;
1465 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
1469 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
1471 m_cache.add(odr_decode(),
1472 pr->records->u.databaseOrSurDiagnostics,
1473 m_resultSetStartPoint, -1);
1474 m_resultSetStartPoint = 0;
1478 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
1481 m_server->send_to_client(apdu);
1483 if (apdu->which == Z_APDU_close)
1489 void Yaz_Proxy::server(const char *addr)
1491 Yaz_Z_Assoc::server(addr);