1 /* $Id: logic.c,v 1.4 2007-04-17 07:52:03 marc 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 (MasterKey)",
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 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
217 pull_terms(nmem, n->u.p[0], termlist, num);
218 pull_terms(nmem, n->u.p[1], termlist, num);
221 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
228 // Extract terms from query into null-terminated termlist
229 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
233 pull_terms(nmem, query, termlist, &num);
237 static void send_search(IOCHAN i)
239 struct connection *co = iochan_getdata(i);
240 struct client *cl = co->client;
241 struct session *se = cl->session;
242 struct session_database *sdb = cl->database;
243 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
244 int ndb, cerror, cpos;
247 struct ccl_rpn_node *cn;
248 int ssub = 0, lslb = 100000, mspn = 10;
252 yaz_iconv_t iconv = 0;
254 yaz_log(YLOG_DEBUG, "Sending search to %s", cl->database->database->url);
256 cn = ccl_find_str(sdb->database->ccl_map, se->query, &cerror, &cpos);
262 // Initialize relevance structure with query terms
264 extract_terms(se->nmem, cn, p);
265 se->relevance = relevance_create(se->nmem, (const char **) p,
266 se->expected_maxrecs);
269 // constructing RPN query
270 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
272 zquery->which = Z_Query_type_1;
273 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
276 // converting to target encoding
277 if ((queryenc = session_setting_oneval(sdb, PZ_QUERYENCODING))){
278 iconv = yaz_iconv_open(queryenc, "UTF-8");
280 yaz_query_charset_convert_rpnquery(zquery->u.type_1,
281 global_parameters.odr_out,
283 yaz_iconv_close(iconv);
285 yaz_log(YLOG_WARN, "Query encoding failed %s %s",
286 cl->database->database->url, queryenc);
289 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
291 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
292 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
293 databaselist[ndb] = sdb->database->databases[ndb];
295 if (!(piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK)) || *piggyback == '1')
297 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
299 #if YAZ_VERSIONL >= 0x020163
300 a->u.searchRequest->preferredRecordSyntax =
301 yaz_string_to_oid_odr(yaz_oid_std(),
302 CLASS_RECSYN, recsyn,
303 global_parameters.odr_out);
305 a->u.searchRequest->preferredRecordSyntax =
306 yaz_str_to_z3950oid(global_parameters.odr_out,
307 CLASS_RECSYN, recsyn);
310 a->u.searchRequest->smallSetUpperBound = &ssub;
311 a->u.searchRequest->largeSetLowerBound = &lslb;
312 a->u.searchRequest->mediumSetPresentNumber = &mspn;
314 a->u.searchRequest->resultSetName = "Default";
315 a->u.searchRequest->databaseNames = databaselist;
316 a->u.searchRequest->num_databaseNames = ndb;
319 { //scope for sending and logging queries
320 WRBUF wbquery = wrbuf_alloc();
321 yaz_query_to_wrbuf(wbquery, zquery);
324 if (send_apdu(cl, a) >= 0)
326 iochan_setflags(i, EVENT_INPUT);
327 cl->state = Client_Searching;
328 cl->requestid = se->requestid;
329 yaz_log(YLOG_LOG, "SearchRequest %s %s %s",
330 cl->database->database->url,
331 queryenc ? queryenc : "UTF-8",
332 wrbuf_cstr(wbquery));
335 cl->state = Client_Error;
336 yaz_log(YLOG_WARN, "Failed SearchRequest %s %s %s",
337 cl->database->database->url,
338 queryenc ? queryenc : "UTF-8",
339 wrbuf_cstr(wbquery));
342 wrbuf_destroy(wbquery);
345 odr_reset(global_parameters.odr_out);
348 static void send_present(IOCHAN i)
350 struct connection *co = iochan_getdata(i);
351 struct client *cl = co->client;
352 struct session_database *sdb = cl->database;
353 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
355 int start = cl->records + 1;
358 toget = global_parameters.chunk;
359 if (toget > global_parameters.toget - cl->records)
360 toget = global_parameters.toget - cl->records;
361 if (toget > cl->hits - cl->records)
362 toget = cl->hits - cl->records;
364 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
366 a->u.presentRequest->resultSetStartPoint = &start;
367 a->u.presentRequest->numberOfRecordsRequested = &toget;
369 a->u.presentRequest->resultSetId = "Default";
371 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
373 #if YAZ_VERSIONL >= 0x020163
374 a->u.presentRequest->preferredRecordSyntax =
375 yaz_string_to_oid_odr(yaz_oid_std(),
376 CLASS_RECSYN, recsyn,
377 global_parameters.odr_out);
379 a->u.presentRequest->preferredRecordSyntax =
380 yaz_str_to_z3950oid(global_parameters.odr_out,
381 CLASS_RECSYN, recsyn);
385 if (send_apdu(cl, a) >= 0)
387 iochan_setflags(i, EVENT_INPUT);
388 cl->state = Client_Presenting;
391 cl->state = Client_Error;
392 odr_reset(global_parameters.odr_out);
395 static void do_initResponse(IOCHAN i, Z_APDU *a)
397 struct connection *co = iochan_getdata(i);
398 struct client *cl = co->client;
399 Z_InitResponse *r = a->u.initResponse;
401 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->database->url);
405 cl->state = Client_Idle;
408 cl->state = Client_Failed; // FIXME need to do something to the connection
411 static void do_searchResponse(IOCHAN i, Z_APDU *a)
413 struct connection *co = iochan_getdata(i);
414 struct client *cl = co->client;
415 struct session *se = cl->session;
416 Z_SearchResponse *r = a->u.searchResponse;
418 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
419 cl->database->database->url, *r->searchStatus);
421 if (*r->searchStatus)
423 cl->hits = *r->resultCount;
424 se->total_hits += cl->hits;
425 if (r->presentStatus && !*r->presentStatus && r->records)
427 yaz_log(YLOG_DEBUG, "Records in search response %s",
428 cl->database->database->url);
429 ingest_records(cl, r->records);
431 cl->state = Client_Idle;
436 cl->state = Client_Error;
438 Z_Records *recs = r->records;
439 if (recs->which == Z_Records_NSD)
442 "Search response: Non-surrogate diagnostic %s",
443 cl->database->database->url);
444 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
445 cl->state = Client_Error;
451 static void do_closeResponse(IOCHAN i, Z_APDU *a)
453 struct connection *co = iochan_getdata(i);
454 struct client *cl = co->client;
455 /* Z_Close *r = a->u.close; */
457 yaz_log(YLOG_WARN, "Close response %s", cl->database->database->url);
459 cl->state = Client_Failed;
460 connection_destroy(co);
464 char *normalize_mergekey(char *buf, int skiparticle)
466 char *p = buf, *pout = buf;
471 char articles[] = "the den der die des an a "; // must end in space
473 while (*p && !isalnum(*p))
476 while (*p && *p != ' ' && pout - firstword < 62)
477 *(pout++) = tolower(*(p++));
480 if (!strstr(articles, firstword))
487 while (*p && !isalnum(*p))
490 *(pout++) = tolower(*(p++));
493 while (*p && !isalnum(*p))
500 while (pout > buf && *pout == ' ');
505 static void add_facet(struct session *s, const char *type, const char *value)
511 for (i = 0; i < s->num_termlists; i++)
512 if (!strcmp(s->termlists[i].name, type))
514 if (i == s->num_termlists)
516 if (i == SESSION_MAX_TERMLISTS)
518 yaz_log(YLOG_FATAL, "Too many termlists");
521 s->termlists[i].name = nmem_strdup(s->nmem, type);
522 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
523 s->num_termlists = i + 1;
525 termlist_insert(s->termlists[i].termlist, value);
528 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
530 struct database_retrievalmap *m;
531 struct database *db = cl->database->database;
535 // First normalize to XML
540 if (rec->which != Z_External_octet)
542 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
543 cl->database->database->url);
546 buf = (char*) rec->u.octet_aligned->buf;
547 len = rec->u.octet_aligned->len;
548 if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
550 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
551 cl->database->database->url);
555 yaz_marc_write_using_libxml2(db->yaz_marc, 1);
556 if (yaz_marc_write_xml(db->yaz_marc, &res,
557 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
559 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
560 cl->database->database->url);
563 rdoc = xmlNewDoc((xmlChar *) "1.0");
564 xmlDocSetRootElement(rdoc, res);
570 "Unknown native_syntax in normalize_record from %s",
571 cl->database->database->url);
575 if (global_parameters.dump_records){
577 "Input Record (normalized) from %s\n----------------\n",
578 cl->database->database->url);
579 #if LIBXML_VERSION >= 20600
580 xmlDocFormatDump(stderr, rdoc, 1);
582 xmlDocDump(stderr, rdoc);
586 for (m = db->map; m; m = m->next){
592 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
593 root= xmlDocGetRootElement(new);
594 if (!new || !root || !(root->children))
596 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
597 cl->database->database->url);
606 // do it another way to detect transformation errors right now
607 // but does not seem to work either!
609 xsltTransformContextPtr ctxt;
610 ctxt = xsltNewTransformContext(m->stylesheet, rdoc);
611 new = xsltApplyStylesheetUser(m->stylesheet, rdoc, 0, 0, 0, ctxt);
612 if ((ctxt->state == XSLT_STATE_ERROR) ||
613 (ctxt->state == XSLT_STATE_STOPPED)){
614 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
615 cl->database->database->url);
626 if (global_parameters.dump_records)
628 fprintf(stderr, "Record from %s\n----------------\n",
629 cl->database->database->url);
630 #if LIBXML_VERSION >= 20600
631 xmlDocFormatDump(stderr, rdoc, 1);
633 xmlDocDump(stderr, rdoc);
639 // Extract what appears to be years from buf, storing highest and
641 static int extract_years(const char *buf, int *first, int *last)
650 while (*buf && !isdigit(*buf))
653 for (e = buf; *e && isdigit(*e); e++)
657 int value = atoi(buf);
658 if (*first < 0 || value < *first)
660 if (*last < 0 || value > *last)
668 static struct record *ingest_record(struct client *cl, Z_External *rec)
670 xmlDoc *xdoc = normalize_record(cl, rec);
673 struct record_cluster *cluster;
674 struct session *se = cl->session;
675 xmlChar *mergekey, *mergekey_norm;
678 struct conf_service *service = global_parameters.server->service;
683 root = xmlDocGetRootElement(xdoc);
684 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
686 yaz_log(YLOG_WARN, "No mergekey found in record");
691 res = nmem_malloc(se->nmem, sizeof(struct record));
694 res->metadata = nmem_malloc(se->nmem,
695 sizeof(struct record_metadata*) * service->num_metadata);
696 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
698 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
700 normalize_mergekey((char *) mergekey_norm, 0);
702 cluster = reclist_insert(se->reclist,
703 global_parameters.server->service,
704 res, (char *) mergekey_norm,
706 if (global_parameters.dump_records)
707 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
708 cl->database->database->url, cl->records);
711 /* no room for record */
715 relevance_newrec(se->relevance, cluster);
717 for (n = root->children; n; n = n->next)
725 if (n->type != XML_ELEMENT_NODE)
727 if (!strcmp((const char *) n->name, "metadata"))
729 struct conf_metadata *md = 0;
730 struct conf_sortkey *sk = 0;
731 struct record_metadata **wheretoput, *newm;
735 type = xmlGetProp(n, (xmlChar *) "type");
736 value = xmlNodeListGetString(xdoc, n->children, 0);
741 // First, find out what field we're looking at
742 for (imeta = 0; imeta < service->num_metadata; imeta++)
743 if (!strcmp((const char *) type, service->metadata[imeta].name))
745 md = &service->metadata[imeta];
746 if (md->sortkey_offset >= 0)
747 sk = &service->sortkeys[md->sortkey_offset];
752 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
756 // Find out where we are putting it
757 if (md->merge == Metadata_merge_no)
758 wheretoput = &res->metadata[imeta];
760 wheretoput = &cluster->metadata[imeta];
763 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
765 if (md->type == Metadata_type_generic)
768 for (p = (char *) value; *p && isspace(*p); p++)
770 for (pe = p + strlen(p) - 1;
771 pe > p && strchr(" ,/.:([", *pe); pe--)
773 newm->data.text = nmem_strdup(se->nmem, p);
776 else if (md->type == Metadata_type_year)
778 if (extract_years((char *) value, &first, &last) < 0)
783 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
786 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
788 yaz_log(YLOG_WARN, "Only range merging supported for years");
791 if (md->merge == Metadata_merge_unique)
793 struct record_metadata *mnode;
794 for (mnode = *wheretoput; mnode; mnode = mnode->next)
795 if (!strcmp((const char *) mnode->data.text, newm->data.text))
799 newm->next = *wheretoput;
803 else if (md->merge == Metadata_merge_longest)
806 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
811 char *s = nmem_strdup(se->nmem, newm->data.text);
812 if (!cluster->sortkeys[md->sortkey_offset])
813 cluster->sortkeys[md->sortkey_offset] =
814 nmem_malloc(se->nmem, sizeof(union data_types));
815 normalize_mergekey(s,
816 (sk->type == Metadata_sortkey_skiparticle));
817 cluster->sortkeys[md->sortkey_offset]->text = s;
821 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
823 newm->next = *wheretoput;
826 else if (md->merge == Metadata_merge_range)
828 assert(md->type == Metadata_type_year);
832 (*wheretoput)->data.number.min = first;
833 (*wheretoput)->data.number.max = last;
835 cluster->sortkeys[md->sortkey_offset] = &newm->data;
839 if (first < (*wheretoput)->data.number.min)
840 (*wheretoput)->data.number.min = first;
841 if (last > (*wheretoput)->data.number.max)
842 (*wheretoput)->data.number.max = last;
847 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
848 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
853 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
856 relevance_countwords(se->relevance, cluster,
857 (char *) value, md->rank);
860 if (md->type == Metadata_type_year)
863 sprintf(year, "%d", last);
864 add_facet(se, (char *) type, year);
867 sprintf(year, "%d", first);
868 add_facet(se, (char *) type, year);
872 add_facet(se, (char *) type, (char *) value);
879 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
888 relevance_donerecord(se->relevance, cluster);
894 // Retrieve first defined value for 'name' for given database.
895 // Will be extended to take into account user associated with session
896 char *session_setting_oneval(struct session_database *db, int offset)
898 if (!db->settings[offset])
900 return db->settings[offset]->value;
903 static void ingest_records(struct client *cl, Z_Records *r)
906 yaz_timing_t t = yaz_timing_create();
909 struct session *s = cl->session;
910 Z_NamePlusRecordList *rlist;
913 if (r->which != Z_Records_DBOSD)
915 rlist = r->u.databaseOrSurDiagnostics;
916 for (i = 0; i < rlist->num_records; i++)
918 Z_NamePlusRecord *npr = rlist->records[i];
921 if (npr->which != Z_NamePlusRecord_databaseRecord)
924 "Unexpected record type, probably diagnostic %s",
925 cl->database->database->url);
929 rec = ingest_record(cl, npr->u.databaseRecord);
933 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
934 session_alert_watch(s, SESSION_WATCH_RECORDS);
938 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
939 yaz_timing_get_real(t), yaz_timing_get_user(t),
940 yaz_timing_get_sys(t));
941 yaz_timing_destroy(&t);
945 static void do_presentResponse(IOCHAN i, Z_APDU *a)
947 struct connection *co = iochan_getdata(i);
948 struct client *cl = co->client;
949 Z_PresentResponse *r = a->u.presentResponse;
952 Z_Records *recs = r->records;
953 if (recs->which == Z_Records_NSD)
955 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
956 cl->database->database->url);
957 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
958 cl->state = Client_Error;
962 if (!*r->presentStatus && cl->state != Client_Error)
964 yaz_log(YLOG_DEBUG, "Good Present response %s",
965 cl->database->database->url);
966 ingest_records(cl, r->records);
967 cl->state = Client_Idle;
969 else if (*r->presentStatus)
971 yaz_log(YLOG_WARN, "Bad Present response %s",
972 cl->database->database->url);
973 cl->state = Client_Error;
977 static void handler(IOCHAN i, int event)
979 struct connection *co = iochan_getdata(i);
980 struct client *cl = co->client;
981 struct session *se = 0;
987 yaz_log(YLOG_WARN, "Destroying orphan connection");
988 connection_destroy(co);
992 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
995 socklen_t errlen = sizeof(errcode);
997 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
998 &errlen) < 0 || errcode != 0)
1005 yaz_log(YLOG_DEBUG, "Connect OK");
1006 co->state = Conn_Open;
1008 cl->state = Client_Connected;
1012 else if (event & EVENT_INPUT)
1014 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
1018 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
1019 cl->database->database->url);
1020 connection_destroy(co);
1025 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
1026 connection_destroy(co);
1029 else if (len > 1) // We discard input if we have no connection
1031 co->state = Conn_Open;
1033 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
1037 odr_reset(global_parameters.odr_in);
1038 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
1039 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
1046 case Z_APDU_initResponse:
1047 do_initResponse(i, a);
1049 case Z_APDU_searchResponse:
1050 do_searchResponse(i, a);
1052 case Z_APDU_presentResponse:
1053 do_presentResponse(i, a);
1056 do_closeResponse(i, a);
1060 "Unexpected Z39.50 response from %s",
1061 cl->database->database->url);
1065 // We aren't expecting staggered output from target
1066 // if (cs_more(t->link))
1067 // iochan_setevent(i, EVENT_INPUT);
1069 else // we throw away response and go to idle mode
1071 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
1072 cl->state = Client_Idle;
1075 /* if len==1 we do nothing but wait for more input */
1078 if (cl->state == Client_Connected) {
1082 if (cl->state == Client_Idle)
1084 if (cl->requestid != se->requestid && *se->query) {
1087 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
1088 cl->records < cl->hits) {
1094 // Disassociate connection from client
1095 static void connection_release(struct connection *co)
1097 struct client *cl = co->client;
1099 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1106 // Close connection and recycle structure
1107 static void connection_destroy(struct connection *co)
1109 struct host *h = co->host;
1111 iochan_destroy(co->iochan);
1113 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1114 if (h->connections == co)
1115 h->connections = co->next;
1118 struct connection *pco;
1119 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1122 pco->next = co->next;
1128 if (co->client->state != Client_Idle)
1129 co->client->state = Client_Disconnected;
1130 co->client->connection = 0;
1132 co->next = connection_freelist;
1133 connection_freelist = co;
1136 // Creates a new connection for client, associated with the host of
1137 // client's database
1138 static struct connection *connection_create(struct client *cl)
1140 struct connection *new;
1146 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1148 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1152 if (0 == strlen(global_parameters.zproxy_override)){
1153 /* no Z39.50 proxy needed - direct connect */
1154 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
1156 if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
1158 yaz_log(YLOG_WARN|YLOG_ERRNO,
1159 "Lookup of IP address %s failed",
1160 cl->database->database->host->ipport);
1165 /* Z39.50 proxy connect */
1166 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1167 cl->database->database->url, global_parameters.zproxy_override);
1169 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1171 yaz_log(YLOG_WARN|YLOG_ERRNO,
1172 "Lookup of IP address %s failed",
1173 global_parameters.zproxy_override);
1178 res = cs_connect(link, addr);
1181 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
1185 if ((new = connection_freelist))
1186 connection_freelist = new->next;
1189 new = xmalloc(sizeof (struct connection));
1193 new->state = Conn_Connecting;
1194 new->host = cl->database->database->host;
1195 new->next = new->host->connections;
1196 new->host->connections = new;
1198 cl->connection = new;
1201 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1202 iochan_setdata(new->iochan, new);
1203 new->iochan->next = channel_list;
1204 channel_list = new->iochan;
1208 // Close connection and set state to error
1209 static void client_fatal(struct client *cl)
1211 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
1212 connection_destroy(cl->connection);
1213 cl->state = Client_Error;
1216 // Ensure that client has a connection associated
1217 static int client_prep_connection(struct client *cl)
1219 struct connection *co;
1220 struct session *se = cl->session;
1221 struct host *host = cl->database->database->host;
1223 co = cl->connection;
1225 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
1229 // See if someone else has an idle connection
1230 // We should look at timestamps here to select the longest-idle connection
1231 for (co = host->connections; co; co = co->next)
1232 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1236 connection_release(co);
1237 cl->connection = co;
1241 co = connection_create(cl);
1245 if (co->state == Conn_Connecting)
1247 cl->state = Client_Connecting;
1248 iochan_setflag(co->iochan, EVENT_OUTPUT);
1250 else if (co->state == Conn_Open)
1252 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1253 cl->state = Client_Idle;
1254 iochan_setflag(co->iochan, EVENT_OUTPUT);
1262 static struct client *client_create(void)
1265 if (client_freelist)
1267 r = client_freelist;
1268 client_freelist = client_freelist->next;
1271 r = xmalloc(sizeof(struct client));
1280 r->state = Client_Disconnected;
1285 void client_destroy(struct client *c)
1287 struct session *se = c->session;
1288 if (c == se->clients)
1289 se->clients = c->next;
1293 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1299 connection_release(c->connection);
1300 c->next = client_freelist;
1301 client_freelist = c;
1304 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1306 s->watchlist[what].fun = fun;
1307 s->watchlist[what].data = data;
1310 void session_alert_watch(struct session *s, int what)
1312 if (!s->watchlist[what].fun)
1314 (*s->watchlist[what].fun)(s->watchlist[what].data);
1315 s->watchlist[what].fun = 0;
1316 s->watchlist[what].data = 0;
1319 //callback for grep_databases
1320 static void select_targets_callback(void *context, struct session_database *db)
1322 struct session *se = (struct session*) context;
1323 struct client *cl = client_create();
1326 cl->next = se->clients;
1330 // Associates a set of clients with a session;
1331 // Note: Session-databases represent databases with per-session setting overrides
1332 int select_targets(struct session *se, struct database_criterion *crit)
1335 client_destroy(se->clients);
1337 return session_grep_databases(se, crit, select_targets_callback);
1340 int session_active_clients(struct session *s)
1345 for (c = s->clients; c; c = c->next)
1346 if (c->connection && (c->state == Client_Connecting ||
1347 c->state == Client_Initializing ||
1348 c->state == Client_Searching ||
1349 c->state == Client_Presenting))
1355 // parses crit1=val1,crit2=val2|val3,...
1356 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1358 struct database_criterion *res = 0;
1365 nmem_strsplit(m, ",", buf, &values, &num);
1366 for (i = 0; i < num; i++)
1371 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1372 char *eq = strchr(values[i], '=');
1375 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1379 new->name = values[i];
1380 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1382 for (subi = 0; subi < subnum; subi++)
1384 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1385 newv->value = subvalues[subi];
1386 newv->next = new->values;
1395 char *search(struct session *se, char *query, char *filter)
1397 int live_channels = 0;
1399 struct database_criterion *criteria;
1401 yaz_log(YLOG_DEBUG, "Search");
1403 nmem_reset(se->nmem);
1404 criteria = parse_filter(se->nmem, filter);
1405 strcpy(se->query, query);
1407 select_targets(se, criteria);
1408 for (cl = se->clients; cl; cl = cl->next)
1410 if (client_prep_connection(cl))
1415 int maxrecs = live_channels * global_parameters.toget;
1416 se->num_termlists = 0;
1417 se->reclist = reclist_create(se->nmem, maxrecs);
1418 // This will be initialized in send_search()
1420 se->total_records = se->total_hits = se->total_merged = 0;
1421 se->expected_maxrecs = maxrecs;
1429 // Apply a session override to a database
1430 void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
1432 struct session_database *sdb;
1434 for (sdb = se->databases; sdb; sdb = sdb->next)
1435 if (!strcmp(dbname, sdb->database->url))
1437 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
1438 int offset = settings_offset(setting);
1442 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
1445 new->precedence = 0;
1446 new->target = dbname;
1447 new->name = setting;
1449 new->next = sdb->settings[offset];
1450 sdb->settings[offset] = new;
1454 yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
1457 void session_init_databases_fun(void *context, struct database *db)
1459 struct session *se = (struct session *) context;
1460 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
1461 int num = settings_num();
1465 new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
1466 for (i = 0; i < num; i++)
1467 new->settings[i] = db->settings[i];
1468 new->next = se->databases;
1469 se->databases = new;
1472 // Initialize session_database list -- this represents this session's view
1473 // of the database list -- subject to modification by the settings ws command
1474 void session_init_databases(struct session *se)
1477 grep_databases(se, 0, session_init_databases_fun);
1480 void destroy_session(struct session *s)
1482 yaz_log(YLOG_LOG, "Destroying session");
1484 client_destroy(s->clients);
1485 nmem_destroy(s->nmem);
1486 wrbuf_destroy(s->wrbuf);
1489 struct session *new_session(NMEM nmem)
1492 struct session *session = nmem_malloc(nmem, sizeof(*session));
1494 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
1496 session->total_hits = 0;
1497 session->total_records = 0;
1498 session->num_termlists = 0;
1499 session->reclist = 0;
1500 session->requestid = -1;
1501 session->clients = 0;
1502 session->expected_maxrecs = 0;
1503 session->query[0] = '\0';
1504 session->session_nmem = nmem;
1505 session->nmem = nmem_create();
1506 session->wrbuf = wrbuf_alloc();
1507 session_init_databases(session);
1508 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1510 session->watchlist[i].data = 0;
1511 session->watchlist[i].fun = 0;
1517 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1519 static struct hitsbytarget res[1000]; // FIXME MM
1523 for (cl = se->clients; cl; cl = cl->next)
1525 char *name = session_setting_oneval(cl->database, PZ_NAME);
1527 res[*count].id = cl->database->database->url;
1528 res[*count].name = *name ? name : "Unknown";
1529 res[*count].hits = cl->hits;
1530 res[*count].records = cl->records;
1531 res[*count].diagnostic = cl->diagnostic;
1532 res[*count].state = client_states[cl->state];
1533 res[*count].connected = cl->connection ? 1 : 0;
1540 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1544 for (i = 0; i < s->num_termlists; i++)
1545 if (!strcmp((const char *) s->termlists[i].name, name))
1546 return termlist_highscore(s->termlists[i].termlist, num);
1550 #ifdef MISSING_HEADERS
1551 void report_nmem_stats(void)
1553 size_t in_use, is_free;
1555 nmem_get_memory_in_use(&in_use);
1556 nmem_get_memory_free(&is_free);
1558 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1559 (long) in_use, (long) is_free);
1563 struct record_cluster *show_single(struct session *s, int id)
1565 struct record_cluster *r;
1567 reclist_rewind(s->reclist);
1568 while ((r = reclist_read_record(s->reclist)))
1574 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1575 int *num, int *total, int *sumhits, NMEM nmem_show)
1577 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1578 * sizeof(struct record_cluster *));
1579 struct reclist_sortparms *spp;
1582 yaz_timing_t t = yaz_timing_create();
1585 for (spp = sp; spp; spp = spp->next)
1586 if (spp->type == Metadata_sortkey_relevance)
1588 relevance_prepare_read(s->relevance, s->reclist);
1591 reclist_sort(s->reclist, sp);
1593 *total = s->reclist->num_records;
1594 *sumhits = s->total_hits;
1596 for (i = 0; i < start; i++)
1597 if (!reclist_read_record(s->reclist))
1604 for (i = 0; i < *num; i++)
1606 struct record_cluster *r = reclist_read_record(s->reclist);
1616 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1617 yaz_timing_get_real(t), yaz_timing_get_user(t),
1618 yaz_timing_get_sys(t));
1619 yaz_timing_destroy(&t);
1624 void statistics(struct session *se, struct statistics *stat)
1629 memset(stat, 0, sizeof(*stat));
1630 for (cl = se->clients; cl; cl = cl->next)
1632 if (!cl->connection)
1633 stat->num_no_connection++;
1636 case Client_Connecting: stat->num_connecting++; break;
1637 case Client_Initializing: stat->num_initializing++; break;
1638 case Client_Searching: stat->num_searching++; break;
1639 case Client_Presenting: stat->num_presenting++; break;
1640 case Client_Idle: stat->num_idle++; break;
1641 case Client_Failed: stat->num_failed++; break;
1642 case Client_Error: stat->num_error++; break;
1647 stat->num_hits = se->total_hits;
1648 stat->num_records = se->total_records;
1650 stat->num_clients = count;
1653 void start_http_listener(void)
1656 struct conf_server *ser = global_parameters.server;
1658 if (*global_parameters.listener_override)
1659 strcpy(hp, global_parameters.listener_override);
1662 strcpy(hp, ser->host ? ser->host : "");
1667 sprintf(hp + strlen(hp), "%d", ser->port);
1673 void start_proxy(void)
1676 struct conf_server *ser = global_parameters.server;
1678 if (*global_parameters.proxy_override)
1679 strcpy(hp, global_parameters.proxy_override);
1680 else if (ser->proxy_host || ser->proxy_port)
1682 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1683 if (ser->proxy_port)
1687 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1693 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1696 void start_zproxy(void)
1698 struct conf_server *ser = global_parameters.server;
1700 if (*global_parameters.zproxy_override){
1701 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1702 global_parameters.zproxy_override);
1706 else if (ser->zproxy_host || ser->zproxy_port)
1710 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1711 if (ser->zproxy_port)
1718 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1720 strcpy(global_parameters.zproxy_override, hp);
1721 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1722 global_parameters.zproxy_override);
1734 * indent-tabs-mode: nil
1736 * vim: shiftwidth=4 tabstop=8 expandtab