1 /* $Id: pazpar2.c,v 1.57 2007-03-30 02:45:07 quinn Exp $ */
8 #include <sys/socket.h>
14 #include <yaz/marcdisp.h>
15 #include <yaz/comstack.h>
16 #include <yaz/tcpip.h>
17 #include <yaz/proto.h>
18 #include <yaz/readconf.h>
19 #include <yaz/pquery.h>
20 #include <yaz/otherinfo.h>
21 #include <yaz/yaz-util.h>
30 #include <yaz/timing.h>
33 #include <netinet/in.h>
38 #include "termlists.h"
40 #include "relevance.h"
47 static void client_fatal(struct client *cl);
48 static void connection_destroy(struct connection *co);
49 static int client_prep_connection(struct client *cl);
50 static void ingest_records(struct client *cl, Z_Records *r);
51 //static struct conf_retrievalprofile *database_retrieval_profile(struct database *db);
52 void session_alert_watch(struct session *s, int what);
54 IOCHAN channel_list = 0; // Master list of connections we're handling events to
56 static struct connection *connection_freelist = 0;
57 static struct client *client_freelist = 0;
59 static char *client_states[] = {
63 "Client_Initializing",
68 "Client_Disconnected",
72 // Note: Some things in this structure will eventually move to configuration
73 struct parameters global_parameters =
83 "Index Data PazPar2 (MasterKey)",
94 static int send_apdu(struct client *c, Z_APDU *a)
96 struct connection *co = c->connection;
100 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
102 odr_perror(global_parameters.odr_out, "Encoding APDU");
105 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
106 r = cs_put(co->link, buf, len);
109 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
114 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
117 odr_reset(global_parameters.odr_out); /* release the APDU structure */
118 co->state = Conn_Waiting;
123 static void send_init(IOCHAN i)
126 struct connection *co = iochan_getdata(i);
127 struct client *cl = co->client;
128 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
130 a->u.initRequest->implementationId = global_parameters.implementationId;
131 a->u.initRequest->implementationName = global_parameters.implementationName;
132 a->u.initRequest->implementationVersion =
133 global_parameters.implementationVersion;
134 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
135 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
136 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
138 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
139 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
140 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
143 /* add virtual host if tunneling through Z39.50 proxy */
145 if (0 < strlen(global_parameters.zproxy_override)
146 && 0 < strlen(cl->database->url))
147 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
148 global_parameters.odr_out, VAL_PROXY,
149 1, cl->database->url);
153 if (send_apdu(cl, a) >= 0)
155 iochan_setflags(i, EVENT_INPUT);
156 cl->state = Client_Initializing;
159 cl->state = Client_Error;
160 odr_reset(global_parameters.odr_out);
163 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
171 pull_terms(nmem, n->u.p[0], termlist, num);
172 pull_terms(nmem, n->u.p[1], termlist, num);
175 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
182 // Extract terms from query into null-terminated termlist
183 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
187 pull_terms(nmem, query, termlist, &num);
191 static void send_search(IOCHAN i)
193 struct connection *co = iochan_getdata(i);
194 struct client *cl = co->client;
195 struct session *se = cl->session;
196 struct database *db = cl->database;
197 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
198 int ndb, cerror, cpos;
201 struct ccl_rpn_node *cn;
202 int ssub = 0, lslb = 100000, mspn = 10;
204 yaz_log(YLOG_DEBUG, "Sending search");
206 cn = ccl_find_str(db->ccl_map, se->query, &cerror, &cpos);
212 // Initialize relevance structure with query terms
214 extract_terms(se->nmem, cn, p);
215 se->relevance = relevance_create(se->nmem, (const char **) p,
216 se->expected_maxrecs);
219 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
221 zquery->which = Z_Query_type_1;
222 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
225 for (ndb = 0; db->databases[ndb]; ndb++)
227 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
228 for (ndb = 0; db->databases[ndb]; ndb++)
229 databaselist[ndb] = db->databases[ndb];
231 a->u.searchRequest->preferredRecordSyntax =
232 yaz_oidval_to_z3950oid(global_parameters.odr_out,
233 CLASS_RECSYN, VAL_USMARC);
234 a->u.searchRequest->smallSetUpperBound = &ssub;
235 a->u.searchRequest->largeSetLowerBound = &lslb;
236 a->u.searchRequest->mediumSetPresentNumber = &mspn;
237 a->u.searchRequest->resultSetName = "Default";
238 a->u.searchRequest->databaseNames = databaselist;
239 a->u.searchRequest->num_databaseNames = ndb;
241 if (send_apdu(cl, a) >= 0)
243 iochan_setflags(i, EVENT_INPUT);
244 cl->state = Client_Searching;
245 cl->requestid = se->requestid;
248 cl->state = Client_Error;
250 odr_reset(global_parameters.odr_out);
253 static void send_present(IOCHAN i)
255 struct connection *co = iochan_getdata(i);
256 struct client *cl = co->client;
257 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
259 int start = cl->records + 1;
261 toget = global_parameters.chunk;
262 if (toget > global_parameters.toget - cl->records)
263 toget = global_parameters.toget - cl->records;
264 if (toget > cl->hits - cl->records)
265 toget = cl->hits - cl->records;
267 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
269 a->u.presentRequest->resultSetStartPoint = &start;
270 a->u.presentRequest->numberOfRecordsRequested = &toget;
272 a->u.presentRequest->resultSetId = "Default";
274 a->u.presentRequest->preferredRecordSyntax =
275 yaz_oidval_to_z3950oid(global_parameters.odr_out,
276 CLASS_RECSYN, VAL_USMARC);
278 if (send_apdu(cl, a) >= 0)
280 iochan_setflags(i, EVENT_INPUT);
281 cl->state = Client_Presenting;
284 cl->state = Client_Error;
285 odr_reset(global_parameters.odr_out);
288 static void do_initResponse(IOCHAN i, Z_APDU *a)
290 struct connection *co = iochan_getdata(i);
291 struct client *cl = co->client;
292 Z_InitResponse *r = a->u.initResponse;
294 yaz_log(YLOG_DEBUG, "Received init response");
298 cl->state = Client_Idle;
301 cl->state = Client_Failed; // FIXME need to do something to the connection
304 static void do_searchResponse(IOCHAN i, Z_APDU *a)
306 struct connection *co = iochan_getdata(i);
307 struct client *cl = co->client;
308 struct session *se = cl->session;
309 Z_SearchResponse *r = a->u.searchResponse;
311 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
313 if (*r->searchStatus)
315 cl->hits = *r->resultCount;
316 se->total_hits += cl->hits;
317 if (r->presentStatus && !*r->presentStatus && r->records)
319 yaz_log(YLOG_DEBUG, "Records in search response");
320 ingest_records(cl, r->records);
322 cl->state = Client_Idle;
327 cl->state = Client_Error;
329 Z_Records *recs = r->records;
330 if (recs->which == Z_Records_NSD)
332 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
333 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
334 cl->state = Client_Error;
340 char *normalize_mergekey(char *buf, int skiparticle)
342 char *p = buf, *pout = buf;
347 char articles[] = "the den der die des an a "; // must end in space
349 while (*p && !isalnum(*p))
352 while (*p && *p != ' ' && pout - firstword < 62)
353 *(pout++) = tolower(*(p++));
356 if (!strstr(articles, firstword))
363 while (*p && !isalnum(*p))
366 *(pout++) = tolower(*(p++));
369 while (*p && !isalnum(*p))
376 while (pout > buf && *pout == ' ');
383 // FIXME needs to be generalized. Should flexibly generate X lists per search
384 static void extract_subject(struct session *s, const char *rec)
386 const char *field, *subfield;
388 while ((field = find_field(rec, "650")))
391 if ((subfield = find_subfield(field, 'a')))
397 ef = index(subfield, '\n');
400 if ((e = index(subfield, '\t')) && e < ef)
402 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
406 memcpy(buf, subfield, len);
410 termlist_insert(s->termlist, buf);
417 static void add_facet(struct session *s, const char *type, const char *value)
423 for (i = 0; i < s->num_termlists; i++)
424 if (!strcmp(s->termlists[i].name, type))
426 if (i == s->num_termlists)
428 if (i == SESSION_MAX_TERMLISTS)
430 yaz_log(YLOG_FATAL, "Too many termlists");
433 s->termlists[i].name = nmem_strdup(s->nmem, type);
434 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
435 s->num_termlists = i + 1;
437 termlist_insert(s->termlists[i].termlist, value);
440 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
442 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
443 struct conf_retrievalmap *m;
447 // First normalize to XML
448 if (rprofile->native_syntax == Nativesyn_iso2709)
452 if (rec->which != Z_External_octet)
454 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
457 buf = (char*) rec->u.octet_aligned->buf;
458 len = rec->u.octet_aligned->len;
459 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
461 yaz_log(YLOG_WARN, "Failed to decode MARC");
464 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
465 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
467 yaz_log(YLOG_WARN, "Failed to encode as XML");
470 rdoc = xmlNewDoc((xmlChar *) "1.0");
471 xmlDocSetRootElement(rdoc, res);
475 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
479 if (global_parameters.dump_records)
481 fprintf(stderr, "Input Record (normalized):\n----------------\n");
482 #if LIBXML_VERSION >= 20600
483 xmlDocFormatDump(stderr, rdoc, 1);
485 xmlDocDump(stderr, rdoc);
489 for (m = rprofile->maplist; m; m = m->next)
492 if (m->type != Map_xslt)
494 yaz_log(YLOG_WARN, "Unknown map type");
497 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
499 yaz_log(YLOG_WARN, "XSLT transformation failed");
505 if (global_parameters.dump_records)
507 fprintf(stderr, "Record:\n----------------\n");
508 #if LIBXML_VERSION >= 20600
509 xmlDocFormatDump(stderr, rdoc, 1);
511 xmlDocDump(stderr, rdoc);
517 // Extract what appears to be years from buf, storing highest and
519 static int extract_years(const char *buf, int *first, int *last)
528 while (*buf && !isdigit(*buf))
531 for (e = buf; *e && isdigit(*e); e++)
535 int value = atoi(buf);
536 if (*first < 0 || value < *first)
538 if (*last < 0 || value > *last)
546 static struct record *ingest_record(struct client *cl, Z_External *rec)
548 xmlDoc *xdoc = normalize_record(cl, rec);
551 struct record_cluster *cluster;
552 struct session *se = cl->session;
553 xmlChar *mergekey, *mergekey_norm;
556 struct conf_service *service = global_parameters.server->service;
561 root = xmlDocGetRootElement(xdoc);
562 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
564 yaz_log(YLOG_WARN, "No mergekey found in record");
569 res = nmem_malloc(se->nmem, sizeof(struct record));
572 res->metadata = nmem_malloc(se->nmem,
573 sizeof(struct record_metadata*) * service->num_metadata);
574 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
576 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
578 normalize_mergekey((char *) mergekey_norm, 0);
580 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
582 if (global_parameters.dump_records)
583 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
584 cl->database->url, cl->records);
587 /* no room for record */
591 relevance_newrec(se->relevance, cluster);
593 for (n = root->children; n; n = n->next)
601 if (n->type != XML_ELEMENT_NODE)
603 if (!strcmp((const char *) n->name, "metadata"))
605 struct conf_metadata *md = 0;
606 struct conf_sortkey *sk = 0;
607 struct record_metadata **wheretoput, *newm;
611 type = xmlGetProp(n, (xmlChar *) "type");
612 value = xmlNodeListGetString(xdoc, n->children, 0);
617 // First, find out what field we're looking at
618 for (imeta = 0; imeta < service->num_metadata; imeta++)
619 if (!strcmp((const char *) type, service->metadata[imeta].name))
621 md = &service->metadata[imeta];
622 if (md->sortkey_offset >= 0)
623 sk = &service->sortkeys[md->sortkey_offset];
628 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
632 // Find out where we are putting it
633 if (md->merge == Metadata_merge_no)
634 wheretoput = &res->metadata[imeta];
636 wheretoput = &cluster->metadata[imeta];
639 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
641 if (md->type == Metadata_type_generic)
644 for (p = (char *) value; *p && isspace(*p); p++)
646 for (pe = p + strlen(p) - 1;
647 pe > p && strchr(" ,/.:([", *pe); pe--)
649 newm->data.text = nmem_strdup(se->nmem, p);
652 else if (md->type == Metadata_type_year)
654 if (extract_years((char *) value, &first, &last) < 0)
659 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
662 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
664 yaz_log(YLOG_WARN, "Only range merging supported for years");
667 if (md->merge == Metadata_merge_unique)
669 struct record_metadata *mnode;
670 for (mnode = *wheretoput; mnode; mnode = mnode->next)
671 if (!strcmp((const char *) mnode->data.text, newm->data.text))
675 newm->next = *wheretoput;
679 else if (md->merge == Metadata_merge_longest)
682 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
687 char *s = nmem_strdup(se->nmem, newm->data.text);
688 if (!cluster->sortkeys[md->sortkey_offset])
689 cluster->sortkeys[md->sortkey_offset] =
690 nmem_malloc(se->nmem, sizeof(union data_types));
691 normalize_mergekey(s,
692 (sk->type == Metadata_sortkey_skiparticle));
693 cluster->sortkeys[md->sortkey_offset]->text = s;
697 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
699 newm->next = *wheretoput;
702 else if (md->merge == Metadata_merge_range)
704 assert(md->type == Metadata_type_year);
708 (*wheretoput)->data.number.min = first;
709 (*wheretoput)->data.number.max = last;
711 cluster->sortkeys[md->sortkey_offset] = &newm->data;
715 if (first < (*wheretoput)->data.number.min)
716 (*wheretoput)->data.number.min = first;
717 if (last > (*wheretoput)->data.number.max)
718 (*wheretoput)->data.number.max = last;
723 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
724 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
729 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
732 relevance_countwords(se->relevance, cluster,
733 (char *) value, md->rank);
736 if (md->type == Metadata_type_year)
739 sprintf(year, "%d", last);
740 add_facet(se, (char *) type, year);
743 sprintf(year, "%d", first);
744 add_facet(se, (char *) type, year);
748 add_facet(se, (char *) type, (char *) value);
755 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
764 relevance_donerecord(se->relevance, cluster);
770 static void ingest_records(struct client *cl, Z_Records *r)
773 yaz_timing_t t = yaz_timing_create();
776 struct session *s = cl->session;
777 Z_NamePlusRecordList *rlist;
780 if (r->which != Z_Records_DBOSD)
782 rlist = r->u.databaseOrSurDiagnostics;
783 for (i = 0; i < rlist->num_records; i++)
785 Z_NamePlusRecord *npr = rlist->records[i];
788 if (npr->which != Z_NamePlusRecord_databaseRecord)
790 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
794 rec = ingest_record(cl, npr->u.databaseRecord);
798 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
799 session_alert_watch(s, SESSION_WATCH_RECORDS);
803 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
804 yaz_timing_get_real(t), yaz_timing_get_user(t),
805 yaz_timing_get_sys(t));
806 yaz_timing_destroy(&t);
810 static void do_presentResponse(IOCHAN i, Z_APDU *a)
812 struct connection *co = iochan_getdata(i);
813 struct client *cl = co->client;
814 Z_PresentResponse *r = a->u.presentResponse;
817 Z_Records *recs = r->records;
818 if (recs->which == Z_Records_NSD)
820 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
821 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
822 cl->state = Client_Error;
826 if (!*r->presentStatus && cl->state != Client_Error)
828 yaz_log(YLOG_DEBUG, "Good Present response");
829 ingest_records(cl, r->records);
830 cl->state = Client_Idle;
832 else if (*r->presentStatus)
834 yaz_log(YLOG_WARN, "Bad Present response");
835 cl->state = Client_Error;
839 static void handler(IOCHAN i, int event)
841 struct connection *co = iochan_getdata(i);
842 struct client *cl = co->client;
843 struct session *se = 0;
849 yaz_log(YLOG_WARN, "Destroying orphan connection");
850 connection_destroy(co);
854 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
857 socklen_t errlen = sizeof(errcode);
859 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
860 &errlen) < 0 || errcode != 0)
867 yaz_log(YLOG_DEBUG, "Connect OK");
868 co->state = Conn_Open;
870 cl->state = Client_Connected;
874 else if (event & EVENT_INPUT)
876 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
880 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
881 connection_destroy(co);
886 yaz_log(YLOG_WARN, "EOF reading from Z server");
887 connection_destroy(co);
890 else if (len > 1) // We discard input if we have no connection
892 co->state = Conn_Open;
894 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
898 odr_reset(global_parameters.odr_in);
899 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
900 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
907 case Z_APDU_initResponse:
908 do_initResponse(i, a);
910 case Z_APDU_searchResponse:
911 do_searchResponse(i, a);
913 case Z_APDU_presentResponse:
914 do_presentResponse(i, a);
917 yaz_log(YLOG_WARN, "Unexpected result from server");
921 // We aren't expecting staggered output from target
922 // if (cs_more(t->link))
923 // iochan_setevent(i, EVENT_INPUT);
925 else // we throw away response and go to idle mode
927 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
928 cl->state = Client_Idle;
931 /* if len==1 we do nothing but wait for more input */
934 if (cl->state == Client_Connected) {
938 if (cl->state == Client_Idle)
940 if (cl->requestid != se->requestid && *se->query) {
943 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
944 cl->records < cl->hits) {
950 // Disassociate connection from client
951 static void connection_release(struct connection *co)
953 struct client *cl = co->client;
955 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
962 // Close connection and recycle structure
963 static void connection_destroy(struct connection *co)
965 struct host *h = co->host;
967 iochan_destroy(co->iochan);
969 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
970 if (h->connections == co)
971 h->connections = co->next;
974 struct connection *pco;
975 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
978 pco->next = co->next;
984 if (co->client->state != Client_Idle)
985 co->client->state = Client_Disconnected;
986 co->client->connection = 0;
988 co->next = connection_freelist;
989 connection_freelist = co;
992 // Creates a new connection for client, associated with the host of
994 static struct connection *connection_create(struct client *cl)
996 struct connection *new;
1002 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1004 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1008 if (0 == strlen(global_parameters.zproxy_override)){
1009 /* no Z39.50 proxy needed - direct connect */
1010 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
1012 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
1014 yaz_log(YLOG_WARN|YLOG_ERRNO,
1015 "Lookup of IP address %s failed",
1016 cl->database->host->ipport);
1021 /* Z39.50 proxy connect */
1022 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1023 cl->database->url, global_parameters.zproxy_override);
1025 yaz_log(YLOG_LOG, "Connection cs_create_host %s proxy %s",
1026 cl->database->url, global_parameters.zproxy_override);
1028 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1030 yaz_log(YLOG_WARN|YLOG_ERRNO,
1031 "Lookup of IP address %s failed",
1032 global_parameters.zproxy_override);
1037 res = cs_connect(link, addr);
1040 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
1044 if ((new = connection_freelist))
1045 connection_freelist = new->next;
1048 new = xmalloc(sizeof (struct connection));
1052 new->state = Conn_Connecting;
1053 new->host = cl->database->host;
1054 new->next = new->host->connections;
1055 new->host->connections = new;
1057 cl->connection = new;
1060 new->iochan = iochan_create(cs_fileno(link), 0, handler, 0);
1061 iochan_setdata(new->iochan, new);
1062 new->iochan->next = channel_list;
1063 channel_list = new->iochan;
1067 // Close connection and set state to error
1068 static void client_fatal(struct client *cl)
1070 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
1071 connection_destroy(cl->connection);
1072 cl->state = Client_Error;
1075 // Ensure that client has a connection associated
1076 static int client_prep_connection(struct client *cl)
1078 struct connection *co;
1079 struct session *se = cl->session;
1080 struct host *host = cl->database->host;
1082 co = cl->connection;
1084 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1088 // See if someone else has an idle connection
1089 // We should look at timestamps here to select the longest-idle connection
1090 for (co = host->connections; co; co = co->next)
1091 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1095 connection_release(co);
1096 cl->connection = co;
1100 co = connection_create(cl);
1104 if (co->state == Conn_Connecting)
1106 cl->state = Client_Connecting;
1107 iochan_setflag(co->iochan, EVENT_OUTPUT);
1109 else if (co->state == Conn_Open)
1111 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1112 cl->state = Client_Idle;
1113 iochan_setflag(co->iochan, EVENT_OUTPUT);
1121 #ifdef GAGA // Moved to database.c
1123 // This function will most likely vanish when a proper target profile mechanism is
1125 void load_simpletargets(const char *fn)
1127 FILE *f = fopen(fn, "r");
1132 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1136 while (fgets(line, 255, f))
1141 struct database *database;
1143 if (strncmp(line, "target ", 7))
1145 line[strlen(line) - 1] = '\0';
1147 if ((name = strchr(line, ';')))
1151 if ((db = strchr(url, '/')))
1156 yaz_log(YLOG_LOG, "Target: %s, '%s'", url, db);
1157 for (host = hosts; host; host = host->next)
1158 if (!strcmp((const char *) url, host->hostport))
1162 struct addrinfo *addrinfo, hints;
1165 unsigned char addrbuf[4];
1168 host = xmalloc(sizeof(struct host));
1169 host->hostport = xstrdup(url);
1170 host->connections = 0;
1172 if ((port = strchr(url, ':')))
1178 hints.ai_family = PF_INET;
1179 hints.ai_socktype = SOCK_STREAM;
1180 hints.ai_protocol = IPPROTO_TCP;
1181 hints.ai_addrlen = 0;
1183 hints.ai_canonname = 0;
1185 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1187 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1189 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1190 xfree(host->hostport);
1194 assert(addrinfo->ai_family == PF_INET);
1195 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1196 sprintf(ipport, "%u.%u.%u.%u:%s",
1197 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1198 host->ipport = xstrdup(ipport);
1199 freeaddrinfo(addrinfo);
1203 database = xmalloc(sizeof(struct database));
1204 database->host = host;
1205 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1206 strcpy(database->url, url);
1207 strcat(database->url, "/");
1208 strcat(database->url, db);
1210 database->name = xstrdup(name);
1214 database->databases = xmalloc(2 * sizeof(char *));
1215 database->databases[0] = xstrdup(db);
1216 database->databases[1] = 0;
1217 database->errors = 0;
1218 database->qprofile = 0;
1219 database->rprofile = database_retrieval_profile(database);
1220 database->next = databases;
1221 databases = database;
1229 static struct client *client_create(void)
1232 if (client_freelist)
1234 r = client_freelist;
1235 client_freelist = client_freelist->next;
1238 r = xmalloc(sizeof(struct client));
1247 r->state = Client_Disconnected;
1252 void client_destroy(struct client *c)
1254 struct session *se = c->session;
1255 if (c == se->clients)
1256 se->clients = c->next;
1260 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1266 connection_release(c->connection);
1267 c->next = client_freelist;
1268 client_freelist = c;
1271 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1273 s->watchlist[what].fun = fun;
1274 s->watchlist[what].data = data;
1277 void session_alert_watch(struct session *s, int what)
1279 if (!s->watchlist[what].fun)
1281 (*s->watchlist[what].fun)(s->watchlist[what].data);
1282 s->watchlist[what].fun = 0;
1283 s->watchlist[what].data = 0;
1286 //callback for grep_databases
1287 static void select_targets_callback(void *context, struct database *db)
1289 struct session *se = (struct session*) context;
1290 struct client *cl = client_create();
1293 cl->next = se->clients;
1297 // This should be extended with parameters to control selection criteria
1298 // Associates a set of clients with a session;
1299 int select_targets(struct session *se, struct database_criterion *crit)
1302 client_destroy(se->clients);
1304 return grep_databases(se, crit, select_targets_callback);
1307 int session_active_clients(struct session *s)
1312 for (c = s->clients; c; c = c->next)
1313 if (c->connection && (c->state == Client_Connecting ||
1314 c->state == Client_Initializing ||
1315 c->state == Client_Searching ||
1316 c->state == Client_Presenting))
1322 // parses crit1=val1,crit2=val2|val3,...
1323 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1325 struct database_criterion *res = 0;
1332 nmem_strsplit(m, ",", buf, &values, &num);
1333 for (i = 0; i < num; i++)
1338 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1339 char *eq = strchr(values[i], '=');
1342 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1346 new->name = values[i];
1347 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1349 for (subi = 0; subi < subnum; subi++)
1351 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1352 newv->value = subvalues[subi];
1353 newv->next = new->values;
1362 char *search(struct session *se, char *query, char *filter)
1364 int live_channels = 0;
1366 struct database_criterion *criteria;
1368 yaz_log(YLOG_DEBUG, "Search");
1370 nmem_reset(se->nmem);
1371 criteria = parse_filter(se->nmem, filter);
1372 strcpy(se->query, query);
1374 // Release any existing clients
1375 select_targets(se, criteria);
1376 for (cl = se->clients; cl; cl = cl->next)
1378 if (client_prep_connection(cl))
1383 int maxrecs = live_channels * global_parameters.toget;
1384 se->num_termlists = 0;
1385 se->reclist = reclist_create(se->nmem, maxrecs);
1386 // This will be initialized in send_search()
1388 se->total_records = se->total_hits = se->total_merged = 0;
1389 se->expected_maxrecs = maxrecs;
1397 void destroy_session(struct session *s)
1399 yaz_log(YLOG_LOG, "Destroying session");
1401 client_destroy(s->clients);
1402 nmem_destroy(s->nmem);
1403 wrbuf_destroy(s->wrbuf);
1406 struct session *new_session()
1409 struct session *session = xmalloc(sizeof(*session));
1411 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1413 session->total_hits = 0;
1414 session->total_records = 0;
1415 session->num_termlists = 0;
1416 session->reclist = 0;
1417 session->requestid = -1;
1418 session->clients = 0;
1419 session->expected_maxrecs = 0;
1420 session->query[0] = '\0';
1421 session->nmem = nmem_create();
1422 session->wrbuf = wrbuf_alloc();
1423 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1425 session->watchlist[i].data = 0;
1426 session->watchlist[i].fun = 0;
1432 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1434 static struct hitsbytarget res[1000]; // FIXME MM
1438 for (cl = se->clients; cl; cl = cl->next)
1440 res[*count].id = cl->database->url;
1441 res[*count].name = cl->database->name;
1442 res[*count].hits = cl->hits;
1443 res[*count].records = cl->records;
1444 res[*count].diagnostic = cl->diagnostic;
1445 res[*count].state = client_states[cl->state];
1446 res[*count].connected = cl->connection ? 1 : 0;
1453 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1457 for (i = 0; i < s->num_termlists; i++)
1458 if (!strcmp((const char *) s->termlists[i].name, name))
1459 return termlist_highscore(s->termlists[i].termlist, num);
1463 #ifdef MISSING_HEADERS
1464 void report_nmem_stats(void)
1466 size_t in_use, is_free;
1468 nmem_get_memory_in_use(&in_use);
1469 nmem_get_memory_free(&is_free);
1471 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1472 (long) in_use, (long) is_free);
1476 struct record_cluster *show_single(struct session *s, int id)
1478 struct record_cluster *r;
1480 reclist_rewind(s->reclist);
1481 while ((r = reclist_read_record(s->reclist)))
1487 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1488 int *num, int *total, int *sumhits, NMEM nmem_show)
1490 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1491 * sizeof(struct record_cluster *));
1492 struct reclist_sortparms *spp;
1495 yaz_timing_t t = yaz_timing_create();
1498 for (spp = sp; spp; spp = spp->next)
1499 if (spp->type == Metadata_sortkey_relevance)
1501 relevance_prepare_read(s->relevance, s->reclist);
1504 reclist_sort(s->reclist, sp);
1506 *total = s->reclist->num_records;
1507 *sumhits = s->total_hits;
1509 for (i = 0; i < start; i++)
1510 if (!reclist_read_record(s->reclist))
1517 for (i = 0; i < *num; i++)
1519 struct record_cluster *r = reclist_read_record(s->reclist);
1529 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1530 yaz_timing_get_real(t), yaz_timing_get_user(t),
1531 yaz_timing_get_sys(t));
1532 yaz_timing_destroy(&t);
1537 void statistics(struct session *se, struct statistics *stat)
1542 memset(stat, 0, sizeof(*stat));
1543 for (cl = se->clients; cl; cl = cl->next)
1545 if (!cl->connection)
1546 stat->num_no_connection++;
1549 case Client_Connecting: stat->num_connecting++; break;
1550 case Client_Initializing: stat->num_initializing++; break;
1551 case Client_Searching: stat->num_searching++; break;
1552 case Client_Presenting: stat->num_presenting++; break;
1553 case Client_Idle: stat->num_idle++; break;
1554 case Client_Failed: stat->num_failed++; break;
1555 case Client_Error: stat->num_error++; break;
1560 stat->num_hits = se->total_hits;
1561 stat->num_records = se->total_records;
1563 stat->num_clients = count;
1566 static void start_http_listener(void)
1569 struct conf_server *ser = global_parameters.server;
1571 if (*global_parameters.listener_override)
1572 strcpy(hp, global_parameters.listener_override);
1575 strcpy(hp, ser->host ? ser->host : "");
1580 sprintf(hp + strlen(hp), "%d", ser->port);
1586 // Initialize CCL map for a target
1587 // Note: This approach ignores user-specific CCL maps, for which I
1588 // don't presently see any application.
1589 static void prepare_cclmap(void *context, struct database *db)
1595 db->ccl_map = ccl_qual_mk();
1596 for (s = db->settings[PZ_CCLMAP]; s; s = s->next)
1599 char *p = strchr(s->name + 3, ':');
1602 yaz_log(YLOG_FATAL, "Malformed cclmap name: %s", s->name);
1606 ccl_qual_fitem(db->ccl_map, s->value, p);
1610 // Read settings for each database, and prepare a CCL map for that database
1611 static void prepare_cclmaps(void)
1613 grep_databases(0, 0, prepare_cclmap);
1616 static void start_proxy(void)
1619 struct conf_server *ser = global_parameters.server;
1621 if (*global_parameters.proxy_override)
1622 strcpy(hp, global_parameters.proxy_override);
1623 else if (ser->proxy_host || ser->proxy_port)
1625 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1626 if (ser->proxy_port)
1630 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1636 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1639 static void start_zproxy(void)
1641 struct conf_server *ser = global_parameters.server;
1643 if (*global_parameters.zproxy_override){
1644 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1645 global_parameters.zproxy_override);
1649 else if (ser->zproxy_host || ser->zproxy_port)
1653 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1654 if (ser->zproxy_port)
1661 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1663 strcpy(global_parameters.zproxy_override, hp);
1664 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1665 global_parameters.zproxy_override);
1674 int main(int argc, char **argv)
1679 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1680 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1682 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1684 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1688 if (!read_config(arg))
1692 strcpy(global_parameters.listener_override, arg);
1695 strcpy(global_parameters.proxy_override, arg);
1698 strcpy(global_parameters.zproxy_override, arg);
1701 strcpy(global_parameters.settings_path_override, arg);
1704 load_simpletargets(arg);
1707 global_parameters.dump_records = 1;
1710 fprintf(stderr, "Usage: pazpar2\n"
1712 " -h [host:]port (REST protocol listener)\n"
1714 " -s simpletargetfile\n"
1715 " -p hostname[:portno] (HTTP proxy)\n"
1716 " -z hostname[:portno] (Z39.50 proxy)\n"
1717 " -d (show internal records)\n");
1724 yaz_log(YLOG_FATAL, "Load config with -f");
1727 global_parameters.server = config->servers;
1729 start_http_listener();
1733 if (*global_parameters.settings_path_override)
1734 settings_read(global_parameters.settings_path_override);
1735 else if (global_parameters.server->settings)
1736 settings_read(global_parameters.server->settings);
1738 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may ensue!");
1740 global_parameters.yaz_marc = yaz_marc_create();
1741 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1742 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1743 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1745 event_loop(&channel_list);
1753 * indent-tabs-mode: nil
1755 * vim: shiftwidth=4 tabstop=8 expandtab