1 /* $Id: logic.c,v 1.7 2007-04-18 04:22:55 quinn Exp $
2 Copyright (c) 2006-2007, Index Data.
4 This file is part of Pazpar2.
6 Pazpar2 is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
11 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with Pazpar2; see the file LICENSE. If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
27 #include <sys/socket.h>
33 #include <yaz/marcdisp.h>
34 #include <yaz/comstack.h>
35 #include <yaz/tcpip.h>
36 #include <yaz/proto.h>
37 #include <yaz/readconf.h>
38 #include <yaz/pquery.h>
39 #include <yaz/otherinfo.h>
40 #include <yaz/yaz-util.h>
42 #include <yaz/query-charset.h>
43 #include <yaz/querytowrbuf.h>
44 #if YAZ_VERSIONL >= 0x020163
45 #include <yaz/oid_db.h>
54 #include <yaz/timing.h>
57 #include <netinet/in.h>
62 #include "termlists.h"
64 #include "relevance.h"
71 static void client_fatal(struct client *cl);
72 static void connection_destroy(struct connection *co);
73 static int client_prep_connection(struct client *cl);
74 static void ingest_records(struct client *cl, Z_Records *r);
75 void session_alert_watch(struct session *s, int what);
77 IOCHAN channel_list = 0; // Master list of connections we're handling events to
79 static struct connection *connection_freelist = 0;
80 static struct client *client_freelist = 0;
82 static char *client_states[] = {
86 "Client_Initializing",
91 "Client_Disconnected",
95 // Note: Some things in this structure will eventually move to configuration
96 struct parameters global_parameters =
106 "Index Data PazPar2 (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);
247 int ssub = 0, lslb = 100000, mspn = 10;
251 yaz_iconv_t iconv = 0;
253 yaz_log(YLOG_DEBUG, "Sending search to %s", cl->database->database->url);
255 // constructing RPN query
256 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
258 zquery->which = Z_Query_type_1;
259 zquery->u.type_1 = p_query_rpn(global_parameters.odr_out, cl->pquery);
261 // converting to target encoding
262 if ((queryenc = session_setting_oneval(sdb, PZ_QUERYENCODING))){
263 iconv = yaz_iconv_open(queryenc, "UTF-8");
265 yaz_query_charset_convert_rpnquery(zquery->u.type_1,
266 global_parameters.odr_out,
268 yaz_iconv_close(iconv);
270 yaz_log(YLOG_WARN, "Query encoding failed %s %s",
271 cl->database->database->url, queryenc);
274 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
276 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
277 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
278 databaselist[ndb] = sdb->database->databases[ndb];
280 if (!(piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK)) || *piggyback == '1')
282 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
284 #if YAZ_VERSIONL >= 0x020163
285 a->u.searchRequest->preferredRecordSyntax =
286 yaz_string_to_oid_odr(yaz_oid_std(),
287 CLASS_RECSYN, recsyn,
288 global_parameters.odr_out);
290 a->u.searchRequest->preferredRecordSyntax =
291 yaz_str_to_z3950oid(global_parameters.odr_out,
292 CLASS_RECSYN, recsyn);
295 a->u.searchRequest->smallSetUpperBound = &ssub;
296 a->u.searchRequest->largeSetLowerBound = &lslb;
297 a->u.searchRequest->mediumSetPresentNumber = &mspn;
299 a->u.searchRequest->resultSetName = "Default";
300 a->u.searchRequest->databaseNames = databaselist;
301 a->u.searchRequest->num_databaseNames = ndb;
304 { //scope for sending and logging queries
305 WRBUF wbquery = wrbuf_alloc();
306 yaz_query_to_wrbuf(wbquery, zquery);
309 if (send_apdu(cl, a) >= 0)
311 iochan_setflags(i, EVENT_INPUT);
312 cl->state = Client_Searching;
313 cl->requestid = se->requestid;
314 yaz_log(YLOG_LOG, "SearchRequest %s %s %s",
315 cl->database->database->url,
316 queryenc ? queryenc : "UTF-8",
317 wrbuf_cstr(wbquery));
320 cl->state = Client_Error;
321 yaz_log(YLOG_WARN, "Failed SearchRequest %s %s %s",
322 cl->database->database->url,
323 queryenc ? queryenc : "UTF-8",
324 wrbuf_cstr(wbquery));
327 wrbuf_destroy(wbquery);
330 odr_reset(global_parameters.odr_out);
333 static void send_present(IOCHAN i)
335 struct connection *co = iochan_getdata(i);
336 struct client *cl = co->client;
337 struct session_database *sdb = cl->database;
338 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
340 int start = cl->records + 1;
343 toget = global_parameters.chunk;
344 if (toget > global_parameters.toget - cl->records)
345 toget = global_parameters.toget - cl->records;
346 if (toget > cl->hits - cl->records)
347 toget = cl->hits - cl->records;
349 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
351 a->u.presentRequest->resultSetStartPoint = &start;
352 a->u.presentRequest->numberOfRecordsRequested = &toget;
354 a->u.presentRequest->resultSetId = "Default";
356 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
358 #if YAZ_VERSIONL >= 0x020163
359 a->u.presentRequest->preferredRecordSyntax =
360 yaz_string_to_oid_odr(yaz_oid_std(),
361 CLASS_RECSYN, recsyn,
362 global_parameters.odr_out);
364 a->u.presentRequest->preferredRecordSyntax =
365 yaz_str_to_z3950oid(global_parameters.odr_out,
366 CLASS_RECSYN, recsyn);
370 if (send_apdu(cl, a) >= 0)
372 iochan_setflags(i, EVENT_INPUT);
373 cl->state = Client_Presenting;
376 cl->state = Client_Error;
377 odr_reset(global_parameters.odr_out);
380 static void do_initResponse(IOCHAN i, Z_APDU *a)
382 struct connection *co = iochan_getdata(i);
383 struct client *cl = co->client;
384 Z_InitResponse *r = a->u.initResponse;
386 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->database->url);
390 cl->state = Client_Idle;
393 cl->state = Client_Failed; // FIXME need to do something to the connection
396 static void do_searchResponse(IOCHAN i, Z_APDU *a)
398 struct connection *co = iochan_getdata(i);
399 struct client *cl = co->client;
400 struct session *se = cl->session;
401 Z_SearchResponse *r = a->u.searchResponse;
403 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
404 cl->database->database->url, *r->searchStatus);
406 if (*r->searchStatus)
408 cl->hits = *r->resultCount;
409 se->total_hits += cl->hits;
410 if (r->presentStatus && !*r->presentStatus && r->records)
412 yaz_log(YLOG_DEBUG, "Records in search response %s",
413 cl->database->database->url);
414 ingest_records(cl, r->records);
416 cl->state = Client_Idle;
421 cl->state = Client_Error;
423 Z_Records *recs = r->records;
424 if (recs->which == Z_Records_NSD)
427 "Search response: Non-surrogate diagnostic %s",
428 cl->database->database->url);
429 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
430 cl->state = Client_Error;
436 static void do_closeResponse(IOCHAN i, Z_APDU *a)
438 struct connection *co = iochan_getdata(i);
439 struct client *cl = co->client;
440 /* Z_Close *r = a->u.close; */
442 yaz_log(YLOG_WARN, "Close response %s", cl->database->database->url);
444 cl->state = Client_Failed;
445 connection_destroy(co);
449 char *normalize_mergekey(char *buf, int skiparticle)
451 char *p = buf, *pout = buf;
456 char articles[] = "the den der die des an a "; // must end in space
458 while (*p && !isalnum(*p))
461 while (*p && *p != ' ' && pout - firstword < 62)
462 *(pout++) = tolower(*(p++));
465 if (!strstr(articles, firstword))
472 while (*p && !isalnum(*p))
475 *(pout++) = tolower(*(p++));
478 while (*p && !isalnum(*p))
485 while (pout > buf && *pout == ' ');
490 static void add_facet(struct session *s, const char *type, const char *value)
496 for (i = 0; i < s->num_termlists; i++)
497 if (!strcmp(s->termlists[i].name, type))
499 if (i == s->num_termlists)
501 if (i == SESSION_MAX_TERMLISTS)
503 yaz_log(YLOG_FATAL, "Too many termlists");
506 s->termlists[i].name = nmem_strdup(s->nmem, type);
507 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
508 s->num_termlists = i + 1;
510 termlist_insert(s->termlists[i].termlist, value);
513 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
515 struct database_retrievalmap *m;
516 struct database *db = cl->database->database;
520 // First normalize to XML
525 if (rec->which != Z_External_octet)
527 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
528 cl->database->database->url);
531 buf = (char*) rec->u.octet_aligned->buf;
532 len = rec->u.octet_aligned->len;
533 if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
535 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
536 cl->database->database->url);
540 yaz_marc_write_using_libxml2(db->yaz_marc, 1);
541 if (yaz_marc_write_xml(db->yaz_marc, &res,
542 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
544 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
545 cl->database->database->url);
548 rdoc = xmlNewDoc((xmlChar *) "1.0");
549 xmlDocSetRootElement(rdoc, res);
555 "Unknown native_syntax in normalize_record from %s",
556 cl->database->database->url);
560 if (global_parameters.dump_records){
562 "Input Record (normalized) from %s\n----------------\n",
563 cl->database->database->url);
564 #if LIBXML_VERSION >= 20600
565 xmlDocFormatDump(stderr, rdoc, 1);
567 xmlDocDump(stderr, rdoc);
571 for (m = db->map; m; m = m->next){
577 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
578 root= xmlDocGetRootElement(new);
579 if (!new || !root || !(root->children))
581 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
582 cl->database->database->url);
591 // do it another way to detect transformation errors right now
592 // but does not seem to work either!
594 xsltTransformContextPtr ctxt;
595 ctxt = xsltNewTransformContext(m->stylesheet, rdoc);
596 new = xsltApplyStylesheetUser(m->stylesheet, rdoc, 0, 0, 0, ctxt);
597 if ((ctxt->state == XSLT_STATE_ERROR) ||
598 (ctxt->state == XSLT_STATE_STOPPED)){
599 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
600 cl->database->database->url);
611 if (global_parameters.dump_records)
613 fprintf(stderr, "Record from %s\n----------------\n",
614 cl->database->database->url);
615 #if LIBXML_VERSION >= 20600
616 xmlDocFormatDump(stderr, rdoc, 1);
618 xmlDocDump(stderr, rdoc);
624 // Extract what appears to be years from buf, storing highest and
626 static int extract_years(const char *buf, int *first, int *last)
635 while (*buf && !isdigit(*buf))
638 for (e = buf; *e && isdigit(*e); e++)
642 int value = atoi(buf);
643 if (*first < 0 || value < *first)
645 if (*last < 0 || value > *last)
653 static struct record *ingest_record(struct client *cl, Z_External *rec)
655 xmlDoc *xdoc = normalize_record(cl, rec);
658 struct record_cluster *cluster;
659 struct session *se = cl->session;
660 xmlChar *mergekey, *mergekey_norm;
663 struct conf_service *service = global_parameters.server->service;
668 root = xmlDocGetRootElement(xdoc);
669 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
671 yaz_log(YLOG_WARN, "No mergekey found in record");
676 res = nmem_malloc(se->nmem, sizeof(struct record));
679 res->metadata = nmem_malloc(se->nmem,
680 sizeof(struct record_metadata*) * service->num_metadata);
681 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
683 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
685 normalize_mergekey((char *) mergekey_norm, 0);
687 cluster = reclist_insert(se->reclist,
688 global_parameters.server->service,
689 res, (char *) mergekey_norm,
691 if (global_parameters.dump_records)
692 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
693 cl->database->database->url, cl->records);
696 /* no room for record */
700 relevance_newrec(se->relevance, cluster);
702 for (n = root->children; n; n = n->next)
710 if (n->type != XML_ELEMENT_NODE)
712 if (!strcmp((const char *) n->name, "metadata"))
714 struct conf_metadata *md = 0;
715 struct conf_sortkey *sk = 0;
716 struct record_metadata **wheretoput, *newm;
720 type = xmlGetProp(n, (xmlChar *) "type");
721 value = xmlNodeListGetString(xdoc, n->children, 0);
726 // First, find out what field we're looking at
727 for (imeta = 0; imeta < service->num_metadata; imeta++)
728 if (!strcmp((const char *) type, service->metadata[imeta].name))
730 md = &service->metadata[imeta];
731 if (md->sortkey_offset >= 0)
732 sk = &service->sortkeys[md->sortkey_offset];
737 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
741 // Find out where we are putting it
742 if (md->merge == Metadata_merge_no)
743 wheretoput = &res->metadata[imeta];
745 wheretoput = &cluster->metadata[imeta];
748 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
750 if (md->type == Metadata_type_generic)
753 for (p = (char *) value; *p && isspace(*p); p++)
755 for (pe = p + strlen(p) - 1;
756 pe > p && strchr(" ,/.:([", *pe); pe--)
758 newm->data.text = nmem_strdup(se->nmem, p);
761 else if (md->type == Metadata_type_year)
763 if (extract_years((char *) value, &first, &last) < 0)
768 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
771 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
773 yaz_log(YLOG_WARN, "Only range merging supported for years");
776 if (md->merge == Metadata_merge_unique)
778 struct record_metadata *mnode;
779 for (mnode = *wheretoput; mnode; mnode = mnode->next)
780 if (!strcmp((const char *) mnode->data.text, newm->data.text))
784 newm->next = *wheretoput;
788 else if (md->merge == Metadata_merge_longest)
791 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
796 char *s = nmem_strdup(se->nmem, newm->data.text);
797 if (!cluster->sortkeys[md->sortkey_offset])
798 cluster->sortkeys[md->sortkey_offset] =
799 nmem_malloc(se->nmem, sizeof(union data_types));
800 normalize_mergekey(s,
801 (sk->type == Metadata_sortkey_skiparticle));
802 cluster->sortkeys[md->sortkey_offset]->text = s;
806 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
808 newm->next = *wheretoput;
811 else if (md->merge == Metadata_merge_range)
813 assert(md->type == Metadata_type_year);
817 (*wheretoput)->data.number.min = first;
818 (*wheretoput)->data.number.max = last;
820 cluster->sortkeys[md->sortkey_offset] = &newm->data;
824 if (first < (*wheretoput)->data.number.min)
825 (*wheretoput)->data.number.min = first;
826 if (last > (*wheretoput)->data.number.max)
827 (*wheretoput)->data.number.max = last;
832 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
833 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
838 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
841 relevance_countwords(se->relevance, cluster,
842 (char *) value, md->rank);
845 if (md->type == Metadata_type_year)
848 sprintf(year, "%d", last);
849 add_facet(se, (char *) type, year);
852 sprintf(year, "%d", first);
853 add_facet(se, (char *) type, year);
857 add_facet(se, (char *) type, (char *) value);
864 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
873 relevance_donerecord(se->relevance, cluster);
879 // Retrieve first defined value for 'name' for given database.
880 // Will be extended to take into account user associated with session
881 char *session_setting_oneval(struct session_database *db, int offset)
883 if (!db->settings[offset])
885 return db->settings[offset]->value;
888 static void ingest_records(struct client *cl, Z_Records *r)
891 yaz_timing_t t = yaz_timing_create();
894 struct session *s = cl->session;
895 Z_NamePlusRecordList *rlist;
898 if (r->which != Z_Records_DBOSD)
900 rlist = r->u.databaseOrSurDiagnostics;
901 for (i = 0; i < rlist->num_records; i++)
903 Z_NamePlusRecord *npr = rlist->records[i];
906 if (npr->which != Z_NamePlusRecord_databaseRecord)
909 "Unexpected record type, probably diagnostic %s",
910 cl->database->database->url);
914 rec = ingest_record(cl, npr->u.databaseRecord);
918 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
919 session_alert_watch(s, SESSION_WATCH_RECORDS);
923 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
924 yaz_timing_get_real(t), yaz_timing_get_user(t),
925 yaz_timing_get_sys(t));
926 yaz_timing_destroy(&t);
930 static void do_presentResponse(IOCHAN i, Z_APDU *a)
932 struct connection *co = iochan_getdata(i);
933 struct client *cl = co->client;
934 Z_PresentResponse *r = a->u.presentResponse;
937 Z_Records *recs = r->records;
938 if (recs->which == Z_Records_NSD)
940 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
941 cl->database->database->url);
942 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
943 cl->state = Client_Error;
947 if (!*r->presentStatus && cl->state != Client_Error)
949 yaz_log(YLOG_DEBUG, "Good Present response %s",
950 cl->database->database->url);
951 ingest_records(cl, r->records);
952 cl->state = Client_Idle;
954 else if (*r->presentStatus)
956 yaz_log(YLOG_WARN, "Bad Present response %s",
957 cl->database->database->url);
958 cl->state = Client_Error;
962 static void handler(IOCHAN i, int event)
964 struct connection *co = iochan_getdata(i);
965 struct client *cl = co->client;
966 struct session *se = 0;
972 yaz_log(YLOG_WARN, "Destroying orphan connection");
973 connection_destroy(co);
977 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
980 socklen_t errlen = sizeof(errcode);
982 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
983 &errlen) < 0 || errcode != 0)
990 yaz_log(YLOG_DEBUG, "Connect OK");
991 co->state = Conn_Open;
993 cl->state = Client_Connected;
997 else if (event & EVENT_INPUT)
999 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
1003 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
1004 cl->database->database->url);
1005 connection_destroy(co);
1010 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
1011 connection_destroy(co);
1014 else if (len > 1) // We discard input if we have no connection
1016 co->state = Conn_Open;
1018 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
1022 odr_reset(global_parameters.odr_in);
1023 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
1024 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
1031 case Z_APDU_initResponse:
1032 do_initResponse(i, a);
1034 case Z_APDU_searchResponse:
1035 do_searchResponse(i, a);
1037 case Z_APDU_presentResponse:
1038 do_presentResponse(i, a);
1041 do_closeResponse(i, a);
1045 "Unexpected Z39.50 response from %s",
1046 cl->database->database->url);
1050 // We aren't expecting staggered output from target
1051 // if (cs_more(t->link))
1052 // iochan_setevent(i, EVENT_INPUT);
1054 else // we throw away response and go to idle mode
1056 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
1057 cl->state = Client_Idle;
1060 /* if len==1 we do nothing but wait for more input */
1063 if (cl->state == Client_Connected) {
1067 if (cl->state == Client_Idle)
1069 if (cl->requestid != se->requestid && *se->query) {
1072 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
1073 cl->records < cl->hits) {
1079 // Disassociate connection from client
1080 static void connection_release(struct connection *co)
1082 struct client *cl = co->client;
1084 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1091 // Close connection and recycle structure
1092 static void connection_destroy(struct connection *co)
1094 struct host *h = co->host;
1096 iochan_destroy(co->iochan);
1098 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1099 if (h->connections == co)
1100 h->connections = co->next;
1103 struct connection *pco;
1104 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1107 pco->next = co->next;
1113 if (co->client->state != Client_Idle)
1114 co->client->state = Client_Disconnected;
1115 co->client->connection = 0;
1117 co->next = connection_freelist;
1118 connection_freelist = co;
1121 // Creates a new connection for client, associated with the host of
1122 // client's database
1123 static struct connection *connection_create(struct client *cl)
1125 struct connection *new;
1131 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1133 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1137 if (0 == strlen(global_parameters.zproxy_override)){
1138 /* no Z39.50 proxy needed - direct connect */
1139 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
1141 if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
1143 yaz_log(YLOG_WARN|YLOG_ERRNO,
1144 "Lookup of IP address %s failed",
1145 cl->database->database->host->ipport);
1150 /* Z39.50 proxy connect */
1151 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1152 cl->database->database->url, global_parameters.zproxy_override);
1154 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1156 yaz_log(YLOG_WARN|YLOG_ERRNO,
1157 "Lookup of IP address %s failed",
1158 global_parameters.zproxy_override);
1163 res = cs_connect(link, addr);
1166 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
1170 if ((new = connection_freelist))
1171 connection_freelist = new->next;
1174 new = xmalloc(sizeof (struct connection));
1178 new->state = Conn_Connecting;
1179 new->host = cl->database->database->host;
1180 new->next = new->host->connections;
1181 new->host->connections = new;
1183 cl->connection = new;
1186 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1187 iochan_setdata(new->iochan, new);
1188 new->iochan->next = channel_list;
1189 channel_list = new->iochan;
1193 // Close connection and set state to error
1194 static void client_fatal(struct client *cl)
1196 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
1197 connection_destroy(cl->connection);
1198 cl->state = Client_Error;
1201 // Ensure that client has a connection associated
1202 static int client_prep_connection(struct client *cl)
1204 struct connection *co;
1205 struct session *se = cl->session;
1206 struct host *host = cl->database->database->host;
1208 co = cl->connection;
1210 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
1214 // See if someone else has an idle connection
1215 // We should look at timestamps here to select the longest-idle connection
1216 for (co = host->connections; co; co = co->next)
1217 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1221 connection_release(co);
1222 cl->connection = co;
1226 co = connection_create(cl);
1230 if (co->state == Conn_Connecting)
1232 cl->state = Client_Connecting;
1233 iochan_setflag(co->iochan, EVENT_OUTPUT);
1235 else if (co->state == Conn_Open)
1237 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1238 cl->state = Client_Idle;
1239 iochan_setflag(co->iochan, EVENT_OUTPUT);
1247 // Parse the query given the settings specific to this client
1248 static int client_parse_query(struct client *cl)
1250 struct session *se = cl->session;
1251 struct ccl_rpn_node *cn;
1254 cn = ccl_find_str(cl->database->database->ccl_map, se->query, &cerror, &cpos);
1257 cl->state = Client_Error;
1258 yaz_log(YLOG_WARN, "Failed to parse query for %s",
1259 cl->database->database->url);
1262 wrbuf_rewind(se->wrbuf);
1263 ccl_pquery(se->wrbuf, cn);
1264 wrbuf_putc(se->wrbuf, '\0');
1267 cl->pquery = xstrdup(wrbuf_buf(se->wrbuf));
1271 // Initialize relevance structure with query terms
1273 extract_terms(se->nmem, cn, p);
1274 se->relevance = relevance_create(se->nmem, (const char **) p,
1275 se->expected_maxrecs);
1282 static struct client *client_create(void)
1285 if (client_freelist)
1287 r = client_freelist;
1288 client_freelist = client_freelist->next;
1291 r = xmalloc(sizeof(struct client));
1301 r->state = Client_Disconnected;
1306 void client_destroy(struct client *c)
1308 struct session *se = c->session;
1309 if (c == se->clients)
1310 se->clients = c->next;
1314 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1320 connection_release(c->connection);
1321 c->next = client_freelist;
1322 client_freelist = c;
1325 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1327 s->watchlist[what].fun = fun;
1328 s->watchlist[what].data = data;
1331 void session_alert_watch(struct session *s, int what)
1333 if (!s->watchlist[what].fun)
1335 (*s->watchlist[what].fun)(s->watchlist[what].data);
1336 s->watchlist[what].fun = 0;
1337 s->watchlist[what].data = 0;
1340 //callback for grep_databases
1341 static void select_targets_callback(void *context, struct session_database *db)
1343 struct session *se = (struct session*) context;
1344 struct client *cl = client_create();
1347 cl->next = se->clients;
1351 // Associates a set of clients with a session;
1352 // Note: Session-databases represent databases with per-session setting overrides
1353 int select_targets(struct session *se, struct database_criterion *crit)
1356 client_destroy(se->clients);
1358 return session_grep_databases(se, crit, select_targets_callback);
1361 int session_active_clients(struct session *s)
1366 for (c = s->clients; c; c = c->next)
1367 if (c->connection && (c->state == Client_Connecting ||
1368 c->state == Client_Initializing ||
1369 c->state == Client_Searching ||
1370 c->state == Client_Presenting))
1376 // parses crit1=val1,crit2=val2|val3,...
1377 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1379 struct database_criterion *res = 0;
1386 nmem_strsplit(m, ",", buf, &values, &num);
1387 for (i = 0; i < num; i++)
1392 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1393 char *eq = strchr(values[i], '=');
1396 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1400 new->name = values[i];
1401 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1403 for (subi = 0; subi < subnum; subi++)
1405 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1406 newv->value = subvalues[subi];
1407 newv->next = new->values;
1416 char *search(struct session *se, char *query, char *filter)
1418 int live_channels = 0;
1420 struct database_criterion *criteria;
1422 yaz_log(YLOG_DEBUG, "Search");
1424 nmem_reset(se->nmem);
1425 criteria = parse_filter(se->nmem, filter);
1426 strcpy(se->query, query);
1428 live_channels = select_targets(se, criteria);
1431 int maxrecs = live_channels * global_parameters.toget;
1432 se->num_termlists = 0;
1433 se->reclist = reclist_create(se->nmem, maxrecs);
1434 // This will be initialized in send_search()
1435 se->total_records = se->total_hits = se->total_merged = 0;
1436 se->expected_maxrecs = maxrecs;
1442 for (cl = se->clients; cl; cl = cl->next)
1443 if (client_parse_query(cl) < 0) // Query must parse for all targets
1445 for (cl = se->clients; cl; cl = cl->next)
1446 client_prep_connection(cl);
1451 // Apply a session override to a database
1452 void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
1454 struct session_database *sdb;
1456 for (sdb = se->databases; sdb; sdb = sdb->next)
1457 if (!strcmp(dbname, sdb->database->url))
1459 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
1460 int offset = settings_offset(setting);
1464 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
1467 new->precedence = 0;
1468 new->target = dbname;
1469 new->name = setting;
1471 new->next = sdb->settings[offset];
1472 sdb->settings[offset] = new;
1476 yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
1479 void session_init_databases_fun(void *context, struct database *db)
1481 struct session *se = (struct session *) context;
1482 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
1483 int num = settings_num();
1487 new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
1488 for (i = 0; i < num; i++)
1489 new->settings[i] = db->settings[i];
1490 new->next = se->databases;
1491 se->databases = new;
1494 // Initialize session_database list -- this represents this session's view
1495 // of the database list -- subject to modification by the settings ws command
1496 void session_init_databases(struct session *se)
1499 grep_databases(se, 0, session_init_databases_fun);
1502 void destroy_session(struct session *s)
1504 yaz_log(YLOG_LOG, "Destroying session");
1506 client_destroy(s->clients);
1507 nmem_destroy(s->nmem);
1508 wrbuf_destroy(s->wrbuf);
1511 struct session *new_session(NMEM nmem)
1514 struct session *session = nmem_malloc(nmem, sizeof(*session));
1516 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
1518 session->total_hits = 0;
1519 session->total_records = 0;
1520 session->num_termlists = 0;
1521 session->reclist = 0;
1522 session->requestid = -1;
1523 session->clients = 0;
1524 session->expected_maxrecs = 0;
1525 session->query[0] = '\0';
1526 session->session_nmem = nmem;
1527 session->nmem = nmem_create();
1528 session->wrbuf = wrbuf_alloc();
1529 session_init_databases(session);
1530 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1532 session->watchlist[i].data = 0;
1533 session->watchlist[i].fun = 0;
1539 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1541 static struct hitsbytarget res[1000]; // FIXME MM
1545 for (cl = se->clients; cl; cl = cl->next)
1547 char *name = session_setting_oneval(cl->database, PZ_NAME);
1549 res[*count].id = cl->database->database->url;
1550 res[*count].name = *name ? name : "Unknown";
1551 res[*count].hits = cl->hits;
1552 res[*count].records = cl->records;
1553 res[*count].diagnostic = cl->diagnostic;
1554 res[*count].state = client_states[cl->state];
1555 res[*count].connected = cl->connection ? 1 : 0;
1562 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1566 for (i = 0; i < s->num_termlists; i++)
1567 if (!strcmp((const char *) s->termlists[i].name, name))
1568 return termlist_highscore(s->termlists[i].termlist, num);
1572 #ifdef MISSING_HEADERS
1573 void report_nmem_stats(void)
1575 size_t in_use, is_free;
1577 nmem_get_memory_in_use(&in_use);
1578 nmem_get_memory_free(&is_free);
1580 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1581 (long) in_use, (long) is_free);
1585 struct record_cluster *show_single(struct session *s, int id)
1587 struct record_cluster *r;
1589 reclist_rewind(s->reclist);
1590 while ((r = reclist_read_record(s->reclist)))
1596 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1597 int *num, int *total, int *sumhits, NMEM nmem_show)
1599 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1600 * sizeof(struct record_cluster *));
1601 struct reclist_sortparms *spp;
1604 yaz_timing_t t = yaz_timing_create();
1607 for (spp = sp; spp; spp = spp->next)
1608 if (spp->type == Metadata_sortkey_relevance)
1610 relevance_prepare_read(s->relevance, s->reclist);
1613 reclist_sort(s->reclist, sp);
1615 *total = s->reclist->num_records;
1616 *sumhits = s->total_hits;
1618 for (i = 0; i < start; i++)
1619 if (!reclist_read_record(s->reclist))
1626 for (i = 0; i < *num; i++)
1628 struct record_cluster *r = reclist_read_record(s->reclist);
1638 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1639 yaz_timing_get_real(t), yaz_timing_get_user(t),
1640 yaz_timing_get_sys(t));
1641 yaz_timing_destroy(&t);
1646 void statistics(struct session *se, struct statistics *stat)
1651 memset(stat, 0, sizeof(*stat));
1652 for (cl = se->clients; cl; cl = cl->next)
1654 if (!cl->connection)
1655 stat->num_no_connection++;
1658 case Client_Connecting: stat->num_connecting++; break;
1659 case Client_Initializing: stat->num_initializing++; break;
1660 case Client_Searching: stat->num_searching++; break;
1661 case Client_Presenting: stat->num_presenting++; break;
1662 case Client_Idle: stat->num_idle++; break;
1663 case Client_Failed: stat->num_failed++; break;
1664 case Client_Error: stat->num_error++; break;
1669 stat->num_hits = se->total_hits;
1670 stat->num_records = se->total_records;
1672 stat->num_clients = count;
1675 void start_http_listener(void)
1678 struct conf_server *ser = global_parameters.server;
1680 if (*global_parameters.listener_override)
1681 strcpy(hp, global_parameters.listener_override);
1684 strcpy(hp, ser->host ? ser->host : "");
1689 sprintf(hp + strlen(hp), "%d", ser->port);
1695 void start_proxy(void)
1698 struct conf_server *ser = global_parameters.server;
1700 if (*global_parameters.proxy_override)
1701 strcpy(hp, global_parameters.proxy_override);
1702 else if (ser->proxy_host || ser->proxy_port)
1704 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1705 if (ser->proxy_port)
1709 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1715 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1718 void start_zproxy(void)
1720 struct conf_server *ser = global_parameters.server;
1722 if (*global_parameters.zproxy_override){
1723 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1724 global_parameters.zproxy_override);
1728 else if (ser->zproxy_host || ser->zproxy_port)
1732 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1733 if (ser->zproxy_port)
1740 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1742 strcpy(global_parameters.zproxy_override, hp);
1743 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1744 global_parameters.zproxy_override);
1756 * indent-tabs-mode: nil
1758 * vim: shiftwidth=4 tabstop=8 expandtab