1 /* $Id: pazpar2.c,v 1.55 2007-03-28 04:33:41 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)",
95 static int send_apdu(struct client *c, Z_APDU *a)
97 struct connection *co = c->connection;
101 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
103 odr_perror(global_parameters.odr_out, "Encoding APDU");
106 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
107 r = cs_put(co->link, buf, len);
110 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
115 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
118 odr_reset(global_parameters.odr_out); /* release the APDU structure */
119 co->state = Conn_Waiting;
124 static void send_init(IOCHAN i)
127 struct connection *co = iochan_getdata(i);
128 struct client *cl = co->client;
129 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
131 a->u.initRequest->implementationId = global_parameters.implementationId;
132 a->u.initRequest->implementationName = global_parameters.implementationName;
133 a->u.initRequest->implementationVersion =
134 global_parameters.implementationVersion;
135 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
136 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
137 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
139 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
140 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
141 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
144 /* add virtual host if tunneling through Z39.50 proxy */
146 if (0 < strlen(global_parameters.zproxy_override)
147 && 0 < strlen(cl->database->url))
148 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
149 global_parameters.odr_out, VAL_PROXY,
150 1, cl->database->url);
154 if (send_apdu(cl, a) >= 0)
156 iochan_setflags(i, EVENT_INPUT);
157 cl->state = Client_Initializing;
160 cl->state = Client_Error;
161 odr_reset(global_parameters.odr_out);
164 static void send_search(IOCHAN i)
166 struct connection *co = iochan_getdata(i);
167 struct client *cl = co->client;
168 struct session *se = cl->session;
169 struct database *db = cl->database;
170 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
171 int ndb, cerror, cpos;
174 struct ccl_rpn_node *cn;
175 int ssub = 0, lslb = 100000, mspn = 10;
177 yaz_log(YLOG_DEBUG, "Sending search");
179 cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
182 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
184 zquery->which = Z_Query_type_1;
185 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
188 for (ndb = 0; db->databases[ndb]; ndb++)
190 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
191 for (ndb = 0; db->databases[ndb]; ndb++)
192 databaselist[ndb] = db->databases[ndb];
194 a->u.searchRequest->preferredRecordSyntax =
195 yaz_oidval_to_z3950oid(global_parameters.odr_out,
196 CLASS_RECSYN, VAL_USMARC);
197 a->u.searchRequest->smallSetUpperBound = &ssub;
198 a->u.searchRequest->largeSetLowerBound = &lslb;
199 a->u.searchRequest->mediumSetPresentNumber = &mspn;
200 a->u.searchRequest->resultSetName = "Default";
201 a->u.searchRequest->databaseNames = databaselist;
202 a->u.searchRequest->num_databaseNames = ndb;
204 if (send_apdu(cl, a) >= 0)
206 iochan_setflags(i, EVENT_INPUT);
207 cl->state = Client_Searching;
208 cl->requestid = se->requestid;
211 cl->state = Client_Error;
213 odr_reset(global_parameters.odr_out);
216 static void send_present(IOCHAN i)
218 struct connection *co = iochan_getdata(i);
219 struct client *cl = co->client;
220 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
222 int start = cl->records + 1;
224 toget = global_parameters.chunk;
225 if (toget > global_parameters.toget - cl->records)
226 toget = global_parameters.toget - cl->records;
227 if (toget > cl->hits - cl->records)
228 toget = cl->hits - cl->records;
230 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
232 a->u.presentRequest->resultSetStartPoint = &start;
233 a->u.presentRequest->numberOfRecordsRequested = &toget;
235 a->u.presentRequest->resultSetId = "Default";
237 a->u.presentRequest->preferredRecordSyntax =
238 yaz_oidval_to_z3950oid(global_parameters.odr_out,
239 CLASS_RECSYN, VAL_USMARC);
241 if (send_apdu(cl, a) >= 0)
243 iochan_setflags(i, EVENT_INPUT);
244 cl->state = Client_Presenting;
247 cl->state = Client_Error;
248 odr_reset(global_parameters.odr_out);
251 static void do_initResponse(IOCHAN i, Z_APDU *a)
253 struct connection *co = iochan_getdata(i);
254 struct client *cl = co->client;
255 Z_InitResponse *r = a->u.initResponse;
257 yaz_log(YLOG_DEBUG, "Received init response");
261 cl->state = Client_Idle;
264 cl->state = Client_Failed; // FIXME need to do something to the connection
267 static void do_searchResponse(IOCHAN i, Z_APDU *a)
269 struct connection *co = iochan_getdata(i);
270 struct client *cl = co->client;
271 struct session *se = cl->session;
272 Z_SearchResponse *r = a->u.searchResponse;
274 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
276 if (*r->searchStatus)
278 cl->hits = *r->resultCount;
279 se->total_hits += cl->hits;
280 if (r->presentStatus && !*r->presentStatus && r->records)
282 yaz_log(YLOG_DEBUG, "Records in search response");
283 ingest_records(cl, r->records);
285 cl->state = Client_Idle;
290 cl->state = Client_Error;
292 Z_Records *recs = r->records;
293 if (recs->which == Z_Records_NSD)
295 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
296 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
297 cl->state = Client_Error;
303 char *normalize_mergekey(char *buf, int skiparticle)
305 char *p = buf, *pout = buf;
310 char articles[] = "the den der die des an a "; // must end in space
312 while (*p && !isalnum(*p))
315 while (*p && *p != ' ' && pout - firstword < 62)
316 *(pout++) = tolower(*(p++));
319 if (!strstr(articles, firstword))
326 while (*p && !isalnum(*p))
329 *(pout++) = tolower(*(p++));
332 while (*p && !isalnum(*p))
339 while (pout > buf && *pout == ' ');
346 // FIXME needs to be generalized. Should flexibly generate X lists per search
347 static void extract_subject(struct session *s, const char *rec)
349 const char *field, *subfield;
351 while ((field = find_field(rec, "650")))
354 if ((subfield = find_subfield(field, 'a')))
360 ef = index(subfield, '\n');
363 if ((e = index(subfield, '\t')) && e < ef)
365 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
369 memcpy(buf, subfield, len);
373 termlist_insert(s->termlist, buf);
380 static void add_facet(struct session *s, const char *type, const char *value)
386 for (i = 0; i < s->num_termlists; i++)
387 if (!strcmp(s->termlists[i].name, type))
389 if (i == s->num_termlists)
391 if (i == SESSION_MAX_TERMLISTS)
393 yaz_log(YLOG_FATAL, "Too many termlists");
396 s->termlists[i].name = nmem_strdup(s->nmem, type);
397 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
398 s->num_termlists = i + 1;
400 termlist_insert(s->termlists[i].termlist, value);
403 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
405 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
406 struct conf_retrievalmap *m;
410 // First normalize to XML
411 if (rprofile->native_syntax == Nativesyn_iso2709)
415 if (rec->which != Z_External_octet)
417 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
420 buf = (char*) rec->u.octet_aligned->buf;
421 len = rec->u.octet_aligned->len;
422 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
424 yaz_log(YLOG_WARN, "Failed to decode MARC");
427 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
428 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
430 yaz_log(YLOG_WARN, "Failed to encode as XML");
433 rdoc = xmlNewDoc((xmlChar *) "1.0");
434 xmlDocSetRootElement(rdoc, res);
438 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
442 if (global_parameters.dump_records)
444 fprintf(stderr, "Input Record (normalized):\n----------------\n");
445 #if LIBXML_VERSION >= 20600
446 xmlDocFormatDump(stderr, rdoc, 1);
448 xmlDocDump(stderr, rdoc);
452 for (m = rprofile->maplist; m; m = m->next)
455 if (m->type != Map_xslt)
457 yaz_log(YLOG_WARN, "Unknown map type");
460 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
462 yaz_log(YLOG_WARN, "XSLT transformation failed");
468 if (global_parameters.dump_records)
470 fprintf(stderr, "Record:\n----------------\n");
471 #if LIBXML_VERSION >= 20600
472 xmlDocFormatDump(stderr, rdoc, 1);
474 xmlDocDump(stderr, rdoc);
480 // Extract what appears to be years from buf, storing highest and
482 static int extract_years(const char *buf, int *first, int *last)
491 while (*buf && !isdigit(*buf))
494 for (e = buf; *e && isdigit(*e); e++)
498 int value = atoi(buf);
499 if (*first < 0 || value < *first)
501 if (*last < 0 || value > *last)
509 static struct record *ingest_record(struct client *cl, Z_External *rec)
511 xmlDoc *xdoc = normalize_record(cl, rec);
514 struct record_cluster *cluster;
515 struct session *se = cl->session;
516 xmlChar *mergekey, *mergekey_norm;
519 struct conf_service *service = global_parameters.server->service;
524 root = xmlDocGetRootElement(xdoc);
525 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
527 yaz_log(YLOG_WARN, "No mergekey found in record");
532 res = nmem_malloc(se->nmem, sizeof(struct record));
535 res->metadata = nmem_malloc(se->nmem,
536 sizeof(struct record_metadata*) * service->num_metadata);
537 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
539 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
541 normalize_mergekey((char *) mergekey_norm, 0);
543 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
545 if (global_parameters.dump_records)
546 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
547 cl->database->url, cl->records);
550 /* no room for record */
554 relevance_newrec(se->relevance, cluster);
556 for (n = root->children; n; n = n->next)
564 if (n->type != XML_ELEMENT_NODE)
566 if (!strcmp((const char *) n->name, "metadata"))
568 struct conf_metadata *md = 0;
569 struct conf_sortkey *sk = 0;
570 struct record_metadata **wheretoput, *newm;
574 type = xmlGetProp(n, (xmlChar *) "type");
575 value = xmlNodeListGetString(xdoc, n->children, 0);
580 // First, find out what field we're looking at
581 for (imeta = 0; imeta < service->num_metadata; imeta++)
582 if (!strcmp((const char *) type, service->metadata[imeta].name))
584 md = &service->metadata[imeta];
585 if (md->sortkey_offset >= 0)
586 sk = &service->sortkeys[md->sortkey_offset];
591 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
595 // Find out where we are putting it
596 if (md->merge == Metadata_merge_no)
597 wheretoput = &res->metadata[imeta];
599 wheretoput = &cluster->metadata[imeta];
602 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
604 if (md->type == Metadata_type_generic)
607 for (p = (char *) value; *p && isspace(*p); p++)
609 for (pe = p + strlen(p) - 1;
610 pe > p && strchr(" ,/.:([", *pe); pe--)
612 newm->data.text = nmem_strdup(se->nmem, p);
615 else if (md->type == Metadata_type_year)
617 if (extract_years((char *) value, &first, &last) < 0)
622 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
625 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
627 yaz_log(YLOG_WARN, "Only range merging supported for years");
630 if (md->merge == Metadata_merge_unique)
632 struct record_metadata *mnode;
633 for (mnode = *wheretoput; mnode; mnode = mnode->next)
634 if (!strcmp((const char *) mnode->data.text, newm->data.text))
638 newm->next = *wheretoput;
642 else if (md->merge == Metadata_merge_longest)
645 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
650 char *s = nmem_strdup(se->nmem, newm->data.text);
651 if (!cluster->sortkeys[md->sortkey_offset])
652 cluster->sortkeys[md->sortkey_offset] =
653 nmem_malloc(se->nmem, sizeof(union data_types));
654 normalize_mergekey(s,
655 (sk->type == Metadata_sortkey_skiparticle));
656 cluster->sortkeys[md->sortkey_offset]->text = s;
660 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
662 newm->next = *wheretoput;
665 else if (md->merge == Metadata_merge_range)
667 assert(md->type == Metadata_type_year);
671 (*wheretoput)->data.number.min = first;
672 (*wheretoput)->data.number.max = last;
674 cluster->sortkeys[md->sortkey_offset] = &newm->data;
678 if (first < (*wheretoput)->data.number.min)
679 (*wheretoput)->data.number.min = first;
680 if (last > (*wheretoput)->data.number.max)
681 (*wheretoput)->data.number.max = last;
686 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
687 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
692 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
695 relevance_countwords(se->relevance, cluster,
696 (char *) value, md->rank);
699 if (md->type == Metadata_type_year)
702 sprintf(year, "%d", last);
703 add_facet(se, (char *) type, year);
706 sprintf(year, "%d", first);
707 add_facet(se, (char *) type, year);
711 add_facet(se, (char *) type, (char *) value);
718 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
727 relevance_donerecord(se->relevance, cluster);
733 static void ingest_records(struct client *cl, Z_Records *r)
736 yaz_timing_t t = yaz_timing_create();
739 struct session *s = cl->session;
740 Z_NamePlusRecordList *rlist;
743 if (r->which != Z_Records_DBOSD)
745 rlist = r->u.databaseOrSurDiagnostics;
746 for (i = 0; i < rlist->num_records; i++)
748 Z_NamePlusRecord *npr = rlist->records[i];
751 if (npr->which != Z_NamePlusRecord_databaseRecord)
753 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
757 rec = ingest_record(cl, npr->u.databaseRecord);
761 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
762 session_alert_watch(s, SESSION_WATCH_RECORDS);
766 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
767 yaz_timing_get_real(t), yaz_timing_get_user(t),
768 yaz_timing_get_sys(t));
769 yaz_timing_destroy(&t);
773 static void do_presentResponse(IOCHAN i, Z_APDU *a)
775 struct connection *co = iochan_getdata(i);
776 struct client *cl = co->client;
777 Z_PresentResponse *r = a->u.presentResponse;
780 Z_Records *recs = r->records;
781 if (recs->which == Z_Records_NSD)
783 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
784 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
785 cl->state = Client_Error;
789 if (!*r->presentStatus && cl->state != Client_Error)
791 yaz_log(YLOG_DEBUG, "Good Present response");
792 ingest_records(cl, r->records);
793 cl->state = Client_Idle;
795 else if (*r->presentStatus)
797 yaz_log(YLOG_WARN, "Bad Present response");
798 cl->state = Client_Error;
802 static void handler(IOCHAN i, int event)
804 struct connection *co = iochan_getdata(i);
805 struct client *cl = co->client;
806 struct session *se = 0;
812 yaz_log(YLOG_WARN, "Destroying orphan connection");
813 connection_destroy(co);
817 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
820 socklen_t errlen = sizeof(errcode);
822 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
823 &errlen) < 0 || errcode != 0)
830 yaz_log(YLOG_DEBUG, "Connect OK");
831 co->state = Conn_Open;
833 cl->state = Client_Connected;
837 else if (event & EVENT_INPUT)
839 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
843 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
844 connection_destroy(co);
849 yaz_log(YLOG_WARN, "EOF reading from Z server");
850 connection_destroy(co);
853 else if (len > 1) // We discard input if we have no connection
855 co->state = Conn_Open;
857 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
861 odr_reset(global_parameters.odr_in);
862 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
863 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
870 case Z_APDU_initResponse:
871 do_initResponse(i, a);
873 case Z_APDU_searchResponse:
874 do_searchResponse(i, a);
876 case Z_APDU_presentResponse:
877 do_presentResponse(i, a);
880 yaz_log(YLOG_WARN, "Unexpected result from server");
884 // We aren't expecting staggered output from target
885 // if (cs_more(t->link))
886 // iochan_setevent(i, EVENT_INPUT);
888 else // we throw away response and go to idle mode
890 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
891 cl->state = Client_Idle;
894 /* if len==1 we do nothing but wait for more input */
897 if (cl->state == Client_Connected) {
901 if (cl->state == Client_Idle)
903 if (cl->requestid != se->requestid && *se->query) {
906 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
907 cl->records < cl->hits) {
913 // Disassociate connection from client
914 static void connection_release(struct connection *co)
916 struct client *cl = co->client;
918 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
925 // Close connection and recycle structure
926 static void connection_destroy(struct connection *co)
928 struct host *h = co->host;
930 iochan_destroy(co->iochan);
932 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
933 if (h->connections == co)
934 h->connections = co->next;
937 struct connection *pco;
938 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
941 pco->next = co->next;
947 if (co->client->state != Client_Idle)
948 co->client->state = Client_Disconnected;
949 co->client->connection = 0;
951 co->next = connection_freelist;
952 connection_freelist = co;
955 // Creates a new connection for client, associated with the host of
957 static struct connection *connection_create(struct client *cl)
959 struct connection *new;
965 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
967 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
971 if (0 == strlen(global_parameters.zproxy_override)){
972 /* no Z39.50 proxy needed - direct connect */
973 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
975 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
977 yaz_log(YLOG_WARN|YLOG_ERRNO,
978 "Lookup of IP address %s failed",
979 cl->database->host->ipport);
984 /* Z39.50 proxy connect */
985 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
986 cl->database->url, global_parameters.zproxy_override);
988 yaz_log(YLOG_LOG, "Connection cs_create_host %s proxy %s",
989 cl->database->url, global_parameters.zproxy_override);
991 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
993 yaz_log(YLOG_WARN|YLOG_ERRNO,
994 "Lookup of IP address %s failed",
995 global_parameters.zproxy_override);
1000 res = cs_connect(link, addr);
1003 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
1007 if ((new = connection_freelist))
1008 connection_freelist = new->next;
1011 new = xmalloc(sizeof (struct connection));
1015 new->state = Conn_Connecting;
1016 new->host = cl->database->host;
1017 new->next = new->host->connections;
1018 new->host->connections = new;
1020 cl->connection = new;
1023 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1024 iochan_setdata(new->iochan, new);
1025 new->iochan->next = channel_list;
1026 channel_list = new->iochan;
1030 // Close connection and set state to error
1031 static void client_fatal(struct client *cl)
1033 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
1034 connection_destroy(cl->connection);
1035 cl->state = Client_Error;
1038 // Ensure that client has a connection associated
1039 static int client_prep_connection(struct client *cl)
1041 struct connection *co;
1042 struct session *se = cl->session;
1043 struct host *host = cl->database->host;
1045 co = cl->connection;
1047 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1051 // See if someone else has an idle connection
1052 // We should look at timestamps here to select the longest-idle connection
1053 for (co = host->connections; co; co = co->next)
1054 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1058 connection_release(co);
1059 cl->connection = co;
1063 co = connection_create(cl);
1067 if (co->state == Conn_Connecting)
1069 cl->state = Client_Connecting;
1070 iochan_setflag(co->iochan, EVENT_OUTPUT);
1072 else if (co->state == Conn_Open)
1074 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1075 cl->state = Client_Idle;
1076 iochan_setflag(co->iochan, EVENT_OUTPUT);
1084 #ifdef GAGA // Moved to database.c
1086 // This function will most likely vanish when a proper target profile mechanism is
1088 void load_simpletargets(const char *fn)
1090 FILE *f = fopen(fn, "r");
1095 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1099 while (fgets(line, 255, f))
1104 struct database *database;
1106 if (strncmp(line, "target ", 7))
1108 line[strlen(line) - 1] = '\0';
1110 if ((name = strchr(line, ';')))
1114 if ((db = strchr(url, '/')))
1119 yaz_log(YLOG_LOG, "Target: %s, '%s'", url, db);
1120 for (host = hosts; host; host = host->next)
1121 if (!strcmp((const char *) url, host->hostport))
1125 struct addrinfo *addrinfo, hints;
1128 unsigned char addrbuf[4];
1131 host = xmalloc(sizeof(struct host));
1132 host->hostport = xstrdup(url);
1133 host->connections = 0;
1135 if ((port = strchr(url, ':')))
1141 hints.ai_family = PF_INET;
1142 hints.ai_socktype = SOCK_STREAM;
1143 hints.ai_protocol = IPPROTO_TCP;
1144 hints.ai_addrlen = 0;
1146 hints.ai_canonname = 0;
1148 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1150 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1152 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1153 xfree(host->hostport);
1157 assert(addrinfo->ai_family == PF_INET);
1158 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1159 sprintf(ipport, "%u.%u.%u.%u:%s",
1160 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1161 host->ipport = xstrdup(ipport);
1162 freeaddrinfo(addrinfo);
1166 database = xmalloc(sizeof(struct database));
1167 database->host = host;
1168 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1169 strcpy(database->url, url);
1170 strcat(database->url, "/");
1171 strcat(database->url, db);
1173 database->name = xstrdup(name);
1177 database->databases = xmalloc(2 * sizeof(char *));
1178 database->databases[0] = xstrdup(db);
1179 database->databases[1] = 0;
1180 database->errors = 0;
1181 database->qprofile = 0;
1182 database->rprofile = database_retrieval_profile(database);
1183 database->next = databases;
1184 databases = database;
1192 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1200 pull_terms(nmem, n->u.p[0], termlist, num);
1201 pull_terms(nmem, n->u.p[1], termlist, num);
1204 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1211 // Extract terms from query into null-terminated termlist
1212 static int extract_terms(NMEM nmem, char *query, char **termlist)
1215 struct ccl_rpn_node *n;
1218 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1221 pull_terms(nmem, n, termlist, &num);
1227 static struct client *client_create(void)
1230 if (client_freelist)
1232 r = client_freelist;
1233 client_freelist = client_freelist->next;
1236 r = xmalloc(sizeof(struct client));
1245 r->state = Client_Disconnected;
1250 void client_destroy(struct client *c)
1252 struct session *se = c->session;
1253 if (c == se->clients)
1254 se->clients = c->next;
1258 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1264 connection_release(c->connection);
1265 c->next = client_freelist;
1266 client_freelist = c;
1269 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1271 s->watchlist[what].fun = fun;
1272 s->watchlist[what].data = data;
1275 void session_alert_watch(struct session *s, int what)
1277 if (!s->watchlist[what].fun)
1279 (*s->watchlist[what].fun)(s->watchlist[what].data);
1280 s->watchlist[what].fun = 0;
1281 s->watchlist[what].data = 0;
1284 //callback for grep_databases
1285 static void select_targets_callback(void *context, struct database *db)
1287 struct session *se = (struct session*) context;
1288 struct client *cl = client_create();
1291 cl->next = se->clients;
1295 // This should be extended with parameters to control selection criteria
1296 // Associates a set of clients with a session;
1297 int select_targets(struct session *se, struct database_criterion *crit)
1300 client_destroy(se->clients);
1302 return grep_databases(se, crit, select_targets_callback);
1305 int session_active_clients(struct session *s)
1310 for (c = s->clients; c; c = c->next)
1311 if (c->connection && (c->state == Client_Connecting ||
1312 c->state == Client_Initializing ||
1313 c->state == Client_Searching ||
1314 c->state == Client_Presenting))
1320 // parses crit1=val1,crit2=val2|val3,...
1321 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1323 struct database_criterion *res = 0;
1330 nmem_strsplit(m, ",", buf, &values, &num);
1331 for (i = 0; i < num; i++)
1336 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1337 char *eq = strchr(values[i], '=');
1340 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1344 new->name = values[i];
1345 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1347 for (subi = 0; subi < subnum; subi++)
1349 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1350 newv->value = subvalues[subi];
1351 newv->next = new->values;
1360 char *search(struct session *se, char *query, char *filter)
1362 int live_channels = 0;
1364 struct database_criterion *criteria;
1366 yaz_log(YLOG_DEBUG, "Search");
1368 nmem_reset(se->nmem);
1369 criteria = parse_filter(se->nmem, filter);
1370 strcpy(se->query, query);
1372 // Release any existing clients
1373 select_targets(se, criteria);
1374 for (cl = se->clients; cl; cl = cl->next)
1376 if (client_prep_connection(cl))
1382 int maxrecs = live_channels * global_parameters.toget;
1383 se->num_termlists = 0;
1384 se->reclist = reclist_create(se->nmem, maxrecs);
1385 extract_terms(se->nmem, query, p);
1386 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1387 se->total_records = se->total_hits = se->total_merged = 0;
1388 se->expected_maxrecs = maxrecs;
1396 void destroy_session(struct session *s)
1398 yaz_log(YLOG_LOG, "Destroying session");
1400 client_destroy(s->clients);
1401 nmem_destroy(s->nmem);
1402 wrbuf_destroy(s->wrbuf);
1405 struct session *new_session()
1408 struct session *session = xmalloc(sizeof(*session));
1410 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1412 session->total_hits = 0;
1413 session->total_records = 0;
1414 session->num_termlists = 0;
1415 session->reclist = 0;
1416 session->requestid = -1;
1417 session->clients = 0;
1418 session->expected_maxrecs = 0;
1419 session->query[0] = '\0';
1420 session->nmem = nmem_create();
1421 session->wrbuf = wrbuf_alloc();
1422 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1424 session->watchlist[i].data = 0;
1425 session->watchlist[i].fun = 0;
1431 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1433 static struct hitsbytarget res[1000]; // FIXME MM
1437 for (cl = se->clients; cl; cl = cl->next)
1439 res[*count].id = cl->database->url;
1440 res[*count].name = cl->database->name;
1441 res[*count].hits = cl->hits;
1442 res[*count].records = cl->records;
1443 res[*count].diagnostic = cl->diagnostic;
1444 res[*count].state = client_states[cl->state];
1445 res[*count].connected = cl->connection ? 1 : 0;
1452 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1456 for (i = 0; i < s->num_termlists; i++)
1457 if (!strcmp((const char *) s->termlists[i].name, name))
1458 return termlist_highscore(s->termlists[i].termlist, num);
1462 #ifdef MISSING_HEADERS
1463 void report_nmem_stats(void)
1465 size_t in_use, is_free;
1467 nmem_get_memory_in_use(&in_use);
1468 nmem_get_memory_free(&is_free);
1470 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1471 (long) in_use, (long) is_free);
1475 struct record_cluster *show_single(struct session *s, int id)
1477 struct record_cluster *r;
1479 reclist_rewind(s->reclist);
1480 while ((r = reclist_read_record(s->reclist)))
1486 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1487 int *num, int *total, int *sumhits, NMEM nmem_show)
1489 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1490 * sizeof(struct record_cluster *));
1491 struct reclist_sortparms *spp;
1494 yaz_timing_t t = yaz_timing_create();
1497 for (spp = sp; spp; spp = spp->next)
1498 if (spp->type == Metadata_sortkey_relevance)
1500 relevance_prepare_read(s->relevance, s->reclist);
1503 reclist_sort(s->reclist, sp);
1505 *total = s->reclist->num_records;
1506 *sumhits = s->total_hits;
1508 for (i = 0; i < start; i++)
1509 if (!reclist_read_record(s->reclist))
1516 for (i = 0; i < *num; i++)
1518 struct record_cluster *r = reclist_read_record(s->reclist);
1528 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1529 yaz_timing_get_real(t), yaz_timing_get_user(t),
1530 yaz_timing_get_sys(t));
1531 yaz_timing_destroy(&t);
1536 void statistics(struct session *se, struct statistics *stat)
1541 memset(stat, 0, sizeof(*stat));
1542 for (cl = se->clients; cl; cl = cl->next)
1544 if (!cl->connection)
1545 stat->num_no_connection++;
1548 case Client_Connecting: stat->num_connecting++; break;
1549 case Client_Initializing: stat->num_initializing++; break;
1550 case Client_Searching: stat->num_searching++; break;
1551 case Client_Presenting: stat->num_presenting++; break;
1552 case Client_Idle: stat->num_idle++; break;
1553 case Client_Failed: stat->num_failed++; break;
1554 case Client_Error: stat->num_error++; break;
1559 stat->num_hits = se->total_hits;
1560 stat->num_records = se->total_records;
1562 stat->num_clients = count;
1565 static CCL_bibset load_cclfile(const char *fn)
1567 CCL_bibset res = ccl_qual_mk();
1568 if (ccl_qual_fname(res, fn) < 0)
1570 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1576 static void start_http_listener(void)
1579 struct conf_server *ser = global_parameters.server;
1581 if (*global_parameters.listener_override)
1582 strcpy(hp, global_parameters.listener_override);
1585 strcpy(hp, ser->host ? ser->host : "");
1590 sprintf(hp + strlen(hp), "%d", ser->port);
1596 static void start_proxy(void)
1599 struct conf_server *ser = global_parameters.server;
1601 if (*global_parameters.proxy_override)
1602 strcpy(hp, global_parameters.proxy_override);
1603 else if (ser->proxy_host || ser->proxy_port)
1605 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1606 if (ser->proxy_port)
1610 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1616 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1619 static void start_zproxy(void)
1621 struct conf_server *ser = global_parameters.server;
1623 if (*global_parameters.zproxy_override){
1624 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1625 global_parameters.zproxy_override);
1629 else if (ser->zproxy_host || ser->zproxy_port)
1633 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1634 if (ser->zproxy_port)
1641 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1643 strcpy(global_parameters.zproxy_override, hp);
1644 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1645 global_parameters.zproxy_override);
1654 int main(int argc, char **argv)
1659 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1660 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1662 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1664 while ((ret = options("t:f:x:h:p:z:C:s:d", argv, argc, &arg)) != -2)
1668 if (!read_config(arg))
1672 strcpy(global_parameters.listener_override, arg);
1675 global_parameters.ccl_filter = load_cclfile(arg);
1678 strcpy(global_parameters.proxy_override, arg);
1681 strcpy(global_parameters.zproxy_override, arg);
1684 strcpy(global_parameters.settings_path, arg);
1687 load_simpletargets(arg);
1690 global_parameters.dump_records = 1;
1693 fprintf(stderr, "Usage: pazpar2\n"
1695 " -h [host:]port (REST protocol listener)\n"
1697 " -s simpletargetfile\n"
1698 " -p hostname[:portno] (HTTP proxy)\n"
1699 " -z hostname[:portno] (Z39.50 proxy)\n"
1700 " -d (show internal records)\n");
1707 yaz_log(YLOG_FATAL, "Load config with -f");
1710 global_parameters.server = config->servers;
1712 start_http_listener();
1716 if (*global_parameters.settings_path)
1717 settings_read(global_parameters.settings_path);
1718 if (!global_parameters.ccl_filter)
1719 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1720 global_parameters.yaz_marc = yaz_marc_create();
1721 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1722 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1723 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1725 event_loop(&channel_list);
1733 * indent-tabs-mode: nil
1735 * vim: shiftwidth=4 tabstop=8 expandtab