1 /* $Id: pazpar2.c,v 1.75 2007-04-12 09:59:47 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>
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);
489 yaz_marc_write_using_libxml2(db->yaz_marc, 1);
490 if (yaz_marc_write_xml(db->yaz_marc, &res,
491 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
493 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
494 cl->database->database->url);
497 rdoc = xmlNewDoc((xmlChar *) "1.0");
498 xmlDocSetRootElement(rdoc, res);
504 "Unknown native_syntax in normalize_record from %s",
505 cl->database->database->url);
509 if (global_parameters.dump_records){
511 "Input Record (normalized) from %s\n----------------\n",
512 cl->database->database->url);
513 #if LIBXML_VERSION >= 20600
514 xmlDocFormatDump(stderr, rdoc, 1);
516 xmlDocDump(stderr, rdoc);
520 for (m = db->map; m; m = m->next){
526 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
527 root= xmlDocGetRootElement(new);
528 if (!new || !root || !(root->children))
530 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
531 cl->database->database->url);
540 // do it another way to detect transformation errors right now
541 // but does not seem to work either!
543 xsltTransformContextPtr ctxt;
544 ctxt = xsltNewTransformContext(m->stylesheet, rdoc);
545 new = xsltApplyStylesheetUser(m->stylesheet, rdoc, 0, 0, 0, ctxt);
546 if ((ctxt->state == XSLT_STATE_ERROR) ||
547 (ctxt->state == XSLT_STATE_STOPPED)){
548 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
549 cl->database->database->url);
560 if (global_parameters.dump_records)
562 fprintf(stderr, "Record from %s\n----------------\n",
563 cl->database->database->url);
564 #if LIBXML_VERSION >= 20600
565 xmlDocFormatDump(stderr, rdoc, 1);
567 xmlDocDump(stderr, rdoc);
573 // Extract what appears to be years from buf, storing highest and
575 static int extract_years(const char *buf, int *first, int *last)
584 while (*buf && !isdigit(*buf))
587 for (e = buf; *e && isdigit(*e); e++)
591 int value = atoi(buf);
592 if (*first < 0 || value < *first)
594 if (*last < 0 || value > *last)
602 static struct record *ingest_record(struct client *cl, Z_External *rec)
604 xmlDoc *xdoc = normalize_record(cl, rec);
607 struct record_cluster *cluster;
608 struct session *se = cl->session;
609 xmlChar *mergekey, *mergekey_norm;
612 struct conf_service *service = global_parameters.server->service;
617 root = xmlDocGetRootElement(xdoc);
618 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
620 yaz_log(YLOG_WARN, "No mergekey found in record");
625 res = nmem_malloc(se->nmem, sizeof(struct record));
628 res->metadata = nmem_malloc(se->nmem,
629 sizeof(struct record_metadata*) * service->num_metadata);
630 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
632 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
634 normalize_mergekey((char *) mergekey_norm, 0);
636 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
638 if (global_parameters.dump_records)
639 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
640 cl->database->database->url, cl->records);
643 /* no room for record */
647 relevance_newrec(se->relevance, cluster);
649 for (n = root->children; n; n = n->next)
657 if (n->type != XML_ELEMENT_NODE)
659 if (!strcmp((const char *) n->name, "metadata"))
661 struct conf_metadata *md = 0;
662 struct conf_sortkey *sk = 0;
663 struct record_metadata **wheretoput, *newm;
667 type = xmlGetProp(n, (xmlChar *) "type");
668 value = xmlNodeListGetString(xdoc, n->children, 0);
673 // First, find out what field we're looking at
674 for (imeta = 0; imeta < service->num_metadata; imeta++)
675 if (!strcmp((const char *) type, service->metadata[imeta].name))
677 md = &service->metadata[imeta];
678 if (md->sortkey_offset >= 0)
679 sk = &service->sortkeys[md->sortkey_offset];
684 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
688 // Find out where we are putting it
689 if (md->merge == Metadata_merge_no)
690 wheretoput = &res->metadata[imeta];
692 wheretoput = &cluster->metadata[imeta];
695 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
697 if (md->type == Metadata_type_generic)
700 for (p = (char *) value; *p && isspace(*p); p++)
702 for (pe = p + strlen(p) - 1;
703 pe > p && strchr(" ,/.:([", *pe); pe--)
705 newm->data.text = nmem_strdup(se->nmem, p);
708 else if (md->type == Metadata_type_year)
710 if (extract_years((char *) value, &first, &last) < 0)
715 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
718 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
720 yaz_log(YLOG_WARN, "Only range merging supported for years");
723 if (md->merge == Metadata_merge_unique)
725 struct record_metadata *mnode;
726 for (mnode = *wheretoput; mnode; mnode = mnode->next)
727 if (!strcmp((const char *) mnode->data.text, newm->data.text))
731 newm->next = *wheretoput;
735 else if (md->merge == Metadata_merge_longest)
738 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
743 char *s = nmem_strdup(se->nmem, newm->data.text);
744 if (!cluster->sortkeys[md->sortkey_offset])
745 cluster->sortkeys[md->sortkey_offset] =
746 nmem_malloc(se->nmem, sizeof(union data_types));
747 normalize_mergekey(s,
748 (sk->type == Metadata_sortkey_skiparticle));
749 cluster->sortkeys[md->sortkey_offset]->text = s;
753 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
755 newm->next = *wheretoput;
758 else if (md->merge == Metadata_merge_range)
760 assert(md->type == Metadata_type_year);
764 (*wheretoput)->data.number.min = first;
765 (*wheretoput)->data.number.max = last;
767 cluster->sortkeys[md->sortkey_offset] = &newm->data;
771 if (first < (*wheretoput)->data.number.min)
772 (*wheretoput)->data.number.min = first;
773 if (last > (*wheretoput)->data.number.max)
774 (*wheretoput)->data.number.max = last;
779 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
780 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
785 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
788 relevance_countwords(se->relevance, cluster,
789 (char *) value, md->rank);
792 if (md->type == Metadata_type_year)
795 sprintf(year, "%d", last);
796 add_facet(se, (char *) type, year);
799 sprintf(year, "%d", first);
800 add_facet(se, (char *) type, year);
804 add_facet(se, (char *) type, (char *) value);
811 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
820 relevance_donerecord(se->relevance, cluster);
826 // Retrieve first defined value for 'name' for given database.
827 // Will be extended to take into account user associated with session
828 char *session_setting_oneval(struct session_database *db, int offset)
830 if (!db->settings[offset])
832 return db->settings[offset]->value;
835 static void ingest_records(struct client *cl, Z_Records *r)
838 yaz_timing_t t = yaz_timing_create();
841 struct session *s = cl->session;
842 Z_NamePlusRecordList *rlist;
845 if (r->which != Z_Records_DBOSD)
847 rlist = r->u.databaseOrSurDiagnostics;
848 for (i = 0; i < rlist->num_records; i++)
850 Z_NamePlusRecord *npr = rlist->records[i];
853 if (npr->which != Z_NamePlusRecord_databaseRecord)
856 "Unexpected record type, probably diagnostic %s",
857 cl->database->database->url);
861 rec = ingest_record(cl, npr->u.databaseRecord);
865 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
866 session_alert_watch(s, SESSION_WATCH_RECORDS);
870 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
871 yaz_timing_get_real(t), yaz_timing_get_user(t),
872 yaz_timing_get_sys(t));
873 yaz_timing_destroy(&t);
877 static void do_presentResponse(IOCHAN i, Z_APDU *a)
879 struct connection *co = iochan_getdata(i);
880 struct client *cl = co->client;
881 Z_PresentResponse *r = a->u.presentResponse;
884 Z_Records *recs = r->records;
885 if (recs->which == Z_Records_NSD)
887 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
888 cl->database->database->url);
889 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
890 cl->state = Client_Error;
894 if (!*r->presentStatus && cl->state != Client_Error)
896 yaz_log(YLOG_DEBUG, "Good Present response %s",
897 cl->database->database->url);
898 ingest_records(cl, r->records);
899 cl->state = Client_Idle;
901 else if (*r->presentStatus)
903 yaz_log(YLOG_WARN, "Bad Present response %s",
904 cl->database->database->url);
905 cl->state = Client_Error;
909 static void handler(IOCHAN i, int event)
911 struct connection *co = iochan_getdata(i);
912 struct client *cl = co->client;
913 struct session *se = 0;
919 yaz_log(YLOG_WARN, "Destroying orphan connection");
920 connection_destroy(co);
924 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
927 socklen_t errlen = sizeof(errcode);
929 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
930 &errlen) < 0 || errcode != 0)
937 yaz_log(YLOG_DEBUG, "Connect OK");
938 co->state = Conn_Open;
940 cl->state = Client_Connected;
944 else if (event & EVENT_INPUT)
946 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
950 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
951 cl->database->database->url);
952 connection_destroy(co);
957 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
958 connection_destroy(co);
961 else if (len > 1) // We discard input if we have no connection
963 co->state = Conn_Open;
965 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
969 odr_reset(global_parameters.odr_in);
970 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
971 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
978 case Z_APDU_initResponse:
979 do_initResponse(i, a);
981 case Z_APDU_searchResponse:
982 do_searchResponse(i, a);
984 case Z_APDU_presentResponse:
985 do_presentResponse(i, a);
988 do_closeResponse(i, a);
992 "Unexpected Z39.50 response from %s",
993 cl->database->database->url);
997 // We aren't expecting staggered output from target
998 // if (cs_more(t->link))
999 // iochan_setevent(i, EVENT_INPUT);
1001 else // we throw away response and go to idle mode
1003 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
1004 cl->state = Client_Idle;
1007 /* if len==1 we do nothing but wait for more input */
1010 if (cl->state == Client_Connected) {
1014 if (cl->state == Client_Idle)
1016 if (cl->requestid != se->requestid && *se->query) {
1019 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
1020 cl->records < cl->hits) {
1026 // Disassociate connection from client
1027 static void connection_release(struct connection *co)
1029 struct client *cl = co->client;
1031 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1038 // Close connection and recycle structure
1039 static void connection_destroy(struct connection *co)
1041 struct host *h = co->host;
1043 iochan_destroy(co->iochan);
1045 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1046 if (h->connections == co)
1047 h->connections = co->next;
1050 struct connection *pco;
1051 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1054 pco->next = co->next;
1060 if (co->client->state != Client_Idle)
1061 co->client->state = Client_Disconnected;
1062 co->client->connection = 0;
1064 co->next = connection_freelist;
1065 connection_freelist = co;
1068 // Creates a new connection for client, associated with the host of
1069 // client's database
1070 static struct connection *connection_create(struct client *cl)
1072 struct connection *new;
1078 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1080 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1084 if (0 == strlen(global_parameters.zproxy_override)){
1085 /* no Z39.50 proxy needed - direct connect */
1086 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
1088 if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
1090 yaz_log(YLOG_WARN|YLOG_ERRNO,
1091 "Lookup of IP address %s failed",
1092 cl->database->database->host->ipport);
1097 /* Z39.50 proxy connect */
1098 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1099 cl->database->database->url, global_parameters.zproxy_override);
1101 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1103 yaz_log(YLOG_WARN|YLOG_ERRNO,
1104 "Lookup of IP address %s failed",
1105 global_parameters.zproxy_override);
1110 res = cs_connect(link, addr);
1113 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
1117 if ((new = connection_freelist))
1118 connection_freelist = new->next;
1121 new = xmalloc(sizeof (struct connection));
1125 new->state = Conn_Connecting;
1126 new->host = cl->database->database->host;
1127 new->next = new->host->connections;
1128 new->host->connections = new;
1130 cl->connection = new;
1133 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1134 iochan_setdata(new->iochan, new);
1135 new->iochan->next = channel_list;
1136 channel_list = new->iochan;
1140 // Close connection and set state to error
1141 static void client_fatal(struct client *cl)
1143 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
1144 connection_destroy(cl->connection);
1145 cl->state = Client_Error;
1148 // Ensure that client has a connection associated
1149 static int client_prep_connection(struct client *cl)
1151 struct connection *co;
1152 struct session *se = cl->session;
1153 struct host *host = cl->database->database->host;
1155 co = cl->connection;
1157 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
1161 // See if someone else has an idle connection
1162 // We should look at timestamps here to select the longest-idle connection
1163 for (co = host->connections; co; co = co->next)
1164 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1168 connection_release(co);
1169 cl->connection = co;
1173 co = connection_create(cl);
1177 if (co->state == Conn_Connecting)
1179 cl->state = Client_Connecting;
1180 iochan_setflag(co->iochan, EVENT_OUTPUT);
1182 else if (co->state == Conn_Open)
1184 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1185 cl->state = Client_Idle;
1186 iochan_setflag(co->iochan, EVENT_OUTPUT);
1194 static struct client *client_create(void)
1197 if (client_freelist)
1199 r = client_freelist;
1200 client_freelist = client_freelist->next;
1203 r = xmalloc(sizeof(struct client));
1212 r->state = Client_Disconnected;
1217 void client_destroy(struct client *c)
1219 struct session *se = c->session;
1220 if (c == se->clients)
1221 se->clients = c->next;
1225 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1231 connection_release(c->connection);
1232 c->next = client_freelist;
1233 client_freelist = c;
1236 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1238 s->watchlist[what].fun = fun;
1239 s->watchlist[what].data = data;
1242 void session_alert_watch(struct session *s, int what)
1244 if (!s->watchlist[what].fun)
1246 (*s->watchlist[what].fun)(s->watchlist[what].data);
1247 s->watchlist[what].fun = 0;
1248 s->watchlist[what].data = 0;
1251 //callback for grep_databases
1252 static void select_targets_callback(void *context, struct session_database *db)
1254 struct session *se = (struct session*) context;
1255 struct client *cl = client_create();
1258 cl->next = se->clients;
1262 // Associates a set of clients with a session;
1263 // Note: Session-databases represent databases with per-session setting overrides
1264 int select_targets(struct session *se, struct database_criterion *crit)
1267 client_destroy(se->clients);
1269 return session_grep_databases(se, crit, select_targets_callback);
1272 int session_active_clients(struct session *s)
1277 for (c = s->clients; c; c = c->next)
1278 if (c->connection && (c->state == Client_Connecting ||
1279 c->state == Client_Initializing ||
1280 c->state == Client_Searching ||
1281 c->state == Client_Presenting))
1287 // parses crit1=val1,crit2=val2|val3,...
1288 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1290 struct database_criterion *res = 0;
1297 nmem_strsplit(m, ",", buf, &values, &num);
1298 for (i = 0; i < num; i++)
1303 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1304 char *eq = strchr(values[i], '=');
1307 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1311 new->name = values[i];
1312 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1314 for (subi = 0; subi < subnum; subi++)
1316 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1317 newv->value = subvalues[subi];
1318 newv->next = new->values;
1327 char *search(struct session *se, char *query, char *filter)
1329 int live_channels = 0;
1331 struct database_criterion *criteria;
1333 yaz_log(YLOG_DEBUG, "Search");
1335 nmem_reset(se->nmem);
1336 criteria = parse_filter(se->nmem, filter);
1337 strcpy(se->query, query);
1339 select_targets(se, criteria);
1340 for (cl = se->clients; cl; cl = cl->next)
1342 if (client_prep_connection(cl))
1347 int maxrecs = live_channels * global_parameters.toget;
1348 se->num_termlists = 0;
1349 se->reclist = reclist_create(se->nmem, maxrecs);
1350 // This will be initialized in send_search()
1352 se->total_records = se->total_hits = se->total_merged = 0;
1353 se->expected_maxrecs = maxrecs;
1361 // Apply a session override to a database
1362 void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
1364 struct session_database *sdb;
1366 for (sdb = se->databases; sdb; sdb = sdb->next)
1367 if (!strcmp(dbname, sdb->database->url))
1369 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
1370 int offset = settings_offset(setting);
1374 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
1377 new->precedence = 0;
1378 new->target = dbname;
1379 new->name = setting;
1381 new->next = sdb->settings[offset];
1382 sdb->settings[offset] = new;
1386 yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
1389 void session_init_databases_fun(void *context, struct database *db)
1391 struct session *se = (struct session *) context;
1392 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
1393 int num = settings_num();
1397 new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
1398 for (i = 0; i < num; i++)
1399 new->settings[i] = db->settings[i];
1400 new->next = se->databases;
1401 se->databases = new;
1404 // Initialize session_database list -- this represents this session's view
1405 // of the database list -- subject to modification by the settings ws command
1406 void session_init_databases(struct session *se)
1409 grep_databases(se, 0, session_init_databases_fun);
1412 void destroy_session(struct session *s)
1414 yaz_log(YLOG_LOG, "Destroying session");
1416 client_destroy(s->clients);
1417 nmem_destroy(s->nmem);
1418 wrbuf_destroy(s->wrbuf);
1421 struct session *new_session(NMEM nmem)
1424 struct session *session = nmem_malloc(nmem, sizeof(*session));
1426 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
1428 session->total_hits = 0;
1429 session->total_records = 0;
1430 session->num_termlists = 0;
1431 session->reclist = 0;
1432 session->requestid = -1;
1433 session->clients = 0;
1434 session->expected_maxrecs = 0;
1435 session->query[0] = '\0';
1436 session->session_nmem = nmem;
1437 session->nmem = nmem_create();
1438 session->wrbuf = wrbuf_alloc();
1439 session_init_databases(session);
1440 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1442 session->watchlist[i].data = 0;
1443 session->watchlist[i].fun = 0;
1449 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1451 static struct hitsbytarget res[1000]; // FIXME MM
1455 for (cl = se->clients; cl; cl = cl->next)
1457 char *name = session_setting_oneval(cl->database, PZ_NAME);
1459 res[*count].id = cl->database->database->url;
1460 res[*count].name = *name ? name : "Unknown";
1461 res[*count].hits = cl->hits;
1462 res[*count].records = cl->records;
1463 res[*count].diagnostic = cl->diagnostic;
1464 res[*count].state = client_states[cl->state];
1465 res[*count].connected = cl->connection ? 1 : 0;
1472 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1476 for (i = 0; i < s->num_termlists; i++)
1477 if (!strcmp((const char *) s->termlists[i].name, name))
1478 return termlist_highscore(s->termlists[i].termlist, num);
1482 #ifdef MISSING_HEADERS
1483 void report_nmem_stats(void)
1485 size_t in_use, is_free;
1487 nmem_get_memory_in_use(&in_use);
1488 nmem_get_memory_free(&is_free);
1490 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1491 (long) in_use, (long) is_free);
1495 struct record_cluster *show_single(struct session *s, int id)
1497 struct record_cluster *r;
1499 reclist_rewind(s->reclist);
1500 while ((r = reclist_read_record(s->reclist)))
1506 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1507 int *num, int *total, int *sumhits, NMEM nmem_show)
1509 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1510 * sizeof(struct record_cluster *));
1511 struct reclist_sortparms *spp;
1514 yaz_timing_t t = yaz_timing_create();
1517 for (spp = sp; spp; spp = spp->next)
1518 if (spp->type == Metadata_sortkey_relevance)
1520 relevance_prepare_read(s->relevance, s->reclist);
1523 reclist_sort(s->reclist, sp);
1525 *total = s->reclist->num_records;
1526 *sumhits = s->total_hits;
1528 for (i = 0; i < start; i++)
1529 if (!reclist_read_record(s->reclist))
1536 for (i = 0; i < *num; i++)
1538 struct record_cluster *r = reclist_read_record(s->reclist);
1548 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1549 yaz_timing_get_real(t), yaz_timing_get_user(t),
1550 yaz_timing_get_sys(t));
1551 yaz_timing_destroy(&t);
1556 void statistics(struct session *se, struct statistics *stat)
1561 memset(stat, 0, sizeof(*stat));
1562 for (cl = se->clients; cl; cl = cl->next)
1564 if (!cl->connection)
1565 stat->num_no_connection++;
1568 case Client_Connecting: stat->num_connecting++; break;
1569 case Client_Initializing: stat->num_initializing++; break;
1570 case Client_Searching: stat->num_searching++; break;
1571 case Client_Presenting: stat->num_presenting++; break;
1572 case Client_Idle: stat->num_idle++; break;
1573 case Client_Failed: stat->num_failed++; break;
1574 case Client_Error: stat->num_error++; break;
1579 stat->num_hits = se->total_hits;
1580 stat->num_records = se->total_records;
1582 stat->num_clients = count;
1585 static void start_http_listener(void)
1588 struct conf_server *ser = global_parameters.server;
1590 if (*global_parameters.listener_override)
1591 strcpy(hp, global_parameters.listener_override);
1594 strcpy(hp, ser->host ? ser->host : "");
1599 sprintf(hp + strlen(hp), "%d", ser->port);
1605 static void start_proxy(void)
1608 struct conf_server *ser = global_parameters.server;
1610 if (*global_parameters.proxy_override)
1611 strcpy(hp, global_parameters.proxy_override);
1612 else if (ser->proxy_host || ser->proxy_port)
1614 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1615 if (ser->proxy_port)
1619 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1625 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1628 static void start_zproxy(void)
1630 struct conf_server *ser = global_parameters.server;
1632 if (*global_parameters.zproxy_override){
1633 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1634 global_parameters.zproxy_override);
1638 else if (ser->zproxy_host || ser->zproxy_port)
1642 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1643 if (ser->zproxy_port)
1650 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1652 strcpy(global_parameters.zproxy_override, hp);
1653 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1654 global_parameters.zproxy_override);
1663 int main(int argc, char **argv)
1668 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1669 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1671 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1673 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1677 if (!read_config(arg))
1681 strcpy(global_parameters.listener_override, arg);
1684 strcpy(global_parameters.proxy_override, arg);
1687 strcpy(global_parameters.zproxy_override, arg);
1690 strcpy(global_parameters.settings_path_override, arg);
1693 load_simpletargets(arg);
1696 global_parameters.dump_records = 1;
1699 fprintf(stderr, "Usage: pazpar2\n"
1701 " -h [host:]port (REST protocol listener)\n"
1703 " -s simpletargetfile\n"
1704 " -p hostname[:portno] (HTTP proxy)\n"
1705 " -z hostname[:portno] (Z39.50 proxy)\n"
1706 " -d (show internal records)\n");
1713 yaz_log(YLOG_FATAL, "Load config with -f");
1716 global_parameters.server = config->servers;
1718 start_http_listener();
1722 if (*global_parameters.settings_path_override)
1723 settings_read(global_parameters.settings_path_override);
1724 else if (global_parameters.server->settings)
1725 settings_read(global_parameters.server->settings);
1727 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may well ensue!");
1728 prepare_databases();
1729 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1730 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1732 event_loop(&channel_list);
1740 * indent-tabs-mode: nil
1742 * vim: shiftwidth=4 tabstop=8 expandtab