1 /* $Id: logic.c,v 1.3 2007-04-16 21:54:43 adam 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(global_parameters.server->service, se->reclist, res, (char *) mergekey_norm,
704 if (global_parameters.dump_records)
705 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
706 cl->database->database->url, cl->records);
709 /* no room for record */
713 relevance_newrec(se->relevance, cluster);
715 for (n = root->children; n; n = n->next)
723 if (n->type != XML_ELEMENT_NODE)
725 if (!strcmp((const char *) n->name, "metadata"))
727 struct conf_metadata *md = 0;
728 struct conf_sortkey *sk = 0;
729 struct record_metadata **wheretoput, *newm;
733 type = xmlGetProp(n, (xmlChar *) "type");
734 value = xmlNodeListGetString(xdoc, n->children, 0);
739 // First, find out what field we're looking at
740 for (imeta = 0; imeta < service->num_metadata; imeta++)
741 if (!strcmp((const char *) type, service->metadata[imeta].name))
743 md = &service->metadata[imeta];
744 if (md->sortkey_offset >= 0)
745 sk = &service->sortkeys[md->sortkey_offset];
750 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
754 // Find out where we are putting it
755 if (md->merge == Metadata_merge_no)
756 wheretoput = &res->metadata[imeta];
758 wheretoput = &cluster->metadata[imeta];
761 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
763 if (md->type == Metadata_type_generic)
766 for (p = (char *) value; *p && isspace(*p); p++)
768 for (pe = p + strlen(p) - 1;
769 pe > p && strchr(" ,/.:([", *pe); pe--)
771 newm->data.text = nmem_strdup(se->nmem, p);
774 else if (md->type == Metadata_type_year)
776 if (extract_years((char *) value, &first, &last) < 0)
781 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
784 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
786 yaz_log(YLOG_WARN, "Only range merging supported for years");
789 if (md->merge == Metadata_merge_unique)
791 struct record_metadata *mnode;
792 for (mnode = *wheretoput; mnode; mnode = mnode->next)
793 if (!strcmp((const char *) mnode->data.text, newm->data.text))
797 newm->next = *wheretoput;
801 else if (md->merge == Metadata_merge_longest)
804 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
809 char *s = nmem_strdup(se->nmem, newm->data.text);
810 if (!cluster->sortkeys[md->sortkey_offset])
811 cluster->sortkeys[md->sortkey_offset] =
812 nmem_malloc(se->nmem, sizeof(union data_types));
813 normalize_mergekey(s,
814 (sk->type == Metadata_sortkey_skiparticle));
815 cluster->sortkeys[md->sortkey_offset]->text = s;
819 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
821 newm->next = *wheretoput;
824 else if (md->merge == Metadata_merge_range)
826 assert(md->type == Metadata_type_year);
830 (*wheretoput)->data.number.min = first;
831 (*wheretoput)->data.number.max = last;
833 cluster->sortkeys[md->sortkey_offset] = &newm->data;
837 if (first < (*wheretoput)->data.number.min)
838 (*wheretoput)->data.number.min = first;
839 if (last > (*wheretoput)->data.number.max)
840 (*wheretoput)->data.number.max = last;
845 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
846 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
851 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
854 relevance_countwords(se->relevance, cluster,
855 (char *) value, md->rank);
858 if (md->type == Metadata_type_year)
861 sprintf(year, "%d", last);
862 add_facet(se, (char *) type, year);
865 sprintf(year, "%d", first);
866 add_facet(se, (char *) type, year);
870 add_facet(se, (char *) type, (char *) value);
877 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
886 relevance_donerecord(se->relevance, cluster);
892 // Retrieve first defined value for 'name' for given database.
893 // Will be extended to take into account user associated with session
894 char *session_setting_oneval(struct session_database *db, int offset)
896 if (!db->settings[offset])
898 return db->settings[offset]->value;
901 static void ingest_records(struct client *cl, Z_Records *r)
904 yaz_timing_t t = yaz_timing_create();
907 struct session *s = cl->session;
908 Z_NamePlusRecordList *rlist;
911 if (r->which != Z_Records_DBOSD)
913 rlist = r->u.databaseOrSurDiagnostics;
914 for (i = 0; i < rlist->num_records; i++)
916 Z_NamePlusRecord *npr = rlist->records[i];
919 if (npr->which != Z_NamePlusRecord_databaseRecord)
922 "Unexpected record type, probably diagnostic %s",
923 cl->database->database->url);
927 rec = ingest_record(cl, npr->u.databaseRecord);
931 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
932 session_alert_watch(s, SESSION_WATCH_RECORDS);
936 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
937 yaz_timing_get_real(t), yaz_timing_get_user(t),
938 yaz_timing_get_sys(t));
939 yaz_timing_destroy(&t);
943 static void do_presentResponse(IOCHAN i, Z_APDU *a)
945 struct connection *co = iochan_getdata(i);
946 struct client *cl = co->client;
947 Z_PresentResponse *r = a->u.presentResponse;
950 Z_Records *recs = r->records;
951 if (recs->which == Z_Records_NSD)
953 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
954 cl->database->database->url);
955 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
956 cl->state = Client_Error;
960 if (!*r->presentStatus && cl->state != Client_Error)
962 yaz_log(YLOG_DEBUG, "Good Present response %s",
963 cl->database->database->url);
964 ingest_records(cl, r->records);
965 cl->state = Client_Idle;
967 else if (*r->presentStatus)
969 yaz_log(YLOG_WARN, "Bad Present response %s",
970 cl->database->database->url);
971 cl->state = Client_Error;
975 static void handler(IOCHAN i, int event)
977 struct connection *co = iochan_getdata(i);
978 struct client *cl = co->client;
979 struct session *se = 0;
985 yaz_log(YLOG_WARN, "Destroying orphan connection");
986 connection_destroy(co);
990 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
993 socklen_t errlen = sizeof(errcode);
995 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
996 &errlen) < 0 || errcode != 0)
1003 yaz_log(YLOG_DEBUG, "Connect OK");
1004 co->state = Conn_Open;
1006 cl->state = Client_Connected;
1010 else if (event & EVENT_INPUT)
1012 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
1016 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
1017 cl->database->database->url);
1018 connection_destroy(co);
1023 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
1024 connection_destroy(co);
1027 else if (len > 1) // We discard input if we have no connection
1029 co->state = Conn_Open;
1031 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
1035 odr_reset(global_parameters.odr_in);
1036 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
1037 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
1044 case Z_APDU_initResponse:
1045 do_initResponse(i, a);
1047 case Z_APDU_searchResponse:
1048 do_searchResponse(i, a);
1050 case Z_APDU_presentResponse:
1051 do_presentResponse(i, a);
1054 do_closeResponse(i, a);
1058 "Unexpected Z39.50 response from %s",
1059 cl->database->database->url);
1063 // We aren't expecting staggered output from target
1064 // if (cs_more(t->link))
1065 // iochan_setevent(i, EVENT_INPUT);
1067 else // we throw away response and go to idle mode
1069 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
1070 cl->state = Client_Idle;
1073 /* if len==1 we do nothing but wait for more input */
1076 if (cl->state == Client_Connected) {
1080 if (cl->state == Client_Idle)
1082 if (cl->requestid != se->requestid && *se->query) {
1085 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
1086 cl->records < cl->hits) {
1092 // Disassociate connection from client
1093 static void connection_release(struct connection *co)
1095 struct client *cl = co->client;
1097 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1104 // Close connection and recycle structure
1105 static void connection_destroy(struct connection *co)
1107 struct host *h = co->host;
1109 iochan_destroy(co->iochan);
1111 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1112 if (h->connections == co)
1113 h->connections = co->next;
1116 struct connection *pco;
1117 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1120 pco->next = co->next;
1126 if (co->client->state != Client_Idle)
1127 co->client->state = Client_Disconnected;
1128 co->client->connection = 0;
1130 co->next = connection_freelist;
1131 connection_freelist = co;
1134 // Creates a new connection for client, associated with the host of
1135 // client's database
1136 static struct connection *connection_create(struct client *cl)
1138 struct connection *new;
1144 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1146 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1150 if (0 == strlen(global_parameters.zproxy_override)){
1151 /* no Z39.50 proxy needed - direct connect */
1152 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
1154 if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
1156 yaz_log(YLOG_WARN|YLOG_ERRNO,
1157 "Lookup of IP address %s failed",
1158 cl->database->database->host->ipport);
1163 /* Z39.50 proxy connect */
1164 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1165 cl->database->database->url, global_parameters.zproxy_override);
1167 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1169 yaz_log(YLOG_WARN|YLOG_ERRNO,
1170 "Lookup of IP address %s failed",
1171 global_parameters.zproxy_override);
1176 res = cs_connect(link, addr);
1179 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
1183 if ((new = connection_freelist))
1184 connection_freelist = new->next;
1187 new = xmalloc(sizeof (struct connection));
1191 new->state = Conn_Connecting;
1192 new->host = cl->database->database->host;
1193 new->next = new->host->connections;
1194 new->host->connections = new;
1196 cl->connection = new;
1199 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1200 iochan_setdata(new->iochan, new);
1201 new->iochan->next = channel_list;
1202 channel_list = new->iochan;
1206 // Close connection and set state to error
1207 static void client_fatal(struct client *cl)
1209 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
1210 connection_destroy(cl->connection);
1211 cl->state = Client_Error;
1214 // Ensure that client has a connection associated
1215 static int client_prep_connection(struct client *cl)
1217 struct connection *co;
1218 struct session *se = cl->session;
1219 struct host *host = cl->database->database->host;
1221 co = cl->connection;
1223 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
1227 // See if someone else has an idle connection
1228 // We should look at timestamps here to select the longest-idle connection
1229 for (co = host->connections; co; co = co->next)
1230 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1234 connection_release(co);
1235 cl->connection = co;
1239 co = connection_create(cl);
1243 if (co->state == Conn_Connecting)
1245 cl->state = Client_Connecting;
1246 iochan_setflag(co->iochan, EVENT_OUTPUT);
1248 else if (co->state == Conn_Open)
1250 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1251 cl->state = Client_Idle;
1252 iochan_setflag(co->iochan, EVENT_OUTPUT);
1260 static struct client *client_create(void)
1263 if (client_freelist)
1265 r = client_freelist;
1266 client_freelist = client_freelist->next;
1269 r = xmalloc(sizeof(struct client));
1278 r->state = Client_Disconnected;
1283 void client_destroy(struct client *c)
1285 struct session *se = c->session;
1286 if (c == se->clients)
1287 se->clients = c->next;
1291 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1297 connection_release(c->connection);
1298 c->next = client_freelist;
1299 client_freelist = c;
1302 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1304 s->watchlist[what].fun = fun;
1305 s->watchlist[what].data = data;
1308 void session_alert_watch(struct session *s, int what)
1310 if (!s->watchlist[what].fun)
1312 (*s->watchlist[what].fun)(s->watchlist[what].data);
1313 s->watchlist[what].fun = 0;
1314 s->watchlist[what].data = 0;
1317 //callback for grep_databases
1318 static void select_targets_callback(void *context, struct session_database *db)
1320 struct session *se = (struct session*) context;
1321 struct client *cl = client_create();
1324 cl->next = se->clients;
1328 // Associates a set of clients with a session;
1329 // Note: Session-databases represent databases with per-session setting overrides
1330 int select_targets(struct session *se, struct database_criterion *crit)
1333 client_destroy(se->clients);
1335 return session_grep_databases(se, crit, select_targets_callback);
1338 int session_active_clients(struct session *s)
1343 for (c = s->clients; c; c = c->next)
1344 if (c->connection && (c->state == Client_Connecting ||
1345 c->state == Client_Initializing ||
1346 c->state == Client_Searching ||
1347 c->state == Client_Presenting))
1353 // parses crit1=val1,crit2=val2|val3,...
1354 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1356 struct database_criterion *res = 0;
1363 nmem_strsplit(m, ",", buf, &values, &num);
1364 for (i = 0; i < num; i++)
1369 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1370 char *eq = strchr(values[i], '=');
1373 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1377 new->name = values[i];
1378 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1380 for (subi = 0; subi < subnum; subi++)
1382 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1383 newv->value = subvalues[subi];
1384 newv->next = new->values;
1393 char *search(struct session *se, char *query, char *filter)
1395 int live_channels = 0;
1397 struct database_criterion *criteria;
1399 yaz_log(YLOG_DEBUG, "Search");
1401 nmem_reset(se->nmem);
1402 criteria = parse_filter(se->nmem, filter);
1403 strcpy(se->query, query);
1405 select_targets(se, criteria);
1406 for (cl = se->clients; cl; cl = cl->next)
1408 if (client_prep_connection(cl))
1413 int maxrecs = live_channels * global_parameters.toget;
1414 se->num_termlists = 0;
1415 se->reclist = reclist_create(se->nmem, maxrecs);
1416 // This will be initialized in send_search()
1418 se->total_records = se->total_hits = se->total_merged = 0;
1419 se->expected_maxrecs = maxrecs;
1427 // Apply a session override to a database
1428 void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
1430 struct session_database *sdb;
1432 for (sdb = se->databases; sdb; sdb = sdb->next)
1433 if (!strcmp(dbname, sdb->database->url))
1435 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
1436 int offset = settings_offset(setting);
1440 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
1443 new->precedence = 0;
1444 new->target = dbname;
1445 new->name = setting;
1447 new->next = sdb->settings[offset];
1448 sdb->settings[offset] = new;
1452 yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
1455 void session_init_databases_fun(void *context, struct database *db)
1457 struct session *se = (struct session *) context;
1458 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
1459 int num = settings_num();
1463 new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
1464 for (i = 0; i < num; i++)
1465 new->settings[i] = db->settings[i];
1466 new->next = se->databases;
1467 se->databases = new;
1470 // Initialize session_database list -- this represents this session's view
1471 // of the database list -- subject to modification by the settings ws command
1472 void session_init_databases(struct session *se)
1475 grep_databases(se, 0, session_init_databases_fun);
1478 void destroy_session(struct session *s)
1480 yaz_log(YLOG_LOG, "Destroying session");
1482 client_destroy(s->clients);
1483 nmem_destroy(s->nmem);
1484 wrbuf_destroy(s->wrbuf);
1487 struct session *new_session(NMEM nmem)
1490 struct session *session = nmem_malloc(nmem, sizeof(*session));
1492 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
1494 session->total_hits = 0;
1495 session->total_records = 0;
1496 session->num_termlists = 0;
1497 session->reclist = 0;
1498 session->requestid = -1;
1499 session->clients = 0;
1500 session->expected_maxrecs = 0;
1501 session->query[0] = '\0';
1502 session->session_nmem = nmem;
1503 session->nmem = nmem_create();
1504 session->wrbuf = wrbuf_alloc();
1505 session_init_databases(session);
1506 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1508 session->watchlist[i].data = 0;
1509 session->watchlist[i].fun = 0;
1515 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1517 static struct hitsbytarget res[1000]; // FIXME MM
1521 for (cl = se->clients; cl; cl = cl->next)
1523 char *name = session_setting_oneval(cl->database, PZ_NAME);
1525 res[*count].id = cl->database->database->url;
1526 res[*count].name = *name ? name : "Unknown";
1527 res[*count].hits = cl->hits;
1528 res[*count].records = cl->records;
1529 res[*count].diagnostic = cl->diagnostic;
1530 res[*count].state = client_states[cl->state];
1531 res[*count].connected = cl->connection ? 1 : 0;
1538 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1542 for (i = 0; i < s->num_termlists; i++)
1543 if (!strcmp((const char *) s->termlists[i].name, name))
1544 return termlist_highscore(s->termlists[i].termlist, num);
1548 #ifdef MISSING_HEADERS
1549 void report_nmem_stats(void)
1551 size_t in_use, is_free;
1553 nmem_get_memory_in_use(&in_use);
1554 nmem_get_memory_free(&is_free);
1556 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1557 (long) in_use, (long) is_free);
1561 struct record_cluster *show_single(struct session *s, int id)
1563 struct record_cluster *r;
1565 reclist_rewind(s->reclist);
1566 while ((r = reclist_read_record(s->reclist)))
1572 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1573 int *num, int *total, int *sumhits, NMEM nmem_show)
1575 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1576 * sizeof(struct record_cluster *));
1577 struct reclist_sortparms *spp;
1580 yaz_timing_t t = yaz_timing_create();
1583 for (spp = sp; spp; spp = spp->next)
1584 if (spp->type == Metadata_sortkey_relevance)
1586 relevance_prepare_read(s->relevance, s->reclist);
1589 reclist_sort(s->reclist, sp);
1591 *total = s->reclist->num_records;
1592 *sumhits = s->total_hits;
1594 for (i = 0; i < start; i++)
1595 if (!reclist_read_record(s->reclist))
1602 for (i = 0; i < *num; i++)
1604 struct record_cluster *r = reclist_read_record(s->reclist);
1614 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1615 yaz_timing_get_real(t), yaz_timing_get_user(t),
1616 yaz_timing_get_sys(t));
1617 yaz_timing_destroy(&t);
1622 void statistics(struct session *se, struct statistics *stat)
1627 memset(stat, 0, sizeof(*stat));
1628 for (cl = se->clients; cl; cl = cl->next)
1630 if (!cl->connection)
1631 stat->num_no_connection++;
1634 case Client_Connecting: stat->num_connecting++; break;
1635 case Client_Initializing: stat->num_initializing++; break;
1636 case Client_Searching: stat->num_searching++; break;
1637 case Client_Presenting: stat->num_presenting++; break;
1638 case Client_Idle: stat->num_idle++; break;
1639 case Client_Failed: stat->num_failed++; break;
1640 case Client_Error: stat->num_error++; break;
1645 stat->num_hits = se->total_hits;
1646 stat->num_records = se->total_records;
1648 stat->num_clients = count;
1651 void start_http_listener(void)
1654 struct conf_server *ser = global_parameters.server;
1656 if (*global_parameters.listener_override)
1657 strcpy(hp, global_parameters.listener_override);
1660 strcpy(hp, ser->host ? ser->host : "");
1665 sprintf(hp + strlen(hp), "%d", ser->port);
1671 void start_proxy(void)
1674 struct conf_server *ser = global_parameters.server;
1676 if (*global_parameters.proxy_override)
1677 strcpy(hp, global_parameters.proxy_override);
1678 else if (ser->proxy_host || ser->proxy_port)
1680 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1681 if (ser->proxy_port)
1685 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1691 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1694 void start_zproxy(void)
1696 struct conf_server *ser = global_parameters.server;
1698 if (*global_parameters.zproxy_override){
1699 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1700 global_parameters.zproxy_override);
1704 else if (ser->zproxy_host || ser->zproxy_port)
1708 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1709 if (ser->zproxy_port)
1716 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1718 strcpy(global_parameters.zproxy_override, hp);
1719 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1720 global_parameters.zproxy_override);
1732 * indent-tabs-mode: nil
1734 * vim: shiftwidth=4 tabstop=8 expandtab