1 /* $Id: logic.c,v 1.9 2007-04-18 19:45:09 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 IOCHAN channel_list = 0; // Master list of connections we're handling events to
79 static struct connection *connection_freelist = 0;
80 static struct client *client_freelist = 0;
82 static char *client_states[] = {
86 "Client_Initializing",
91 "Client_Disconnected",
95 // Note: Some things in this structure will eventually move to configuration
96 struct parameters global_parameters =
106 "Index Data PazPar2",
116 static int send_apdu(struct client *c, Z_APDU *a)
118 struct connection *co = c->connection;
122 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
124 odr_perror(global_parameters.odr_out, "Encoding APDU");
127 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
128 r = cs_put(co->link, buf, len);
131 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
136 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
139 odr_reset(global_parameters.odr_out); /* release the APDU structure */
140 co->state = Conn_Waiting;
144 // Set authentication token in init if one is set for the client
145 // TODO: Extend this to handle other schemes than open (should be simple)
146 static void init_authentication(struct client *cl, Z_InitRequest *req)
148 struct session_database *sdb = cl->database;
149 char *auth = session_setting_oneval(sdb, PZ_AUTHENTICATION);
153 Z_IdAuthentication *idAuth = odr_malloc(global_parameters.odr_out,
155 idAuth->which = Z_IdAuthentication_open;
156 idAuth->u.open = auth;
157 req->idAuthentication = idAuth;
161 static void send_init(IOCHAN i)
164 struct connection *co = iochan_getdata(i);
165 struct client *cl = co->client;
166 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
168 a->u.initRequest->implementationId = global_parameters.implementationId;
169 a->u.initRequest->implementationName = global_parameters.implementationName;
170 a->u.initRequest->implementationVersion =
171 global_parameters.implementationVersion;
172 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
173 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
174 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
176 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
177 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
178 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
180 init_authentication(cl, a->u.initRequest);
182 /* add virtual host if tunneling through Z39.50 proxy */
184 if (0 < strlen(global_parameters.zproxy_override)
185 && 0 < strlen(cl->database->database->url))
187 #if YAZ_VERSIONL >= 0x020163
188 yaz_oi_set_string_oid(&a->u.initRequest->otherInfo,
189 global_parameters.odr_out,
190 yaz_oid_userinfo_proxy,
191 1, cl->database->database->url);
193 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
194 global_parameters.odr_out, VAL_PROXY,
195 1, cl->database->database->url);
199 if (send_apdu(cl, a) >= 0)
201 iochan_setflags(i, EVENT_INPUT);
202 cl->state = Client_Initializing;
205 cl->state = Client_Error;
206 odr_reset(global_parameters.odr_out);
209 // Recursively traverse query structure to extract terms.
210 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
222 pull_terms(nmem, n->u.p[0], termlist, num);
223 pull_terms(nmem, n->u.p[1], termlist, num);
226 nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
227 for (i = 0; i < numwords; i++)
228 termlist[(*num)++] = words[i];
235 // Extract terms from query into null-terminated termlist
236 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
240 pull_terms(nmem, query, termlist, &num);
244 static void send_search(IOCHAN i)
246 struct connection *co = iochan_getdata(i);
247 struct client *cl = co->client;
248 struct session *se = cl->session;
249 struct session_database *sdb = cl->database;
250 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
254 int ssub = 0, lslb = 100000, mspn = 10;
258 yaz_iconv_t iconv = 0;
260 yaz_log(YLOG_DEBUG, "Sending search to %s", cl->database->database->url);
262 // constructing RPN query
263 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
265 zquery->which = Z_Query_type_1;
266 zquery->u.type_1 = p_query_rpn(global_parameters.odr_out, cl->pquery);
268 // converting to target encoding
269 if ((queryenc = session_setting_oneval(sdb, PZ_QUERYENCODING))){
270 iconv = yaz_iconv_open(queryenc, "UTF-8");
272 yaz_query_charset_convert_rpnquery(zquery->u.type_1,
273 global_parameters.odr_out,
275 yaz_iconv_close(iconv);
277 yaz_log(YLOG_WARN, "Query encoding failed %s %s",
278 cl->database->database->url, queryenc);
281 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
283 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
284 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
285 databaselist[ndb] = sdb->database->databases[ndb];
287 if (!(piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK)) || *piggyback == '1')
289 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
291 #if YAZ_VERSIONL >= 0x020163
292 a->u.searchRequest->preferredRecordSyntax =
293 yaz_string_to_oid_odr(yaz_oid_std(),
294 CLASS_RECSYN, recsyn,
295 global_parameters.odr_out);
297 a->u.searchRequest->preferredRecordSyntax =
298 yaz_str_to_z3950oid(global_parameters.odr_out,
299 CLASS_RECSYN, recsyn);
302 a->u.searchRequest->smallSetUpperBound = &ssub;
303 a->u.searchRequest->largeSetLowerBound = &lslb;
304 a->u.searchRequest->mediumSetPresentNumber = &mspn;
306 a->u.searchRequest->resultSetName = "Default";
307 a->u.searchRequest->databaseNames = databaselist;
308 a->u.searchRequest->num_databaseNames = ndb;
311 { //scope for sending and logging queries
312 WRBUF wbquery = wrbuf_alloc();
313 yaz_query_to_wrbuf(wbquery, zquery);
316 if (send_apdu(cl, a) >= 0)
318 iochan_setflags(i, EVENT_INPUT);
319 cl->state = Client_Searching;
320 cl->requestid = se->requestid;
321 yaz_log(YLOG_LOG, "SearchRequest %s %s %s",
322 cl->database->database->url,
323 queryenc ? queryenc : "UTF-8",
324 wrbuf_cstr(wbquery));
327 cl->state = Client_Error;
328 yaz_log(YLOG_WARN, "Failed SearchRequest %s %s %s",
329 cl->database->database->url,
330 queryenc ? queryenc : "UTF-8",
331 wrbuf_cstr(wbquery));
334 wrbuf_destroy(wbquery);
337 odr_reset(global_parameters.odr_out);
340 static void send_present(IOCHAN i)
342 struct connection *co = iochan_getdata(i);
343 struct client *cl = co->client;
344 struct session_database *sdb = cl->database;
345 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
347 int start = cl->records + 1;
350 toget = global_parameters.chunk;
351 if (toget > global_parameters.toget - cl->records)
352 toget = global_parameters.toget - cl->records;
353 if (toget > cl->hits - cl->records)
354 toget = cl->hits - cl->records;
356 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
358 a->u.presentRequest->resultSetStartPoint = &start;
359 a->u.presentRequest->numberOfRecordsRequested = &toget;
361 a->u.presentRequest->resultSetId = "Default";
363 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
365 #if YAZ_VERSIONL >= 0x020163
366 a->u.presentRequest->preferredRecordSyntax =
367 yaz_string_to_oid_odr(yaz_oid_std(),
368 CLASS_RECSYN, recsyn,
369 global_parameters.odr_out);
371 a->u.presentRequest->preferredRecordSyntax =
372 yaz_str_to_z3950oid(global_parameters.odr_out,
373 CLASS_RECSYN, recsyn);
377 if (send_apdu(cl, a) >= 0)
379 iochan_setflags(i, EVENT_INPUT);
380 cl->state = Client_Presenting;
383 cl->state = Client_Error;
384 odr_reset(global_parameters.odr_out);
387 static void do_initResponse(IOCHAN i, Z_APDU *a)
389 struct connection *co = iochan_getdata(i);
390 struct client *cl = co->client;
391 Z_InitResponse *r = a->u.initResponse;
393 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->database->url);
397 cl->state = Client_Idle;
400 cl->state = Client_Failed; // FIXME need to do something to the connection
403 static void do_searchResponse(IOCHAN i, Z_APDU *a)
405 struct connection *co = iochan_getdata(i);
406 struct client *cl = co->client;
407 struct session *se = cl->session;
408 Z_SearchResponse *r = a->u.searchResponse;
410 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
411 cl->database->database->url, *r->searchStatus);
413 if (*r->searchStatus)
415 cl->hits = *r->resultCount;
416 se->total_hits += cl->hits;
417 if (r->presentStatus && !*r->presentStatus && r->records)
419 yaz_log(YLOG_DEBUG, "Records in search response %s",
420 cl->database->database->url);
421 ingest_records(cl, r->records);
423 cl->state = Client_Idle;
428 cl->state = Client_Error;
430 Z_Records *recs = r->records;
431 if (recs->which == Z_Records_NSD)
434 "Search response: Non-surrogate diagnostic %s",
435 cl->database->database->url);
436 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
437 cl->state = Client_Error;
443 static void do_closeResponse(IOCHAN i, Z_APDU *a)
445 struct connection *co = iochan_getdata(i);
446 struct client *cl = co->client;
447 /* Z_Close *r = a->u.close; */
449 yaz_log(YLOG_WARN, "Close response %s", cl->database->database->url);
451 cl->state = Client_Failed;
452 connection_destroy(co);
456 char *normalize_mergekey(char *buf, int skiparticle)
458 char *p = buf, *pout = buf;
463 char articles[] = "the den der die des an a "; // must end in space
465 while (*p && !isalnum(*p))
468 while (*p && *p != ' ' && pout - firstword < 62)
469 *(pout++) = tolower(*(p++));
472 if (!strstr(articles, firstword))
479 while (*p && !isalnum(*p))
482 *(pout++) = tolower(*(p++));
485 while (*p && !isalnum(*p))
492 while (pout > buf && *pout == ' ');
497 static void add_facet(struct session *s, const char *type, const char *value)
503 for (i = 0; i < s->num_termlists; i++)
504 if (!strcmp(s->termlists[i].name, type))
506 if (i == s->num_termlists)
508 if (i == SESSION_MAX_TERMLISTS)
510 yaz_log(YLOG_FATAL, "Too many termlists");
513 s->termlists[i].name = nmem_strdup(s->nmem, type);
514 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
515 s->num_termlists = i + 1;
517 termlist_insert(s->termlists[i].termlist, value);
520 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
522 struct database_retrievalmap *m;
523 struct database *db = cl->database->database;
527 // First normalize to XML
532 if (rec->which != Z_External_octet)
534 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
535 cl->database->database->url);
538 buf = (char*) rec->u.octet_aligned->buf;
539 len = rec->u.octet_aligned->len;
540 if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
542 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
543 cl->database->database->url);
547 yaz_marc_write_using_libxml2(db->yaz_marc, 1);
548 if (yaz_marc_write_xml(db->yaz_marc, &res,
549 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
551 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
552 cl->database->database->url);
555 rdoc = xmlNewDoc((xmlChar *) "1.0");
556 xmlDocSetRootElement(rdoc, res);
562 "Unknown native_syntax in normalize_record from %s",
563 cl->database->database->url);
567 if (global_parameters.dump_records){
569 "Input Record (normalized) from %s\n----------------\n",
570 cl->database->database->url);
571 #if LIBXML_VERSION >= 20600
572 xmlDocFormatDump(stderr, rdoc, 1);
574 xmlDocDump(stderr, rdoc);
578 for (m = db->map; m; m = m->next){
584 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
585 root= xmlDocGetRootElement(new);
586 if (!new || !root || !(root->children))
588 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
589 cl->database->database->url);
598 // do it another way to detect transformation errors right now
599 // but does not seem to work either!
601 xsltTransformContextPtr ctxt;
602 ctxt = xsltNewTransformContext(m->stylesheet, rdoc);
603 new = xsltApplyStylesheetUser(m->stylesheet, rdoc, 0, 0, 0, ctxt);
604 if ((ctxt->state == XSLT_STATE_ERROR) ||
605 (ctxt->state == XSLT_STATE_STOPPED)){
606 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
607 cl->database->database->url);
618 if (global_parameters.dump_records)
620 fprintf(stderr, "Record from %s\n----------------\n",
621 cl->database->database->url);
622 #if LIBXML_VERSION >= 20600
623 xmlDocFormatDump(stderr, rdoc, 1);
625 xmlDocDump(stderr, rdoc);
631 // Extract what appears to be years from buf, storing highest and
633 static int extract_years(const char *buf, int *first, int *last)
642 while (*buf && !isdigit(*buf))
645 for (e = buf; *e && isdigit(*e); e++)
649 int value = atoi(buf);
650 if (*first < 0 || value < *first)
652 if (*last < 0 || value > *last)
660 static struct record *ingest_record(struct client *cl, Z_External *rec)
662 xmlDoc *xdoc = normalize_record(cl, rec);
665 struct record_cluster *cluster;
666 struct session *se = cl->session;
667 xmlChar *mergekey, *mergekey_norm;
670 struct conf_service *service = global_parameters.server->service;
675 root = xmlDocGetRootElement(xdoc);
676 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
678 yaz_log(YLOG_WARN, "No mergekey found in record");
683 res = nmem_malloc(se->nmem, sizeof(struct record));
686 res->metadata = nmem_malloc(se->nmem,
687 sizeof(struct record_metadata*) * service->num_metadata);
688 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
690 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
692 normalize_mergekey((char *) mergekey_norm, 0);
694 cluster = reclist_insert(se->reclist,
695 global_parameters.server->service,
696 res, (char *) mergekey_norm,
698 if (global_parameters.dump_records)
699 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
700 cl->database->database->url, cl->records);
703 /* no room for record */
707 relevance_newrec(se->relevance, cluster);
709 for (n = root->children; n; n = n->next)
717 if (n->type != XML_ELEMENT_NODE)
719 if (!strcmp((const char *) n->name, "metadata"))
721 struct conf_metadata *md = 0;
722 struct conf_sortkey *sk = 0;
723 struct record_metadata **wheretoput, *newm;
727 type = xmlGetProp(n, (xmlChar *) "type");
728 value = xmlNodeListGetString(xdoc, n->children, 0);
733 // First, find out what field we're looking at
734 for (imeta = 0; imeta < service->num_metadata; imeta++)
735 if (!strcmp((const char *) type, service->metadata[imeta].name))
737 md = &service->metadata[imeta];
738 if (md->sortkey_offset >= 0)
739 sk = &service->sortkeys[md->sortkey_offset];
744 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
748 // Find out where we are putting it
749 if (md->merge == Metadata_merge_no)
750 wheretoput = &res->metadata[imeta];
752 wheretoput = &cluster->metadata[imeta];
755 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
757 if (md->type == Metadata_type_generic)
760 for (p = (char *) value; *p && isspace(*p); p++)
762 for (pe = p + strlen(p) - 1;
763 pe > p && strchr(" ,/.:([", *pe); pe--)
765 newm->data.text = nmem_strdup(se->nmem, p);
768 else if (md->type == Metadata_type_year)
770 if (extract_years((char *) value, &first, &last) < 0)
775 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
778 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
780 yaz_log(YLOG_WARN, "Only range merging supported for years");
783 if (md->merge == Metadata_merge_unique)
785 struct record_metadata *mnode;
786 for (mnode = *wheretoput; mnode; mnode = mnode->next)
787 if (!strcmp((const char *) mnode->data.text, newm->data.text))
791 newm->next = *wheretoput;
795 else if (md->merge == Metadata_merge_longest)
798 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
803 char *s = nmem_strdup(se->nmem, newm->data.text);
804 if (!cluster->sortkeys[md->sortkey_offset])
805 cluster->sortkeys[md->sortkey_offset] =
806 nmem_malloc(se->nmem, sizeof(union data_types));
807 normalize_mergekey(s,
808 (sk->type == Metadata_sortkey_skiparticle));
809 cluster->sortkeys[md->sortkey_offset]->text = s;
813 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
815 newm->next = *wheretoput;
818 else if (md->merge == Metadata_merge_range)
820 assert(md->type == Metadata_type_year);
824 (*wheretoput)->data.number.min = first;
825 (*wheretoput)->data.number.max = last;
827 cluster->sortkeys[md->sortkey_offset] = &newm->data;
831 if (first < (*wheretoput)->data.number.min)
832 (*wheretoput)->data.number.min = first;
833 if (last > (*wheretoput)->data.number.max)
834 (*wheretoput)->data.number.max = last;
839 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
840 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
845 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
848 relevance_countwords(se->relevance, cluster,
849 (char *) value, md->rank);
852 if (md->type == Metadata_type_year)
855 sprintf(year, "%d", last);
856 add_facet(se, (char *) type, year);
859 sprintf(year, "%d", first);
860 add_facet(se, (char *) type, year);
864 add_facet(se, (char *) type, (char *) value);
871 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
880 relevance_donerecord(se->relevance, cluster);
886 // Retrieve first defined value for 'name' for given database.
887 // Will be extended to take into account user associated with session
888 char *session_setting_oneval(struct session_database *db, int offset)
890 if (!db->settings[offset])
892 return db->settings[offset]->value;
895 static void ingest_records(struct client *cl, Z_Records *r)
898 yaz_timing_t t = yaz_timing_create();
901 struct session *s = cl->session;
902 Z_NamePlusRecordList *rlist;
905 if (r->which != Z_Records_DBOSD)
907 rlist = r->u.databaseOrSurDiagnostics;
908 for (i = 0; i < rlist->num_records; i++)
910 Z_NamePlusRecord *npr = rlist->records[i];
913 if (npr->which != Z_NamePlusRecord_databaseRecord)
916 "Unexpected record type, probably diagnostic %s",
917 cl->database->database->url);
921 rec = ingest_record(cl, npr->u.databaseRecord);
925 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
926 session_alert_watch(s, SESSION_WATCH_RECORDS);
930 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
931 yaz_timing_get_real(t), yaz_timing_get_user(t),
932 yaz_timing_get_sys(t));
933 yaz_timing_destroy(&t);
937 static void do_presentResponse(IOCHAN i, Z_APDU *a)
939 struct connection *co = iochan_getdata(i);
940 struct client *cl = co->client;
941 Z_PresentResponse *r = a->u.presentResponse;
944 Z_Records *recs = r->records;
945 if (recs->which == Z_Records_NSD)
947 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
948 cl->database->database->url);
949 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
950 cl->state = Client_Error;
954 if (!*r->presentStatus && cl->state != Client_Error)
956 yaz_log(YLOG_DEBUG, "Good Present response %s",
957 cl->database->database->url);
958 ingest_records(cl, r->records);
959 cl->state = Client_Idle;
961 else if (*r->presentStatus)
963 yaz_log(YLOG_WARN, "Bad Present response %s",
964 cl->database->database->url);
965 cl->state = Client_Error;
969 static void handler(IOCHAN i, int event)
971 struct connection *co = iochan_getdata(i);
972 struct client *cl = co->client;
973 struct session *se = 0;
979 yaz_log(YLOG_WARN, "Destroying orphan connection");
980 connection_destroy(co);
984 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
987 socklen_t errlen = sizeof(errcode);
989 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
990 &errlen) < 0 || errcode != 0)
997 yaz_log(YLOG_DEBUG, "Connect OK");
998 co->state = Conn_Open;
1000 cl->state = Client_Connected;
1004 else if (event & EVENT_INPUT)
1006 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
1010 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
1011 cl->database->database->url);
1012 connection_destroy(co);
1017 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
1018 connection_destroy(co);
1021 else if (len > 1) // We discard input if we have no connection
1023 co->state = Conn_Open;
1025 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
1029 odr_reset(global_parameters.odr_in);
1030 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
1031 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
1038 case Z_APDU_initResponse:
1039 do_initResponse(i, a);
1041 case Z_APDU_searchResponse:
1042 do_searchResponse(i, a);
1044 case Z_APDU_presentResponse:
1045 do_presentResponse(i, a);
1048 do_closeResponse(i, a);
1052 "Unexpected Z39.50 response from %s",
1053 cl->database->database->url);
1057 // We aren't expecting staggered output from target
1058 // if (cs_more(t->link))
1059 // iochan_setevent(i, EVENT_INPUT);
1061 else // we throw away response and go to idle mode
1063 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
1064 cl->state = Client_Idle;
1067 /* if len==1 we do nothing but wait for more input */
1070 if (cl->state == Client_Connected) {
1074 if (cl->state == Client_Idle)
1076 if (cl->requestid != se->requestid && *se->query) {
1079 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
1080 cl->records < cl->hits) {
1086 // Disassociate connection from client
1087 static void connection_release(struct connection *co)
1089 struct client *cl = co->client;
1091 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1098 // Close connection and recycle structure
1099 static void connection_destroy(struct connection *co)
1101 struct host *h = co->host;
1103 iochan_destroy(co->iochan);
1105 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1106 if (h->connections == co)
1107 h->connections = co->next;
1110 struct connection *pco;
1111 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1114 pco->next = co->next;
1120 if (co->client->state != Client_Idle)
1121 co->client->state = Client_Disconnected;
1122 co->client->connection = 0;
1124 co->next = connection_freelist;
1125 connection_freelist = co;
1128 // Creates a new connection for client, associated with the host of
1129 // client's database
1130 static struct connection *connection_create(struct client *cl)
1132 struct connection *new;
1138 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1140 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1144 if (0 == strlen(global_parameters.zproxy_override)){
1145 /* no Z39.50 proxy needed - direct connect */
1146 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
1148 if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
1150 yaz_log(YLOG_WARN|YLOG_ERRNO,
1151 "Lookup of IP address %s failed",
1152 cl->database->database->host->ipport);
1157 /* Z39.50 proxy connect */
1158 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1159 cl->database->database->url, global_parameters.zproxy_override);
1161 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1163 yaz_log(YLOG_WARN|YLOG_ERRNO,
1164 "Lookup of IP address %s failed",
1165 global_parameters.zproxy_override);
1170 res = cs_connect(link, addr);
1173 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
1177 if ((new = connection_freelist))
1178 connection_freelist = new->next;
1181 new = xmalloc(sizeof (struct connection));
1185 new->state = Conn_Connecting;
1186 new->host = cl->database->database->host;
1187 new->next = new->host->connections;
1188 new->host->connections = new;
1190 cl->connection = new;
1193 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1194 iochan_setdata(new->iochan, new);
1195 new->iochan->next = channel_list;
1196 channel_list = new->iochan;
1200 // Close connection and set state to error
1201 static void client_fatal(struct client *cl)
1203 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
1204 connection_destroy(cl->connection);
1205 cl->state = Client_Error;
1208 // Ensure that client has a connection associated
1209 static int client_prep_connection(struct client *cl)
1211 struct connection *co;
1212 struct session *se = cl->session;
1213 struct host *host = cl->database->database->host;
1215 co = cl->connection;
1217 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
1221 // See if someone else has an idle connection
1222 // We should look at timestamps here to select the longest-idle connection
1223 for (co = host->connections; co; co = co->next)
1224 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1228 connection_release(co);
1229 cl->connection = co;
1233 co = connection_create(cl);
1237 if (co->state == Conn_Connecting)
1239 cl->state = Client_Connecting;
1240 iochan_setflag(co->iochan, EVENT_OUTPUT);
1242 else if (co->state == Conn_Open)
1244 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1245 cl->state = Client_Idle;
1246 iochan_setflag(co->iochan, EVENT_OUTPUT);
1254 // Parse the query given the settings specific to this client
1255 static int client_parse_query(struct client *cl)
1257 struct session *se = cl->session;
1258 struct ccl_rpn_node *cn;
1261 cn = ccl_find_str(cl->database->database->ccl_map, se->query, &cerror, &cpos);
1264 cl->state = Client_Error;
1265 yaz_log(YLOG_WARN, "Failed to parse query for %s",
1266 cl->database->database->url);
1269 wrbuf_rewind(se->wrbuf);
1270 ccl_pquery(se->wrbuf, cn);
1271 wrbuf_putc(se->wrbuf, '\0');
1274 cl->pquery = xstrdup(wrbuf_buf(se->wrbuf));
1278 // Initialize relevance structure with query terms
1280 extract_terms(se->nmem, cn, p);
1281 se->relevance = relevance_create(se->nmem, (const char **) p,
1282 se->expected_maxrecs);
1289 static struct client *client_create(void)
1292 if (client_freelist)
1294 r = client_freelist;
1295 client_freelist = client_freelist->next;
1298 r = xmalloc(sizeof(struct client));
1308 r->state = Client_Disconnected;
1313 void client_destroy(struct client *c)
1315 struct session *se = c->session;
1316 if (c == se->clients)
1317 se->clients = c->next;
1321 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1327 connection_release(c->connection);
1328 c->next = client_freelist;
1329 client_freelist = c;
1332 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1334 s->watchlist[what].fun = fun;
1335 s->watchlist[what].data = data;
1338 void session_alert_watch(struct session *s, int what)
1340 if (!s->watchlist[what].fun)
1342 (*s->watchlist[what].fun)(s->watchlist[what].data);
1343 s->watchlist[what].fun = 0;
1344 s->watchlist[what].data = 0;
1347 //callback for grep_databases
1348 static void select_targets_callback(void *context, struct session_database *db)
1350 struct session *se = (struct session*) context;
1351 struct client *cl = client_create();
1354 cl->next = se->clients;
1358 // Associates a set of clients with a session;
1359 // Note: Session-databases represent databases with per-session setting overrides
1360 int select_targets(struct session *se, struct database_criterion *crit)
1363 client_destroy(se->clients);
1365 return session_grep_databases(se, crit, select_targets_callback);
1368 int session_active_clients(struct session *s)
1373 for (c = s->clients; c; c = c->next)
1374 if (c->connection && (c->state == Client_Connecting ||
1375 c->state == Client_Initializing ||
1376 c->state == Client_Searching ||
1377 c->state == Client_Presenting))
1383 // parses crit1=val1,crit2=val2|val3,...
1384 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1386 struct database_criterion *res = 0;
1393 nmem_strsplit(m, ",", buf, &values, &num);
1394 for (i = 0; i < num; i++)
1399 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1400 char *eq = strchr(values[i], '=');
1403 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1407 new->name = values[i];
1408 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1410 for (subi = 0; subi < subnum; subi++)
1412 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1413 newv->value = subvalues[subi];
1414 newv->next = new->values;
1423 char *search(struct session *se, char *query, char *filter)
1425 int live_channels = 0;
1427 struct database_criterion *criteria;
1429 yaz_log(YLOG_DEBUG, "Search");
1431 nmem_reset(se->nmem);
1432 criteria = parse_filter(se->nmem, filter);
1433 strcpy(se->query, query);
1435 live_channels = select_targets(se, criteria);
1438 int maxrecs = live_channels * global_parameters.toget;
1439 se->num_termlists = 0;
1440 se->reclist = reclist_create(se->nmem, maxrecs);
1441 // This will be initialized in send_search()
1442 se->total_records = se->total_hits = se->total_merged = 0;
1443 se->expected_maxrecs = maxrecs;
1449 for (cl = se->clients; cl; cl = cl->next)
1450 if (client_parse_query(cl) < 0) // Query must parse for all targets
1452 for (cl = se->clients; cl; cl = cl->next)
1453 client_prep_connection(cl);
1458 // Apply a session override to a database
1459 void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
1461 struct session_database *sdb;
1463 for (sdb = se->databases; sdb; sdb = sdb->next)
1464 if (!strcmp(dbname, sdb->database->url))
1466 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
1467 int offset = settings_offset(setting);
1471 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
1474 new->precedence = 0;
1475 new->target = dbname;
1476 new->name = setting;
1478 new->next = sdb->settings[offset];
1479 sdb->settings[offset] = new;
1483 yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
1486 void session_init_databases_fun(void *context, struct database *db)
1488 struct session *se = (struct session *) context;
1489 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
1490 int num = settings_num();
1494 new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
1495 for (i = 0; i < num; i++)
1496 new->settings[i] = db->settings[i];
1497 new->next = se->databases;
1498 se->databases = new;
1501 // Initialize session_database list -- this represents this session's view
1502 // of the database list -- subject to modification by the settings ws command
1503 void session_init_databases(struct session *se)
1506 grep_databases(se, 0, session_init_databases_fun);
1509 void destroy_session(struct session *s)
1511 yaz_log(YLOG_LOG, "Destroying session");
1513 client_destroy(s->clients);
1514 nmem_destroy(s->nmem);
1515 wrbuf_destroy(s->wrbuf);
1518 struct session *new_session(NMEM nmem)
1521 struct session *session = nmem_malloc(nmem, sizeof(*session));
1523 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
1525 session->total_hits = 0;
1526 session->total_records = 0;
1527 session->num_termlists = 0;
1528 session->reclist = 0;
1529 session->requestid = -1;
1530 session->clients = 0;
1531 session->expected_maxrecs = 0;
1532 session->query[0] = '\0';
1533 session->session_nmem = nmem;
1534 session->nmem = nmem_create();
1535 session->wrbuf = wrbuf_alloc();
1536 session_init_databases(session);
1537 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1539 session->watchlist[i].data = 0;
1540 session->watchlist[i].fun = 0;
1546 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1548 static struct hitsbytarget res[1000]; // FIXME MM
1552 for (cl = se->clients; cl; cl = cl->next)
1554 char *name = session_setting_oneval(cl->database, PZ_NAME);
1556 res[*count].id = cl->database->database->url;
1557 res[*count].name = *name ? name : "Unknown";
1558 res[*count].hits = cl->hits;
1559 res[*count].records = cl->records;
1560 res[*count].diagnostic = cl->diagnostic;
1561 res[*count].state = client_states[cl->state];
1562 res[*count].connected = cl->connection ? 1 : 0;
1569 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1573 for (i = 0; i < s->num_termlists; i++)
1574 if (!strcmp((const char *) s->termlists[i].name, name))
1575 return termlist_highscore(s->termlists[i].termlist, num);
1579 #ifdef MISSING_HEADERS
1580 void report_nmem_stats(void)
1582 size_t in_use, is_free;
1584 nmem_get_memory_in_use(&in_use);
1585 nmem_get_memory_free(&is_free);
1587 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1588 (long) in_use, (long) is_free);
1592 struct record_cluster *show_single(struct session *s, int id)
1594 struct record_cluster *r;
1596 reclist_rewind(s->reclist);
1597 while ((r = reclist_read_record(s->reclist)))
1603 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1604 int *num, int *total, int *sumhits, NMEM nmem_show)
1606 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1607 * sizeof(struct record_cluster *));
1608 struct reclist_sortparms *spp;
1611 yaz_timing_t t = yaz_timing_create();
1614 for (spp = sp; spp; spp = spp->next)
1615 if (spp->type == Metadata_sortkey_relevance)
1617 relevance_prepare_read(s->relevance, s->reclist);
1620 reclist_sort(s->reclist, sp);
1622 *total = s->reclist->num_records;
1623 *sumhits = s->total_hits;
1625 for (i = 0; i < start; i++)
1626 if (!reclist_read_record(s->reclist))
1633 for (i = 0; i < *num; i++)
1635 struct record_cluster *r = reclist_read_record(s->reclist);
1645 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1646 yaz_timing_get_real(t), yaz_timing_get_user(t),
1647 yaz_timing_get_sys(t));
1648 yaz_timing_destroy(&t);
1653 void statistics(struct session *se, struct statistics *stat)
1658 memset(stat, 0, sizeof(*stat));
1659 for (cl = se->clients; cl; cl = cl->next)
1661 if (!cl->connection)
1662 stat->num_no_connection++;
1665 case Client_Connecting: stat->num_connecting++; break;
1666 case Client_Initializing: stat->num_initializing++; break;
1667 case Client_Searching: stat->num_searching++; break;
1668 case Client_Presenting: stat->num_presenting++; break;
1669 case Client_Idle: stat->num_idle++; break;
1670 case Client_Failed: stat->num_failed++; break;
1671 case Client_Error: stat->num_error++; break;
1676 stat->num_hits = se->total_hits;
1677 stat->num_records = se->total_records;
1679 stat->num_clients = count;
1682 void start_http_listener(void)
1685 struct conf_server *ser = global_parameters.server;
1687 if (*global_parameters.listener_override)
1688 strcpy(hp, global_parameters.listener_override);
1691 strcpy(hp, ser->host ? ser->host : "");
1696 sprintf(hp + strlen(hp), "%d", ser->port);
1702 void start_proxy(void)
1705 struct conf_server *ser = global_parameters.server;
1707 if (*global_parameters.proxy_override)
1708 strcpy(hp, global_parameters.proxy_override);
1709 else if (ser->proxy_host || ser->proxy_port)
1711 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1712 if (ser->proxy_port)
1716 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1722 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1725 void start_zproxy(void)
1727 struct conf_server *ser = global_parameters.server;
1729 if (*global_parameters.zproxy_override){
1730 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1731 global_parameters.zproxy_override);
1735 else if (ser->zproxy_host || ser->zproxy_port)
1739 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1740 if (ser->zproxy_port)
1747 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1749 strcpy(global_parameters.zproxy_override, hp);
1750 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1751 global_parameters.zproxy_override);
1763 * indent-tabs-mode: nil
1765 * vim: shiftwidth=4 tabstop=8 expandtab