1 /* $Id: pazpar2.c,v 1.71 2007-04-11 02:14:15 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);
71 char *session_setting_oneval(struct session_database *db, int offset);
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");
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;
280 if (send_apdu(cl, a) >= 0)
282 iochan_setflags(i, EVENT_INPUT);
283 cl->state = Client_Searching;
284 cl->requestid = se->requestid;
287 cl->state = Client_Error;
289 odr_reset(global_parameters.odr_out);
292 static void send_present(IOCHAN i)
294 struct connection *co = iochan_getdata(i);
295 struct client *cl = co->client;
296 struct session_database *sdb = cl->database;
297 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
299 int start = cl->records + 1;
302 toget = global_parameters.chunk;
303 if (toget > global_parameters.toget - cl->records)
304 toget = global_parameters.toget - cl->records;
305 if (toget > cl->hits - cl->records)
306 toget = cl->hits - cl->records;
308 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
310 a->u.presentRequest->resultSetStartPoint = &start;
311 a->u.presentRequest->numberOfRecordsRequested = &toget;
313 a->u.presentRequest->resultSetId = "Default";
315 if ((recsyn = session_setting_oneval(sdb, PZ_REQUESTSYNTAX)))
316 a->u.presentRequest->preferredRecordSyntax =
317 yaz_str_to_z3950oid(global_parameters.odr_out,
318 CLASS_RECSYN, recsyn);
320 if (send_apdu(cl, a) >= 0)
322 iochan_setflags(i, EVENT_INPUT);
323 cl->state = Client_Presenting;
326 cl->state = Client_Error;
327 odr_reset(global_parameters.odr_out);
330 static void do_initResponse(IOCHAN i, Z_APDU *a)
332 struct connection *co = iochan_getdata(i);
333 struct client *cl = co->client;
334 Z_InitResponse *r = a->u.initResponse;
336 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->database->url);
340 cl->state = Client_Idle;
343 cl->state = Client_Failed; // FIXME need to do something to the connection
346 static void do_searchResponse(IOCHAN i, Z_APDU *a)
348 struct connection *co = iochan_getdata(i);
349 struct client *cl = co->client;
350 struct session *se = cl->session;
351 Z_SearchResponse *r = a->u.searchResponse;
353 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
354 cl->database->database->url, *r->searchStatus);
356 if (*r->searchStatus)
358 cl->hits = *r->resultCount;
359 se->total_hits += cl->hits;
360 if (r->presentStatus && !*r->presentStatus && r->records)
362 yaz_log(YLOG_DEBUG, "Records in search response %s",
363 cl->database->database->url);
364 ingest_records(cl, r->records);
366 cl->state = Client_Idle;
371 cl->state = Client_Error;
373 Z_Records *recs = r->records;
374 if (recs->which == Z_Records_NSD)
377 "Search response: Non-surrogate diagnostic %s",
378 cl->database->database->url);
379 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
380 cl->state = Client_Error;
386 static void do_closeResponse(IOCHAN i, Z_APDU *a)
388 struct connection *co = iochan_getdata(i);
389 struct client *cl = co->client;
390 /* Z_Close *r = a->u.close; */
392 yaz_log(YLOG_WARN, "Close response %s", cl->database->database->url);
394 cl->state = Client_Failed;
395 connection_destroy(co);
399 char *normalize_mergekey(char *buf, int skiparticle)
401 char *p = buf, *pout = buf;
406 char articles[] = "the den der die des an a "; // must end in space
408 while (*p && !isalnum(*p))
411 while (*p && *p != ' ' && pout - firstword < 62)
412 *(pout++) = tolower(*(p++));
415 if (!strstr(articles, firstword))
422 while (*p && !isalnum(*p))
425 *(pout++) = tolower(*(p++));
428 while (*p && !isalnum(*p))
435 while (pout > buf && *pout == ' ');
440 static void add_facet(struct session *s, const char *type, const char *value)
446 for (i = 0; i < s->num_termlists; i++)
447 if (!strcmp(s->termlists[i].name, type))
449 if (i == s->num_termlists)
451 if (i == SESSION_MAX_TERMLISTS)
453 yaz_log(YLOG_FATAL, "Too many termlists");
456 s->termlists[i].name = nmem_strdup(s->nmem, type);
457 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
458 s->num_termlists = i + 1;
460 termlist_insert(s->termlists[i].termlist, value);
463 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
465 struct database_retrievalmap *m;
466 struct database *db = cl->database->database;
470 // First normalize to XML
475 if (rec->which != Z_External_octet)
477 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
478 cl->database->database->url);
481 buf = (char*) rec->u.octet_aligned->buf;
482 len = rec->u.octet_aligned->len;
483 if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
485 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
486 cl->database->database->url);
489 if (yaz_marc_write_xml(db->yaz_marc, &res,
490 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
492 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
493 cl->database->database->url);
496 rdoc = xmlNewDoc((xmlChar *) "1.0");
497 xmlDocSetRootElement(rdoc, res);
501 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
505 if (global_parameters.dump_records)
507 fprintf(stderr, "Input Record (normalized):\n----------------\n");
508 #if LIBXML_VERSION >= 20600
509 xmlDocFormatDump(stderr, rdoc, 1);
511 xmlDocDump(stderr, rdoc);
515 for (m = db->map; m; m = m->next)
518 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
520 yaz_log(YLOG_WARN, "XSLT transformation failed");
526 if (global_parameters.dump_records)
528 fprintf(stderr, "Record:\n----------------\n");
529 #if LIBXML_VERSION >= 20600
530 xmlDocFormatDump(stderr, rdoc, 1);
532 xmlDocDump(stderr, rdoc);
538 // Extract what appears to be years from buf, storing highest and
540 static int extract_years(const char *buf, int *first, int *last)
549 while (*buf && !isdigit(*buf))
552 for (e = buf; *e && isdigit(*e); e++)
556 int value = atoi(buf);
557 if (*first < 0 || value < *first)
559 if (*last < 0 || value > *last)
567 static struct record *ingest_record(struct client *cl, Z_External *rec)
569 xmlDoc *xdoc = normalize_record(cl, rec);
572 struct record_cluster *cluster;
573 struct session *se = cl->session;
574 xmlChar *mergekey, *mergekey_norm;
577 struct conf_service *service = global_parameters.server->service;
582 root = xmlDocGetRootElement(xdoc);
583 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
585 yaz_log(YLOG_WARN, "No mergekey found in record");
590 res = nmem_malloc(se->nmem, sizeof(struct record));
593 res->metadata = nmem_malloc(se->nmem,
594 sizeof(struct record_metadata*) * service->num_metadata);
595 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
597 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
599 normalize_mergekey((char *) mergekey_norm, 0);
601 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
603 if (global_parameters.dump_records)
604 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
605 cl->database->database->url, cl->records);
608 /* no room for record */
612 relevance_newrec(se->relevance, cluster);
614 for (n = root->children; n; n = n->next)
622 if (n->type != XML_ELEMENT_NODE)
624 if (!strcmp((const char *) n->name, "metadata"))
626 struct conf_metadata *md = 0;
627 struct conf_sortkey *sk = 0;
628 struct record_metadata **wheretoput, *newm;
632 type = xmlGetProp(n, (xmlChar *) "type");
633 value = xmlNodeListGetString(xdoc, n->children, 0);
638 // First, find out what field we're looking at
639 for (imeta = 0; imeta < service->num_metadata; imeta++)
640 if (!strcmp((const char *) type, service->metadata[imeta].name))
642 md = &service->metadata[imeta];
643 if (md->sortkey_offset >= 0)
644 sk = &service->sortkeys[md->sortkey_offset];
649 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
653 // Find out where we are putting it
654 if (md->merge == Metadata_merge_no)
655 wheretoput = &res->metadata[imeta];
657 wheretoput = &cluster->metadata[imeta];
660 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
662 if (md->type == Metadata_type_generic)
665 for (p = (char *) value; *p && isspace(*p); p++)
667 for (pe = p + strlen(p) - 1;
668 pe > p && strchr(" ,/.:([", *pe); pe--)
670 newm->data.text = nmem_strdup(se->nmem, p);
673 else if (md->type == Metadata_type_year)
675 if (extract_years((char *) value, &first, &last) < 0)
680 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
683 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
685 yaz_log(YLOG_WARN, "Only range merging supported for years");
688 if (md->merge == Metadata_merge_unique)
690 struct record_metadata *mnode;
691 for (mnode = *wheretoput; mnode; mnode = mnode->next)
692 if (!strcmp((const char *) mnode->data.text, newm->data.text))
696 newm->next = *wheretoput;
700 else if (md->merge == Metadata_merge_longest)
703 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
708 char *s = nmem_strdup(se->nmem, newm->data.text);
709 if (!cluster->sortkeys[md->sortkey_offset])
710 cluster->sortkeys[md->sortkey_offset] =
711 nmem_malloc(se->nmem, sizeof(union data_types));
712 normalize_mergekey(s,
713 (sk->type == Metadata_sortkey_skiparticle));
714 cluster->sortkeys[md->sortkey_offset]->text = s;
718 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
720 newm->next = *wheretoput;
723 else if (md->merge == Metadata_merge_range)
725 assert(md->type == Metadata_type_year);
729 (*wheretoput)->data.number.min = first;
730 (*wheretoput)->data.number.max = last;
732 cluster->sortkeys[md->sortkey_offset] = &newm->data;
736 if (first < (*wheretoput)->data.number.min)
737 (*wheretoput)->data.number.min = first;
738 if (last > (*wheretoput)->data.number.max)
739 (*wheretoput)->data.number.max = last;
744 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
745 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
750 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
753 relevance_countwords(se->relevance, cluster,
754 (char *) value, md->rank);
757 if (md->type == Metadata_type_year)
760 sprintf(year, "%d", last);
761 add_facet(se, (char *) type, year);
764 sprintf(year, "%d", first);
765 add_facet(se, (char *) type, year);
769 add_facet(se, (char *) type, (char *) value);
776 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
785 relevance_donerecord(se->relevance, cluster);
791 // Retrieve first defined value for 'name' for given database.
792 // Will be extended to take into account user associated with session
793 char *session_setting_oneval(struct session_database *db, int offset)
795 if (!db->settings[offset])
797 return db->settings[offset]->value;
800 static void ingest_records(struct client *cl, Z_Records *r)
803 yaz_timing_t t = yaz_timing_create();
806 struct session *s = cl->session;
807 Z_NamePlusRecordList *rlist;
810 if (r->which != Z_Records_DBOSD)
812 rlist = r->u.databaseOrSurDiagnostics;
813 for (i = 0; i < rlist->num_records; i++)
815 Z_NamePlusRecord *npr = rlist->records[i];
818 if (npr->which != Z_NamePlusRecord_databaseRecord)
821 "Unexpected record type, probably diagnostic %s",
822 cl->database->database->url);
826 rec = ingest_record(cl, npr->u.databaseRecord);
830 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
831 session_alert_watch(s, SESSION_WATCH_RECORDS);
835 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
836 yaz_timing_get_real(t), yaz_timing_get_user(t),
837 yaz_timing_get_sys(t));
838 yaz_timing_destroy(&t);
842 static void do_presentResponse(IOCHAN i, Z_APDU *a)
844 struct connection *co = iochan_getdata(i);
845 struct client *cl = co->client;
846 Z_PresentResponse *r = a->u.presentResponse;
849 Z_Records *recs = r->records;
850 if (recs->which == Z_Records_NSD)
852 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
853 cl->database->database->url);
854 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
855 cl->state = Client_Error;
859 if (!*r->presentStatus && cl->state != Client_Error)
861 yaz_log(YLOG_DEBUG, "Good Present response %s",
862 cl->database->database->url);
863 ingest_records(cl, r->records);
864 cl->state = Client_Idle;
866 else if (*r->presentStatus)
868 yaz_log(YLOG_WARN, "Bad Present response %s",
869 cl->database->database->url);
870 cl->state = Client_Error;
874 static void handler(IOCHAN i, int event)
876 struct connection *co = iochan_getdata(i);
877 struct client *cl = co->client;
878 struct session *se = 0;
884 yaz_log(YLOG_WARN, "Destroying orphan connection");
885 connection_destroy(co);
889 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
892 socklen_t errlen = sizeof(errcode);
894 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
895 &errlen) < 0 || errcode != 0)
902 yaz_log(YLOG_DEBUG, "Connect OK");
903 co->state = Conn_Open;
905 cl->state = Client_Connected;
909 else if (event & EVENT_INPUT)
911 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
915 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
916 cl->database->database->url);
917 connection_destroy(co);
922 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
923 connection_destroy(co);
926 else if (len > 1) // We discard input if we have no connection
928 co->state = Conn_Open;
930 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
934 odr_reset(global_parameters.odr_in);
935 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
936 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
943 case Z_APDU_initResponse:
944 do_initResponse(i, a);
946 case Z_APDU_searchResponse:
947 do_searchResponse(i, a);
949 case Z_APDU_presentResponse:
950 do_presentResponse(i, a);
953 do_closeResponse(i, a);
957 "Unexpected Z39.50 response from %s",
958 cl->database->database->url);
962 // We aren't expecting staggered output from target
963 // if (cs_more(t->link))
964 // iochan_setevent(i, EVENT_INPUT);
966 else // we throw away response and go to idle mode
968 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
969 cl->state = Client_Idle;
972 /* if len==1 we do nothing but wait for more input */
975 if (cl->state == Client_Connected) {
979 if (cl->state == Client_Idle)
981 if (cl->requestid != se->requestid && *se->query) {
984 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
985 cl->records < cl->hits) {
991 // Disassociate connection from client
992 static void connection_release(struct connection *co)
994 struct client *cl = co->client;
996 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1003 // Close connection and recycle structure
1004 static void connection_destroy(struct connection *co)
1006 struct host *h = co->host;
1008 iochan_destroy(co->iochan);
1010 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1011 if (h->connections == co)
1012 h->connections = co->next;
1015 struct connection *pco;
1016 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1019 pco->next = co->next;
1025 if (co->client->state != Client_Idle)
1026 co->client->state = Client_Disconnected;
1027 co->client->connection = 0;
1029 co->next = connection_freelist;
1030 connection_freelist = co;
1033 // Creates a new connection for client, associated with the host of
1034 // client's database
1035 static struct connection *connection_create(struct client *cl)
1037 struct connection *new;
1043 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1045 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1049 if (0 == strlen(global_parameters.zproxy_override)){
1050 /* no Z39.50 proxy needed - direct connect */
1051 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
1053 if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
1055 yaz_log(YLOG_WARN|YLOG_ERRNO,
1056 "Lookup of IP address %s failed",
1057 cl->database->database->host->ipport);
1062 /* Z39.50 proxy connect */
1063 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1064 cl->database->database->url, global_parameters.zproxy_override);
1066 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1068 yaz_log(YLOG_WARN|YLOG_ERRNO,
1069 "Lookup of IP address %s failed",
1070 global_parameters.zproxy_override);
1075 res = cs_connect(link, addr);
1078 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
1082 if ((new = connection_freelist))
1083 connection_freelist = new->next;
1086 new = xmalloc(sizeof (struct connection));
1090 new->state = Conn_Connecting;
1091 new->host = cl->database->database->host;
1092 new->next = new->host->connections;
1093 new->host->connections = new;
1095 cl->connection = new;
1098 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1099 iochan_setdata(new->iochan, new);
1100 new->iochan->next = channel_list;
1101 channel_list = new->iochan;
1105 // Close connection and set state to error
1106 static void client_fatal(struct client *cl)
1108 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
1109 connection_destroy(cl->connection);
1110 cl->state = Client_Error;
1113 // Ensure that client has a connection associated
1114 static int client_prep_connection(struct client *cl)
1116 struct connection *co;
1117 struct session *se = cl->session;
1118 struct host *host = cl->database->database->host;
1120 co = cl->connection;
1122 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
1126 // See if someone else has an idle connection
1127 // We should look at timestamps here to select the longest-idle connection
1128 for (co = host->connections; co; co = co->next)
1129 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1133 connection_release(co);
1134 cl->connection = co;
1138 co = connection_create(cl);
1142 if (co->state == Conn_Connecting)
1144 cl->state = Client_Connecting;
1145 iochan_setflag(co->iochan, EVENT_OUTPUT);
1147 else if (co->state == Conn_Open)
1149 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1150 cl->state = Client_Idle;
1151 iochan_setflag(co->iochan, EVENT_OUTPUT);
1159 static struct client *client_create(void)
1162 if (client_freelist)
1164 r = client_freelist;
1165 client_freelist = client_freelist->next;
1168 r = xmalloc(sizeof(struct client));
1177 r->state = Client_Disconnected;
1182 void client_destroy(struct client *c)
1184 struct session *se = c->session;
1185 if (c == se->clients)
1186 se->clients = c->next;
1190 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1196 connection_release(c->connection);
1197 c->next = client_freelist;
1198 client_freelist = c;
1201 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1203 s->watchlist[what].fun = fun;
1204 s->watchlist[what].data = data;
1207 void session_alert_watch(struct session *s, int what)
1209 if (!s->watchlist[what].fun)
1211 (*s->watchlist[what].fun)(s->watchlist[what].data);
1212 s->watchlist[what].fun = 0;
1213 s->watchlist[what].data = 0;
1216 //callback for grep_databases
1217 static void select_targets_callback(void *context, struct session_database *db)
1219 struct session *se = (struct session*) context;
1220 struct client *cl = client_create();
1223 cl->next = se->clients;
1227 // Associates a set of clients with a session;
1228 // Note: Session-databases represent databases with per-session setting overrides
1229 int select_targets(struct session *se, struct database_criterion *crit)
1232 client_destroy(se->clients);
1234 return session_grep_databases(se, crit, select_targets_callback);
1237 int session_active_clients(struct session *s)
1242 for (c = s->clients; c; c = c->next)
1243 if (c->connection && (c->state == Client_Connecting ||
1244 c->state == Client_Initializing ||
1245 c->state == Client_Searching ||
1246 c->state == Client_Presenting))
1252 // parses crit1=val1,crit2=val2|val3,...
1253 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1255 struct database_criterion *res = 0;
1262 nmem_strsplit(m, ",", buf, &values, &num);
1263 for (i = 0; i < num; i++)
1268 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1269 char *eq = strchr(values[i], '=');
1272 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1276 new->name = values[i];
1277 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1279 for (subi = 0; subi < subnum; subi++)
1281 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1282 newv->value = subvalues[subi];
1283 newv->next = new->values;
1292 char *search(struct session *se, char *query, char *filter)
1294 int live_channels = 0;
1296 struct database_criterion *criteria;
1298 yaz_log(YLOG_DEBUG, "Search");
1300 nmem_reset(se->nmem);
1301 criteria = parse_filter(se->nmem, filter);
1302 strcpy(se->query, query);
1304 select_targets(se, criteria);
1305 for (cl = se->clients; cl; cl = cl->next)
1307 if (client_prep_connection(cl))
1312 int maxrecs = live_channels * global_parameters.toget;
1313 se->num_termlists = 0;
1314 se->reclist = reclist_create(se->nmem, maxrecs);
1315 // This will be initialized in send_search()
1317 se->total_records = se->total_hits = se->total_merged = 0;
1318 se->expected_maxrecs = maxrecs;
1326 // Apply a session override to a database
1327 void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
1329 struct session_database *sdb;
1331 for (sdb = se->databases; sdb; sdb = sdb->next)
1332 if (!strcmp(dbname, sdb->database->url))
1334 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
1335 int offset = settings_offset(setting);
1339 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
1342 new->precedence = 0;
1343 new->target = dbname;
1344 new->name = setting;
1347 new->next = sdb->settings[offset];
1348 sdb->settings[offset] = new;
1352 yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
1355 void session_init_databases_fun(void *context, struct database *db)
1357 struct session *se = (struct session *) context;
1358 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
1359 int num = settings_num();
1363 new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
1364 for (i = 0; i < num; i++)
1365 new->settings[i] = db->settings[i];
1366 new->next = se->databases;
1367 se->databases = new;
1370 // Initialize session_database list -- this represents this session's view
1371 // of the database list -- subject to modification by the settings ws command
1372 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 res[*count].id = cl->database->database->url;
1423 res[*count].name = cl->database->database->name;
1424 res[*count].hits = cl->hits;
1425 res[*count].records = cl->records;
1426 res[*count].diagnostic = cl->diagnostic;
1427 res[*count].state = client_states[cl->state];
1428 res[*count].connected = cl->connection ? 1 : 0;
1435 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1439 for (i = 0; i < s->num_termlists; i++)
1440 if (!strcmp((const char *) s->termlists[i].name, name))
1441 return termlist_highscore(s->termlists[i].termlist, num);
1445 #ifdef MISSING_HEADERS
1446 void report_nmem_stats(void)
1448 size_t in_use, is_free;
1450 nmem_get_memory_in_use(&in_use);
1451 nmem_get_memory_free(&is_free);
1453 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1454 (long) in_use, (long) is_free);
1458 struct record_cluster *show_single(struct session *s, int id)
1460 struct record_cluster *r;
1462 reclist_rewind(s->reclist);
1463 while ((r = reclist_read_record(s->reclist)))
1469 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1470 int *num, int *total, int *sumhits, NMEM nmem_show)
1472 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1473 * sizeof(struct record_cluster *));
1474 struct reclist_sortparms *spp;
1477 yaz_timing_t t = yaz_timing_create();
1480 for (spp = sp; spp; spp = spp->next)
1481 if (spp->type == Metadata_sortkey_relevance)
1483 relevance_prepare_read(s->relevance, s->reclist);
1486 reclist_sort(s->reclist, sp);
1488 *total = s->reclist->num_records;
1489 *sumhits = s->total_hits;
1491 for (i = 0; i < start; i++)
1492 if (!reclist_read_record(s->reclist))
1499 for (i = 0; i < *num; i++)
1501 struct record_cluster *r = reclist_read_record(s->reclist);
1511 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1512 yaz_timing_get_real(t), yaz_timing_get_user(t),
1513 yaz_timing_get_sys(t));
1514 yaz_timing_destroy(&t);
1519 void statistics(struct session *se, struct statistics *stat)
1524 memset(stat, 0, sizeof(*stat));
1525 for (cl = se->clients; cl; cl = cl->next)
1527 if (!cl->connection)
1528 stat->num_no_connection++;
1531 case Client_Connecting: stat->num_connecting++; break;
1532 case Client_Initializing: stat->num_initializing++; break;
1533 case Client_Searching: stat->num_searching++; break;
1534 case Client_Presenting: stat->num_presenting++; break;
1535 case Client_Idle: stat->num_idle++; break;
1536 case Client_Failed: stat->num_failed++; break;
1537 case Client_Error: stat->num_error++; break;
1542 stat->num_hits = se->total_hits;
1543 stat->num_records = se->total_records;
1545 stat->num_clients = count;
1548 static void start_http_listener(void)
1551 struct conf_server *ser = global_parameters.server;
1553 if (*global_parameters.listener_override)
1554 strcpy(hp, global_parameters.listener_override);
1557 strcpy(hp, ser->host ? ser->host : "");
1562 sprintf(hp + strlen(hp), "%d", ser->port);
1568 static void start_proxy(void)
1571 struct conf_server *ser = global_parameters.server;
1573 if (*global_parameters.proxy_override)
1574 strcpy(hp, global_parameters.proxy_override);
1575 else if (ser->proxy_host || ser->proxy_port)
1577 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1578 if (ser->proxy_port)
1582 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1588 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1591 static void start_zproxy(void)
1593 struct conf_server *ser = global_parameters.server;
1595 if (*global_parameters.zproxy_override){
1596 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1597 global_parameters.zproxy_override);
1601 else if (ser->zproxy_host || ser->zproxy_port)
1605 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1606 if (ser->zproxy_port)
1613 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1615 strcpy(global_parameters.zproxy_override, hp);
1616 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1617 global_parameters.zproxy_override);
1626 int main(int argc, char **argv)
1631 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1632 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1634 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1636 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1640 if (!read_config(arg))
1644 strcpy(global_parameters.listener_override, arg);
1647 strcpy(global_parameters.proxy_override, arg);
1650 strcpy(global_parameters.zproxy_override, arg);
1653 strcpy(global_parameters.settings_path_override, arg);
1656 load_simpletargets(arg);
1659 global_parameters.dump_records = 1;
1662 fprintf(stderr, "Usage: pazpar2\n"
1664 " -h [host:]port (REST protocol listener)\n"
1666 " -s simpletargetfile\n"
1667 " -p hostname[:portno] (HTTP proxy)\n"
1668 " -z hostname[:portno] (Z39.50 proxy)\n"
1669 " -d (show internal records)\n");
1676 yaz_log(YLOG_FATAL, "Load config with -f");
1679 global_parameters.server = config->servers;
1681 start_http_listener();
1685 if (*global_parameters.settings_path_override)
1686 settings_read(global_parameters.settings_path_override);
1687 else if (global_parameters.server->settings)
1688 settings_read(global_parameters.server->settings);
1690 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may well ensue!");
1691 prepare_databases();
1692 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1693 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1695 event_loop(&channel_list);
1703 * indent-tabs-mode: nil
1705 * vim: shiftwidth=4 tabstop=8 expandtab