1 /* $Id: logic.c,v 1.11 2007-04-20 04:08:14 quinn Exp $
2 Copyright (c) 2006-2007, Index Data.
4 This file is part of Pazpar2.
6 Pazpar2 is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
11 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with Pazpar2; see the file LICENSE. If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
27 #include <sys/socket.h>
33 #include <yaz/marcdisp.h>
34 #include <yaz/comstack.h>
35 #include <yaz/tcpip.h>
36 #include <yaz/proto.h>
37 #include <yaz/readconf.h>
38 #include <yaz/pquery.h>
39 #include <yaz/otherinfo.h>
40 #include <yaz/yaz-util.h>
42 #include <yaz/query-charset.h>
43 #include <yaz/querytowrbuf.h>
44 #if YAZ_VERSIONL >= 0x020163
45 #include <yaz/oid_db.h>
54 #include <yaz/timing.h>
57 #include <netinet/in.h>
62 #include "termlists.h"
64 #include "relevance.h"
71 static void client_fatal(struct client *cl);
72 static void connection_destroy(struct connection *co);
73 static int client_prep_connection(struct client *cl);
74 static void ingest_records(struct client *cl, Z_Records *r);
75 void session_alert_watch(struct session *s, int what);
77 static struct connection *connection_freelist = 0;
78 static struct client *client_freelist = 0;
80 static char *client_states[] = {
84 "Client_Initializing",
89 "Client_Disconnected",
93 // Note: Some things in this structure will eventually move to configuration
94 struct parameters global_parameters =
104 "Index Data PazPar2",
114 static int send_apdu(struct client *c, Z_APDU *a)
116 struct connection *co = c->connection;
120 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
122 odr_perror(global_parameters.odr_out, "Encoding APDU");
125 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
126 r = cs_put(co->link, buf, len);
129 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
134 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
137 odr_reset(global_parameters.odr_out); /* release the APDU structure */
138 co->state = Conn_Waiting;
142 // Set authentication token in init if one is set for the client
143 // TODO: Extend this to handle other schemes than open (should be simple)
144 static void init_authentication(struct client *cl, Z_InitRequest *req)
146 struct session_database *sdb = cl->database;
147 char *auth = session_setting_oneval(sdb, PZ_AUTHENTICATION);
151 Z_IdAuthentication *idAuth = odr_malloc(global_parameters.odr_out,
153 idAuth->which = Z_IdAuthentication_open;
154 idAuth->u.open = auth;
155 req->idAuthentication = idAuth;
159 static void send_init(IOCHAN i)
162 struct connection *co = iochan_getdata(i);
163 struct client *cl = co->client;
164 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
166 a->u.initRequest->implementationId = global_parameters.implementationId;
167 a->u.initRequest->implementationName = global_parameters.implementationName;
168 a->u.initRequest->implementationVersion =
169 global_parameters.implementationVersion;
170 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
171 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
172 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
174 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
175 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
176 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
178 init_authentication(cl, a->u.initRequest);
180 /* add virtual host if tunneling through Z39.50 proxy */
182 if (0 < strlen(global_parameters.zproxy_override)
183 && 0 < strlen(cl->database->database->url))
185 #if YAZ_VERSIONL >= 0x020163
186 yaz_oi_set_string_oid(&a->u.initRequest->otherInfo,
187 global_parameters.odr_out,
188 yaz_oid_userinfo_proxy,
189 1, cl->database->database->url);
191 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
192 global_parameters.odr_out, VAL_PROXY,
193 1, cl->database->database->url);
197 if (send_apdu(cl, a) >= 0)
199 iochan_setflags(i, EVENT_INPUT);
200 cl->state = Client_Initializing;
203 cl->state = Client_Error;
204 odr_reset(global_parameters.odr_out);
207 // Recursively traverse query structure to extract terms.
208 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
220 pull_terms(nmem, n->u.p[0], termlist, num);
221 pull_terms(nmem, n->u.p[1], termlist, num);
224 nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
225 for (i = 0; i < numwords; i++)
226 termlist[(*num)++] = words[i];
233 // Extract terms from query into null-terminated termlist
234 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
238 pull_terms(nmem, query, termlist, &num);
242 static void send_search(IOCHAN i)
244 struct connection *co = iochan_getdata(i);
245 struct client *cl = co->client;
246 struct session *se = cl->session;
247 struct session_database *sdb = cl->database;
248 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
252 int ssub = 0, lslb = 100000, mspn = 10;
256 yaz_iconv_t iconv = 0;
258 yaz_log(YLOG_DEBUG, "Sending search to %s", cl->database->database->url);
260 // constructing RPN query
261 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
263 zquery->which = Z_Query_type_1;
264 zquery->u.type_1 = p_query_rpn(global_parameters.odr_out, cl->pquery);
266 // converting to target encoding
267 if ((queryenc = session_setting_oneval(sdb, PZ_QUERYENCODING))){
268 iconv = yaz_iconv_open(queryenc, "UTF-8");
270 yaz_query_charset_convert_rpnquery(zquery->u.type_1,
271 global_parameters.odr_out,
273 yaz_iconv_close(iconv);
275 yaz_log(YLOG_WARN, "Query encoding failed %s %s",
276 cl->database->database->url, queryenc);
279 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
281 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
282 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
283 databaselist[ndb] = sdb->database->databases[ndb];
285 if (!(piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK)) || *piggyback == '1')
287 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
289 #if YAZ_VERSIONL >= 0x020163
290 a->u.searchRequest->preferredRecordSyntax =
291 yaz_string_to_oid_odr(yaz_oid_std(),
292 CLASS_RECSYN, recsyn,
293 global_parameters.odr_out);
295 a->u.searchRequest->preferredRecordSyntax =
296 yaz_str_to_z3950oid(global_parameters.odr_out,
297 CLASS_RECSYN, recsyn);
300 a->u.searchRequest->smallSetUpperBound = &ssub;
301 a->u.searchRequest->largeSetLowerBound = &lslb;
302 a->u.searchRequest->mediumSetPresentNumber = &mspn;
304 a->u.searchRequest->resultSetName = "Default";
305 a->u.searchRequest->databaseNames = databaselist;
306 a->u.searchRequest->num_databaseNames = ndb;
309 { //scope for sending and logging queries
310 WRBUF wbquery = wrbuf_alloc();
311 yaz_query_to_wrbuf(wbquery, zquery);
314 if (send_apdu(cl, a) >= 0)
316 iochan_setflags(i, EVENT_INPUT);
317 cl->state = Client_Searching;
318 cl->requestid = se->requestid;
319 yaz_log(YLOG_LOG, "SearchRequest %s %s %s",
320 cl->database->database->url,
321 queryenc ? queryenc : "UTF-8",
322 wrbuf_cstr(wbquery));
325 cl->state = Client_Error;
326 yaz_log(YLOG_WARN, "Failed SearchRequest %s %s %s",
327 cl->database->database->url,
328 queryenc ? queryenc : "UTF-8",
329 wrbuf_cstr(wbquery));
332 wrbuf_destroy(wbquery);
335 odr_reset(global_parameters.odr_out);
338 static void send_present(IOCHAN i)
340 struct connection *co = iochan_getdata(i);
341 struct client *cl = co->client;
342 struct session_database *sdb = cl->database;
343 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
345 int start = cl->records + 1;
348 toget = global_parameters.chunk;
349 if (toget > global_parameters.toget - cl->records)
350 toget = global_parameters.toget - cl->records;
351 if (toget > cl->hits - cl->records)
352 toget = cl->hits - cl->records;
354 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
356 a->u.presentRequest->resultSetStartPoint = &start;
357 a->u.presentRequest->numberOfRecordsRequested = &toget;
359 a->u.presentRequest->resultSetId = "Default";
361 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
363 #if YAZ_VERSIONL >= 0x020163
364 a->u.presentRequest->preferredRecordSyntax =
365 yaz_string_to_oid_odr(yaz_oid_std(),
366 CLASS_RECSYN, recsyn,
367 global_parameters.odr_out);
369 a->u.presentRequest->preferredRecordSyntax =
370 yaz_str_to_z3950oid(global_parameters.odr_out,
371 CLASS_RECSYN, recsyn);
375 if (send_apdu(cl, a) >= 0)
377 iochan_setflags(i, EVENT_INPUT);
378 cl->state = Client_Presenting;
381 cl->state = Client_Error;
382 odr_reset(global_parameters.odr_out);
385 static void do_initResponse(IOCHAN i, Z_APDU *a)
387 struct connection *co = iochan_getdata(i);
388 struct client *cl = co->client;
389 Z_InitResponse *r = a->u.initResponse;
391 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->database->url);
395 cl->state = Client_Idle;
398 cl->state = Client_Failed; // FIXME need to do something to the connection
401 static void do_searchResponse(IOCHAN i, Z_APDU *a)
403 struct connection *co = iochan_getdata(i);
404 struct client *cl = co->client;
405 struct session *se = cl->session;
406 Z_SearchResponse *r = a->u.searchResponse;
408 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
409 cl->database->database->url, *r->searchStatus);
411 if (*r->searchStatus)
413 cl->hits = *r->resultCount;
414 se->total_hits += cl->hits;
415 if (r->presentStatus && !*r->presentStatus && r->records)
417 yaz_log(YLOG_DEBUG, "Records in search response %s",
418 cl->database->database->url);
419 ingest_records(cl, r->records);
421 cl->state = Client_Idle;
426 cl->state = Client_Error;
428 Z_Records *recs = r->records;
429 if (recs->which == Z_Records_NSD)
432 "Search response: Non-surrogate diagnostic %s",
433 cl->database->database->url);
434 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
435 cl->state = Client_Error;
441 static void do_closeResponse(IOCHAN i, Z_APDU *a)
443 struct connection *co = iochan_getdata(i);
444 struct client *cl = co->client;
445 /* Z_Close *r = a->u.close; */
447 yaz_log(YLOG_WARN, "Close response %s", cl->database->database->url);
449 cl->state = Client_Failed;
450 connection_destroy(co);
454 char *normalize_mergekey(char *buf, int skiparticle)
456 char *p = buf, *pout = buf;
461 char articles[] = "the den der die des an a "; // must end in space
463 while (*p && !isalnum(*p))
466 while (*p && *p != ' ' && pout - firstword < 62)
467 *(pout++) = tolower(*(p++));
470 if (!strstr(articles, firstword))
477 while (*p && !isalnum(*p))
480 *(pout++) = tolower(*(p++));
483 while (*p && !isalnum(*p))
490 while (pout > buf && *pout == ' ');
495 static void add_facet(struct session *s, const char *type, const char *value)
501 for (i = 0; i < s->num_termlists; i++)
502 if (!strcmp(s->termlists[i].name, type))
504 if (i == s->num_termlists)
506 if (i == SESSION_MAX_TERMLISTS)
508 yaz_log(YLOG_FATAL, "Too many termlists");
511 s->termlists[i].name = nmem_strdup(s->nmem, type);
512 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
513 s->num_termlists = i + 1;
515 termlist_insert(s->termlists[i].termlist, value);
518 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
520 struct database_retrievalmap *m;
521 struct database *db = cl->database->database;
525 // First normalize to XML
530 if (rec->which != Z_External_octet)
532 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
533 cl->database->database->url);
536 buf = (char*) rec->u.octet_aligned->buf;
537 len = rec->u.octet_aligned->len;
538 if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
540 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
541 cl->database->database->url);
545 yaz_marc_write_using_libxml2(db->yaz_marc, 1);
546 if (yaz_marc_write_xml(db->yaz_marc, &res,
547 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
549 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
550 cl->database->database->url);
553 rdoc = xmlNewDoc((xmlChar *) "1.0");
554 xmlDocSetRootElement(rdoc, res);
560 "Unknown native_syntax in normalize_record from %s",
561 cl->database->database->url);
565 if (global_parameters.dump_records){
567 "Input Record (normalized) from %s\n----------------\n",
568 cl->database->database->url);
569 #if LIBXML_VERSION >= 20600
570 xmlDocFormatDump(stderr, rdoc, 1);
572 xmlDocDump(stderr, rdoc);
576 for (m = db->map; m; m = m->next){
582 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
583 root= xmlDocGetRootElement(new);
584 if (!new || !root || !(root->children))
586 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
587 cl->database->database->url);
596 // do it another way to detect transformation errors right now
597 // but does not seem to work either!
599 xsltTransformContextPtr ctxt;
600 ctxt = xsltNewTransformContext(m->stylesheet, rdoc);
601 new = xsltApplyStylesheetUser(m->stylesheet, rdoc, 0, 0, 0, ctxt);
602 if ((ctxt->state == XSLT_STATE_ERROR) ||
603 (ctxt->state == XSLT_STATE_STOPPED)){
604 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
605 cl->database->database->url);
616 if (global_parameters.dump_records)
618 fprintf(stderr, "Record from %s\n----------------\n",
619 cl->database->database->url);
620 #if LIBXML_VERSION >= 20600
621 xmlDocFormatDump(stderr, rdoc, 1);
623 xmlDocDump(stderr, rdoc);
629 // Extract what appears to be years from buf, storing highest and
631 static int extract_years(const char *buf, int *first, int *last)
640 while (*buf && !isdigit(*buf))
643 for (e = buf; *e && isdigit(*e); e++)
647 int value = atoi(buf);
648 if (*first < 0 || value < *first)
650 if (*last < 0 || value > *last)
658 static struct record *ingest_record(struct client *cl, Z_External *rec)
660 xmlDoc *xdoc = normalize_record(cl, rec);
663 struct record_cluster *cluster;
664 struct session *se = cl->session;
665 xmlChar *mergekey, *mergekey_norm;
668 struct conf_service *service = global_parameters.server->service;
673 root = xmlDocGetRootElement(xdoc);
674 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
676 yaz_log(YLOG_WARN, "No mergekey found in record");
681 res = nmem_malloc(se->nmem, sizeof(struct record));
684 res->metadata = nmem_malloc(se->nmem,
685 sizeof(struct record_metadata*) * service->num_metadata);
686 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
688 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
690 normalize_mergekey((char *) mergekey_norm, 0);
692 cluster = reclist_insert(se->reclist,
693 global_parameters.server->service,
694 res, (char *) mergekey_norm,
696 if (global_parameters.dump_records)
697 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
698 cl->database->database->url, cl->records);
701 /* no room for record */
705 relevance_newrec(se->relevance, cluster);
707 for (n = root->children; n; n = n->next)
715 if (n->type != XML_ELEMENT_NODE)
717 if (!strcmp((const char *) n->name, "metadata"))
719 struct conf_metadata *md = 0;
720 struct conf_sortkey *sk = 0;
721 struct record_metadata **wheretoput, *newm;
725 type = xmlGetProp(n, (xmlChar *) "type");
726 value = xmlNodeListGetString(xdoc, n->children, 0);
731 // First, find out what field we're looking at
732 for (imeta = 0; imeta < service->num_metadata; imeta++)
733 if (!strcmp((const char *) type, service->metadata[imeta].name))
735 md = &service->metadata[imeta];
736 if (md->sortkey_offset >= 0)
737 sk = &service->sortkeys[md->sortkey_offset];
742 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
746 // Find out where we are putting it
747 if (md->merge == Metadata_merge_no)
748 wheretoput = &res->metadata[imeta];
750 wheretoput = &cluster->metadata[imeta];
753 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
755 if (md->type == Metadata_type_generic)
758 for (p = (char *) value; *p && isspace(*p); p++)
760 for (pe = p + strlen(p) - 1;
761 pe > p && strchr(" ,/.:([", *pe); pe--)
763 newm->data.text = nmem_strdup(se->nmem, p);
766 else if (md->type == Metadata_type_year)
768 if (extract_years((char *) value, &first, &last) < 0)
773 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
776 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
778 yaz_log(YLOG_WARN, "Only range merging supported for years");
781 if (md->merge == Metadata_merge_unique)
783 struct record_metadata *mnode;
784 for (mnode = *wheretoput; mnode; mnode = mnode->next)
785 if (!strcmp((const char *) mnode->data.text, newm->data.text))
789 newm->next = *wheretoput;
793 else if (md->merge == Metadata_merge_longest)
796 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
801 char *s = nmem_strdup(se->nmem, newm->data.text);
802 if (!cluster->sortkeys[md->sortkey_offset])
803 cluster->sortkeys[md->sortkey_offset] =
804 nmem_malloc(se->nmem, sizeof(union data_types));
805 normalize_mergekey(s,
806 (sk->type == Metadata_sortkey_skiparticle));
807 cluster->sortkeys[md->sortkey_offset]->text = s;
811 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
813 newm->next = *wheretoput;
816 else if (md->merge == Metadata_merge_range)
818 assert(md->type == Metadata_type_year);
822 (*wheretoput)->data.number.min = first;
823 (*wheretoput)->data.number.max = last;
825 cluster->sortkeys[md->sortkey_offset] = &newm->data;
829 if (first < (*wheretoput)->data.number.min)
830 (*wheretoput)->data.number.min = first;
831 if (last > (*wheretoput)->data.number.max)
832 (*wheretoput)->data.number.max = last;
837 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
838 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
843 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
846 relevance_countwords(se->relevance, cluster,
847 (char *) value, md->rank);
850 if (md->type == Metadata_type_year)
853 sprintf(year, "%d", last);
854 add_facet(se, (char *) type, year);
857 sprintf(year, "%d", first);
858 add_facet(se, (char *) type, year);
862 add_facet(se, (char *) type, (char *) value);
869 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
878 relevance_donerecord(se->relevance, cluster);
884 // Retrieve first defined value for 'name' for given database.
885 // Will be extended to take into account user associated with session
886 char *session_setting_oneval(struct session_database *db, int offset)
888 if (!db->settings[offset])
890 return db->settings[offset]->value;
893 static void ingest_records(struct client *cl, Z_Records *r)
896 yaz_timing_t t = yaz_timing_create();
899 struct session *s = cl->session;
900 Z_NamePlusRecordList *rlist;
903 if (r->which != Z_Records_DBOSD)
905 rlist = r->u.databaseOrSurDiagnostics;
906 for (i = 0; i < rlist->num_records; i++)
908 Z_NamePlusRecord *npr = rlist->records[i];
911 if (npr->which != Z_NamePlusRecord_databaseRecord)
914 "Unexpected record type, probably diagnostic %s",
915 cl->database->database->url);
919 rec = ingest_record(cl, npr->u.databaseRecord);
923 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
924 session_alert_watch(s, SESSION_WATCH_RECORDS);
928 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
929 yaz_timing_get_real(t), yaz_timing_get_user(t),
930 yaz_timing_get_sys(t));
931 yaz_timing_destroy(&t);
935 static void do_presentResponse(IOCHAN i, Z_APDU *a)
937 struct connection *co = iochan_getdata(i);
938 struct client *cl = co->client;
939 Z_PresentResponse *r = a->u.presentResponse;
942 Z_Records *recs = r->records;
943 if (recs->which == Z_Records_NSD)
945 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
946 cl->database->database->url);
947 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
948 cl->state = Client_Error;
952 if (!*r->presentStatus && cl->state != Client_Error)
954 yaz_log(YLOG_DEBUG, "Good Present response %s",
955 cl->database->database->url);
956 ingest_records(cl, r->records);
957 cl->state = Client_Idle;
959 else if (*r->presentStatus)
961 yaz_log(YLOG_WARN, "Bad Present response %s",
962 cl->database->database->url);
963 cl->state = Client_Error;
967 static void handler(IOCHAN i, int event)
969 struct connection *co = iochan_getdata(i);
970 struct client *cl = co->client;
971 struct session *se = 0;
977 yaz_log(YLOG_WARN, "Destroying orphan connection");
978 connection_destroy(co);
982 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
985 socklen_t errlen = sizeof(errcode);
987 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
988 &errlen) < 0 || errcode != 0)
995 yaz_log(YLOG_DEBUG, "Connect OK");
996 co->state = Conn_Open;
998 cl->state = Client_Connected;
1002 else if (event & EVENT_INPUT)
1004 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
1008 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
1009 cl->database->database->url);
1010 connection_destroy(co);
1015 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
1016 connection_destroy(co);
1019 else if (len > 1) // We discard input if we have no connection
1021 co->state = Conn_Open;
1023 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
1027 odr_reset(global_parameters.odr_in);
1028 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
1029 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
1036 case Z_APDU_initResponse:
1037 do_initResponse(i, a);
1039 case Z_APDU_searchResponse:
1040 do_searchResponse(i, a);
1042 case Z_APDU_presentResponse:
1043 do_presentResponse(i, a);
1046 do_closeResponse(i, a);
1050 "Unexpected Z39.50 response from %s",
1051 cl->database->database->url);
1055 // We aren't expecting staggered output from target
1056 // if (cs_more(t->link))
1057 // iochan_setevent(i, EVENT_INPUT);
1059 else // we throw away response and go to idle mode
1061 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
1062 cl->state = Client_Idle;
1065 /* if len==1 we do nothing but wait for more input */
1068 if (cl->state == Client_Connected) {
1072 if (cl->state == Client_Idle)
1074 if (cl->requestid != se->requestid && cl->pquery) {
1077 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
1078 cl->records < cl->hits) {
1084 // Disassociate connection from client
1085 static void connection_release(struct connection *co)
1087 struct client *cl = co->client;
1089 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1096 // Close connection and recycle structure
1097 static void connection_destroy(struct connection *co)
1099 struct host *h = co->host;
1101 iochan_destroy(co->iochan);
1103 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1104 if (h->connections == co)
1105 h->connections = co->next;
1108 struct connection *pco;
1109 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1112 pco->next = co->next;
1118 if (co->client->state != Client_Idle)
1119 co->client->state = Client_Disconnected;
1120 co->client->connection = 0;
1122 co->next = connection_freelist;
1123 connection_freelist = co;
1126 // Creates a new connection for client, associated with the host of
1127 // client's database
1128 static struct connection *connection_create(struct client *cl)
1130 struct connection *new;
1136 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1138 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1142 if (0 == strlen(global_parameters.zproxy_override)){
1143 /* no Z39.50 proxy needed - direct connect */
1144 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
1146 if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
1148 yaz_log(YLOG_WARN|YLOG_ERRNO,
1149 "Lookup of IP address %s failed",
1150 cl->database->database->host->ipport);
1155 /* Z39.50 proxy connect */
1156 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1157 cl->database->database->url, global_parameters.zproxy_override);
1159 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1161 yaz_log(YLOG_WARN|YLOG_ERRNO,
1162 "Lookup of IP address %s failed",
1163 global_parameters.zproxy_override);
1168 res = cs_connect(link, addr);
1171 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
1175 if ((new = connection_freelist))
1176 connection_freelist = new->next;
1179 new = xmalloc(sizeof (struct connection));
1183 new->state = Conn_Connecting;
1184 new->host = cl->database->database->host;
1185 new->next = new->host->connections;
1186 new->host->connections = new;
1188 cl->connection = new;
1191 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1192 iochan_setdata(new->iochan, new);
1193 pazpar2_add_channel(new->iochan);
1197 // Close connection and set state to error
1198 static void client_fatal(struct client *cl)
1200 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
1201 connection_destroy(cl->connection);
1202 cl->state = Client_Error;
1205 // Ensure that client has a connection associated
1206 static int client_prep_connection(struct client *cl)
1208 struct connection *co;
1209 struct session *se = cl->session;
1210 struct host *host = cl->database->database->host;
1212 co = cl->connection;
1214 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
1218 // See if someone else has an idle connection
1219 // We should look at timestamps here to select the longest-idle connection
1220 for (co = host->connections; co; co = co->next)
1221 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1225 connection_release(co);
1226 cl->connection = co;
1230 co = connection_create(cl);
1234 if (co->state == Conn_Connecting)
1236 cl->state = Client_Connecting;
1237 iochan_setflag(co->iochan, EVENT_OUTPUT);
1239 else if (co->state == Conn_Open)
1241 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1242 cl->state = Client_Idle;
1243 iochan_setflag(co->iochan, EVENT_OUTPUT);
1251 // Parse the query given the settings specific to this client
1252 static int client_parse_query(struct client *cl, const char *query)
1254 struct session *se = cl->session;
1255 struct ccl_rpn_node *cn;
1258 cn = ccl_find_str(cl->database->database->ccl_map, query, &cerror, &cpos);
1261 cl->state = Client_Error;
1262 yaz_log(YLOG_WARN, "Failed to parse query for %s",
1263 cl->database->database->url);
1266 wrbuf_rewind(se->wrbuf);
1267 ccl_pquery(se->wrbuf, cn);
1268 wrbuf_putc(se->wrbuf, '\0');
1271 cl->pquery = xstrdup(wrbuf_buf(se->wrbuf));
1275 // Initialize relevance structure with query terms
1277 extract_terms(se->nmem, cn, p);
1278 se->relevance = relevance_create(se->nmem, (const char **) p,
1279 se->expected_maxrecs);
1286 static struct client *client_create(void)
1289 if (client_freelist)
1291 r = client_freelist;
1292 client_freelist = client_freelist->next;
1295 r = xmalloc(sizeof(struct client));
1305 r->state = Client_Disconnected;
1310 void client_destroy(struct client *c)
1312 struct session *se = c->session;
1313 if (c == se->clients)
1314 se->clients = c->next;
1318 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1324 connection_release(c->connection);
1325 c->next = client_freelist;
1326 client_freelist = c;
1329 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1331 s->watchlist[what].fun = fun;
1332 s->watchlist[what].data = data;
1335 void session_alert_watch(struct session *s, int what)
1337 if (!s->watchlist[what].fun)
1339 (*s->watchlist[what].fun)(s->watchlist[what].data);
1340 s->watchlist[what].fun = 0;
1341 s->watchlist[what].data = 0;
1344 //callback for grep_databases
1345 static void select_targets_callback(void *context, struct session_database *db)
1347 struct session *se = (struct session*) context;
1348 struct client *cl = client_create();
1351 cl->next = se->clients;
1355 // Associates a set of clients with a session;
1356 // Note: Session-databases represent databases with per-session setting overrides
1357 int select_targets(struct session *se, struct database_criterion *crit)
1360 client_destroy(se->clients);
1362 return session_grep_databases(se, crit, select_targets_callback);
1365 int session_active_clients(struct session *s)
1370 for (c = s->clients; c; c = c->next)
1371 if (c->connection && (c->state == Client_Connecting ||
1372 c->state == Client_Initializing ||
1373 c->state == Client_Searching ||
1374 c->state == Client_Presenting))
1380 // parses crit1=val1,crit2=val2|val3,...
1381 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1383 struct database_criterion *res = 0;
1390 nmem_strsplit(m, ",", buf, &values, &num);
1391 for (i = 0; i < num; i++)
1396 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1397 char *eq = strchr(values[i], '=');
1400 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1404 new->name = values[i];
1405 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1407 for (subi = 0; subi < subnum; subi++)
1409 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1410 newv->value = subvalues[subi];
1411 newv->next = new->values;
1420 char *search(struct session *se, char *query, char *filter)
1422 int live_channels = 0;
1424 struct database_criterion *criteria;
1426 yaz_log(YLOG_DEBUG, "Search");
1428 nmem_reset(se->nmem);
1429 criteria = parse_filter(se->nmem, filter);
1431 live_channels = select_targets(se, criteria);
1434 int maxrecs = live_channels * global_parameters.toget;
1435 se->num_termlists = 0;
1436 se->reclist = reclist_create(se->nmem, maxrecs);
1437 // This will be initialized in send_search()
1438 se->total_records = se->total_hits = se->total_merged = 0;
1439 se->expected_maxrecs = maxrecs;
1445 for (cl = se->clients; cl; cl = cl->next)
1446 if (client_parse_query(cl, query) < 0) // Query must parse for all targets
1448 for (cl = se->clients; cl; cl = cl->next)
1449 client_prep_connection(cl);
1454 // Apply a session override to a database
1455 void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
1457 struct session_database *sdb;
1459 for (sdb = se->databases; sdb; sdb = sdb->next)
1460 if (!strcmp(dbname, sdb->database->url))
1462 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
1463 int offset = settings_offset(setting);
1467 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
1470 new->precedence = 0;
1471 new->target = dbname;
1472 new->name = setting;
1474 new->next = sdb->settings[offset];
1475 sdb->settings[offset] = new;
1479 yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
1482 void session_init_databases_fun(void *context, struct database *db)
1484 struct session *se = (struct session *) context;
1485 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
1486 int num = settings_num();
1490 new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
1491 for (i = 0; i < num; i++)
1492 new->settings[i] = db->settings[i];
1493 new->next = se->databases;
1494 se->databases = new;
1497 // Initialize session_database list -- this represents this session's view
1498 // of the database list -- subject to modification by the settings ws command
1499 void session_init_databases(struct session *se)
1502 grep_databases(se, 0, session_init_databases_fun);
1505 void destroy_session(struct session *s)
1507 yaz_log(YLOG_LOG, "Destroying session");
1509 client_destroy(s->clients);
1510 nmem_destroy(s->nmem);
1511 wrbuf_destroy(s->wrbuf);
1514 struct session *new_session(NMEM nmem)
1517 struct session *session = nmem_malloc(nmem, sizeof(*session));
1519 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
1521 session->total_hits = 0;
1522 session->total_records = 0;
1523 session->num_termlists = 0;
1524 session->reclist = 0;
1525 session->requestid = -1;
1526 session->clients = 0;
1527 session->expected_maxrecs = 0;
1528 session->session_nmem = nmem;
1529 session->nmem = nmem_create();
1530 session->wrbuf = wrbuf_alloc();
1531 session_init_databases(session);
1532 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1534 session->watchlist[i].data = 0;
1535 session->watchlist[i].fun = 0;
1541 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1543 static struct hitsbytarget res[1000]; // FIXME MM
1547 for (cl = se->clients; cl; cl = cl->next)
1549 char *name = session_setting_oneval(cl->database, PZ_NAME);
1551 res[*count].id = cl->database->database->url;
1552 res[*count].name = *name ? name : "Unknown";
1553 res[*count].hits = cl->hits;
1554 res[*count].records = cl->records;
1555 res[*count].diagnostic = cl->diagnostic;
1556 res[*count].state = client_states[cl->state];
1557 res[*count].connected = cl->connection ? 1 : 0;
1564 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1568 for (i = 0; i < s->num_termlists; i++)
1569 if (!strcmp((const char *) s->termlists[i].name, name))
1570 return termlist_highscore(s->termlists[i].termlist, num);
1574 #ifdef MISSING_HEADERS
1575 void report_nmem_stats(void)
1577 size_t in_use, is_free;
1579 nmem_get_memory_in_use(&in_use);
1580 nmem_get_memory_free(&is_free);
1582 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1583 (long) in_use, (long) is_free);
1587 struct record_cluster *show_single(struct session *s, int id)
1589 struct record_cluster *r;
1591 reclist_rewind(s->reclist);
1592 while ((r = reclist_read_record(s->reclist)))
1598 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1599 int *num, int *total, int *sumhits, NMEM nmem_show)
1601 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1602 * sizeof(struct record_cluster *));
1603 struct reclist_sortparms *spp;
1606 yaz_timing_t t = yaz_timing_create();
1609 for (spp = sp; spp; spp = spp->next)
1610 if (spp->type == Metadata_sortkey_relevance)
1612 relevance_prepare_read(s->relevance, s->reclist);
1615 reclist_sort(s->reclist, sp);
1617 *total = s->reclist->num_records;
1618 *sumhits = s->total_hits;
1620 for (i = 0; i < start; i++)
1621 if (!reclist_read_record(s->reclist))
1628 for (i = 0; i < *num; i++)
1630 struct record_cluster *r = reclist_read_record(s->reclist);
1640 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1641 yaz_timing_get_real(t), yaz_timing_get_user(t),
1642 yaz_timing_get_sys(t));
1643 yaz_timing_destroy(&t);
1648 void statistics(struct session *se, struct statistics *stat)
1653 memset(stat, 0, sizeof(*stat));
1654 for (cl = se->clients; cl; cl = cl->next)
1656 if (!cl->connection)
1657 stat->num_no_connection++;
1660 case Client_Connecting: stat->num_connecting++; break;
1661 case Client_Initializing: stat->num_initializing++; break;
1662 case Client_Searching: stat->num_searching++; break;
1663 case Client_Presenting: stat->num_presenting++; break;
1664 case Client_Idle: stat->num_idle++; break;
1665 case Client_Failed: stat->num_failed++; break;
1666 case Client_Error: stat->num_error++; break;
1671 stat->num_hits = se->total_hits;
1672 stat->num_records = se->total_records;
1674 stat->num_clients = count;
1677 void start_http_listener(void)
1680 struct conf_server *ser = global_parameters.server;
1682 if (*global_parameters.listener_override)
1683 strcpy(hp, global_parameters.listener_override);
1686 strcpy(hp, ser->host ? ser->host : "");
1691 sprintf(hp + strlen(hp), "%d", ser->port);
1697 void start_proxy(void)
1700 struct conf_server *ser = global_parameters.server;
1702 if (*global_parameters.proxy_override)
1703 strcpy(hp, global_parameters.proxy_override);
1704 else if (ser->proxy_host || ser->proxy_port)
1706 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1707 if (ser->proxy_port)
1711 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1717 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1720 void start_zproxy(void)
1722 struct conf_server *ser = global_parameters.server;
1724 if (*global_parameters.zproxy_override){
1725 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1726 global_parameters.zproxy_override);
1730 else if (ser->zproxy_host || ser->zproxy_port)
1734 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1735 if (ser->zproxy_port)
1742 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1744 strcpy(global_parameters.zproxy_override, hp);
1745 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1746 global_parameters.zproxy_override);
1753 // Master list of connections we're handling events to
1754 static IOCHAN channel_list = 0;
1755 void pazpar2_add_channel(IOCHAN chan)
1757 chan->next = channel_list;
1758 channel_list = chan;
1761 void pazpar2_event_loop()
1763 event_loop(&channel_list);
1769 * indent-tabs-mode: nil
1771 * vim: shiftwidth=4 tabstop=8 expandtab