2 * Copyright (c) 1998-2003, Index Data.
3 * See the file LICENSE for details.
5 * $Id: yaz-proxy.cpp,v 1.70 2003-11-08 18:51: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;
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();
262 /* only to be enabled for debugging... */
263 if (!strcmp(proxy_host, "stop"))
266 xfree(m_default_target);
267 m_default_target = xstrdup(proxy_host);
268 proxy_host = m_default_target;
270 int client_idletime = -1;
271 url[0] = m_default_target;
276 cfg->get_target_info(proxy_host, url, &m_bw_max,
277 &m_pdu_max, &m_max_record_retrieve,
278 &m_target_idletime, &client_idletime,
279 &parent->m_max_clients,
280 &m_keepalive_limit_bw,
281 &m_keepalive_limit_pdu,
284 if (client_idletime != -1)
286 m_client_idletime = client_idletime;
287 timeout(m_client_idletime);
291 yaz_log(LOG_LOG, "%sNo default target", m_session_str);
294 // we don't handle multiplexing for cookie session, so we just
295 // pick the first one in this case (anonymous users will be able
296 // to use any backend)
297 if (cookie && *cookie)
298 m_proxyTarget = (char*) xstrdup(url[0]);
300 m_proxyTarget = (char*) xstrdup(load_balance(url));
302 if (cookie && *cookie)
303 { // search in sessions with a cookie
304 for (c = parent->m_clientPool; c; c = c->m_next)
307 assert (*c->m_prev == c);
308 if (c->m_cookie && !strcmp(cookie,c->m_cookie) &&
309 !strcmp(m_proxyTarget, c->get_hostname()))
312 // The following handles "cancel"
313 // If connection is busy (waiting for PDU) and
314 // we have an initRequest we can safely do re-open
315 if (c->m_waiting && apdu->which == Z_APDU_initRequest)
317 yaz_log (LOG_LOG, "%s REOPEN target=%s", m_session_str,
324 c->m_last_resultCount = 0;
325 c->m_sr_transform = 0;
327 c->m_resultSetStartPoint = 0;
328 c->m_target_idletime = m_target_idletime;
329 if (c->client(m_proxyTarget))
336 c->m_seqno = parent->m_seqno;
337 if (c->m_server && c->m_server != this)
338 c->m_server->m_client = 0;
341 yaz_log (LOG_DEBUG, "get_client 1 %p %p", this, c);
348 // don't have a client session yet. Search in session w/o cookie
349 for (c = parent->m_clientPool; c; c = c->m_next)
352 assert (*c->m_prev == c);
353 if (c->m_server == 0 && c->m_cookie == 0 &&
355 !strcmp(m_proxyTarget, c->get_hostname()))
358 yaz_log (LOG_LOG, "%sREUSE %s",
359 m_session_str, c->get_hostname());
361 c->m_seqno = parent->m_seqno;
362 assert(c->m_server == 0);
365 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
366 c->set_APDU_yazlog(1);
368 c->set_APDU_yazlog(0);
380 if (apdu->which != Z_APDU_initRequest)
382 yaz_log (LOG_LOG, "no first INIT!");
385 Z_InitRequest *initRequest = apdu->u.initRequest;
387 if (!initRequest->idAuthentication)
389 if (m_proxy_authentication)
391 initRequest->idAuthentication =
392 (Z_IdAuthentication *)
393 odr_malloc (odr_encode(),
394 sizeof(*initRequest->idAuthentication));
395 initRequest->idAuthentication->which =
396 Z_IdAuthentication_open;
397 initRequest->idAuthentication->u.open =
398 odr_strdup (odr_encode(), m_proxy_authentication);
402 // go through list of clients - and find the lowest/oldest one.
403 Yaz_ProxyClient *c_min = 0;
405 int no_of_clients = 0;
406 if (parent->m_clientPool)
407 yaz_log (LOG_DEBUG, "Existing sessions");
408 for (c = parent->m_clientPool; c; c = c->m_next)
410 yaz_log (LOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
411 c->m_waiting, c->get_hostname(),
412 c->m_cookie ? c->m_cookie : "");
414 if (min_seq < 0 || c->m_seqno < min_seq)
416 min_seq = c->m_seqno;
420 if (no_of_clients >= parent->m_max_clients)
423 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
425 yaz_log (LOG_LOG, "%sMAXCLIENTS Destroy %d",
426 m_session_str, c->m_seqno);
427 if (c->m_server && c->m_server != this)
433 yaz_log (LOG_LOG, "%sMAXCLIENTS Reuse %d %d %s",
435 c->m_seqno, parent->m_seqno, c->get_hostname());
439 c->m_cookie = xstrdup(cookie);
440 c->m_seqno = parent->m_seqno;
441 if (c->m_server && c->m_server != this)
443 c->m_server->m_client = 0;
447 c->m_target_idletime = m_target_idletime;
448 c->timeout(m_target_idletime);
450 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
451 c->set_APDU_yazlog(1);
453 c->set_APDU_yazlog(0);
460 yaz_log (LOG_LOG, "%sNEW %d %s",
461 m_session_str, parent->m_seqno, m_proxyTarget);
462 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
463 c->m_next = parent->m_clientPool;
465 c->m_next->m_prev = &c->m_next;
466 parent->m_clientPool = c;
467 c->m_prev = &parent->m_clientPool;
473 c->m_cookie = xstrdup(cookie);
475 c->m_seqno = parent->m_seqno;
477 c->m_last_resultCount = 0;
480 c->m_sr_transform = 0;
482 c->m_resultSetStartPoint = 0;
484 if (c->client(m_proxyTarget))
489 c->m_target_idletime = m_target_idletime;
492 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
493 c->set_APDU_yazlog(1);
495 c->set_APDU_yazlog(0);
497 yaz_log (LOG_DEBUG, "get_client 3 %p %p", this, c);
501 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
504 for (i = 0; i<num; i++)
507 Z_DefaultDiagFormat *r;
508 Z_DiagRec *p = pp[i];
509 if (p->which != Z_DiagRec_defaultFormat)
511 yaz_log(LOG_LOG, "%sError no diagnostics", m_session_str);
515 r = p->u.defaultFormat;
516 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
517 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
518 yaz_log(LOG_LOG, "%sError unknown diagnostic set", m_session_str);
521 case Z_DefaultDiagFormat_v2Addinfo:
522 yaz_log(LOG_LOG, "%sError %d %s:%s",
524 *r->condition, diagbib1_str(*r->condition),
527 case Z_DefaultDiagFormat_v3Addinfo:
528 yaz_log(LOG_LOG, "%sError %d %s:%s",
530 *r->condition, diagbib1_str(*r->condition),
537 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p)
541 yaz_marc_t mt = yaz_marc_create();
542 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
543 for (i = 0; i < p->num_records; i++)
545 Z_NamePlusRecord *npr = p->records[i];
546 if (npr->which == Z_NamePlusRecord_databaseRecord)
548 Z_External *r = npr->u.databaseRecord;
549 if (r->which == Z_External_octet)
553 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
554 r->u.octet_aligned->len,
557 yaz_iconv_t cd = yaz_iconv_open("UTF-8", "MARC-8");
558 WRBUF wrbuf = wrbuf_alloc();
561 size_t inbytesleft = rlen;
562 const char *inp = result;
563 while (cd && inbytesleft)
565 size_t outbytesleft = sizeof(outbuf);
569 r = yaz_iconv (cd, (char**) &inp,
571 &outp, &outbytesleft);
572 if (r == (size_t) (-1))
574 int e = yaz_iconv_error(cd);
575 if (e != YAZ_ICONV_E2BIG)
577 yaz_log(LOG_WARN, "conversion failure");
581 wrbuf_write(wrbuf, outbuf, outp - outbuf);
586 npr->u.databaseRecord = z_ext_record(odr_encode(),
590 wrbuf_free(wrbuf, 1);
595 yaz_marc_destroy(mt);
598 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
601 if (apdu->which == Z_APDU_searchResponse)
603 Z_SearchResponse *sr = apdu->u.searchResponse;
604 Z_Records *p = sr->records;
605 if (p && p->which == Z_Records_NSD)
607 Z_DiagRec dr, *dr_p = &dr;
608 dr.which = Z_DiagRec_defaultFormat;
609 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
611 display_diagrecs(&dr_p, 1);
615 if (m_marcxml_flag && p && p->which == Z_Records_DBOSD)
616 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
619 yaz_log(LOG_LOG, "%s%d hits", m_session_str,
621 if (*sr->resultCount < 0)
622 m_invalid_session = 1;
626 else if (apdu->which == Z_APDU_presentResponse)
628 Z_PresentResponse *sr = apdu->u.presentResponse;
629 Z_Records *p = sr->records;
630 if (p && p->which == Z_Records_NSD)
632 Z_DiagRec dr, *dr_p = &dr;
633 dr.which = Z_DiagRec_defaultFormat;
634 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
636 display_diagrecs(&dr_p, 1);
638 if (m_marcxml_flag && p && p->which == Z_Records_DBOSD)
639 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
641 int r = send_Z_PDU(apdu, &len);
642 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
643 yaz_log (LOG_DEBUG, "%sSending %s to client %d bytes", m_session_str,
644 apdu_name(apdu), len);
646 m_bw_stat.add_bytes(len);
650 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
653 int r = send_Z_PDU(apdu, &len);
654 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
655 yaz_log (LOG_LOG, "%sSending %s to %s %d bytes",
657 apdu_name(apdu), get_hostname(), len);
662 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
664 if (apdu->which == Z_APDU_presentRequest)
666 Z_PresentRequest *pr = apdu->u.presentRequest;
667 int toget = *pr->numberOfRecordsRequested;
668 int start = *pr->resultSetStartPoint;
670 yaz_log(LOG_LOG, "%sPresent %s %d+%d", m_session_str,
671 pr->resultSetId, start, toget);
673 if (*m_parent->m_optimize == '0')
676 if (!m_client->m_last_resultSetId)
678 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
679 new_apdu->u.presentResponse->records =
680 create_nonSurrogateDiagnostics(odr_encode(), 30,
682 send_to_client(new_apdu);
686 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
688 if (start+toget-1 > m_client->m_last_resultCount)
690 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
691 new_apdu->u.presentResponse->records =
692 create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
693 send_to_client(new_apdu);
696 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
697 pr->preferredRecordSyntax,
698 pr->recordComposition))
700 yaz_log (LOG_LOG, "%sReturned cached records for present request",
702 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
703 new_apdu->u.presentResponse->referenceId = pr->referenceId;
705 new_apdu->u.presentResponse->numberOfRecordsReturned
706 = odr_intdup(odr_encode(), toget);
708 new_apdu->u.presentResponse->records = (Z_Records*)
709 odr_malloc(odr_encode(), sizeof(Z_Records));
710 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
711 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
712 new_apdu->u.presentResponse->nextResultSetPosition =
713 odr_intdup(odr_encode(), start+toget);
715 send_to_client(new_apdu);
722 if (apdu->which != Z_APDU_searchRequest)
724 Z_SearchRequest *sr = apdu->u.searchRequest;
725 Yaz_Z_Query *this_query = new Yaz_Z_Query;
726 Yaz_Z_Databases this_databases;
728 this_databases.set(sr->num_databaseNames, (const char **)
731 this_query->set_Z_Query(sr->query);
734 this_query->print(query_str, sizeof(query_str)-1);
735 yaz_log(LOG_LOG, "%sSearch %s", m_session_str, query_str);
737 if (*m_parent->m_optimize != '0' &&
738 m_client->m_last_ok && m_client->m_last_query &&
739 m_client->m_last_query->match(this_query) &&
740 !strcmp(m_client->m_last_resultSetId, sr->resultSetName) &&
741 m_client->m_last_databases.match(this_databases))
744 if (m_client->m_last_resultCount > *sr->smallSetUpperBound &&
745 m_client->m_last_resultCount < *sr->largeSetLowerBound)
747 Z_NamePlusRecordList *npr;
748 int toget = *sr->mediumSetPresentNumber;
749 Z_RecordComposition *comp = 0;
751 if (toget > m_client->m_last_resultCount)
752 toget = m_client->m_last_resultCount;
754 if (sr->mediumSetElementSetNames)
756 comp = (Z_RecordComposition *)
757 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
758 comp->which = Z_RecordComp_simple;
759 comp->u.simple = sr->mediumSetElementSetNames;
762 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
763 sr->preferredRecordSyntax, comp))
765 yaz_log (LOG_LOG, "%sReturned cached records for medium set",
767 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
768 new_apdu->u.searchResponse->referenceId = sr->referenceId;
769 new_apdu->u.searchResponse->resultCount =
770 &m_client->m_last_resultCount;
772 new_apdu->u.searchResponse->numberOfRecordsReturned
773 = odr_intdup(odr_encode(), toget);
775 new_apdu->u.searchResponse->presentStatus =
776 odr_intdup(odr_encode(), Z_PresentStatus_success);
777 new_apdu->u.searchResponse->records = (Z_Records*)
778 odr_malloc(odr_encode(), sizeof(Z_Records));
779 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
780 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
781 new_apdu->u.searchResponse->nextResultSetPosition =
782 odr_intdup(odr_encode(), toget+1);
783 send_to_client(new_apdu);
789 // send present request (medium size)
790 yaz_log (LOG_LOG, "%sOptimizing search for medium set",
793 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
794 Z_PresentRequest *pr = new_apdu->u.presentRequest;
795 pr->referenceId = sr->referenceId;
796 pr->resultSetId = sr->resultSetName;
797 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
798 *pr->numberOfRecordsRequested = toget;
799 pr->recordComposition = comp;
800 m_client->m_sr_transform = 1;
804 else if (m_client->m_last_resultCount >= *sr->largeSetLowerBound ||
805 m_client->m_last_resultCount <= 0)
807 // large set. Return pseudo-search response immediately
808 yaz_log (LOG_LOG, "%sOptimizing search for large set",
810 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
811 new_apdu->u.searchResponse->referenceId = sr->referenceId;
812 new_apdu->u.searchResponse->resultCount =
813 &m_client->m_last_resultCount;
814 send_to_client(new_apdu);
819 Z_NamePlusRecordList *npr;
820 int toget = m_client->m_last_resultCount;
821 Z_RecordComposition *comp = 0;
823 // send a present request (small set)
825 if (sr->smallSetElementSetNames)
827 comp = (Z_RecordComposition *)
828 odr_malloc(odr_encode(), sizeof(Z_RecordComposition));
829 comp->which = Z_RecordComp_simple;
830 comp->u.simple = sr->smallSetElementSetNames;
833 if (m_client->m_cache.lookup (odr_encode(), &npr, 1, toget,
834 sr->preferredRecordSyntax, comp))
836 yaz_log (LOG_LOG, "%sReturned cached records for small set",
838 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
839 new_apdu->u.searchResponse->referenceId = sr->referenceId;
840 new_apdu->u.searchResponse->resultCount =
841 &m_client->m_last_resultCount;
843 new_apdu->u.searchResponse->numberOfRecordsReturned
844 = odr_intdup(odr_encode(), toget);
846 new_apdu->u.searchResponse->presentStatus =
847 odr_intdup(odr_encode(), Z_PresentStatus_success);
848 new_apdu->u.searchResponse->records = (Z_Records*)
849 odr_malloc(odr_encode(), sizeof(Z_Records));
850 new_apdu->u.searchResponse->records->which = Z_Records_DBOSD;
851 new_apdu->u.searchResponse->records->u.databaseOrSurDiagnostics = npr;
852 new_apdu->u.searchResponse->nextResultSetPosition =
853 odr_intdup(odr_encode(), toget+1);
854 send_to_client(new_apdu);
859 yaz_log (LOG_LOG, "%sOptimizing search for small set",
861 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentRequest);
862 Z_PresentRequest *pr = new_apdu->u.presentRequest;
863 pr->referenceId = sr->referenceId;
864 pr->resultSetId = sr->resultSetName;
865 pr->preferredRecordSyntax = sr->preferredRecordSyntax;
866 *pr->numberOfRecordsRequested = toget;
867 pr->recordComposition = comp;
868 m_client->m_sr_transform = 1;
873 else // query doesn't match
875 delete m_client->m_last_query;
876 m_client->m_last_query = this_query;
877 m_client->m_last_ok = 0;
878 m_client->m_cache.clear();
879 m_client->m_resultSetStartPoint = 0;
881 xfree (m_client->m_last_resultSetId);
882 m_client->m_last_resultSetId = xstrdup (sr->resultSetName);
884 m_client->m_last_databases.set(sr->num_databaseNames,
885 (const char **) sr->databaseNames);
891 void Yaz_Proxy::recv_Z_PDU(Z_APDU *apdu, int len)
893 char *cp = strchr(m_session_str, ' ');
896 sprintf(cp+1, "%d ", m_request_no);
900 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
901 yaz_log (LOG_DEBUG, "%sReceiving %s from client %d bytes",
902 m_session_str, apdu_name(apdu), len);
904 if (m_bw_hold_PDU) // double incoming PDU. shutdown now.
907 m_bw_stat.add_bytes(len);
908 m_pdu_stat.add_bytes(1);
910 int bw_total = m_bw_stat.get_total();
911 int pdu_total = m_pdu_stat.get_total();
913 yaz_log(LOG_LOG, "%sstat bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
914 m_session_str, bw_total, pdu_total, m_bw_max, m_pdu_max);
918 if (bw_total > m_bw_max)
920 reduce = (bw_total/m_bw_max);
925 if (pdu_total > m_pdu_max)
927 int nreduce = (m_pdu_max >= 60) ? 1 : 60/m_pdu_max;
928 reduce = (reduce > nreduce) ? reduce : nreduce;
933 yaz_log(LOG_LOG, "%sLimit delay=%d", m_session_str, reduce);
934 m_bw_hold_PDU = apdu; // save PDU and signal "on hold"
935 timeout(reduce); // call us reduce seconds later
938 recv_Z_PDU_0(apdu); // all fine. Proceed receive PDU as usual
941 void Yaz_Proxy::handle_max_record_retrieve(Z_APDU *apdu)
943 if (m_max_record_retrieve)
945 if (apdu->which == Z_APDU_presentRequest)
947 Z_PresentRequest *pr = apdu->u.presentRequest;
948 if (pr->numberOfRecordsRequested &&
949 *pr->numberOfRecordsRequested > m_max_record_retrieve)
950 *pr->numberOfRecordsRequested = m_max_record_retrieve;
955 Z_Records *Yaz_Proxy::create_nonSurrogateDiagnostics(ODR odr,
959 Z_Records *rec = (Z_Records *)
960 odr_malloc (odr, sizeof(*rec));
962 odr_malloc (odr, sizeof(*err));
963 Z_DiagRec *drec = (Z_DiagRec *)
964 odr_malloc (odr, sizeof(*drec));
965 Z_DefaultDiagFormat *dr = (Z_DefaultDiagFormat *)
966 odr_malloc (odr, sizeof(*dr));
968 rec->which = Z_Records_NSD;
969 rec->u.nonSurrogateDiagnostic = dr;
970 dr->diagnosticSetId =
971 yaz_oidval_to_z3950oid (odr, CLASS_DIAGSET, VAL_BIB1);
973 dr->which = Z_DefaultDiagFormat_v2Addinfo;
974 dr->u.v2Addinfo = odr_strdup (odr, addinfo ? addinfo : "");
978 Z_APDU *Yaz_Proxy::handle_query_validation(Z_APDU *apdu)
980 if (apdu->which == Z_APDU_searchRequest)
982 Z_SearchRequest *sr = apdu->u.searchRequest;
986 Yaz_ProxyConfig *cfg = check_reconfigure();
988 err = cfg->check_query(odr_encode(), m_default_target,
989 sr->query, &addinfo);
992 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
994 new_apdu->u.searchResponse->referenceId = sr->referenceId;
995 new_apdu->u.searchResponse->records =
996 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
997 *new_apdu->u.searchResponse->searchStatus = 0;
999 send_to_client(new_apdu);
1007 Z_APDU *Yaz_Proxy::handle_syntax_validation(Z_APDU *apdu)
1010 if (apdu->which == Z_APDU_searchRequest)
1012 Z_SearchRequest *sr = apdu->u.searchRequest;
1015 Yaz_ProxyConfig *cfg = check_reconfigure();
1018 err = cfg->check_syntax(odr_encode(),
1020 sr->preferredRecordSyntax,
1024 sr->preferredRecordSyntax =
1025 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN,
1031 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1033 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1034 new_apdu->u.searchResponse->records =
1035 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1036 *new_apdu->u.searchResponse->searchStatus = 0;
1038 send_to_client(new_apdu);
1043 else if (apdu->which == Z_APDU_presentRequest)
1045 Z_PresentRequest *pr = apdu->u.presentRequest;
1048 Yaz_ProxyConfig *cfg = check_reconfigure();
1051 err = cfg->check_syntax(odr_encode(), m_default_target,
1052 pr->preferredRecordSyntax,
1056 pr->preferredRecordSyntax =
1057 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN,
1063 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1065 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1066 new_apdu->u.presentResponse->records =
1067 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1068 *new_apdu->u.presentResponse->presentStatus =
1069 Z_PresentStatus_failure;
1071 send_to_client(new_apdu);
1079 void Yaz_Proxy::recv_Z_PDU_0(Z_APDU *apdu)
1081 // Determine our client.
1082 m_client = get_client(apdu);
1088 m_client->m_server = this;
1090 if (apdu->which == Z_APDU_initRequest)
1092 if (apdu->u.initRequest->implementationId)
1093 yaz_log(LOG_LOG, "%simplementationId: %s",
1094 m_session_str, apdu->u.initRequest->implementationId);
1095 if (apdu->u.initRequest->implementationName)
1096 yaz_log(LOG_LOG, "%simplementationName: %s",
1097 m_session_str, apdu->u.initRequest->implementationName);
1098 if (apdu->u.initRequest->implementationVersion)
1099 yaz_log(LOG_LOG, "%simplementationVersion: %s",
1100 m_session_str, apdu->u.initRequest->implementationVersion);
1101 if (m_client->m_init_flag)
1103 Z_APDU *apdu = m_client->m_initResponse;
1104 apdu->u.initResponse->otherInfo = 0;
1105 if (m_client->m_cookie && *m_client->m_cookie)
1106 set_otherInformationString(apdu, VAL_COOKIE, 1,
1107 m_client->m_cookie);
1108 send_to_client(apdu);
1111 m_client->m_init_flag = 1;
1113 handle_max_record_retrieve(apdu);
1116 apdu = handle_syntax_validation(apdu);
1119 apdu = handle_query_validation(apdu);
1122 apdu = result_set_optimize(apdu);
1125 m_client->timeout(m_target_idletime); // mark it active even
1126 // though we didn't use it
1130 // delete other info part from PDU before sending to target
1131 Z_OtherInformation **oi;
1132 get_otherInfoAPDU(apdu, &oi);
1136 if (apdu->which == Z_APDU_presentRequest &&
1137 m_client->m_resultSetStartPoint == 0)
1139 Z_PresentRequest *pr = apdu->u.presentRequest;
1140 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
1141 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
1143 m_client->m_resultSetStartPoint = 0;
1145 if (m_client->send_to_target(apdu) < 0)
1152 m_client->m_waiting = 1;
1155 void Yaz_Proxy::connectNotify()
1159 void Yaz_Proxy::shutdown()
1161 // only keep if keep_alive flag is set...
1163 !m_invalid_session &&
1164 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
1165 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
1166 m_client->m_waiting == 0)
1168 yaz_log(LOG_LOG, "%sShutdown (client to proxy) keepalive %s",
1170 m_client->get_hostname());
1171 yaz_log(LOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1172 m_session_str, m_client->m_pdu_recv,
1173 m_client->m_bytes_sent + m_client->m_bytes_recv,
1174 m_keepalive_limit_bw, m_keepalive_limit_pdu);
1175 assert (m_client->m_waiting != 2);
1176 // Tell client (if any) that no server connection is there..
1177 m_client->m_server = 0;
1181 yaz_log (LOG_LOG, "%sShutdown (client to proxy) close %s",
1183 m_client->get_hostname());
1184 assert (m_client->m_waiting != 2);
1189 yaz_log (LOG_LOG, "%sshutdown (client to proxy) bad state",
1195 yaz_log (LOG_LOG, "%sShutdown (client to proxy)",
1199 m_parent->pre_init();
1203 const char *Yaz_ProxyClient::get_session_str()
1207 return m_server->get_session_str();
1210 void Yaz_ProxyClient::shutdown()
1212 yaz_log (LOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
1218 void Yaz_Proxy::failNotify()
1220 yaz_log (LOG_LOG, "%sConnection closed by client",
1225 void Yaz_ProxyClient::failNotify()
1227 yaz_log (LOG_LOG, "%sConnection closed by target %s",
1228 get_session_str(), get_hostname());
1232 void Yaz_ProxyClient::connectNotify()
1234 const char *s = get_session_str();
1235 const char *h = get_hostname();
1236 yaz_log (LOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
1238 timeout(m_target_idletime);
1243 IYaz_PDU_Observer *Yaz_ProxyClient::sessionNotify(IYaz_PDU_Observable
1244 *the_PDU_Observable, int fd)
1246 return new Yaz_ProxyClient(the_PDU_Observable, 0);
1249 Yaz_ProxyClient::~Yaz_ProxyClient()
1254 m_next->m_prev = m_prev;
1255 m_waiting = 2; // for debugging purposes only.
1256 odr_destroy(m_init_odr);
1257 delete m_last_query;
1258 xfree (m_last_resultSetId);
1262 void Yaz_ProxyClient::pre_init_client()
1264 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
1265 Z_InitRequest *req = apdu->u.initRequest;
1267 ODR_MASK_SET(req->options, Z_Options_search);
1268 ODR_MASK_SET(req->options, Z_Options_present);
1269 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
1270 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
1271 ODR_MASK_SET(req->options, Z_Options_scan);
1272 ODR_MASK_SET(req->options, Z_Options_sort);
1273 ODR_MASK_SET(req->options, Z_Options_extendedServices);
1274 ODR_MASK_SET(req->options, Z_Options_delSet);
1276 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
1277 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
1278 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
1280 if (send_to_target(apdu) < 0)
1291 void Yaz_Proxy::pre_init()
1294 const char *name = 0;
1295 const char *zurl_in_use[MAX_ZURL_PLEX];
1296 int limit_bw, limit_pdu, limit_req;
1297 int target_idletime, client_idletime;
1299 int keepalive_limit_bw, keepalive_limit_pdu;
1302 Yaz_ProxyConfig *cfg = check_reconfigure();
1306 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
1311 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
1312 &limit_bw, &limit_pdu, &limit_req,
1313 &target_idletime, &client_idletime,
1315 &keepalive_limit_bw,
1316 &keepalive_limit_pdu,
1322 for (j = 0; zurl_in_use[j]; j++)
1328 for (c = m_clientPool; c; c = c->m_next)
1330 if (!strcmp(zurl_in_use[j], c->get_hostname()))
1332 if (c->m_cookie == 0)
1334 if (c->m_server == 0)
1343 yaz_log(LOG_LOG, "%spre-init %s %s use=%d other=%d spare=%d "
1344 "preinit=%d",m_session_str,
1345 name, zurl_in_use[j], in_use, other, spare, pre_init);
1346 if (spare < pre_init)
1348 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
1349 c->m_next = m_clientPool;
1351 c->m_next->m_prev = &c->m_next;
1353 c->m_prev = &m_clientPool;
1355 if (m_log_mask & PROXY_LOG_APDU_SERVER)
1356 c->set_APDU_yazlog(1);
1358 c->set_APDU_yazlog(0);
1360 if (c->client(zurl_in_use[j]))
1368 c->m_target_idletime = target_idletime;
1369 c->m_seqno = m_seqno++;
1376 void Yaz_Proxy::timeoutNotify()
1382 timeout(m_client_idletime);
1383 Z_APDU *apdu = m_bw_hold_PDU;
1389 yaz_log (LOG_LOG, "%sTimeout (client to proxy)", m_session_str);
1400 void Yaz_ProxyClient::timeoutNotify()
1402 yaz_log (LOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
1409 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable,
1410 Yaz_Proxy *parent) :
1411 Yaz_Z_Assoc (the_PDU_Observable)
1418 m_last_resultSetId = 0;
1419 m_last_resultCount = 0;
1423 m_init_odr = odr_createmem (ODR_DECODE);
1425 m_resultSetStartPoint = 0;
1426 m_bytes_sent = m_bytes_recv = 0;
1430 m_target_idletime = 600;
1434 const char *Yaz_Proxy::option(const char *name, const char *value)
1436 if (!strcmp (name, "optimize")) {
1439 m_optimize = xstrdup (value);
1446 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
1448 m_bytes_recv += len;
1451 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1452 yaz_log (LOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
1453 apdu_name(apdu), get_hostname(), len);
1454 if (apdu->which == Z_APDU_initResponse)
1456 if (!m_server) // if this is a pre init session , check for more
1458 NMEM nmem = odr_extract_mem (odr_decode());
1459 odr_reset (m_init_odr);
1460 nmem_transfer (m_init_odr->mem, nmem);
1461 m_initResponse = apdu;
1463 Z_InitResponse *ir = apdu->u.initResponse;
1464 char *im0 = ir->implementationName;
1467 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
1474 strcat(im1, "(YAZ Proxy)");
1475 ir->implementationName = im1;
1477 nmem_destroy (nmem);
1479 if (apdu->which == Z_APDU_searchResponse)
1481 Z_SearchResponse *sr = apdu->u.searchResponse;
1482 m_last_resultCount = *sr->resultCount;
1483 int status = *sr->searchStatus;
1484 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
1488 if (sr->records && sr->records->which == Z_Records_DBOSD)
1490 m_cache.add(odr_decode(),
1491 sr->records->u.databaseOrSurDiagnostics, 1,
1496 if (apdu->which == Z_APDU_presentResponse)
1498 Z_PresentResponse *pr = apdu->u.presentResponse;
1502 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1503 Z_SearchResponse *sr = new_apdu->u.searchResponse;
1504 sr->referenceId = pr->referenceId;
1505 *sr->resultCount = m_last_resultCount;
1506 sr->records = pr->records;
1507 sr->nextResultSetPosition = pr->nextResultSetPosition;
1508 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
1512 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
1514 m_cache.add(odr_decode(),
1515 pr->records->u.databaseOrSurDiagnostics,
1516 m_resultSetStartPoint, -1);
1517 m_resultSetStartPoint = 0;
1521 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
1524 m_server->send_to_client(apdu);
1526 if (apdu->which == Z_APDU_close)
1532 int Yaz_Proxy::server(const char *addr)
1534 int r = Yaz_Z_Assoc::server(addr);
1537 yaz_log(LOG_LOG, "%sStarted listener on %s", m_session_str, addr);