1 /* $Id: logic.c,v 1.2 2007-04-16 13:22:17 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 const int *oid_proxy = yaz_string_to_oid(yaz_oid_std(),
189 CLASS_USERINFO, OID_STR_PROXY);
190 yaz_oi_set_string_oid(&a->u.initRequest->otherInfo,
191 global_parameters.odr_out, oid_proxy,
192 1, cl->database->database->url);
194 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
195 global_parameters.odr_out, VAL_PROXY,
196 1, cl->database->database->url);
200 if (send_apdu(cl, a) >= 0)
202 iochan_setflags(i, EVENT_INPUT);
203 cl->state = Client_Initializing;
206 cl->state = Client_Error;
207 odr_reset(global_parameters.odr_out);
210 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
218 pull_terms(nmem, n->u.p[0], termlist, num);
219 pull_terms(nmem, n->u.p[1], termlist, num);
222 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
229 // Extract terms from query into null-terminated termlist
230 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
234 pull_terms(nmem, query, termlist, &num);
238 static void send_search(IOCHAN i)
240 struct connection *co = iochan_getdata(i);
241 struct client *cl = co->client;
242 struct session *se = cl->session;
243 struct session_database *sdb = cl->database;
244 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
245 int ndb, cerror, cpos;
248 struct ccl_rpn_node *cn;
249 int ssub = 0, lslb = 100000, mspn = 10;
253 yaz_iconv_t iconv = 0;
255 yaz_log(YLOG_DEBUG, "Sending search to %s", cl->database->database->url);
257 cn = ccl_find_str(sdb->database->ccl_map, se->query, &cerror, &cpos);
263 // Initialize relevance structure with query terms
265 extract_terms(se->nmem, cn, p);
266 se->relevance = relevance_create(se->nmem, (const char **) p,
267 se->expected_maxrecs);
270 // constructing RPN query
271 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
273 zquery->which = Z_Query_type_1;
274 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
277 // converting to target encoding
278 if ((queryenc = session_setting_oneval(sdb, PZ_QUERYENCODING))){
279 iconv = yaz_iconv_open(queryenc, "UTF-8");
281 yaz_query_charset_convert_rpnquery(zquery->u.type_1,
282 global_parameters.odr_out,
284 yaz_iconv_close(iconv);
286 yaz_log(YLOG_WARN, "Query encoding failed %s %s",
287 cl->database->database->url, queryenc);
290 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
292 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
293 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
294 databaselist[ndb] = sdb->database->databases[ndb];
296 if (!(piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK)) || *piggyback == '1')
298 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
300 #if YAZ_VERSIONL >= 0x020163
301 a->u.searchRequest->preferredRecordSyntax =
302 yaz_string_to_oid_odr(yaz_oid_std(),
303 CLASS_RECSYN, recsyn,
304 global_parameters.odr_out);
306 a->u.searchRequest->preferredRecordSyntax =
307 yaz_str_to_z3950oid(global_parameters.odr_out,
308 CLASS_RECSYN, recsyn);
311 a->u.searchRequest->smallSetUpperBound = &ssub;
312 a->u.searchRequest->largeSetLowerBound = &lslb;
313 a->u.searchRequest->mediumSetPresentNumber = &mspn;
315 a->u.searchRequest->resultSetName = "Default";
316 a->u.searchRequest->databaseNames = databaselist;
317 a->u.searchRequest->num_databaseNames = ndb;
320 { //scope for sending and logging queries
321 WRBUF wbquery = wrbuf_alloc();
322 yaz_query_to_wrbuf(wbquery, zquery);
325 if (send_apdu(cl, a) >= 0)
327 iochan_setflags(i, EVENT_INPUT);
328 cl->state = Client_Searching;
329 cl->requestid = se->requestid;
330 yaz_log(YLOG_LOG, "SearchRequest %s %s %s",
331 cl->database->database->url,
332 queryenc ? queryenc : "UTF-8",
333 wrbuf_cstr(wbquery));
336 cl->state = Client_Error;
337 yaz_log(YLOG_WARN, "Failed SearchRequest %s %s %s",
338 cl->database->database->url,
339 queryenc ? queryenc : "UTF-8",
340 wrbuf_cstr(wbquery));
343 wrbuf_destroy(wbquery);
346 odr_reset(global_parameters.odr_out);
349 static void send_present(IOCHAN i)
351 struct connection *co = iochan_getdata(i);
352 struct client *cl = co->client;
353 struct session_database *sdb = cl->database;
354 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
356 int start = cl->records + 1;
359 toget = global_parameters.chunk;
360 if (toget > global_parameters.toget - cl->records)
361 toget = global_parameters.toget - cl->records;
362 if (toget > cl->hits - cl->records)
363 toget = cl->hits - cl->records;
365 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
367 a->u.presentRequest->resultSetStartPoint = &start;
368 a->u.presentRequest->numberOfRecordsRequested = &toget;
370 a->u.presentRequest->resultSetId = "Default";
372 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
374 #if YAZ_VERSIONL >= 0x020163
375 a->u.presentRequest->preferredRecordSyntax =
376 yaz_string_to_oid_odr(yaz_oid_std(),
377 CLASS_RECSYN, recsyn,
378 global_parameters.odr_out);
380 a->u.presentRequest->preferredRecordSyntax =
381 yaz_str_to_z3950oid(global_parameters.odr_out,
382 CLASS_RECSYN, recsyn);
386 if (send_apdu(cl, a) >= 0)
388 iochan_setflags(i, EVENT_INPUT);
389 cl->state = Client_Presenting;
392 cl->state = Client_Error;
393 odr_reset(global_parameters.odr_out);
396 static void do_initResponse(IOCHAN i, Z_APDU *a)
398 struct connection *co = iochan_getdata(i);
399 struct client *cl = co->client;
400 Z_InitResponse *r = a->u.initResponse;
402 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->database->url);
406 cl->state = Client_Idle;
409 cl->state = Client_Failed; // FIXME need to do something to the connection
412 static void do_searchResponse(IOCHAN i, Z_APDU *a)
414 struct connection *co = iochan_getdata(i);
415 struct client *cl = co->client;
416 struct session *se = cl->session;
417 Z_SearchResponse *r = a->u.searchResponse;
419 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
420 cl->database->database->url, *r->searchStatus);
422 if (*r->searchStatus)
424 cl->hits = *r->resultCount;
425 se->total_hits += cl->hits;
426 if (r->presentStatus && !*r->presentStatus && r->records)
428 yaz_log(YLOG_DEBUG, "Records in search response %s",
429 cl->database->database->url);
430 ingest_records(cl, r->records);
432 cl->state = Client_Idle;
437 cl->state = Client_Error;
439 Z_Records *recs = r->records;
440 if (recs->which == Z_Records_NSD)
443 "Search response: Non-surrogate diagnostic %s",
444 cl->database->database->url);
445 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
446 cl->state = Client_Error;
452 static void do_closeResponse(IOCHAN i, Z_APDU *a)
454 struct connection *co = iochan_getdata(i);
455 struct client *cl = co->client;
456 /* Z_Close *r = a->u.close; */
458 yaz_log(YLOG_WARN, "Close response %s", cl->database->database->url);
460 cl->state = Client_Failed;
461 connection_destroy(co);
465 char *normalize_mergekey(char *buf, int skiparticle)
467 char *p = buf, *pout = buf;
472 char articles[] = "the den der die des an a "; // must end in space
474 while (*p && !isalnum(*p))
477 while (*p && *p != ' ' && pout - firstword < 62)
478 *(pout++) = tolower(*(p++));
481 if (!strstr(articles, firstword))
488 while (*p && !isalnum(*p))
491 *(pout++) = tolower(*(p++));
494 while (*p && !isalnum(*p))
501 while (pout > buf && *pout == ' ');
506 static void add_facet(struct session *s, const char *type, const char *value)
512 for (i = 0; i < s->num_termlists; i++)
513 if (!strcmp(s->termlists[i].name, type))
515 if (i == s->num_termlists)
517 if (i == SESSION_MAX_TERMLISTS)
519 yaz_log(YLOG_FATAL, "Too many termlists");
522 s->termlists[i].name = nmem_strdup(s->nmem, type);
523 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
524 s->num_termlists = i + 1;
526 termlist_insert(s->termlists[i].termlist, value);
529 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
531 struct database_retrievalmap *m;
532 struct database *db = cl->database->database;
536 // First normalize to XML
541 if (rec->which != Z_External_octet)
543 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
544 cl->database->database->url);
547 buf = (char*) rec->u.octet_aligned->buf;
548 len = rec->u.octet_aligned->len;
549 if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
551 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
552 cl->database->database->url);
556 yaz_marc_write_using_libxml2(db->yaz_marc, 1);
557 if (yaz_marc_write_xml(db->yaz_marc, &res,
558 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
560 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
561 cl->database->database->url);
564 rdoc = xmlNewDoc((xmlChar *) "1.0");
565 xmlDocSetRootElement(rdoc, res);
571 "Unknown native_syntax in normalize_record from %s",
572 cl->database->database->url);
576 if (global_parameters.dump_records){
578 "Input Record (normalized) from %s\n----------------\n",
579 cl->database->database->url);
580 #if LIBXML_VERSION >= 20600
581 xmlDocFormatDump(stderr, rdoc, 1);
583 xmlDocDump(stderr, rdoc);
587 for (m = db->map; m; m = m->next){
593 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
594 root= xmlDocGetRootElement(new);
595 if (!new || !root || !(root->children))
597 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
598 cl->database->database->url);
607 // do it another way to detect transformation errors right now
608 // but does not seem to work either!
610 xsltTransformContextPtr ctxt;
611 ctxt = xsltNewTransformContext(m->stylesheet, rdoc);
612 new = xsltApplyStylesheetUser(m->stylesheet, rdoc, 0, 0, 0, ctxt);
613 if ((ctxt->state == XSLT_STATE_ERROR) ||
614 (ctxt->state == XSLT_STATE_STOPPED)){
615 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
616 cl->database->database->url);
627 if (global_parameters.dump_records)
629 fprintf(stderr, "Record from %s\n----------------\n",
630 cl->database->database->url);
631 #if LIBXML_VERSION >= 20600
632 xmlDocFormatDump(stderr, rdoc, 1);
634 xmlDocDump(stderr, rdoc);
640 // Extract what appears to be years from buf, storing highest and
642 static int extract_years(const char *buf, int *first, int *last)
651 while (*buf && !isdigit(*buf))
654 for (e = buf; *e && isdigit(*e); e++)
658 int value = atoi(buf);
659 if (*first < 0 || value < *first)
661 if (*last < 0 || value > *last)
669 static struct record *ingest_record(struct client *cl, Z_External *rec)
671 xmlDoc *xdoc = normalize_record(cl, rec);
674 struct record_cluster *cluster;
675 struct session *se = cl->session;
676 xmlChar *mergekey, *mergekey_norm;
679 struct conf_service *service = global_parameters.server->service;
684 root = xmlDocGetRootElement(xdoc);
685 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
687 yaz_log(YLOG_WARN, "No mergekey found in record");
692 res = nmem_malloc(se->nmem, sizeof(struct record));
695 res->metadata = nmem_malloc(se->nmem,
696 sizeof(struct record_metadata*) * service->num_metadata);
697 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
699 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
701 normalize_mergekey((char *) mergekey_norm, 0);
703 cluster = reclist_insert(global_parameters.server->service, se->reclist, res, (char *) mergekey_norm,
705 if (global_parameters.dump_records)
706 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
707 cl->database->database->url, cl->records);
710 /* no room for record */
714 relevance_newrec(se->relevance, cluster);
716 for (n = root->children; n; n = n->next)
724 if (n->type != XML_ELEMENT_NODE)
726 if (!strcmp((const char *) n->name, "metadata"))
728 struct conf_metadata *md = 0;
729 struct conf_sortkey *sk = 0;
730 struct record_metadata **wheretoput, *newm;
734 type = xmlGetProp(n, (xmlChar *) "type");
735 value = xmlNodeListGetString(xdoc, n->children, 0);
740 // First, find out what field we're looking at
741 for (imeta = 0; imeta < service->num_metadata; imeta++)
742 if (!strcmp((const char *) type, service->metadata[imeta].name))
744 md = &service->metadata[imeta];
745 if (md->sortkey_offset >= 0)
746 sk = &service->sortkeys[md->sortkey_offset];
751 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
755 // Find out where we are putting it
756 if (md->merge == Metadata_merge_no)
757 wheretoput = &res->metadata[imeta];
759 wheretoput = &cluster->metadata[imeta];
762 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
764 if (md->type == Metadata_type_generic)
767 for (p = (char *) value; *p && isspace(*p); p++)
769 for (pe = p + strlen(p) - 1;
770 pe > p && strchr(" ,/.:([", *pe); pe--)
772 newm->data.text = nmem_strdup(se->nmem, p);
775 else if (md->type == Metadata_type_year)
777 if (extract_years((char *) value, &first, &last) < 0)
782 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
785 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
787 yaz_log(YLOG_WARN, "Only range merging supported for years");
790 if (md->merge == Metadata_merge_unique)
792 struct record_metadata *mnode;
793 for (mnode = *wheretoput; mnode; mnode = mnode->next)
794 if (!strcmp((const char *) mnode->data.text, newm->data.text))
798 newm->next = *wheretoput;
802 else if (md->merge == Metadata_merge_longest)
805 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
810 char *s = nmem_strdup(se->nmem, newm->data.text);
811 if (!cluster->sortkeys[md->sortkey_offset])
812 cluster->sortkeys[md->sortkey_offset] =
813 nmem_malloc(se->nmem, sizeof(union data_types));
814 normalize_mergekey(s,
815 (sk->type == Metadata_sortkey_skiparticle));
816 cluster->sortkeys[md->sortkey_offset]->text = s;
820 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
822 newm->next = *wheretoput;
825 else if (md->merge == Metadata_merge_range)
827 assert(md->type == Metadata_type_year);
831 (*wheretoput)->data.number.min = first;
832 (*wheretoput)->data.number.max = last;
834 cluster->sortkeys[md->sortkey_offset] = &newm->data;
838 if (first < (*wheretoput)->data.number.min)
839 (*wheretoput)->data.number.min = first;
840 if (last > (*wheretoput)->data.number.max)
841 (*wheretoput)->data.number.max = last;
846 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
847 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
852 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
855 relevance_countwords(se->relevance, cluster,
856 (char *) value, md->rank);
859 if (md->type == Metadata_type_year)
862 sprintf(year, "%d", last);
863 add_facet(se, (char *) type, year);
866 sprintf(year, "%d", first);
867 add_facet(se, (char *) type, year);
871 add_facet(se, (char *) type, (char *) value);
878 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
887 relevance_donerecord(se->relevance, cluster);
893 // Retrieve first defined value for 'name' for given database.
894 // Will be extended to take into account user associated with session
895 char *session_setting_oneval(struct session_database *db, int offset)
897 if (!db->settings[offset])
899 return db->settings[offset]->value;
902 static void ingest_records(struct client *cl, Z_Records *r)
905 yaz_timing_t t = yaz_timing_create();
908 struct session *s = cl->session;
909 Z_NamePlusRecordList *rlist;
912 if (r->which != Z_Records_DBOSD)
914 rlist = r->u.databaseOrSurDiagnostics;
915 for (i = 0; i < rlist->num_records; i++)
917 Z_NamePlusRecord *npr = rlist->records[i];
920 if (npr->which != Z_NamePlusRecord_databaseRecord)
923 "Unexpected record type, probably diagnostic %s",
924 cl->database->database->url);
928 rec = ingest_record(cl, npr->u.databaseRecord);
932 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
933 session_alert_watch(s, SESSION_WATCH_RECORDS);
937 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
938 yaz_timing_get_real(t), yaz_timing_get_user(t),
939 yaz_timing_get_sys(t));
940 yaz_timing_destroy(&t);
944 static void do_presentResponse(IOCHAN i, Z_APDU *a)
946 struct connection *co = iochan_getdata(i);
947 struct client *cl = co->client;
948 Z_PresentResponse *r = a->u.presentResponse;
951 Z_Records *recs = r->records;
952 if (recs->which == Z_Records_NSD)
954 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
955 cl->database->database->url);
956 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
957 cl->state = Client_Error;
961 if (!*r->presentStatus && cl->state != Client_Error)
963 yaz_log(YLOG_DEBUG, "Good Present response %s",
964 cl->database->database->url);
965 ingest_records(cl, r->records);
966 cl->state = Client_Idle;
968 else if (*r->presentStatus)
970 yaz_log(YLOG_WARN, "Bad Present response %s",
971 cl->database->database->url);
972 cl->state = Client_Error;
976 static void handler(IOCHAN i, int event)
978 struct connection *co = iochan_getdata(i);
979 struct client *cl = co->client;
980 struct session *se = 0;
986 yaz_log(YLOG_WARN, "Destroying orphan connection");
987 connection_destroy(co);
991 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
994 socklen_t errlen = sizeof(errcode);
996 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
997 &errlen) < 0 || errcode != 0)
1004 yaz_log(YLOG_DEBUG, "Connect OK");
1005 co->state = Conn_Open;
1007 cl->state = Client_Connected;
1011 else if (event & EVENT_INPUT)
1013 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
1017 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
1018 cl->database->database->url);
1019 connection_destroy(co);
1024 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
1025 connection_destroy(co);
1028 else if (len > 1) // We discard input if we have no connection
1030 co->state = Conn_Open;
1032 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
1036 odr_reset(global_parameters.odr_in);
1037 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
1038 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
1045 case Z_APDU_initResponse:
1046 do_initResponse(i, a);
1048 case Z_APDU_searchResponse:
1049 do_searchResponse(i, a);
1051 case Z_APDU_presentResponse:
1052 do_presentResponse(i, a);
1055 do_closeResponse(i, a);
1059 "Unexpected Z39.50 response from %s",
1060 cl->database->database->url);
1064 // We aren't expecting staggered output from target
1065 // if (cs_more(t->link))
1066 // iochan_setevent(i, EVENT_INPUT);
1068 else // we throw away response and go to idle mode
1070 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
1071 cl->state = Client_Idle;
1074 /* if len==1 we do nothing but wait for more input */
1077 if (cl->state == Client_Connected) {
1081 if (cl->state == Client_Idle)
1083 if (cl->requestid != se->requestid && *se->query) {
1086 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
1087 cl->records < cl->hits) {
1093 // Disassociate connection from client
1094 static void connection_release(struct connection *co)
1096 struct client *cl = co->client;
1098 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1105 // Close connection and recycle structure
1106 static void connection_destroy(struct connection *co)
1108 struct host *h = co->host;
1110 iochan_destroy(co->iochan);
1112 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1113 if (h->connections == co)
1114 h->connections = co->next;
1117 struct connection *pco;
1118 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1121 pco->next = co->next;
1127 if (co->client->state != Client_Idle)
1128 co->client->state = Client_Disconnected;
1129 co->client->connection = 0;
1131 co->next = connection_freelist;
1132 connection_freelist = co;
1135 // Creates a new connection for client, associated with the host of
1136 // client's database
1137 static struct connection *connection_create(struct client *cl)
1139 struct connection *new;
1145 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1147 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1151 if (0 == strlen(global_parameters.zproxy_override)){
1152 /* no Z39.50 proxy needed - direct connect */
1153 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
1155 if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
1157 yaz_log(YLOG_WARN|YLOG_ERRNO,
1158 "Lookup of IP address %s failed",
1159 cl->database->database->host->ipport);
1164 /* Z39.50 proxy connect */
1165 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1166 cl->database->database->url, global_parameters.zproxy_override);
1168 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1170 yaz_log(YLOG_WARN|YLOG_ERRNO,
1171 "Lookup of IP address %s failed",
1172 global_parameters.zproxy_override);
1177 res = cs_connect(link, addr);
1180 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
1184 if ((new = connection_freelist))
1185 connection_freelist = new->next;
1188 new = xmalloc(sizeof (struct connection));
1192 new->state = Conn_Connecting;
1193 new->host = cl->database->database->host;
1194 new->next = new->host->connections;
1195 new->host->connections = new;
1197 cl->connection = new;
1200 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1201 iochan_setdata(new->iochan, new);
1202 new->iochan->next = channel_list;
1203 channel_list = new->iochan;
1207 // Close connection and set state to error
1208 static void client_fatal(struct client *cl)
1210 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
1211 connection_destroy(cl->connection);
1212 cl->state = Client_Error;
1215 // Ensure that client has a connection associated
1216 static int client_prep_connection(struct client *cl)
1218 struct connection *co;
1219 struct session *se = cl->session;
1220 struct host *host = cl->database->database->host;
1222 co = cl->connection;
1224 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
1228 // See if someone else has an idle connection
1229 // We should look at timestamps here to select the longest-idle connection
1230 for (co = host->connections; co; co = co->next)
1231 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1235 connection_release(co);
1236 cl->connection = co;
1240 co = connection_create(cl);
1244 if (co->state == Conn_Connecting)
1246 cl->state = Client_Connecting;
1247 iochan_setflag(co->iochan, EVENT_OUTPUT);
1249 else if (co->state == Conn_Open)
1251 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1252 cl->state = Client_Idle;
1253 iochan_setflag(co->iochan, EVENT_OUTPUT);
1261 static struct client *client_create(void)
1264 if (client_freelist)
1266 r = client_freelist;
1267 client_freelist = client_freelist->next;
1270 r = xmalloc(sizeof(struct client));
1279 r->state = Client_Disconnected;
1284 void client_destroy(struct client *c)
1286 struct session *se = c->session;
1287 if (c == se->clients)
1288 se->clients = c->next;
1292 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1298 connection_release(c->connection);
1299 c->next = client_freelist;
1300 client_freelist = c;
1303 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1305 s->watchlist[what].fun = fun;
1306 s->watchlist[what].data = data;
1309 void session_alert_watch(struct session *s, int what)
1311 if (!s->watchlist[what].fun)
1313 (*s->watchlist[what].fun)(s->watchlist[what].data);
1314 s->watchlist[what].fun = 0;
1315 s->watchlist[what].data = 0;
1318 //callback for grep_databases
1319 static void select_targets_callback(void *context, struct session_database *db)
1321 struct session *se = (struct session*) context;
1322 struct client *cl = client_create();
1325 cl->next = se->clients;
1329 // Associates a set of clients with a session;
1330 // Note: Session-databases represent databases with per-session setting overrides
1331 int select_targets(struct session *se, struct database_criterion *crit)
1334 client_destroy(se->clients);
1336 return session_grep_databases(se, crit, select_targets_callback);
1339 int session_active_clients(struct session *s)
1344 for (c = s->clients; c; c = c->next)
1345 if (c->connection && (c->state == Client_Connecting ||
1346 c->state == Client_Initializing ||
1347 c->state == Client_Searching ||
1348 c->state == Client_Presenting))
1354 // parses crit1=val1,crit2=val2|val3,...
1355 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1357 struct database_criterion *res = 0;
1364 nmem_strsplit(m, ",", buf, &values, &num);
1365 for (i = 0; i < num; i++)
1370 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1371 char *eq = strchr(values[i], '=');
1374 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1378 new->name = values[i];
1379 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1381 for (subi = 0; subi < subnum; subi++)
1383 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1384 newv->value = subvalues[subi];
1385 newv->next = new->values;
1394 char *search(struct session *se, char *query, char *filter)
1396 int live_channels = 0;
1398 struct database_criterion *criteria;
1400 yaz_log(YLOG_DEBUG, "Search");
1402 nmem_reset(se->nmem);
1403 criteria = parse_filter(se->nmem, filter);
1404 strcpy(se->query, query);
1406 select_targets(se, criteria);
1407 for (cl = se->clients; cl; cl = cl->next)
1409 if (client_prep_connection(cl))
1414 int maxrecs = live_channels * global_parameters.toget;
1415 se->num_termlists = 0;
1416 se->reclist = reclist_create(se->nmem, maxrecs);
1417 // This will be initialized in send_search()
1419 se->total_records = se->total_hits = se->total_merged = 0;
1420 se->expected_maxrecs = maxrecs;
1428 // Apply a session override to a database
1429 void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
1431 struct session_database *sdb;
1433 for (sdb = se->databases; sdb; sdb = sdb->next)
1434 if (!strcmp(dbname, sdb->database->url))
1436 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
1437 int offset = settings_offset(setting);
1441 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
1444 new->precedence = 0;
1445 new->target = dbname;
1446 new->name = setting;
1448 new->next = sdb->settings[offset];
1449 sdb->settings[offset] = new;
1453 yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
1456 void session_init_databases_fun(void *context, struct database *db)
1458 struct session *se = (struct session *) context;
1459 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
1460 int num = settings_num();
1464 new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
1465 for (i = 0; i < num; i++)
1466 new->settings[i] = db->settings[i];
1467 new->next = se->databases;
1468 se->databases = new;
1471 // Initialize session_database list -- this represents this session's view
1472 // of the database list -- subject to modification by the settings ws command
1473 void session_init_databases(struct session *se)
1476 grep_databases(se, 0, session_init_databases_fun);
1479 void destroy_session(struct session *s)
1481 yaz_log(YLOG_LOG, "Destroying session");
1483 client_destroy(s->clients);
1484 nmem_destroy(s->nmem);
1485 wrbuf_destroy(s->wrbuf);
1488 struct session *new_session(NMEM nmem)
1491 struct session *session = nmem_malloc(nmem, sizeof(*session));
1493 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
1495 session->total_hits = 0;
1496 session->total_records = 0;
1497 session->num_termlists = 0;
1498 session->reclist = 0;
1499 session->requestid = -1;
1500 session->clients = 0;
1501 session->expected_maxrecs = 0;
1502 session->query[0] = '\0';
1503 session->session_nmem = nmem;
1504 session->nmem = nmem_create();
1505 session->wrbuf = wrbuf_alloc();
1506 session_init_databases(session);
1507 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1509 session->watchlist[i].data = 0;
1510 session->watchlist[i].fun = 0;
1516 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1518 static struct hitsbytarget res[1000]; // FIXME MM
1522 for (cl = se->clients; cl; cl = cl->next)
1524 char *name = session_setting_oneval(cl->database, PZ_NAME);
1526 res[*count].id = cl->database->database->url;
1527 res[*count].name = *name ? name : "Unknown";
1528 res[*count].hits = cl->hits;
1529 res[*count].records = cl->records;
1530 res[*count].diagnostic = cl->diagnostic;
1531 res[*count].state = client_states[cl->state];
1532 res[*count].connected = cl->connection ? 1 : 0;
1539 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1543 for (i = 0; i < s->num_termlists; i++)
1544 if (!strcmp((const char *) s->termlists[i].name, name))
1545 return termlist_highscore(s->termlists[i].termlist, num);
1549 #ifdef MISSING_HEADERS
1550 void report_nmem_stats(void)
1552 size_t in_use, is_free;
1554 nmem_get_memory_in_use(&in_use);
1555 nmem_get_memory_free(&is_free);
1557 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1558 (long) in_use, (long) is_free);
1562 struct record_cluster *show_single(struct session *s, int id)
1564 struct record_cluster *r;
1566 reclist_rewind(s->reclist);
1567 while ((r = reclist_read_record(s->reclist)))
1573 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1574 int *num, int *total, int *sumhits, NMEM nmem_show)
1576 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1577 * sizeof(struct record_cluster *));
1578 struct reclist_sortparms *spp;
1581 yaz_timing_t t = yaz_timing_create();
1584 for (spp = sp; spp; spp = spp->next)
1585 if (spp->type == Metadata_sortkey_relevance)
1587 relevance_prepare_read(s->relevance, s->reclist);
1590 reclist_sort(s->reclist, sp);
1592 *total = s->reclist->num_records;
1593 *sumhits = s->total_hits;
1595 for (i = 0; i < start; i++)
1596 if (!reclist_read_record(s->reclist))
1603 for (i = 0; i < *num; i++)
1605 struct record_cluster *r = reclist_read_record(s->reclist);
1615 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1616 yaz_timing_get_real(t), yaz_timing_get_user(t),
1617 yaz_timing_get_sys(t));
1618 yaz_timing_destroy(&t);
1623 void statistics(struct session *se, struct statistics *stat)
1628 memset(stat, 0, sizeof(*stat));
1629 for (cl = se->clients; cl; cl = cl->next)
1631 if (!cl->connection)
1632 stat->num_no_connection++;
1635 case Client_Connecting: stat->num_connecting++; break;
1636 case Client_Initializing: stat->num_initializing++; break;
1637 case Client_Searching: stat->num_searching++; break;
1638 case Client_Presenting: stat->num_presenting++; break;
1639 case Client_Idle: stat->num_idle++; break;
1640 case Client_Failed: stat->num_failed++; break;
1641 case Client_Error: stat->num_error++; break;
1646 stat->num_hits = se->total_hits;
1647 stat->num_records = se->total_records;
1649 stat->num_clients = count;
1652 void start_http_listener(void)
1655 struct conf_server *ser = global_parameters.server;
1657 if (*global_parameters.listener_override)
1658 strcpy(hp, global_parameters.listener_override);
1661 strcpy(hp, ser->host ? ser->host : "");
1666 sprintf(hp + strlen(hp), "%d", ser->port);
1672 void start_proxy(void)
1675 struct conf_server *ser = global_parameters.server;
1677 if (*global_parameters.proxy_override)
1678 strcpy(hp, global_parameters.proxy_override);
1679 else if (ser->proxy_host || ser->proxy_port)
1681 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1682 if (ser->proxy_port)
1686 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1692 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1695 void start_zproxy(void)
1697 struct conf_server *ser = global_parameters.server;
1699 if (*global_parameters.zproxy_override){
1700 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1701 global_parameters.zproxy_override);
1705 else if (ser->zproxy_host || ser->zproxy_port)
1709 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1710 if (ser->zproxy_port)
1717 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1719 strcpy(global_parameters.zproxy_override, hp);
1720 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1721 global_parameters.zproxy_override);
1733 * indent-tabs-mode: nil
1735 * vim: shiftwidth=4 tabstop=8 expandtab