1 /* $Id: pazpar2.c,v 1.76 2007-04-12 12:05:22 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/querytowrbuf.h>
50 #include <yaz/timing.h>
53 #include <netinet/in.h>
58 #include "termlists.h"
60 #include "relevance.h"
67 static void client_fatal(struct client *cl);
68 static void connection_destroy(struct connection *co);
69 static int client_prep_connection(struct client *cl);
70 static void ingest_records(struct client *cl, Z_Records *r);
71 void session_alert_watch(struct session *s, int what);
73 IOCHAN channel_list = 0; // Master list of connections we're handling events to
75 static struct connection *connection_freelist = 0;
76 static struct client *client_freelist = 0;
78 static char *client_states[] = {
82 "Client_Initializing",
87 "Client_Disconnected",
91 // Note: Some things in this structure will eventually move to configuration
92 struct parameters global_parameters =
102 "Index Data PazPar2 (MasterKey)",
112 static int send_apdu(struct client *c, Z_APDU *a)
114 struct connection *co = c->connection;
118 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
120 odr_perror(global_parameters.odr_out, "Encoding APDU");
123 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
124 r = cs_put(co->link, buf, len);
127 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
132 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
135 odr_reset(global_parameters.odr_out); /* release the APDU structure */
136 co->state = Conn_Waiting;
140 // Set authentication token in init if one is set for the client
141 // TODO: Extend this to handle other schemes than open (should be simple)
142 static void init_authentication(struct client *cl, Z_InitRequest *req)
144 struct session_database *sdb = cl->database;
145 char *auth = session_setting_oneval(sdb, PZ_AUTHENTICATION);
149 Z_IdAuthentication *idAuth = odr_malloc(global_parameters.odr_out,
151 idAuth->which = Z_IdAuthentication_open;
152 idAuth->u.open = auth;
153 req->idAuthentication = idAuth;
157 static void send_init(IOCHAN i)
160 struct connection *co = iochan_getdata(i);
161 struct client *cl = co->client;
162 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
164 a->u.initRequest->implementationId = global_parameters.implementationId;
165 a->u.initRequest->implementationName = global_parameters.implementationName;
166 a->u.initRequest->implementationVersion =
167 global_parameters.implementationVersion;
168 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
169 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
170 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
172 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
173 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
174 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
176 init_authentication(cl, a->u.initRequest);
178 /* add virtual host if tunneling through Z39.50 proxy */
180 if (0 < strlen(global_parameters.zproxy_override)
181 && 0 < strlen(cl->database->database->url))
182 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
183 global_parameters.odr_out, VAL_PROXY,
184 1, cl->database->database->url);
186 if (send_apdu(cl, a) >= 0)
188 iochan_setflags(i, EVENT_INPUT);
189 cl->state = Client_Initializing;
192 cl->state = Client_Error;
193 odr_reset(global_parameters.odr_out);
196 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
204 pull_terms(nmem, n->u.p[0], termlist, num);
205 pull_terms(nmem, n->u.p[1], termlist, num);
208 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
215 // Extract terms from query into null-terminated termlist
216 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
220 pull_terms(nmem, query, termlist, &num);
224 static void send_search(IOCHAN i)
226 struct connection *co = iochan_getdata(i);
227 struct client *cl = co->client;
228 struct session *se = cl->session;
229 struct session_database *sdb = cl->database;
230 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
231 int ndb, cerror, cpos;
234 struct ccl_rpn_node *cn;
235 int ssub = 0, lslb = 100000, mspn = 10;
239 yaz_log(YLOG_DEBUG, "Sending search to %s", cl->database->database->url);
241 cn = ccl_find_str(sdb->database->ccl_map, se->query, &cerror, &cpos);
247 // Initialize relevance structure with query terms
249 extract_terms(se->nmem, cn, p);
250 se->relevance = relevance_create(se->nmem, (const char **) p,
251 se->expected_maxrecs);
254 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
256 zquery->which = Z_Query_type_1;
257 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
260 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
262 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
263 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
264 databaselist[ndb] = sdb->database->databases[ndb];
266 if (!(piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK)) || *piggyback == '1')
268 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
269 a->u.searchRequest->preferredRecordSyntax =
270 yaz_str_to_z3950oid(global_parameters.odr_out,
271 CLASS_RECSYN, recsyn);
272 a->u.searchRequest->smallSetUpperBound = &ssub;
273 a->u.searchRequest->largeSetLowerBound = &lslb;
274 a->u.searchRequest->mediumSetPresentNumber = &mspn;
276 a->u.searchRequest->resultSetName = "Default";
277 a->u.searchRequest->databaseNames = databaselist;
278 a->u.searchRequest->num_databaseNames = ndb;
281 { //scope for sending and logging queries
282 WRBUF wbquery = wrbuf_alloc();
283 yaz_query_to_wrbuf(wbquery, zquery);
285 if (send_apdu(cl, a) >= 0)
287 iochan_setflags(i, EVENT_INPUT);
288 cl->state = Client_Searching;
289 cl->requestid = se->requestid;
290 yaz_log(YLOG_LOG, "SearchRequest %s %s",
291 cl->database->database->url, wrbuf_cstr(wbquery));
294 cl->state = Client_Error;
295 yaz_log(YLOG_WARN, "Failed SearchRequest %s %s",
296 cl->database->database->url, wrbuf_cstr(wbquery));
299 wrbuf_destroy(wbquery);
302 odr_reset(global_parameters.odr_out);
305 static void send_present(IOCHAN i)
307 struct connection *co = iochan_getdata(i);
308 struct client *cl = co->client;
309 struct session_database *sdb = cl->database;
310 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
312 int start = cl->records + 1;
315 toget = global_parameters.chunk;
316 if (toget > global_parameters.toget - cl->records)
317 toget = global_parameters.toget - cl->records;
318 if (toget > cl->hits - cl->records)
319 toget = cl->hits - cl->records;
321 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
323 a->u.presentRequest->resultSetStartPoint = &start;
324 a->u.presentRequest->numberOfRecordsRequested = &toget;
326 a->u.presentRequest->resultSetId = "Default";
328 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
329 a->u.presentRequest->preferredRecordSyntax =
330 yaz_str_to_z3950oid(global_parameters.odr_out,
331 CLASS_RECSYN, recsyn);
333 if (send_apdu(cl, a) >= 0)
335 iochan_setflags(i, EVENT_INPUT);
336 cl->state = Client_Presenting;
339 cl->state = Client_Error;
340 odr_reset(global_parameters.odr_out);
343 static void do_initResponse(IOCHAN i, Z_APDU *a)
345 struct connection *co = iochan_getdata(i);
346 struct client *cl = co->client;
347 Z_InitResponse *r = a->u.initResponse;
349 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->database->url);
353 cl->state = Client_Idle;
356 cl->state = Client_Failed; // FIXME need to do something to the connection
359 static void do_searchResponse(IOCHAN i, Z_APDU *a)
361 struct connection *co = iochan_getdata(i);
362 struct client *cl = co->client;
363 struct session *se = cl->session;
364 Z_SearchResponse *r = a->u.searchResponse;
366 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
367 cl->database->database->url, *r->searchStatus);
369 if (*r->searchStatus)
371 cl->hits = *r->resultCount;
372 se->total_hits += cl->hits;
373 if (r->presentStatus && !*r->presentStatus && r->records)
375 yaz_log(YLOG_DEBUG, "Records in search response %s",
376 cl->database->database->url);
377 ingest_records(cl, r->records);
379 cl->state = Client_Idle;
384 cl->state = Client_Error;
386 Z_Records *recs = r->records;
387 if (recs->which == Z_Records_NSD)
390 "Search response: Non-surrogate diagnostic %s",
391 cl->database->database->url);
392 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
393 cl->state = Client_Error;
399 static void do_closeResponse(IOCHAN i, Z_APDU *a)
401 struct connection *co = iochan_getdata(i);
402 struct client *cl = co->client;
403 /* Z_Close *r = a->u.close; */
405 yaz_log(YLOG_WARN, "Close response %s", cl->database->database->url);
407 cl->state = Client_Failed;
408 connection_destroy(co);
412 char *normalize_mergekey(char *buf, int skiparticle)
414 char *p = buf, *pout = buf;
419 char articles[] = "the den der die des an a "; // must end in space
421 while (*p && !isalnum(*p))
424 while (*p && *p != ' ' && pout - firstword < 62)
425 *(pout++) = tolower(*(p++));
428 if (!strstr(articles, firstword))
435 while (*p && !isalnum(*p))
438 *(pout++) = tolower(*(p++));
441 while (*p && !isalnum(*p))
448 while (pout > buf && *pout == ' ');
453 static void add_facet(struct session *s, const char *type, const char *value)
459 for (i = 0; i < s->num_termlists; i++)
460 if (!strcmp(s->termlists[i].name, type))
462 if (i == s->num_termlists)
464 if (i == SESSION_MAX_TERMLISTS)
466 yaz_log(YLOG_FATAL, "Too many termlists");
469 s->termlists[i].name = nmem_strdup(s->nmem, type);
470 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
471 s->num_termlists = i + 1;
473 termlist_insert(s->termlists[i].termlist, value);
476 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
478 struct database_retrievalmap *m;
479 struct database *db = cl->database->database;
483 // First normalize to XML
488 if (rec->which != Z_External_octet)
490 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
491 cl->database->database->url);
494 buf = (char*) rec->u.octet_aligned->buf;
495 len = rec->u.octet_aligned->len;
496 if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
498 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
499 cl->database->database->url);
503 yaz_marc_write_using_libxml2(db->yaz_marc, 1);
504 if (yaz_marc_write_xml(db->yaz_marc, &res,
505 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
507 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
508 cl->database->database->url);
511 rdoc = xmlNewDoc((xmlChar *) "1.0");
512 xmlDocSetRootElement(rdoc, res);
518 "Unknown native_syntax in normalize_record from %s",
519 cl->database->database->url);
523 if (global_parameters.dump_records){
525 "Input Record (normalized) from %s\n----------------\n",
526 cl->database->database->url);
527 #if LIBXML_VERSION >= 20600
528 xmlDocFormatDump(stderr, rdoc, 1);
530 xmlDocDump(stderr, rdoc);
534 for (m = db->map; m; m = m->next){
540 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
541 root= xmlDocGetRootElement(new);
542 if (!new || !root || !(root->children))
544 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
545 cl->database->database->url);
554 // do it another way to detect transformation errors right now
555 // but does not seem to work either!
557 xsltTransformContextPtr ctxt;
558 ctxt = xsltNewTransformContext(m->stylesheet, rdoc);
559 new = xsltApplyStylesheetUser(m->stylesheet, rdoc, 0, 0, 0, ctxt);
560 if ((ctxt->state == XSLT_STATE_ERROR) ||
561 (ctxt->state == XSLT_STATE_STOPPED)){
562 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
563 cl->database->database->url);
574 if (global_parameters.dump_records)
576 fprintf(stderr, "Record from %s\n----------------\n",
577 cl->database->database->url);
578 #if LIBXML_VERSION >= 20600
579 xmlDocFormatDump(stderr, rdoc, 1);
581 xmlDocDump(stderr, rdoc);
587 // Extract what appears to be years from buf, storing highest and
589 static int extract_years(const char *buf, int *first, int *last)
598 while (*buf && !isdigit(*buf))
601 for (e = buf; *e && isdigit(*e); e++)
605 int value = atoi(buf);
606 if (*first < 0 || value < *first)
608 if (*last < 0 || value > *last)
616 static struct record *ingest_record(struct client *cl, Z_External *rec)
618 xmlDoc *xdoc = normalize_record(cl, rec);
621 struct record_cluster *cluster;
622 struct session *se = cl->session;
623 xmlChar *mergekey, *mergekey_norm;
626 struct conf_service *service = global_parameters.server->service;
631 root = xmlDocGetRootElement(xdoc);
632 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
634 yaz_log(YLOG_WARN, "No mergekey found in record");
639 res = nmem_malloc(se->nmem, sizeof(struct record));
642 res->metadata = nmem_malloc(se->nmem,
643 sizeof(struct record_metadata*) * service->num_metadata);
644 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
646 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
648 normalize_mergekey((char *) mergekey_norm, 0);
650 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
652 if (global_parameters.dump_records)
653 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
654 cl->database->database->url, cl->records);
657 /* no room for record */
661 relevance_newrec(se->relevance, cluster);
663 for (n = root->children; n; n = n->next)
671 if (n->type != XML_ELEMENT_NODE)
673 if (!strcmp((const char *) n->name, "metadata"))
675 struct conf_metadata *md = 0;
676 struct conf_sortkey *sk = 0;
677 struct record_metadata **wheretoput, *newm;
681 type = xmlGetProp(n, (xmlChar *) "type");
682 value = xmlNodeListGetString(xdoc, n->children, 0);
687 // First, find out what field we're looking at
688 for (imeta = 0; imeta < service->num_metadata; imeta++)
689 if (!strcmp((const char *) type, service->metadata[imeta].name))
691 md = &service->metadata[imeta];
692 if (md->sortkey_offset >= 0)
693 sk = &service->sortkeys[md->sortkey_offset];
698 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
702 // Find out where we are putting it
703 if (md->merge == Metadata_merge_no)
704 wheretoput = &res->metadata[imeta];
706 wheretoput = &cluster->metadata[imeta];
709 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
711 if (md->type == Metadata_type_generic)
714 for (p = (char *) value; *p && isspace(*p); p++)
716 for (pe = p + strlen(p) - 1;
717 pe > p && strchr(" ,/.:([", *pe); pe--)
719 newm->data.text = nmem_strdup(se->nmem, p);
722 else if (md->type == Metadata_type_year)
724 if (extract_years((char *) value, &first, &last) < 0)
729 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
732 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
734 yaz_log(YLOG_WARN, "Only range merging supported for years");
737 if (md->merge == Metadata_merge_unique)
739 struct record_metadata *mnode;
740 for (mnode = *wheretoput; mnode; mnode = mnode->next)
741 if (!strcmp((const char *) mnode->data.text, newm->data.text))
745 newm->next = *wheretoput;
749 else if (md->merge == Metadata_merge_longest)
752 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
757 char *s = nmem_strdup(se->nmem, newm->data.text);
758 if (!cluster->sortkeys[md->sortkey_offset])
759 cluster->sortkeys[md->sortkey_offset] =
760 nmem_malloc(se->nmem, sizeof(union data_types));
761 normalize_mergekey(s,
762 (sk->type == Metadata_sortkey_skiparticle));
763 cluster->sortkeys[md->sortkey_offset]->text = s;
767 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
769 newm->next = *wheretoput;
772 else if (md->merge == Metadata_merge_range)
774 assert(md->type == Metadata_type_year);
778 (*wheretoput)->data.number.min = first;
779 (*wheretoput)->data.number.max = last;
781 cluster->sortkeys[md->sortkey_offset] = &newm->data;
785 if (first < (*wheretoput)->data.number.min)
786 (*wheretoput)->data.number.min = first;
787 if (last > (*wheretoput)->data.number.max)
788 (*wheretoput)->data.number.max = last;
793 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
794 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
799 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
802 relevance_countwords(se->relevance, cluster,
803 (char *) value, md->rank);
806 if (md->type == Metadata_type_year)
809 sprintf(year, "%d", last);
810 add_facet(se, (char *) type, year);
813 sprintf(year, "%d", first);
814 add_facet(se, (char *) type, year);
818 add_facet(se, (char *) type, (char *) value);
825 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
834 relevance_donerecord(se->relevance, cluster);
840 // Retrieve first defined value for 'name' for given database.
841 // Will be extended to take into account user associated with session
842 char *session_setting_oneval(struct session_database *db, int offset)
844 if (!db->settings[offset])
846 return db->settings[offset]->value;
849 static void ingest_records(struct client *cl, Z_Records *r)
852 yaz_timing_t t = yaz_timing_create();
855 struct session *s = cl->session;
856 Z_NamePlusRecordList *rlist;
859 if (r->which != Z_Records_DBOSD)
861 rlist = r->u.databaseOrSurDiagnostics;
862 for (i = 0; i < rlist->num_records; i++)
864 Z_NamePlusRecord *npr = rlist->records[i];
867 if (npr->which != Z_NamePlusRecord_databaseRecord)
870 "Unexpected record type, probably diagnostic %s",
871 cl->database->database->url);
875 rec = ingest_record(cl, npr->u.databaseRecord);
879 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
880 session_alert_watch(s, SESSION_WATCH_RECORDS);
884 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
885 yaz_timing_get_real(t), yaz_timing_get_user(t),
886 yaz_timing_get_sys(t));
887 yaz_timing_destroy(&t);
891 static void do_presentResponse(IOCHAN i, Z_APDU *a)
893 struct connection *co = iochan_getdata(i);
894 struct client *cl = co->client;
895 Z_PresentResponse *r = a->u.presentResponse;
898 Z_Records *recs = r->records;
899 if (recs->which == Z_Records_NSD)
901 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
902 cl->database->database->url);
903 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
904 cl->state = Client_Error;
908 if (!*r->presentStatus && cl->state != Client_Error)
910 yaz_log(YLOG_DEBUG, "Good Present response %s",
911 cl->database->database->url);
912 ingest_records(cl, r->records);
913 cl->state = Client_Idle;
915 else if (*r->presentStatus)
917 yaz_log(YLOG_WARN, "Bad Present response %s",
918 cl->database->database->url);
919 cl->state = Client_Error;
923 static void handler(IOCHAN i, int event)
925 struct connection *co = iochan_getdata(i);
926 struct client *cl = co->client;
927 struct session *se = 0;
933 yaz_log(YLOG_WARN, "Destroying orphan connection");
934 connection_destroy(co);
938 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
941 socklen_t errlen = sizeof(errcode);
943 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
944 &errlen) < 0 || errcode != 0)
951 yaz_log(YLOG_DEBUG, "Connect OK");
952 co->state = Conn_Open;
954 cl->state = Client_Connected;
958 else if (event & EVENT_INPUT)
960 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
964 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
965 cl->database->database->url);
966 connection_destroy(co);
971 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
972 connection_destroy(co);
975 else if (len > 1) // We discard input if we have no connection
977 co->state = Conn_Open;
979 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
983 odr_reset(global_parameters.odr_in);
984 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
985 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
992 case Z_APDU_initResponse:
993 do_initResponse(i, a);
995 case Z_APDU_searchResponse:
996 do_searchResponse(i, a);
998 case Z_APDU_presentResponse:
999 do_presentResponse(i, a);
1002 do_closeResponse(i, a);
1006 "Unexpected Z39.50 response from %s",
1007 cl->database->database->url);
1011 // We aren't expecting staggered output from target
1012 // if (cs_more(t->link))
1013 // iochan_setevent(i, EVENT_INPUT);
1015 else // we throw away response and go to idle mode
1017 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
1018 cl->state = Client_Idle;
1021 /* if len==1 we do nothing but wait for more input */
1024 if (cl->state == Client_Connected) {
1028 if (cl->state == Client_Idle)
1030 if (cl->requestid != se->requestid && *se->query) {
1033 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
1034 cl->records < cl->hits) {
1040 // Disassociate connection from client
1041 static void connection_release(struct connection *co)
1043 struct client *cl = co->client;
1045 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1052 // Close connection and recycle structure
1053 static void connection_destroy(struct connection *co)
1055 struct host *h = co->host;
1057 iochan_destroy(co->iochan);
1059 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1060 if (h->connections == co)
1061 h->connections = co->next;
1064 struct connection *pco;
1065 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1068 pco->next = co->next;
1074 if (co->client->state != Client_Idle)
1075 co->client->state = Client_Disconnected;
1076 co->client->connection = 0;
1078 co->next = connection_freelist;
1079 connection_freelist = co;
1082 // Creates a new connection for client, associated with the host of
1083 // client's database
1084 static struct connection *connection_create(struct client *cl)
1086 struct connection *new;
1092 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1094 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1098 if (0 == strlen(global_parameters.zproxy_override)){
1099 /* no Z39.50 proxy needed - direct connect */
1100 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
1102 if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
1104 yaz_log(YLOG_WARN|YLOG_ERRNO,
1105 "Lookup of IP address %s failed",
1106 cl->database->database->host->ipport);
1111 /* Z39.50 proxy connect */
1112 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1113 cl->database->database->url, global_parameters.zproxy_override);
1115 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1117 yaz_log(YLOG_WARN|YLOG_ERRNO,
1118 "Lookup of IP address %s failed",
1119 global_parameters.zproxy_override);
1124 res = cs_connect(link, addr);
1127 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
1131 if ((new = connection_freelist))
1132 connection_freelist = new->next;
1135 new = xmalloc(sizeof (struct connection));
1139 new->state = Conn_Connecting;
1140 new->host = cl->database->database->host;
1141 new->next = new->host->connections;
1142 new->host->connections = new;
1144 cl->connection = new;
1147 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1148 iochan_setdata(new->iochan, new);
1149 new->iochan->next = channel_list;
1150 channel_list = new->iochan;
1154 // Close connection and set state to error
1155 static void client_fatal(struct client *cl)
1157 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
1158 connection_destroy(cl->connection);
1159 cl->state = Client_Error;
1162 // Ensure that client has a connection associated
1163 static int client_prep_connection(struct client *cl)
1165 struct connection *co;
1166 struct session *se = cl->session;
1167 struct host *host = cl->database->database->host;
1169 co = cl->connection;
1171 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
1175 // See if someone else has an idle connection
1176 // We should look at timestamps here to select the longest-idle connection
1177 for (co = host->connections; co; co = co->next)
1178 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1182 connection_release(co);
1183 cl->connection = co;
1187 co = connection_create(cl);
1191 if (co->state == Conn_Connecting)
1193 cl->state = Client_Connecting;
1194 iochan_setflag(co->iochan, EVENT_OUTPUT);
1196 else if (co->state == Conn_Open)
1198 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1199 cl->state = Client_Idle;
1200 iochan_setflag(co->iochan, EVENT_OUTPUT);
1208 static struct client *client_create(void)
1211 if (client_freelist)
1213 r = client_freelist;
1214 client_freelist = client_freelist->next;
1217 r = xmalloc(sizeof(struct client));
1226 r->state = Client_Disconnected;
1231 void client_destroy(struct client *c)
1233 struct session *se = c->session;
1234 if (c == se->clients)
1235 se->clients = c->next;
1239 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1245 connection_release(c->connection);
1246 c->next = client_freelist;
1247 client_freelist = c;
1250 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1252 s->watchlist[what].fun = fun;
1253 s->watchlist[what].data = data;
1256 void session_alert_watch(struct session *s, int what)
1258 if (!s->watchlist[what].fun)
1260 (*s->watchlist[what].fun)(s->watchlist[what].data);
1261 s->watchlist[what].fun = 0;
1262 s->watchlist[what].data = 0;
1265 //callback for grep_databases
1266 static void select_targets_callback(void *context, struct session_database *db)
1268 struct session *se = (struct session*) context;
1269 struct client *cl = client_create();
1272 cl->next = se->clients;
1276 // Associates a set of clients with a session;
1277 // Note: Session-databases represent databases with per-session setting overrides
1278 int select_targets(struct session *se, struct database_criterion *crit)
1281 client_destroy(se->clients);
1283 return session_grep_databases(se, crit, select_targets_callback);
1286 int session_active_clients(struct session *s)
1291 for (c = s->clients; c; c = c->next)
1292 if (c->connection && (c->state == Client_Connecting ||
1293 c->state == Client_Initializing ||
1294 c->state == Client_Searching ||
1295 c->state == Client_Presenting))
1301 // parses crit1=val1,crit2=val2|val3,...
1302 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1304 struct database_criterion *res = 0;
1311 nmem_strsplit(m, ",", buf, &values, &num);
1312 for (i = 0; i < num; i++)
1317 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1318 char *eq = strchr(values[i], '=');
1321 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1325 new->name = values[i];
1326 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1328 for (subi = 0; subi < subnum; subi++)
1330 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1331 newv->value = subvalues[subi];
1332 newv->next = new->values;
1341 char *search(struct session *se, char *query, char *filter)
1343 int live_channels = 0;
1345 struct database_criterion *criteria;
1347 yaz_log(YLOG_DEBUG, "Search");
1349 nmem_reset(se->nmem);
1350 criteria = parse_filter(se->nmem, filter);
1351 strcpy(se->query, query);
1353 select_targets(se, criteria);
1354 for (cl = se->clients; cl; cl = cl->next)
1356 if (client_prep_connection(cl))
1361 int maxrecs = live_channels * global_parameters.toget;
1362 se->num_termlists = 0;
1363 se->reclist = reclist_create(se->nmem, maxrecs);
1364 // This will be initialized in send_search()
1366 se->total_records = se->total_hits = se->total_merged = 0;
1367 se->expected_maxrecs = maxrecs;
1375 // Apply a session override to a database
1376 void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
1378 struct session_database *sdb;
1380 for (sdb = se->databases; sdb; sdb = sdb->next)
1381 if (!strcmp(dbname, sdb->database->url))
1383 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
1384 int offset = settings_offset(setting);
1388 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
1391 new->precedence = 0;
1392 new->target = dbname;
1393 new->name = setting;
1395 new->next = sdb->settings[offset];
1396 sdb->settings[offset] = new;
1400 yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
1403 void session_init_databases_fun(void *context, struct database *db)
1405 struct session *se = (struct session *) context;
1406 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
1407 int num = settings_num();
1411 new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
1412 for (i = 0; i < num; i++)
1413 new->settings[i] = db->settings[i];
1414 new->next = se->databases;
1415 se->databases = new;
1418 // Initialize session_database list -- this represents this session's view
1419 // of the database list -- subject to modification by the settings ws command
1420 void session_init_databases(struct session *se)
1423 grep_databases(se, 0, session_init_databases_fun);
1426 void destroy_session(struct session *s)
1428 yaz_log(YLOG_LOG, "Destroying session");
1430 client_destroy(s->clients);
1431 nmem_destroy(s->nmem);
1432 wrbuf_destroy(s->wrbuf);
1435 struct session *new_session(NMEM nmem)
1438 struct session *session = nmem_malloc(nmem, sizeof(*session));
1440 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
1442 session->total_hits = 0;
1443 session->total_records = 0;
1444 session->num_termlists = 0;
1445 session->reclist = 0;
1446 session->requestid = -1;
1447 session->clients = 0;
1448 session->expected_maxrecs = 0;
1449 session->query[0] = '\0';
1450 session->session_nmem = nmem;
1451 session->nmem = nmem_create();
1452 session->wrbuf = wrbuf_alloc();
1453 session_init_databases(session);
1454 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1456 session->watchlist[i].data = 0;
1457 session->watchlist[i].fun = 0;
1463 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1465 static struct hitsbytarget res[1000]; // FIXME MM
1469 for (cl = se->clients; cl; cl = cl->next)
1471 char *name = session_setting_oneval(cl->database, PZ_NAME);
1473 res[*count].id = cl->database->database->url;
1474 res[*count].name = *name ? name : "Unknown";
1475 res[*count].hits = cl->hits;
1476 res[*count].records = cl->records;
1477 res[*count].diagnostic = cl->diagnostic;
1478 res[*count].state = client_states[cl->state];
1479 res[*count].connected = cl->connection ? 1 : 0;
1486 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1490 for (i = 0; i < s->num_termlists; i++)
1491 if (!strcmp((const char *) s->termlists[i].name, name))
1492 return termlist_highscore(s->termlists[i].termlist, num);
1496 #ifdef MISSING_HEADERS
1497 void report_nmem_stats(void)
1499 size_t in_use, is_free;
1501 nmem_get_memory_in_use(&in_use);
1502 nmem_get_memory_free(&is_free);
1504 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1505 (long) in_use, (long) is_free);
1509 struct record_cluster *show_single(struct session *s, int id)
1511 struct record_cluster *r;
1513 reclist_rewind(s->reclist);
1514 while ((r = reclist_read_record(s->reclist)))
1520 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1521 int *num, int *total, int *sumhits, NMEM nmem_show)
1523 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1524 * sizeof(struct record_cluster *));
1525 struct reclist_sortparms *spp;
1528 yaz_timing_t t = yaz_timing_create();
1531 for (spp = sp; spp; spp = spp->next)
1532 if (spp->type == Metadata_sortkey_relevance)
1534 relevance_prepare_read(s->relevance, s->reclist);
1537 reclist_sort(s->reclist, sp);
1539 *total = s->reclist->num_records;
1540 *sumhits = s->total_hits;
1542 for (i = 0; i < start; i++)
1543 if (!reclist_read_record(s->reclist))
1550 for (i = 0; i < *num; i++)
1552 struct record_cluster *r = reclist_read_record(s->reclist);
1562 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1563 yaz_timing_get_real(t), yaz_timing_get_user(t),
1564 yaz_timing_get_sys(t));
1565 yaz_timing_destroy(&t);
1570 void statistics(struct session *se, struct statistics *stat)
1575 memset(stat, 0, sizeof(*stat));
1576 for (cl = se->clients; cl; cl = cl->next)
1578 if (!cl->connection)
1579 stat->num_no_connection++;
1582 case Client_Connecting: stat->num_connecting++; break;
1583 case Client_Initializing: stat->num_initializing++; break;
1584 case Client_Searching: stat->num_searching++; break;
1585 case Client_Presenting: stat->num_presenting++; break;
1586 case Client_Idle: stat->num_idle++; break;
1587 case Client_Failed: stat->num_failed++; break;
1588 case Client_Error: stat->num_error++; break;
1593 stat->num_hits = se->total_hits;
1594 stat->num_records = se->total_records;
1596 stat->num_clients = count;
1599 static void start_http_listener(void)
1602 struct conf_server *ser = global_parameters.server;
1604 if (*global_parameters.listener_override)
1605 strcpy(hp, global_parameters.listener_override);
1608 strcpy(hp, ser->host ? ser->host : "");
1613 sprintf(hp + strlen(hp), "%d", ser->port);
1619 static void start_proxy(void)
1622 struct conf_server *ser = global_parameters.server;
1624 if (*global_parameters.proxy_override)
1625 strcpy(hp, global_parameters.proxy_override);
1626 else if (ser->proxy_host || ser->proxy_port)
1628 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1629 if (ser->proxy_port)
1633 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1639 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1642 static void start_zproxy(void)
1644 struct conf_server *ser = global_parameters.server;
1646 if (*global_parameters.zproxy_override){
1647 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1648 global_parameters.zproxy_override);
1652 else if (ser->zproxy_host || ser->zproxy_port)
1656 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1657 if (ser->zproxy_port)
1664 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1666 strcpy(global_parameters.zproxy_override, hp);
1667 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1668 global_parameters.zproxy_override);
1677 int main(int argc, char **argv)
1682 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1683 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1685 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1687 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1691 if (!read_config(arg))
1695 strcpy(global_parameters.listener_override, arg);
1698 strcpy(global_parameters.proxy_override, arg);
1701 strcpy(global_parameters.zproxy_override, arg);
1704 strcpy(global_parameters.settings_path_override, arg);
1707 load_simpletargets(arg);
1710 global_parameters.dump_records = 1;
1713 fprintf(stderr, "Usage: pazpar2\n"
1715 " -h [host:]port (REST protocol listener)\n"
1717 " -s simpletargetfile\n"
1718 " -p hostname[:portno] (HTTP proxy)\n"
1719 " -z hostname[:portno] (Z39.50 proxy)\n"
1720 " -d (show internal records)\n");
1727 yaz_log(YLOG_FATAL, "Load config with -f");
1730 global_parameters.server = config->servers;
1732 start_http_listener();
1736 if (*global_parameters.settings_path_override)
1737 settings_read(global_parameters.settings_path_override);
1738 else if (global_parameters.server->settings)
1739 settings_read(global_parameters.server->settings);
1741 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may well ensue!");
1742 prepare_databases();
1743 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1744 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1746 event_loop(&channel_list);
1754 * indent-tabs-mode: nil
1756 * vim: shiftwidth=4 tabstop=8 expandtab