2 * Copyright (c) 1998-2003, Index Data.
3 * See the file LICENSE for details.
5 * $Id: yaz-proxy.cpp,v 1.63 2003-10-20 18:31:44 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 %d %d %s",
360 c->m_seqno, parent->m_seqno, c->get_hostname());
362 c->m_seqno = parent->m_seqno;
363 assert(c->m_server == 0);
366 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
367 c->set_APDU_yazlog(1);
369 c->set_APDU_yazlog(0);
381 if (apdu->which != Z_APDU_initRequest)
383 yaz_log (LOG_LOG, "no first INIT!");
386 Z_InitRequest *initRequest = apdu->u.initRequest;
388 if (!initRequest->idAuthentication)
390 if (m_proxy_authentication)
392 initRequest->idAuthentication =
393 (Z_IdAuthentication *)
394 odr_malloc (odr_encode(),
395 sizeof(*initRequest->idAuthentication));
396 initRequest->idAuthentication->which =
397 Z_IdAuthentication_open;
398 initRequest->idAuthentication->u.open =
399 odr_strdup (odr_encode(), m_proxy_authentication);
403 // go through list of clients - and find the lowest/oldest one.
404 Yaz_ProxyClient *c_min = 0;
406 int no_of_clients = 0;
407 if (parent->m_clientPool)
408 yaz_log (LOG_DEBUG, "Existing sessions");
409 for (c = parent->m_clientPool; c; c = c->m_next)
411 yaz_log (LOG_DEBUG, " Session %-3d wait=%d %s cookie=%s", c->m_seqno,
412 c->m_waiting, c->get_hostname(),
413 c->m_cookie ? c->m_cookie : "");
415 if (min_seq < 0 || c->m_seqno < min_seq)
417 min_seq = c->m_seqno;
421 if (no_of_clients >= parent->m_max_clients)
424 if (c->m_waiting || strcmp(m_proxyTarget, c->get_hostname()))
426 yaz_log (LOG_LOG, "%sMAXCLIENTS Destroy %d",
427 m_session_str, c->m_seqno);
428 if (c->m_server && c->m_server != this)
434 yaz_log (LOG_LOG, "%sMAXCLIENTS Reuse %d %d %s",
436 c->m_seqno, parent->m_seqno, c->get_hostname());
440 c->m_cookie = xstrdup(cookie);
441 c->m_seqno = parent->m_seqno;
442 if (c->m_server && c->m_server != this)
444 c->m_server->m_client = 0;
448 c->m_target_idletime = m_target_idletime;
449 c->timeout(m_target_idletime);
451 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
452 c->set_APDU_yazlog(1);
454 c->set_APDU_yazlog(0);
461 yaz_log (LOG_LOG, "%sNEW %d %s",
462 m_session_str, parent->m_seqno, m_proxyTarget);
463 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), parent);
464 c->m_next = parent->m_clientPool;
466 c->m_next->m_prev = &c->m_next;
467 parent->m_clientPool = c;
468 c->m_prev = &parent->m_clientPool;
474 c->m_cookie = xstrdup(cookie);
476 c->m_seqno = parent->m_seqno;
478 c->m_last_resultCount = 0;
481 c->m_sr_transform = 0;
483 c->m_resultSetStartPoint = 0;
485 if (c->client(m_proxyTarget))
490 c->m_target_idletime = m_target_idletime;
493 if (parent->m_log_mask & PROXY_LOG_APDU_SERVER)
494 c->set_APDU_yazlog(1);
496 c->set_APDU_yazlog(0);
498 yaz_log (LOG_DEBUG, "get_client 3 %p %p", this, c);
502 void Yaz_Proxy::display_diagrecs(Z_DiagRec **pp, int num)
505 for (i = 0; i<num; i++)
508 Z_DefaultDiagFormat *r;
509 Z_DiagRec *p = pp[i];
510 if (p->which != Z_DiagRec_defaultFormat)
512 yaz_log(LOG_LOG, "%sError no diagnostics", m_session_str);
516 r = p->u.defaultFormat;
517 if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
518 ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
519 yaz_log(LOG_LOG, "%sError unknown diagnostic set", m_session_str);
522 case Z_DefaultDiagFormat_v2Addinfo:
523 yaz_log(LOG_LOG, "%sError %d %s:%s",
525 *r->condition, diagbib1_str(*r->condition),
528 case Z_DefaultDiagFormat_v3Addinfo:
529 yaz_log(LOG_LOG, "%sError %d %s:%s",
531 *r->condition, diagbib1_str(*r->condition),
538 void Yaz_Proxy::convert_to_marcxml(Z_NamePlusRecordList *p)
542 yaz_marc_t mt = yaz_marc_create();
543 yaz_marc_xml(mt, YAZ_MARC_MARCXML);
544 for (i = 0; i < p->num_records; i++)
546 Z_NamePlusRecord *npr = p->records[i];
547 if (npr->which == Z_NamePlusRecord_databaseRecord)
549 Z_External *r = npr->u.databaseRecord;
550 if (r->which == Z_External_octet)
554 if (yaz_marc_decode_buf(mt, (char*) r->u.octet_aligned->buf,
555 r->u.octet_aligned->len,
558 yaz_iconv_t cd = yaz_iconv_open("UTF-8", "MARC-8");
559 WRBUF wrbuf = wrbuf_alloc();
562 size_t inbytesleft = rlen;
563 const char *inp = result;
564 while (cd && inbytesleft)
566 size_t outbytesleft = sizeof(outbuf);
570 r = yaz_iconv (cd, (char**) &inp,
572 &outp, &outbytesleft);
573 if (r == (size_t) (-1))
575 int e = yaz_iconv_error(cd);
576 if (e != YAZ_ICONV_E2BIG)
578 yaz_log(LOG_WARN, "conversion failure");
582 wrbuf_write(wrbuf, outbuf, outp - outbuf);
587 npr->u.databaseRecord = z_ext_record(odr_encode(),
591 wrbuf_free(wrbuf, 1);
596 yaz_marc_destroy(mt);
599 int Yaz_Proxy::send_to_client(Z_APDU *apdu)
602 if (apdu->which == Z_APDU_searchResponse)
604 Z_SearchResponse *sr = apdu->u.searchResponse;
605 Z_Records *p = sr->records;
606 if (p && p->which == Z_Records_NSD)
608 Z_DiagRec dr, *dr_p = &dr;
609 dr.which = Z_DiagRec_defaultFormat;
610 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
612 display_diagrecs(&dr_p, 1);
616 if (m_marcxml_flag && p && p->which == Z_Records_DBOSD)
617 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
620 yaz_log(LOG_LOG, "%s%d hits", m_session_str,
622 if (*sr->resultCount < 0)
623 m_invalid_session = 1;
627 else if (apdu->which == Z_APDU_presentResponse)
629 Z_PresentResponse *sr = apdu->u.presentResponse;
630 Z_Records *p = sr->records;
631 if (p && p->which == Z_Records_NSD)
633 Z_DiagRec dr, *dr_p = &dr;
634 dr.which = Z_DiagRec_defaultFormat;
635 dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
637 display_diagrecs(&dr_p, 1);
639 if (m_marcxml_flag && p && p->which == Z_Records_DBOSD)
640 convert_to_marcxml(p->u.databaseOrSurDiagnostics);
642 int r = send_Z_PDU(apdu, &len);
643 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
644 yaz_log (LOG_DEBUG, "%sSending %s to client %d bytes", m_session_str,
645 apdu_name(apdu), len);
647 m_bw_stat.add_bytes(len);
651 int Yaz_ProxyClient::send_to_target(Z_APDU *apdu)
654 int r = send_Z_PDU(apdu, &len);
655 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
656 yaz_log (LOG_LOG, "%sSending %s to %s %d bytes",
658 apdu_name(apdu), get_hostname(), len);
663 Z_APDU *Yaz_Proxy::result_set_optimize(Z_APDU *apdu)
665 if (apdu->which == Z_APDU_presentRequest)
667 Z_PresentRequest *pr = apdu->u.presentRequest;
668 Z_NamePlusRecordList *npr;
669 int toget = *pr->numberOfRecordsRequested;
670 int start = *pr->resultSetStartPoint;
672 yaz_log(LOG_LOG, "%sPresent %s %d+%d", m_session_str,
673 pr->resultSetId, start, toget);
675 if (*m_parent->m_optimize == '0')
678 if (!m_client->m_last_resultSetId)
680 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
681 new_apdu->u.presentResponse->records =
682 create_nonSurrogateDiagnostics(odr_encode(), 30,
684 send_to_client(new_apdu);
687 if (!strcmp(m_client->m_last_resultSetId, pr->resultSetId))
689 if (start+toget-1 > m_client->m_last_resultCount)
691 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
692 new_apdu->u.presentResponse->records =
693 create_nonSurrogateDiagnostics(odr_encode(), 13, 0);
694 send_to_client(new_apdu);
697 if (m_client->m_cache.lookup (odr_encode(), &npr, start, toget,
698 pr->preferredRecordSyntax,
699 pr->recordComposition))
701 yaz_log (LOG_LOG, "%sReturned cached records for present request",
703 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
704 new_apdu->u.presentResponse->referenceId = pr->referenceId;
706 new_apdu->u.presentResponse->numberOfRecordsReturned
707 = odr_intdup(odr_encode(), toget);
709 new_apdu->u.presentResponse->records = (Z_Records*)
710 odr_malloc(odr_encode(), sizeof(Z_Records));
711 new_apdu->u.presentResponse->records->which = Z_Records_DBOSD;
712 new_apdu->u.presentResponse->records->u.databaseOrSurDiagnostics = npr;
713 new_apdu->u.presentResponse->nextResultSetPosition =
714 odr_intdup(odr_encode(), start+toget);
716 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);
901 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
902 yaz_log (LOG_DEBUG, "%sReceiving %s from client %d bytes",
903 m_session_str, apdu_name(apdu), len);
905 if (m_bw_hold_PDU) // double incoming PDU. shutdown now.
908 m_bw_stat.add_bytes(len);
909 m_pdu_stat.add_bytes(1);
911 int bw_total = m_bw_stat.get_total();
912 int pdu_total = m_pdu_stat.get_total();
914 yaz_log(LOG_LOG, "%sstat bw=%d pdu=%d limit-bw=%d limit-pdu=%d",
915 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 = (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;
1013 if (*sr->smallSetUpperBound > 0 || *sr->mediumSetPresentNumber > 0)
1017 Yaz_ProxyConfig *cfg = check_reconfigure();
1020 err = cfg->check_syntax(odr_encode(),
1022 sr->preferredRecordSyntax,
1026 sr->preferredRecordSyntax =
1027 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN,
1033 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1035 new_apdu->u.searchResponse->referenceId = sr->referenceId;
1036 new_apdu->u.searchResponse->records =
1037 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1038 *new_apdu->u.searchResponse->searchStatus = 0;
1040 send_to_client(new_apdu);
1046 else if (apdu->which == Z_APDU_presentRequest)
1048 Z_PresentRequest *pr = apdu->u.presentRequest;
1051 Yaz_ProxyConfig *cfg = check_reconfigure();
1054 err = cfg->check_syntax(odr_encode(), m_default_target,
1055 pr->preferredRecordSyntax,
1059 pr->preferredRecordSyntax =
1060 yaz_oidval_to_z3950oid(odr_decode(), CLASS_RECSYN,
1066 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_presentResponse);
1068 new_apdu->u.presentResponse->referenceId = pr->referenceId;
1069 new_apdu->u.presentResponse->records =
1070 create_nonSurrogateDiagnostics(odr_encode(), err, addinfo);
1071 *new_apdu->u.presentResponse->presentStatus =
1072 Z_PresentStatus_failure;
1074 send_to_client(new_apdu);
1082 void Yaz_Proxy::recv_Z_PDU_0(Z_APDU *apdu)
1084 // Determine our client.
1085 m_client = get_client(apdu);
1091 m_client->m_server = this;
1093 if (apdu->which == Z_APDU_initRequest)
1095 if (apdu->u.initRequest->implementationId)
1096 yaz_log(LOG_LOG, "%simplementationId: %s",
1097 m_session_str, apdu->u.initRequest->implementationId);
1098 if (apdu->u.initRequest->implementationName)
1099 yaz_log(LOG_LOG, "%simplementationName: %s",
1100 m_session_str, apdu->u.initRequest->implementationName);
1101 if (apdu->u.initRequest->implementationVersion)
1102 yaz_log(LOG_LOG, "%simplementationVersion: %s",
1103 m_session_str, apdu->u.initRequest->implementationVersion);
1104 if (m_client->m_init_flag)
1106 Z_APDU *apdu = m_client->m_initResponse;
1107 apdu->u.initResponse->otherInfo = 0;
1108 if (m_client->m_cookie && *m_client->m_cookie)
1109 set_otherInformationString(apdu, VAL_COOKIE, 1,
1110 m_client->m_cookie);
1111 send_to_client(apdu);
1114 m_client->m_init_flag = 1;
1116 handle_max_record_retrieve(apdu);
1119 apdu = handle_syntax_validation(apdu);
1122 apdu = handle_query_validation(apdu);
1125 apdu = result_set_optimize(apdu);
1128 m_client->timeout(m_target_idletime); // mark it active even
1129 // though we didn't use it
1133 // delete other info part from PDU before sending to target
1134 Z_OtherInformation **oi;
1135 get_otherInfoAPDU(apdu, &oi);
1139 if (apdu->which == Z_APDU_presentRequest &&
1140 m_client->m_resultSetStartPoint == 0)
1142 Z_PresentRequest *pr = apdu->u.presentRequest;
1143 m_client->m_resultSetStartPoint = *pr->resultSetStartPoint;
1144 m_client->m_cache.copy_presentRequest(apdu->u.presentRequest);
1146 m_client->m_resultSetStartPoint = 0;
1148 if (m_client->send_to_target(apdu) < 0)
1155 m_client->m_waiting = 1;
1158 void Yaz_Proxy::connectNotify()
1162 void Yaz_Proxy::shutdown()
1164 // only keep if keep_alive flag is set...
1166 !m_invalid_session &&
1167 m_client->m_pdu_recv < m_keepalive_limit_pdu &&
1168 m_client->m_bytes_recv+m_client->m_bytes_sent < m_keepalive_limit_bw &&
1169 m_client->m_waiting == 0)
1171 yaz_log(LOG_LOG, "%sShutdown (client to proxy) keepalive %s",
1173 m_client->get_hostname());
1174 yaz_log(LOG_LOG, "%sbw=%d pdu=%d limit-bw=%d limit-pdu=%d",
1175 m_session_str, m_client->m_pdu_recv,
1176 m_client->m_bytes_sent + m_client->m_bytes_recv,
1177 m_keepalive_limit_bw, m_keepalive_limit_pdu);
1178 assert (m_client->m_waiting != 2);
1179 // Tell client (if any) that no server connection is there..
1180 m_client->m_server = 0;
1184 yaz_log (LOG_LOG, "%sShutdown (client to proxy) close %s",
1186 m_client->get_hostname());
1187 assert (m_client->m_waiting != 2);
1192 yaz_log (LOG_LOG, "%sshutdown (client to proxy) bad state",
1198 yaz_log (LOG_LOG, "%sShutdown (client to proxy)",
1202 m_parent->pre_init();
1206 const char *Yaz_ProxyClient::get_session_str()
1210 return m_server->get_session_str();
1213 void Yaz_ProxyClient::shutdown()
1215 yaz_log (LOG_LOG, "%sShutdown (proxy to target) %s", get_session_str(),
1221 void Yaz_Proxy::failNotify()
1223 yaz_log (LOG_LOG, "%sConnection closed by client",
1228 void Yaz_ProxyClient::failNotify()
1230 yaz_log (LOG_LOG, "%sConnection closed by target %s",
1231 get_session_str(), get_hostname());
1235 void Yaz_ProxyClient::connectNotify()
1237 const char *s = get_session_str();
1238 const char *h = get_hostname();
1239 yaz_log (LOG_LOG, "%sConnection accepted by %s timeout=%d", s, h,
1241 timeout(m_target_idletime);
1246 IYaz_PDU_Observer *Yaz_ProxyClient::sessionNotify(IYaz_PDU_Observable
1247 *the_PDU_Observable, int fd)
1249 return new Yaz_ProxyClient(the_PDU_Observable, 0);
1252 Yaz_ProxyClient::~Yaz_ProxyClient()
1257 m_next->m_prev = m_prev;
1258 m_waiting = 2; // for debugging purposes only.
1259 odr_destroy(m_init_odr);
1260 delete m_last_query;
1261 xfree (m_last_resultSetId);
1265 void Yaz_ProxyClient::pre_init_client()
1267 Z_APDU *apdu = create_Z_PDU(Z_APDU_initRequest);
1268 Z_InitRequest *req = apdu->u.initRequest;
1270 ODR_MASK_SET(req->options, Z_Options_search);
1271 ODR_MASK_SET(req->options, Z_Options_present);
1272 ODR_MASK_SET(req->options, Z_Options_namedResultSets);
1273 ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
1274 ODR_MASK_SET(req->options, Z_Options_scan);
1275 ODR_MASK_SET(req->options, Z_Options_sort);
1276 ODR_MASK_SET(req->options, Z_Options_extendedServices);
1277 ODR_MASK_SET(req->options, Z_Options_delSet);
1279 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
1280 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
1281 ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
1283 if (send_to_target(apdu) < 0)
1294 void Yaz_Proxy::pre_init()
1297 const char *name = 0;
1298 const char *zurl_in_use[MAX_ZURL_PLEX];
1299 int limit_bw, limit_pdu, limit_req;
1300 int target_idletime, client_idletime;
1302 int keepalive_limit_bw, keepalive_limit_pdu;
1305 Yaz_ProxyConfig *cfg = check_reconfigure();
1309 if (m_log_mask & PROXY_LOG_APDU_CLIENT)
1314 for (i = 0; cfg && cfg->get_target_no(i, &name, zurl_in_use,
1315 &limit_bw, &limit_pdu, &limit_req,
1316 &target_idletime, &client_idletime,
1318 &keepalive_limit_bw,
1319 &keepalive_limit_pdu,
1325 for (j = 0; zurl_in_use[j]; j++)
1331 for (c = m_clientPool; c; c = c->m_next)
1333 if (!strcmp(zurl_in_use[j], c->get_hostname()))
1335 if (c->m_cookie == 0)
1337 if (c->m_server == 0)
1346 yaz_log(LOG_LOG, "%s pre-init %s %s use=%d other=%d spare=%d preinit=%d",
1348 name, zurl_in_use[j], in_use, other, spare, pre_init);
1349 if (spare < pre_init)
1351 c = new Yaz_ProxyClient(m_PDU_Observable->clone(), this);
1352 c->m_next = m_clientPool;
1354 c->m_next->m_prev = &c->m_next;
1356 c->m_prev = &m_clientPool;
1358 if (m_log_mask & PROXY_LOG_APDU_SERVER)
1359 c->set_APDU_yazlog(1);
1361 c->set_APDU_yazlog(0);
1363 if (c->client(zurl_in_use[j]))
1371 c->m_target_idletime = target_idletime;
1372 c->m_seqno = m_seqno++;
1379 void Yaz_Proxy::timeoutNotify()
1385 timeout(m_client_idletime);
1386 Z_APDU *apdu = m_bw_hold_PDU;
1392 yaz_log (LOG_LOG, "%sTimeout (client to proxy)", m_session_str);
1403 void Yaz_ProxyClient::timeoutNotify()
1405 yaz_log (LOG_LOG, "%sTimeout (proxy to target) %s", get_session_str(),
1412 Yaz_ProxyClient::Yaz_ProxyClient(IYaz_PDU_Observable *the_PDU_Observable,
1413 Yaz_Proxy *parent) :
1414 Yaz_Z_Assoc (the_PDU_Observable)
1421 m_last_resultSetId = 0;
1422 m_last_resultCount = 0;
1426 m_init_odr = odr_createmem (ODR_DECODE);
1428 m_resultSetStartPoint = 0;
1429 m_bytes_sent = m_bytes_recv = 0;
1433 m_target_idletime = 600;
1437 const char *Yaz_Proxy::option(const char *name, const char *value)
1439 if (!strcmp (name, "optimize")) {
1442 m_optimize = xstrdup (value);
1449 void Yaz_ProxyClient::recv_Z_PDU(Z_APDU *apdu, int len)
1451 m_bytes_recv += len;
1454 if (m_root->get_log_mask() & PROXY_LOG_REQ_SERVER)
1455 yaz_log (LOG_LOG, "%sReceiving %s from %s %d bytes", get_session_str(),
1456 apdu_name(apdu), get_hostname(), len);
1457 if (apdu->which == Z_APDU_initResponse)
1459 if (!m_server) // if this is a pre init session , check for more
1461 NMEM nmem = odr_extract_mem (odr_decode());
1462 odr_reset (m_init_odr);
1463 nmem_transfer (m_init_odr->mem, nmem);
1464 m_initResponse = apdu;
1466 Z_InitResponse *ir = apdu->u.initResponse;
1467 char *im0 = ir->implementationName;
1470 odr_malloc(m_init_odr, 20 + (im0 ? strlen(im0) : 0));
1477 strcat(im1, "(YAZ Proxy)");
1478 ir->implementationName = im1;
1480 nmem_destroy (nmem);
1482 if (apdu->which == Z_APDU_searchResponse)
1484 Z_SearchResponse *sr = apdu->u.searchResponse;
1485 m_last_resultCount = *sr->resultCount;
1486 int status = *sr->searchStatus;
1487 if (status && (!sr->records || sr->records->which == Z_Records_DBOSD))
1491 if (sr->records && sr->records->which == Z_Records_DBOSD)
1493 m_cache.add(odr_decode(),
1494 sr->records->u.databaseOrSurDiagnostics, 1,
1499 if (apdu->which == Z_APDU_presentResponse)
1501 Z_PresentResponse *pr = apdu->u.presentResponse;
1505 Z_APDU *new_apdu = create_Z_PDU(Z_APDU_searchResponse);
1506 Z_SearchResponse *sr = new_apdu->u.searchResponse;
1507 sr->referenceId = pr->referenceId;
1508 *sr->resultCount = m_last_resultCount;
1509 sr->records = pr->records;
1510 sr->nextResultSetPosition = pr->nextResultSetPosition;
1511 sr->numberOfRecordsReturned = pr->numberOfRecordsReturned;
1515 pr->records->which == Z_Records_DBOSD && m_resultSetStartPoint)
1517 m_cache.add(odr_decode(),
1518 pr->records->u.databaseOrSurDiagnostics,
1519 m_resultSetStartPoint, -1);
1520 m_resultSetStartPoint = 0;
1524 set_otherInformationString (apdu, VAL_COOKIE, 1, m_cookie);
1527 m_server->send_to_client(apdu);
1529 if (apdu->which == Z_APDU_close)
1535 void Yaz_Proxy::server(const char *addr)
1537 Yaz_Z_Assoc::server(addr);