1 /* $Id: pazpar2.c,v 1.73 2007-04-11 18:42:25 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>
49 #include <yaz/timing.h>
52 #include <netinet/in.h>
57 #include "termlists.h"
59 #include "relevance.h"
66 static void client_fatal(struct client *cl);
67 static void connection_destroy(struct connection *co);
68 static int client_prep_connection(struct client *cl);
69 static void ingest_records(struct client *cl, Z_Records *r);
70 void session_alert_watch(struct session *s, int what);
72 IOCHAN channel_list = 0; // Master list of connections we're handling events to
74 static struct connection *connection_freelist = 0;
75 static struct client *client_freelist = 0;
77 static char *client_states[] = {
81 "Client_Initializing",
86 "Client_Disconnected",
90 // Note: Some things in this structure will eventually move to configuration
91 struct parameters global_parameters =
101 "Index Data PazPar2 (MasterKey)",
111 static int send_apdu(struct client *c, Z_APDU *a)
113 struct connection *co = c->connection;
117 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
119 odr_perror(global_parameters.odr_out, "Encoding APDU");
122 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
123 r = cs_put(co->link, buf, len);
126 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
131 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
134 odr_reset(global_parameters.odr_out); /* release the APDU structure */
135 co->state = Conn_Waiting;
139 // Set authentication token in init if one is set for the client
140 // TODO: Extend this to handle other schemes than open (should be simple)
141 static void init_authentication(struct client *cl, Z_InitRequest *req)
143 struct session_database *sdb = cl->database;
144 char *auth = session_setting_oneval(sdb, PZ_AUTHENTICATION);
148 Z_IdAuthentication *idAuth = odr_malloc(global_parameters.odr_out,
150 idAuth->which = Z_IdAuthentication_open;
151 idAuth->u.open = auth;
152 req->idAuthentication = idAuth;
156 static void send_init(IOCHAN i)
159 struct connection *co = iochan_getdata(i);
160 struct client *cl = co->client;
161 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
163 a->u.initRequest->implementationId = global_parameters.implementationId;
164 a->u.initRequest->implementationName = global_parameters.implementationName;
165 a->u.initRequest->implementationVersion =
166 global_parameters.implementationVersion;
167 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
168 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
169 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
171 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
172 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
173 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
175 init_authentication(cl, a->u.initRequest);
177 /* add virtual host if tunneling through Z39.50 proxy */
179 if (0 < strlen(global_parameters.zproxy_override)
180 && 0 < strlen(cl->database->database->url))
181 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
182 global_parameters.odr_out, VAL_PROXY,
183 1, cl->database->database->url);
185 if (send_apdu(cl, a) >= 0)
187 iochan_setflags(i, EVENT_INPUT);
188 cl->state = Client_Initializing;
191 cl->state = Client_Error;
192 odr_reset(global_parameters.odr_out);
195 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
203 pull_terms(nmem, n->u.p[0], termlist, num);
204 pull_terms(nmem, n->u.p[1], termlist, num);
207 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
214 // Extract terms from query into null-terminated termlist
215 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
219 pull_terms(nmem, query, termlist, &num);
223 static void send_search(IOCHAN i)
225 struct connection *co = iochan_getdata(i);
226 struct client *cl = co->client;
227 struct session *se = cl->session;
228 struct session_database *sdb = cl->database;
229 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
230 int ndb, cerror, cpos;
233 struct ccl_rpn_node *cn;
234 int ssub = 0, lslb = 100000, mspn = 10;
238 yaz_log(YLOG_DEBUG, "Sending search");
240 cn = ccl_find_str(sdb->database->ccl_map, se->query, &cerror, &cpos);
246 // Initialize relevance structure with query terms
248 extract_terms(se->nmem, cn, p);
249 se->relevance = relevance_create(se->nmem, (const char **) p,
250 se->expected_maxrecs);
253 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
255 zquery->which = Z_Query_type_1;
256 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
259 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
261 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
262 for (ndb = 0; sdb->database->databases[ndb]; ndb++)
263 databaselist[ndb] = sdb->database->databases[ndb];
265 if (!(piggyback = session_setting_oneval(sdb, PZ_PIGGYBACK)) || *piggyback == '1')
267 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
268 a->u.searchRequest->preferredRecordSyntax =
269 yaz_str_to_z3950oid(global_parameters.odr_out,
270 CLASS_RECSYN, recsyn);
271 a->u.searchRequest->smallSetUpperBound = &ssub;
272 a->u.searchRequest->largeSetLowerBound = &lslb;
273 a->u.searchRequest->mediumSetPresentNumber = &mspn;
275 a->u.searchRequest->resultSetName = "Default";
276 a->u.searchRequest->databaseNames = databaselist;
277 a->u.searchRequest->num_databaseNames = ndb;
279 if (send_apdu(cl, a) >= 0)
281 iochan_setflags(i, EVENT_INPUT);
282 cl->state = Client_Searching;
283 cl->requestid = se->requestid;
286 cl->state = Client_Error;
288 odr_reset(global_parameters.odr_out);
291 static void send_present(IOCHAN i)
293 struct connection *co = iochan_getdata(i);
294 struct client *cl = co->client;
295 struct session_database *sdb = cl->database;
296 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
298 int start = cl->records + 1;
301 toget = global_parameters.chunk;
302 if (toget > global_parameters.toget - cl->records)
303 toget = global_parameters.toget - cl->records;
304 if (toget > cl->hits - cl->records)
305 toget = cl->hits - cl->records;
307 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
309 a->u.presentRequest->resultSetStartPoint = &start;
310 a->u.presentRequest->numberOfRecordsRequested = &toget;
312 a->u.presentRequest->resultSetId = "Default";
314 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
315 a->u.presentRequest->preferredRecordSyntax =
316 yaz_str_to_z3950oid(global_parameters.odr_out,
317 CLASS_RECSYN, recsyn);
319 if (send_apdu(cl, a) >= 0)
321 iochan_setflags(i, EVENT_INPUT);
322 cl->state = Client_Presenting;
325 cl->state = Client_Error;
326 odr_reset(global_parameters.odr_out);
329 static void do_initResponse(IOCHAN i, Z_APDU *a)
331 struct connection *co = iochan_getdata(i);
332 struct client *cl = co->client;
333 Z_InitResponse *r = a->u.initResponse;
335 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->database->url);
339 cl->state = Client_Idle;
342 cl->state = Client_Failed; // FIXME need to do something to the connection
345 static void do_searchResponse(IOCHAN i, Z_APDU *a)
347 struct connection *co = iochan_getdata(i);
348 struct client *cl = co->client;
349 struct session *se = cl->session;
350 Z_SearchResponse *r = a->u.searchResponse;
352 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
353 cl->database->database->url, *r->searchStatus);
355 if (*r->searchStatus)
357 cl->hits = *r->resultCount;
358 se->total_hits += cl->hits;
359 if (r->presentStatus && !*r->presentStatus && r->records)
361 yaz_log(YLOG_DEBUG, "Records in search response %s",
362 cl->database->database->url);
363 ingest_records(cl, r->records);
365 cl->state = Client_Idle;
370 cl->state = Client_Error;
372 Z_Records *recs = r->records;
373 if (recs->which == Z_Records_NSD)
376 "Search response: Non-surrogate diagnostic %s",
377 cl->database->database->url);
378 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
379 cl->state = Client_Error;
385 static void do_closeResponse(IOCHAN i, Z_APDU *a)
387 struct connection *co = iochan_getdata(i);
388 struct client *cl = co->client;
389 /* Z_Close *r = a->u.close; */
391 yaz_log(YLOG_WARN, "Close response %s", cl->database->database->url);
393 cl->state = Client_Failed;
394 connection_destroy(co);
398 char *normalize_mergekey(char *buf, int skiparticle)
400 char *p = buf, *pout = buf;
405 char articles[] = "the den der die des an a "; // must end in space
407 while (*p && !isalnum(*p))
410 while (*p && *p != ' ' && pout - firstword < 62)
411 *(pout++) = tolower(*(p++));
414 if (!strstr(articles, firstword))
421 while (*p && !isalnum(*p))
424 *(pout++) = tolower(*(p++));
427 while (*p && !isalnum(*p))
434 while (pout > buf && *pout == ' ');
439 static void add_facet(struct session *s, const char *type, const char *value)
445 for (i = 0; i < s->num_termlists; i++)
446 if (!strcmp(s->termlists[i].name, type))
448 if (i == s->num_termlists)
450 if (i == SESSION_MAX_TERMLISTS)
452 yaz_log(YLOG_FATAL, "Too many termlists");
455 s->termlists[i].name = nmem_strdup(s->nmem, type);
456 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
457 s->num_termlists = i + 1;
459 termlist_insert(s->termlists[i].termlist, value);
462 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
464 struct database_retrievalmap *m;
465 struct database *db = cl->database->database;
469 // First normalize to XML
474 if (rec->which != Z_External_octet)
476 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
477 cl->database->database->url);
480 buf = (char*) rec->u.octet_aligned->buf;
481 len = rec->u.octet_aligned->len;
482 if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
484 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
485 cl->database->database->url);
488 if (yaz_marc_write_xml(db->yaz_marc, &res,
489 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
491 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
492 cl->database->database->url);
495 rdoc = xmlNewDoc((xmlChar *) "1.0");
496 xmlDocSetRootElement(rdoc, res);
500 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
504 if (global_parameters.dump_records)
506 fprintf(stderr, "Input Record (normalized):\n----------------\n");
507 #if LIBXML_VERSION >= 20600
508 xmlDocFormatDump(stderr, rdoc, 1);
510 xmlDocDump(stderr, rdoc);
514 for (m = db->map; m; m = m->next)
517 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
519 yaz_log(YLOG_WARN, "XSLT transformation failed");
525 if (global_parameters.dump_records)
527 fprintf(stderr, "Record:\n----------------\n");
528 #if LIBXML_VERSION >= 20600
529 xmlDocFormatDump(stderr, rdoc, 1);
531 xmlDocDump(stderr, rdoc);
537 // Extract what appears to be years from buf, storing highest and
539 static int extract_years(const char *buf, int *first, int *last)
548 while (*buf && !isdigit(*buf))
551 for (e = buf; *e && isdigit(*e); e++)
555 int value = atoi(buf);
556 if (*first < 0 || value < *first)
558 if (*last < 0 || value > *last)
566 static struct record *ingest_record(struct client *cl, Z_External *rec)
568 xmlDoc *xdoc = normalize_record(cl, rec);
571 struct record_cluster *cluster;
572 struct session *se = cl->session;
573 xmlChar *mergekey, *mergekey_norm;
576 struct conf_service *service = global_parameters.server->service;
581 root = xmlDocGetRootElement(xdoc);
582 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
584 yaz_log(YLOG_WARN, "No mergekey found in record");
589 res = nmem_malloc(se->nmem, sizeof(struct record));
592 res->metadata = nmem_malloc(se->nmem,
593 sizeof(struct record_metadata*) * service->num_metadata);
594 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
596 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
598 normalize_mergekey((char *) mergekey_norm, 0);
600 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
602 if (global_parameters.dump_records)
603 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
604 cl->database->database->url, cl->records);
607 /* no room for record */
611 relevance_newrec(se->relevance, cluster);
613 for (n = root->children; n; n = n->next)
621 if (n->type != XML_ELEMENT_NODE)
623 if (!strcmp((const char *) n->name, "metadata"))
625 struct conf_metadata *md = 0;
626 struct conf_sortkey *sk = 0;
627 struct record_metadata **wheretoput, *newm;
631 type = xmlGetProp(n, (xmlChar *) "type");
632 value = xmlNodeListGetString(xdoc, n->children, 0);
637 // First, find out what field we're looking at
638 for (imeta = 0; imeta < service->num_metadata; imeta++)
639 if (!strcmp((const char *) type, service->metadata[imeta].name))
641 md = &service->metadata[imeta];
642 if (md->sortkey_offset >= 0)
643 sk = &service->sortkeys[md->sortkey_offset];
648 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
652 // Find out where we are putting it
653 if (md->merge == Metadata_merge_no)
654 wheretoput = &res->metadata[imeta];
656 wheretoput = &cluster->metadata[imeta];
659 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
661 if (md->type == Metadata_type_generic)
664 for (p = (char *) value; *p && isspace(*p); p++)
666 for (pe = p + strlen(p) - 1;
667 pe > p && strchr(" ,/.:([", *pe); pe--)
669 newm->data.text = nmem_strdup(se->nmem, p);
672 else if (md->type == Metadata_type_year)
674 if (extract_years((char *) value, &first, &last) < 0)
679 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
682 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
684 yaz_log(YLOG_WARN, "Only range merging supported for years");
687 if (md->merge == Metadata_merge_unique)
689 struct record_metadata *mnode;
690 for (mnode = *wheretoput; mnode; mnode = mnode->next)
691 if (!strcmp((const char *) mnode->data.text, newm->data.text))
695 newm->next = *wheretoput;
699 else if (md->merge == Metadata_merge_longest)
702 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
707 char *s = nmem_strdup(se->nmem, newm->data.text);
708 if (!cluster->sortkeys[md->sortkey_offset])
709 cluster->sortkeys[md->sortkey_offset] =
710 nmem_malloc(se->nmem, sizeof(union data_types));
711 normalize_mergekey(s,
712 (sk->type == Metadata_sortkey_skiparticle));
713 cluster->sortkeys[md->sortkey_offset]->text = s;
717 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
719 newm->next = *wheretoput;
722 else if (md->merge == Metadata_merge_range)
724 assert(md->type == Metadata_type_year);
728 (*wheretoput)->data.number.min = first;
729 (*wheretoput)->data.number.max = last;
731 cluster->sortkeys[md->sortkey_offset] = &newm->data;
735 if (first < (*wheretoput)->data.number.min)
736 (*wheretoput)->data.number.min = first;
737 if (last > (*wheretoput)->data.number.max)
738 (*wheretoput)->data.number.max = last;
743 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
744 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
749 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
752 relevance_countwords(se->relevance, cluster,
753 (char *) value, md->rank);
756 if (md->type == Metadata_type_year)
759 sprintf(year, "%d", last);
760 add_facet(se, (char *) type, year);
763 sprintf(year, "%d", first);
764 add_facet(se, (char *) type, year);
768 add_facet(se, (char *) type, (char *) value);
775 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
784 relevance_donerecord(se->relevance, cluster);
790 // Retrieve first defined value for 'name' for given database.
791 // Will be extended to take into account user associated with session
792 char *session_setting_oneval(struct session_database *db, int offset)
794 if (!db->settings[offset])
796 return db->settings[offset]->value;
799 static void ingest_records(struct client *cl, Z_Records *r)
802 yaz_timing_t t = yaz_timing_create();
805 struct session *s = cl->session;
806 Z_NamePlusRecordList *rlist;
809 if (r->which != Z_Records_DBOSD)
811 rlist = r->u.databaseOrSurDiagnostics;
812 for (i = 0; i < rlist->num_records; i++)
814 Z_NamePlusRecord *npr = rlist->records[i];
817 if (npr->which != Z_NamePlusRecord_databaseRecord)
820 "Unexpected record type, probably diagnostic %s",
821 cl->database->database->url);
825 rec = ingest_record(cl, npr->u.databaseRecord);
829 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
830 session_alert_watch(s, SESSION_WATCH_RECORDS);
834 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
835 yaz_timing_get_real(t), yaz_timing_get_user(t),
836 yaz_timing_get_sys(t));
837 yaz_timing_destroy(&t);
841 static void do_presentResponse(IOCHAN i, Z_APDU *a)
843 struct connection *co = iochan_getdata(i);
844 struct client *cl = co->client;
845 Z_PresentResponse *r = a->u.presentResponse;
848 Z_Records *recs = r->records;
849 if (recs->which == Z_Records_NSD)
851 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
852 cl->database->database->url);
853 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
854 cl->state = Client_Error;
858 if (!*r->presentStatus && cl->state != Client_Error)
860 yaz_log(YLOG_DEBUG, "Good Present response %s",
861 cl->database->database->url);
862 ingest_records(cl, r->records);
863 cl->state = Client_Idle;
865 else if (*r->presentStatus)
867 yaz_log(YLOG_WARN, "Bad Present response %s",
868 cl->database->database->url);
869 cl->state = Client_Error;
873 static void handler(IOCHAN i, int event)
875 struct connection *co = iochan_getdata(i);
876 struct client *cl = co->client;
877 struct session *se = 0;
883 yaz_log(YLOG_WARN, "Destroying orphan connection");
884 connection_destroy(co);
888 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
891 socklen_t errlen = sizeof(errcode);
893 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
894 &errlen) < 0 || errcode != 0)
901 yaz_log(YLOG_DEBUG, "Connect OK");
902 co->state = Conn_Open;
904 cl->state = Client_Connected;
908 else if (event & EVENT_INPUT)
910 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
914 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
915 cl->database->database->url);
916 connection_destroy(co);
921 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
922 connection_destroy(co);
925 else if (len > 1) // We discard input if we have no connection
927 co->state = Conn_Open;
929 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
933 odr_reset(global_parameters.odr_in);
934 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
935 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
942 case Z_APDU_initResponse:
943 do_initResponse(i, a);
945 case Z_APDU_searchResponse:
946 do_searchResponse(i, a);
948 case Z_APDU_presentResponse:
949 do_presentResponse(i, a);
952 do_closeResponse(i, a);
956 "Unexpected Z39.50 response from %s",
957 cl->database->database->url);
961 // We aren't expecting staggered output from target
962 // if (cs_more(t->link))
963 // iochan_setevent(i, EVENT_INPUT);
965 else // we throw away response and go to idle mode
967 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
968 cl->state = Client_Idle;
971 /* if len==1 we do nothing but wait for more input */
974 if (cl->state == Client_Connected) {
978 if (cl->state == Client_Idle)
980 if (cl->requestid != se->requestid && *se->query) {
983 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
984 cl->records < cl->hits) {
990 // Disassociate connection from client
991 static void connection_release(struct connection *co)
993 struct client *cl = co->client;
995 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1002 // Close connection and recycle structure
1003 static void connection_destroy(struct connection *co)
1005 struct host *h = co->host;
1007 iochan_destroy(co->iochan);
1009 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1010 if (h->connections == co)
1011 h->connections = co->next;
1014 struct connection *pco;
1015 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1018 pco->next = co->next;
1024 if (co->client->state != Client_Idle)
1025 co->client->state = Client_Disconnected;
1026 co->client->connection = 0;
1028 co->next = connection_freelist;
1029 connection_freelist = co;
1032 // Creates a new connection for client, associated with the host of
1033 // client's database
1034 static struct connection *connection_create(struct client *cl)
1036 struct connection *new;
1042 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1044 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1048 if (0 == strlen(global_parameters.zproxy_override)){
1049 /* no Z39.50 proxy needed - direct connect */
1050 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
1052 if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
1054 yaz_log(YLOG_WARN|YLOG_ERRNO,
1055 "Lookup of IP address %s failed",
1056 cl->database->database->host->ipport);
1061 /* Z39.50 proxy connect */
1062 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1063 cl->database->database->url, global_parameters.zproxy_override);
1065 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1067 yaz_log(YLOG_WARN|YLOG_ERRNO,
1068 "Lookup of IP address %s failed",
1069 global_parameters.zproxy_override);
1074 res = cs_connect(link, addr);
1077 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
1081 if ((new = connection_freelist))
1082 connection_freelist = new->next;
1085 new = xmalloc(sizeof (struct connection));
1089 new->state = Conn_Connecting;
1090 new->host = cl->database->database->host;
1091 new->next = new->host->connections;
1092 new->host->connections = new;
1094 cl->connection = new;
1097 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1098 iochan_setdata(new->iochan, new);
1099 new->iochan->next = channel_list;
1100 channel_list = new->iochan;
1104 // Close connection and set state to error
1105 static void client_fatal(struct client *cl)
1107 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
1108 connection_destroy(cl->connection);
1109 cl->state = Client_Error;
1112 // Ensure that client has a connection associated
1113 static int client_prep_connection(struct client *cl)
1115 struct connection *co;
1116 struct session *se = cl->session;
1117 struct host *host = cl->database->database->host;
1119 co = cl->connection;
1121 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
1125 // See if someone else has an idle connection
1126 // We should look at timestamps here to select the longest-idle connection
1127 for (co = host->connections; co; co = co->next)
1128 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1132 connection_release(co);
1133 cl->connection = co;
1137 co = connection_create(cl);
1141 if (co->state == Conn_Connecting)
1143 cl->state = Client_Connecting;
1144 iochan_setflag(co->iochan, EVENT_OUTPUT);
1146 else if (co->state == Conn_Open)
1148 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1149 cl->state = Client_Idle;
1150 iochan_setflag(co->iochan, EVENT_OUTPUT);
1158 static struct client *client_create(void)
1161 if (client_freelist)
1163 r = client_freelist;
1164 client_freelist = client_freelist->next;
1167 r = xmalloc(sizeof(struct client));
1176 r->state = Client_Disconnected;
1181 void client_destroy(struct client *c)
1183 struct session *se = c->session;
1184 if (c == se->clients)
1185 se->clients = c->next;
1189 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1195 connection_release(c->connection);
1196 c->next = client_freelist;
1197 client_freelist = c;
1200 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1202 s->watchlist[what].fun = fun;
1203 s->watchlist[what].data = data;
1206 void session_alert_watch(struct session *s, int what)
1208 if (!s->watchlist[what].fun)
1210 (*s->watchlist[what].fun)(s->watchlist[what].data);
1211 s->watchlist[what].fun = 0;
1212 s->watchlist[what].data = 0;
1215 //callback for grep_databases
1216 static void select_targets_callback(void *context, struct session_database *db)
1218 struct session *se = (struct session*) context;
1219 struct client *cl = client_create();
1222 cl->next = se->clients;
1226 // Associates a set of clients with a session;
1227 // Note: Session-databases represent databases with per-session setting overrides
1228 int select_targets(struct session *se, struct database_criterion *crit)
1231 client_destroy(se->clients);
1233 return session_grep_databases(se, crit, select_targets_callback);
1236 int session_active_clients(struct session *s)
1241 for (c = s->clients; c; c = c->next)
1242 if (c->connection && (c->state == Client_Connecting ||
1243 c->state == Client_Initializing ||
1244 c->state == Client_Searching ||
1245 c->state == Client_Presenting))
1251 // parses crit1=val1,crit2=val2|val3,...
1252 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1254 struct database_criterion *res = 0;
1261 nmem_strsplit(m, ",", buf, &values, &num);
1262 for (i = 0; i < num; i++)
1267 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1268 char *eq = strchr(values[i], '=');
1271 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1275 new->name = values[i];
1276 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1278 for (subi = 0; subi < subnum; subi++)
1280 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1281 newv->value = subvalues[subi];
1282 newv->next = new->values;
1291 char *search(struct session *se, char *query, char *filter)
1293 int live_channels = 0;
1295 struct database_criterion *criteria;
1297 yaz_log(YLOG_DEBUG, "Search");
1299 nmem_reset(se->nmem);
1300 criteria = parse_filter(se->nmem, filter);
1301 strcpy(se->query, query);
1303 select_targets(se, criteria);
1304 for (cl = se->clients; cl; cl = cl->next)
1306 if (client_prep_connection(cl))
1311 int maxrecs = live_channels * global_parameters.toget;
1312 se->num_termlists = 0;
1313 se->reclist = reclist_create(se->nmem, maxrecs);
1314 // This will be initialized in send_search()
1316 se->total_records = se->total_hits = se->total_merged = 0;
1317 se->expected_maxrecs = maxrecs;
1325 // Apply a session override to a database
1326 void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
1328 struct session_database *sdb;
1330 for (sdb = se->databases; sdb; sdb = sdb->next)
1331 if (!strcmp(dbname, sdb->database->url))
1333 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
1334 int offset = settings_offset(setting);
1338 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
1341 new->precedence = 0;
1342 new->target = dbname;
1343 new->name = setting;
1346 new->next = sdb->settings[offset];
1347 sdb->settings[offset] = new;
1351 yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
1354 void session_init_databases_fun(void *context, struct database *db)
1356 struct session *se = (struct session *) context;
1357 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
1358 int num = settings_num();
1362 new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
1363 for (i = 0; i < num; i++)
1364 new->settings[i] = db->settings[i];
1365 new->next = se->databases;
1366 se->databases = new;
1369 // Initialize session_database list -- this represents this session's view
1370 // of the database list -- subject to modification by the settings ws command
1371 void session_init_databases(struct session *se)
1374 grep_databases(se, 0, session_init_databases_fun);
1377 void destroy_session(struct session *s)
1379 yaz_log(YLOG_LOG, "Destroying session");
1381 client_destroy(s->clients);
1382 nmem_destroy(s->nmem);
1383 wrbuf_destroy(s->wrbuf);
1386 struct session *new_session(NMEM nmem)
1389 struct session *session = nmem_malloc(nmem, sizeof(*session));
1391 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
1393 session->total_hits = 0;
1394 session->total_records = 0;
1395 session->num_termlists = 0;
1396 session->reclist = 0;
1397 session->requestid = -1;
1398 session->clients = 0;
1399 session->expected_maxrecs = 0;
1400 session->query[0] = '\0';
1401 session->session_nmem = nmem;
1402 session->nmem = nmem_create();
1403 session->wrbuf = wrbuf_alloc();
1404 session_init_databases(session);
1405 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1407 session->watchlist[i].data = 0;
1408 session->watchlist[i].fun = 0;
1414 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1416 static struct hitsbytarget res[1000]; // FIXME MM
1420 for (cl = se->clients; cl; cl = cl->next)
1422 char *name = session_setting_oneval(cl->database, PZ_NAME);
1424 res[*count].id = cl->database->database->url;
1425 res[*count].name = *name ? name : "Unknown";
1426 res[*count].hits = cl->hits;
1427 res[*count].records = cl->records;
1428 res[*count].diagnostic = cl->diagnostic;
1429 res[*count].state = client_states[cl->state];
1430 res[*count].connected = cl->connection ? 1 : 0;
1437 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1441 for (i = 0; i < s->num_termlists; i++)
1442 if (!strcmp((const char *) s->termlists[i].name, name))
1443 return termlist_highscore(s->termlists[i].termlist, num);
1447 #ifdef MISSING_HEADERS
1448 void report_nmem_stats(void)
1450 size_t in_use, is_free;
1452 nmem_get_memory_in_use(&in_use);
1453 nmem_get_memory_free(&is_free);
1455 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1456 (long) in_use, (long) is_free);
1460 struct record_cluster *show_single(struct session *s, int id)
1462 struct record_cluster *r;
1464 reclist_rewind(s->reclist);
1465 while ((r = reclist_read_record(s->reclist)))
1471 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1472 int *num, int *total, int *sumhits, NMEM nmem_show)
1474 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1475 * sizeof(struct record_cluster *));
1476 struct reclist_sortparms *spp;
1479 yaz_timing_t t = yaz_timing_create();
1482 for (spp = sp; spp; spp = spp->next)
1483 if (spp->type == Metadata_sortkey_relevance)
1485 relevance_prepare_read(s->relevance, s->reclist);
1488 reclist_sort(s->reclist, sp);
1490 *total = s->reclist->num_records;
1491 *sumhits = s->total_hits;
1493 for (i = 0; i < start; i++)
1494 if (!reclist_read_record(s->reclist))
1501 for (i = 0; i < *num; i++)
1503 struct record_cluster *r = reclist_read_record(s->reclist);
1513 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1514 yaz_timing_get_real(t), yaz_timing_get_user(t),
1515 yaz_timing_get_sys(t));
1516 yaz_timing_destroy(&t);
1521 void statistics(struct session *se, struct statistics *stat)
1526 memset(stat, 0, sizeof(*stat));
1527 for (cl = se->clients; cl; cl = cl->next)
1529 if (!cl->connection)
1530 stat->num_no_connection++;
1533 case Client_Connecting: stat->num_connecting++; break;
1534 case Client_Initializing: stat->num_initializing++; break;
1535 case Client_Searching: stat->num_searching++; break;
1536 case Client_Presenting: stat->num_presenting++; break;
1537 case Client_Idle: stat->num_idle++; break;
1538 case Client_Failed: stat->num_failed++; break;
1539 case Client_Error: stat->num_error++; break;
1544 stat->num_hits = se->total_hits;
1545 stat->num_records = se->total_records;
1547 stat->num_clients = count;
1550 static void start_http_listener(void)
1553 struct conf_server *ser = global_parameters.server;
1555 if (*global_parameters.listener_override)
1556 strcpy(hp, global_parameters.listener_override);
1559 strcpy(hp, ser->host ? ser->host : "");
1564 sprintf(hp + strlen(hp), "%d", ser->port);
1570 static void start_proxy(void)
1573 struct conf_server *ser = global_parameters.server;
1575 if (*global_parameters.proxy_override)
1576 strcpy(hp, global_parameters.proxy_override);
1577 else if (ser->proxy_host || ser->proxy_port)
1579 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1580 if (ser->proxy_port)
1584 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1590 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1593 static void start_zproxy(void)
1595 struct conf_server *ser = global_parameters.server;
1597 if (*global_parameters.zproxy_override){
1598 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1599 global_parameters.zproxy_override);
1603 else if (ser->zproxy_host || ser->zproxy_port)
1607 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1608 if (ser->zproxy_port)
1615 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1617 strcpy(global_parameters.zproxy_override, hp);
1618 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1619 global_parameters.zproxy_override);
1628 int main(int argc, char **argv)
1633 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1634 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1636 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1638 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1642 if (!read_config(arg))
1646 strcpy(global_parameters.listener_override, arg);
1649 strcpy(global_parameters.proxy_override, arg);
1652 strcpy(global_parameters.zproxy_override, arg);
1655 strcpy(global_parameters.settings_path_override, arg);
1658 load_simpletargets(arg);
1661 global_parameters.dump_records = 1;
1664 fprintf(stderr, "Usage: pazpar2\n"
1666 " -h [host:]port (REST protocol listener)\n"
1668 " -s simpletargetfile\n"
1669 " -p hostname[:portno] (HTTP proxy)\n"
1670 " -z hostname[:portno] (Z39.50 proxy)\n"
1671 " -d (show internal records)\n");
1678 yaz_log(YLOG_FATAL, "Load config with -f");
1681 global_parameters.server = config->servers;
1683 start_http_listener();
1687 if (*global_parameters.settings_path_override)
1688 settings_read(global_parameters.settings_path_override);
1689 else if (global_parameters.server->settings)
1690 settings_read(global_parameters.server->settings);
1692 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may well ensue!");
1693 prepare_databases();
1694 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1695 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1697 event_loop(&channel_list);
1705 * indent-tabs-mode: nil
1707 * vim: shiftwidth=4 tabstop=8 expandtab