1 /* $Id: pazpar2.c,v 1.54 2007-03-27 11:25:57 marc 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"
46 static void client_fatal(struct client *cl);
47 static void connection_destroy(struct connection *co);
48 static int client_prep_connection(struct client *cl);
49 static void ingest_records(struct client *cl, Z_Records *r);
50 //static struct conf_retrievalprofile *database_retrieval_profile(struct database *db);
51 void session_alert_watch(struct session *s, int what);
53 IOCHAN channel_list = 0; // Master list of connections we're handling events to
55 static struct connection *connection_freelist = 0;
56 static struct client *client_freelist = 0;
58 static char *client_states[] = {
62 "Client_Initializing",
67 "Client_Disconnected",
71 // Note: Some things in this structure will eventually move to configuration
72 struct parameters global_parameters =
81 "Index Data PazPar2 (MasterKey)",
93 static int send_apdu(struct client *c, Z_APDU *a)
95 struct connection *co = c->connection;
99 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
101 odr_perror(global_parameters.odr_out, "Encoding APDU");
104 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
105 r = cs_put(co->link, buf, len);
108 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
113 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
116 odr_reset(global_parameters.odr_out); /* release the APDU structure */
117 co->state = Conn_Waiting;
122 static void send_init(IOCHAN i)
125 struct connection *co = iochan_getdata(i);
126 struct client *cl = co->client;
127 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
129 a->u.initRequest->implementationId = global_parameters.implementationId;
130 a->u.initRequest->implementationName = global_parameters.implementationName;
131 a->u.initRequest->implementationVersion =
132 global_parameters.implementationVersion;
133 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
134 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
135 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
137 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
138 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
139 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
142 /* add virtual host if tunneling through Z39.50 proxy */
144 if (0 < strlen(global_parameters.zproxy_override)
145 && 0 < strlen(cl->database->url))
146 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
147 global_parameters.odr_out, VAL_PROXY,
148 1, cl->database->url);
152 if (send_apdu(cl, a) >= 0)
154 iochan_setflags(i, EVENT_INPUT);
155 cl->state = Client_Initializing;
158 cl->state = Client_Error;
159 odr_reset(global_parameters.odr_out);
162 static void send_search(IOCHAN i)
164 struct connection *co = iochan_getdata(i);
165 struct client *cl = co->client;
166 struct session *se = cl->session;
167 struct database *db = cl->database;
168 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
169 int ndb, cerror, cpos;
172 struct ccl_rpn_node *cn;
173 int ssub = 0, lslb = 100000, mspn = 10;
175 yaz_log(YLOG_DEBUG, "Sending search");
177 cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
180 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
182 zquery->which = Z_Query_type_1;
183 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
186 for (ndb = 0; db->databases[ndb]; ndb++)
188 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
189 for (ndb = 0; db->databases[ndb]; ndb++)
190 databaselist[ndb] = db->databases[ndb];
192 a->u.searchRequest->preferredRecordSyntax =
193 yaz_oidval_to_z3950oid(global_parameters.odr_out,
194 CLASS_RECSYN, VAL_USMARC);
195 a->u.searchRequest->smallSetUpperBound = &ssub;
196 a->u.searchRequest->largeSetLowerBound = &lslb;
197 a->u.searchRequest->mediumSetPresentNumber = &mspn;
198 a->u.searchRequest->resultSetName = "Default";
199 a->u.searchRequest->databaseNames = databaselist;
200 a->u.searchRequest->num_databaseNames = ndb;
202 if (send_apdu(cl, a) >= 0)
204 iochan_setflags(i, EVENT_INPUT);
205 cl->state = Client_Searching;
206 cl->requestid = se->requestid;
209 cl->state = Client_Error;
211 odr_reset(global_parameters.odr_out);
214 static void send_present(IOCHAN i)
216 struct connection *co = iochan_getdata(i);
217 struct client *cl = co->client;
218 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
220 int start = cl->records + 1;
222 toget = global_parameters.chunk;
223 if (toget > global_parameters.toget - cl->records)
224 toget = global_parameters.toget - cl->records;
225 if (toget > cl->hits - cl->records)
226 toget = cl->hits - cl->records;
228 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
230 a->u.presentRequest->resultSetStartPoint = &start;
231 a->u.presentRequest->numberOfRecordsRequested = &toget;
233 a->u.presentRequest->resultSetId = "Default";
235 a->u.presentRequest->preferredRecordSyntax =
236 yaz_oidval_to_z3950oid(global_parameters.odr_out,
237 CLASS_RECSYN, VAL_USMARC);
239 if (send_apdu(cl, a) >= 0)
241 iochan_setflags(i, EVENT_INPUT);
242 cl->state = Client_Presenting;
245 cl->state = Client_Error;
246 odr_reset(global_parameters.odr_out);
249 static void do_initResponse(IOCHAN i, Z_APDU *a)
251 struct connection *co = iochan_getdata(i);
252 struct client *cl = co->client;
253 Z_InitResponse *r = a->u.initResponse;
255 yaz_log(YLOG_DEBUG, "Received init response");
259 cl->state = Client_Idle;
262 cl->state = Client_Failed; // FIXME need to do something to the connection
265 static void do_searchResponse(IOCHAN i, Z_APDU *a)
267 struct connection *co = iochan_getdata(i);
268 struct client *cl = co->client;
269 struct session *se = cl->session;
270 Z_SearchResponse *r = a->u.searchResponse;
272 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
274 if (*r->searchStatus)
276 cl->hits = *r->resultCount;
277 se->total_hits += cl->hits;
278 if (r->presentStatus && !*r->presentStatus && r->records)
280 yaz_log(YLOG_DEBUG, "Records in search response");
281 ingest_records(cl, r->records);
283 cl->state = Client_Idle;
288 cl->state = Client_Error;
290 Z_Records *recs = r->records;
291 if (recs->which == Z_Records_NSD)
293 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
294 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
295 cl->state = Client_Error;
301 char *normalize_mergekey(char *buf, int skiparticle)
303 char *p = buf, *pout = buf;
308 char articles[] = "the den der die des an a "; // must end in space
310 while (*p && !isalnum(*p))
313 while (*p && *p != ' ' && pout - firstword < 62)
314 *(pout++) = tolower(*(p++));
317 if (!strstr(articles, firstword))
324 while (*p && !isalnum(*p))
327 *(pout++) = tolower(*(p++));
330 while (*p && !isalnum(*p))
337 while (pout > buf && *pout == ' ');
344 // FIXME needs to be generalized. Should flexibly generate X lists per search
345 static void extract_subject(struct session *s, const char *rec)
347 const char *field, *subfield;
349 while ((field = find_field(rec, "650")))
352 if ((subfield = find_subfield(field, 'a')))
358 ef = index(subfield, '\n');
361 if ((e = index(subfield, '\t')) && e < ef)
363 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
367 memcpy(buf, subfield, len);
371 termlist_insert(s->termlist, buf);
378 static void add_facet(struct session *s, const char *type, const char *value)
384 for (i = 0; i < s->num_termlists; i++)
385 if (!strcmp(s->termlists[i].name, type))
387 if (i == s->num_termlists)
389 if (i == SESSION_MAX_TERMLISTS)
391 yaz_log(YLOG_FATAL, "Too many termlists");
394 s->termlists[i].name = nmem_strdup(s->nmem, type);
395 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
396 s->num_termlists = i + 1;
398 termlist_insert(s->termlists[i].termlist, value);
401 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
403 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
404 struct conf_retrievalmap *m;
408 // First normalize to XML
409 if (rprofile->native_syntax == Nativesyn_iso2709)
413 if (rec->which != Z_External_octet)
415 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
418 buf = (char*) rec->u.octet_aligned->buf;
419 len = rec->u.octet_aligned->len;
420 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
422 yaz_log(YLOG_WARN, "Failed to decode MARC");
425 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
426 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
428 yaz_log(YLOG_WARN, "Failed to encode as XML");
431 rdoc = xmlNewDoc((xmlChar *) "1.0");
432 xmlDocSetRootElement(rdoc, res);
436 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
440 if (global_parameters.dump_records)
442 fprintf(stderr, "Input Record (normalized):\n----------------\n");
443 #if LIBXML_VERSION >= 20600
444 xmlDocFormatDump(stderr, rdoc, 1);
446 xmlDocDump(stderr, rdoc);
450 for (m = rprofile->maplist; m; m = m->next)
453 if (m->type != Map_xslt)
455 yaz_log(YLOG_WARN, "Unknown map type");
458 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
460 yaz_log(YLOG_WARN, "XSLT transformation failed");
466 if (global_parameters.dump_records)
468 fprintf(stderr, "Record:\n----------------\n");
469 #if LIBXML_VERSION >= 20600
470 xmlDocFormatDump(stderr, rdoc, 1);
472 xmlDocDump(stderr, rdoc);
478 // Extract what appears to be years from buf, storing highest and
480 static int extract_years(const char *buf, int *first, int *last)
489 while (*buf && !isdigit(*buf))
492 for (e = buf; *e && isdigit(*e); e++)
496 int value = atoi(buf);
497 if (*first < 0 || value < *first)
499 if (*last < 0 || value > *last)
507 static struct record *ingest_record(struct client *cl, Z_External *rec)
509 xmlDoc *xdoc = normalize_record(cl, rec);
512 struct record_cluster *cluster;
513 struct session *se = cl->session;
514 xmlChar *mergekey, *mergekey_norm;
517 struct conf_service *service = global_parameters.server->service;
522 root = xmlDocGetRootElement(xdoc);
523 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
525 yaz_log(YLOG_WARN, "No mergekey found in record");
530 res = nmem_malloc(se->nmem, sizeof(struct record));
533 res->metadata = nmem_malloc(se->nmem,
534 sizeof(struct record_metadata*) * service->num_metadata);
535 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
537 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
539 normalize_mergekey((char *) mergekey_norm, 0);
541 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
543 if (global_parameters.dump_records)
544 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
545 cl->database->url, cl->records);
548 /* no room for record */
552 relevance_newrec(se->relevance, cluster);
554 for (n = root->children; n; n = n->next)
562 if (n->type != XML_ELEMENT_NODE)
564 if (!strcmp((const char *) n->name, "metadata"))
566 struct conf_metadata *md = 0;
567 struct conf_sortkey *sk = 0;
568 struct record_metadata **wheretoput, *newm;
572 type = xmlGetProp(n, (xmlChar *) "type");
573 value = xmlNodeListGetString(xdoc, n->children, 0);
578 // First, find out what field we're looking at
579 for (imeta = 0; imeta < service->num_metadata; imeta++)
580 if (!strcmp((const char *) type, service->metadata[imeta].name))
582 md = &service->metadata[imeta];
583 if (md->sortkey_offset >= 0)
584 sk = &service->sortkeys[md->sortkey_offset];
589 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
593 // Find out where we are putting it
594 if (md->merge == Metadata_merge_no)
595 wheretoput = &res->metadata[imeta];
597 wheretoput = &cluster->metadata[imeta];
600 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
602 if (md->type == Metadata_type_generic)
605 for (p = (char *) value; *p && isspace(*p); p++)
607 for (pe = p + strlen(p) - 1;
608 pe > p && strchr(" ,/.:([", *pe); pe--)
610 newm->data.text = nmem_strdup(se->nmem, p);
613 else if (md->type == Metadata_type_year)
615 if (extract_years((char *) value, &first, &last) < 0)
620 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
623 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
625 yaz_log(YLOG_WARN, "Only range merging supported for years");
628 if (md->merge == Metadata_merge_unique)
630 struct record_metadata *mnode;
631 for (mnode = *wheretoput; mnode; mnode = mnode->next)
632 if (!strcmp((const char *) mnode->data.text, newm->data.text))
636 newm->next = *wheretoput;
640 else if (md->merge == Metadata_merge_longest)
643 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
648 char *s = nmem_strdup(se->nmem, newm->data.text);
649 if (!cluster->sortkeys[md->sortkey_offset])
650 cluster->sortkeys[md->sortkey_offset] =
651 nmem_malloc(se->nmem, sizeof(union data_types));
652 normalize_mergekey(s,
653 (sk->type == Metadata_sortkey_skiparticle));
654 cluster->sortkeys[md->sortkey_offset]->text = s;
658 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
660 newm->next = *wheretoput;
663 else if (md->merge == Metadata_merge_range)
665 assert(md->type == Metadata_type_year);
669 (*wheretoput)->data.number.min = first;
670 (*wheretoput)->data.number.max = last;
672 cluster->sortkeys[md->sortkey_offset] = &newm->data;
676 if (first < (*wheretoput)->data.number.min)
677 (*wheretoput)->data.number.min = first;
678 if (last > (*wheretoput)->data.number.max)
679 (*wheretoput)->data.number.max = last;
684 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
685 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
690 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
693 relevance_countwords(se->relevance, cluster,
694 (char *) value, md->rank);
697 if (md->type == Metadata_type_year)
700 sprintf(year, "%d", last);
701 add_facet(se, (char *) type, year);
704 sprintf(year, "%d", first);
705 add_facet(se, (char *) type, year);
709 add_facet(se, (char *) type, (char *) value);
716 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
725 relevance_donerecord(se->relevance, cluster);
731 static void ingest_records(struct client *cl, Z_Records *r)
734 yaz_timing_t t = yaz_timing_create();
737 struct session *s = cl->session;
738 Z_NamePlusRecordList *rlist;
741 if (r->which != Z_Records_DBOSD)
743 rlist = r->u.databaseOrSurDiagnostics;
744 for (i = 0; i < rlist->num_records; i++)
746 Z_NamePlusRecord *npr = rlist->records[i];
749 if (npr->which != Z_NamePlusRecord_databaseRecord)
751 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
755 rec = ingest_record(cl, npr->u.databaseRecord);
759 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
760 session_alert_watch(s, SESSION_WATCH_RECORDS);
764 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
765 yaz_timing_get_real(t), yaz_timing_get_user(t),
766 yaz_timing_get_sys(t));
767 yaz_timing_destroy(&t);
771 static void do_presentResponse(IOCHAN i, Z_APDU *a)
773 struct connection *co = iochan_getdata(i);
774 struct client *cl = co->client;
775 Z_PresentResponse *r = a->u.presentResponse;
778 Z_Records *recs = r->records;
779 if (recs->which == Z_Records_NSD)
781 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
782 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
783 cl->state = Client_Error;
787 if (!*r->presentStatus && cl->state != Client_Error)
789 yaz_log(YLOG_DEBUG, "Good Present response");
790 ingest_records(cl, r->records);
791 cl->state = Client_Idle;
793 else if (*r->presentStatus)
795 yaz_log(YLOG_WARN, "Bad Present response");
796 cl->state = Client_Error;
800 static void handler(IOCHAN i, int event)
802 struct connection *co = iochan_getdata(i);
803 struct client *cl = co->client;
804 struct session *se = 0;
810 yaz_log(YLOG_WARN, "Destroying orphan connection");
811 connection_destroy(co);
815 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
818 socklen_t errlen = sizeof(errcode);
820 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
821 &errlen) < 0 || errcode != 0)
828 yaz_log(YLOG_DEBUG, "Connect OK");
829 co->state = Conn_Open;
831 cl->state = Client_Connected;
835 else if (event & EVENT_INPUT)
837 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
841 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
842 connection_destroy(co);
847 yaz_log(YLOG_WARN, "EOF reading from Z server");
848 connection_destroy(co);
851 else if (len > 1) // We discard input if we have no connection
853 co->state = Conn_Open;
855 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
859 odr_reset(global_parameters.odr_in);
860 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
861 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
868 case Z_APDU_initResponse:
869 do_initResponse(i, a);
871 case Z_APDU_searchResponse:
872 do_searchResponse(i, a);
874 case Z_APDU_presentResponse:
875 do_presentResponse(i, a);
878 yaz_log(YLOG_WARN, "Unexpected result from server");
882 // We aren't expecting staggered output from target
883 // if (cs_more(t->link))
884 // iochan_setevent(i, EVENT_INPUT);
886 else // we throw away response and go to idle mode
888 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
889 cl->state = Client_Idle;
892 /* if len==1 we do nothing but wait for more input */
895 if (cl->state == Client_Connected) {
899 if (cl->state == Client_Idle)
901 if (cl->requestid != se->requestid && *se->query) {
904 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
905 cl->records < cl->hits) {
911 // Disassociate connection from client
912 static void connection_release(struct connection *co)
914 struct client *cl = co->client;
916 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
923 // Close connection and recycle structure
924 static void connection_destroy(struct connection *co)
926 struct host *h = co->host;
928 iochan_destroy(co->iochan);
930 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
931 if (h->connections == co)
932 h->connections = co->next;
935 struct connection *pco;
936 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
939 pco->next = co->next;
945 if (co->client->state != Client_Idle)
946 co->client->state = Client_Disconnected;
947 co->client->connection = 0;
949 co->next = connection_freelist;
950 connection_freelist = co;
953 // Creates a new connection for client, associated with the host of
955 static struct connection *connection_create(struct client *cl)
957 struct connection *new;
963 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
965 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
969 if (0 == strlen(global_parameters.zproxy_override)){
970 /* no Z39.50 proxy needed - direct connect */
971 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
973 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
975 yaz_log(YLOG_WARN|YLOG_ERRNO,
976 "Lookup of IP address %s failed",
977 cl->database->host->ipport);
982 /* Z39.50 proxy connect */
983 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
984 cl->database->url, global_parameters.zproxy_override);
986 yaz_log(YLOG_LOG, "Connection cs_create_host %s proxy %s",
987 cl->database->url, global_parameters.zproxy_override);
989 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
991 yaz_log(YLOG_WARN|YLOG_ERRNO,
992 "Lookup of IP address %s failed",
993 global_parameters.zproxy_override);
998 res = cs_connect(link, addr);
1001 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
1005 if ((new = connection_freelist))
1006 connection_freelist = new->next;
1009 new = xmalloc(sizeof (struct connection));
1013 new->state = Conn_Connecting;
1014 new->host = cl->database->host;
1015 new->next = new->host->connections;
1016 new->host->connections = new;
1018 cl->connection = new;
1021 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1022 iochan_setdata(new->iochan, new);
1023 new->iochan->next = channel_list;
1024 channel_list = new->iochan;
1028 // Close connection and set state to error
1029 static void client_fatal(struct client *cl)
1031 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
1032 connection_destroy(cl->connection);
1033 cl->state = Client_Error;
1036 // Ensure that client has a connection associated
1037 static int client_prep_connection(struct client *cl)
1039 struct connection *co;
1040 struct session *se = cl->session;
1041 struct host *host = cl->database->host;
1043 co = cl->connection;
1045 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1049 // See if someone else has an idle connection
1050 // We should look at timestamps here to select the longest-idle connection
1051 for (co = host->connections; co; co = co->next)
1052 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1056 connection_release(co);
1057 cl->connection = co;
1061 co = connection_create(cl);
1065 if (co->state == Conn_Connecting)
1067 cl->state = Client_Connecting;
1068 iochan_setflag(co->iochan, EVENT_OUTPUT);
1070 else if (co->state == Conn_Open)
1072 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1073 cl->state = Client_Idle;
1074 iochan_setflag(co->iochan, EVENT_OUTPUT);
1082 #ifdef GAGA // Moved to database.c
1084 // This function will most likely vanish when a proper target profile mechanism is
1086 void load_simpletargets(const char *fn)
1088 FILE *f = fopen(fn, "r");
1093 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1097 while (fgets(line, 255, f))
1102 struct database *database;
1104 if (strncmp(line, "target ", 7))
1106 line[strlen(line) - 1] = '\0';
1108 if ((name = strchr(line, ';')))
1112 if ((db = strchr(url, '/')))
1117 yaz_log(YLOG_LOG, "Target: %s, '%s'", url, db);
1118 for (host = hosts; host; host = host->next)
1119 if (!strcmp((const char *) url, host->hostport))
1123 struct addrinfo *addrinfo, hints;
1126 unsigned char addrbuf[4];
1129 host = xmalloc(sizeof(struct host));
1130 host->hostport = xstrdup(url);
1131 host->connections = 0;
1133 if ((port = strchr(url, ':')))
1139 hints.ai_family = PF_INET;
1140 hints.ai_socktype = SOCK_STREAM;
1141 hints.ai_protocol = IPPROTO_TCP;
1142 hints.ai_addrlen = 0;
1144 hints.ai_canonname = 0;
1146 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1148 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1150 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1151 xfree(host->hostport);
1155 assert(addrinfo->ai_family == PF_INET);
1156 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1157 sprintf(ipport, "%u.%u.%u.%u:%s",
1158 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1159 host->ipport = xstrdup(ipport);
1160 freeaddrinfo(addrinfo);
1164 database = xmalloc(sizeof(struct database));
1165 database->host = host;
1166 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1167 strcpy(database->url, url);
1168 strcat(database->url, "/");
1169 strcat(database->url, db);
1171 database->name = xstrdup(name);
1175 database->databases = xmalloc(2 * sizeof(char *));
1176 database->databases[0] = xstrdup(db);
1177 database->databases[1] = 0;
1178 database->errors = 0;
1179 database->qprofile = 0;
1180 database->rprofile = database_retrieval_profile(database);
1181 database->next = databases;
1182 databases = database;
1190 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1198 pull_terms(nmem, n->u.p[0], termlist, num);
1199 pull_terms(nmem, n->u.p[1], termlist, num);
1202 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1209 // Extract terms from query into null-terminated termlist
1210 static int extract_terms(NMEM nmem, char *query, char **termlist)
1213 struct ccl_rpn_node *n;
1216 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1219 pull_terms(nmem, n, termlist, &num);
1225 static struct client *client_create(void)
1228 if (client_freelist)
1230 r = client_freelist;
1231 client_freelist = client_freelist->next;
1234 r = xmalloc(sizeof(struct client));
1243 r->state = Client_Disconnected;
1248 void client_destroy(struct client *c)
1250 struct session *se = c->session;
1251 if (c == se->clients)
1252 se->clients = c->next;
1256 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1262 connection_release(c->connection);
1263 c->next = client_freelist;
1264 client_freelist = c;
1267 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1269 s->watchlist[what].fun = fun;
1270 s->watchlist[what].data = data;
1273 void session_alert_watch(struct session *s, int what)
1275 if (!s->watchlist[what].fun)
1277 (*s->watchlist[what].fun)(s->watchlist[what].data);
1278 s->watchlist[what].fun = 0;
1279 s->watchlist[what].data = 0;
1282 //callback for grep_databases
1283 static void select_targets_callback(void *context, struct database *db)
1285 struct session *se = (struct session*) context;
1286 struct client *cl = client_create();
1289 cl->next = se->clients;
1293 // This should be extended with parameters to control selection criteria
1294 // Associates a set of clients with a session;
1295 int select_targets(struct session *se, struct database_criterion *crit)
1298 client_destroy(se->clients);
1300 return grep_databases(se, crit, select_targets_callback);
1303 int session_active_clients(struct session *s)
1308 for (c = s->clients; c; c = c->next)
1309 if (c->connection && (c->state == Client_Connecting ||
1310 c->state == Client_Initializing ||
1311 c->state == Client_Searching ||
1312 c->state == Client_Presenting))
1318 // parses crit1=val1,crit2=val2|val3,...
1319 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1321 struct database_criterion *res = 0;
1328 nmem_strsplit(m, ",", buf, &values, &num);
1329 for (i = 0; i < num; i++)
1334 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1335 char *eq = strchr(values[i], '=');
1338 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1342 new->name = values[i];
1343 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1345 for (subi = 0; subi < subnum; subi++)
1347 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1348 newv->value = subvalues[subi];
1349 newv->next = new->values;
1358 char *search(struct session *se, char *query, char *filter)
1360 int live_channels = 0;
1362 struct database_criterion *criteria;
1364 yaz_log(YLOG_DEBUG, "Search");
1366 nmem_reset(se->nmem);
1367 criteria = parse_filter(se->nmem, filter);
1368 strcpy(se->query, query);
1370 // Release any existing clients
1371 select_targets(se, criteria);
1372 for (cl = se->clients; cl; cl = cl->next)
1374 if (client_prep_connection(cl))
1380 int maxrecs = live_channels * global_parameters.toget;
1381 se->num_termlists = 0;
1382 se->reclist = reclist_create(se->nmem, maxrecs);
1383 extract_terms(se->nmem, query, p);
1384 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1385 se->total_records = se->total_hits = se->total_merged = 0;
1386 se->expected_maxrecs = maxrecs;
1394 void destroy_session(struct session *s)
1396 yaz_log(YLOG_LOG, "Destroying session");
1398 client_destroy(s->clients);
1399 nmem_destroy(s->nmem);
1400 wrbuf_destroy(s->wrbuf);
1403 struct session *new_session()
1406 struct session *session = xmalloc(sizeof(*session));
1408 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1410 session->total_hits = 0;
1411 session->total_records = 0;
1412 session->num_termlists = 0;
1413 session->reclist = 0;
1414 session->requestid = -1;
1415 session->clients = 0;
1416 session->expected_maxrecs = 0;
1417 session->query[0] = '\0';
1418 session->nmem = nmem_create();
1419 session->wrbuf = wrbuf_alloc();
1420 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1422 session->watchlist[i].data = 0;
1423 session->watchlist[i].fun = 0;
1429 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1431 static struct hitsbytarget res[1000]; // FIXME MM
1435 for (cl = se->clients; cl; cl = cl->next)
1437 res[*count].id = cl->database->url;
1438 res[*count].name = cl->database->name;
1439 res[*count].hits = cl->hits;
1440 res[*count].records = cl->records;
1441 res[*count].diagnostic = cl->diagnostic;
1442 res[*count].state = client_states[cl->state];
1443 res[*count].connected = cl->connection ? 1 : 0;
1450 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1454 for (i = 0; i < s->num_termlists; i++)
1455 if (!strcmp((const char *) s->termlists[i].name, name))
1456 return termlist_highscore(s->termlists[i].termlist, num);
1460 #ifdef MISSING_HEADERS
1461 void report_nmem_stats(void)
1463 size_t in_use, is_free;
1465 nmem_get_memory_in_use(&in_use);
1466 nmem_get_memory_free(&is_free);
1468 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1469 (long) in_use, (long) is_free);
1473 struct record_cluster *show_single(struct session *s, int id)
1475 struct record_cluster *r;
1477 reclist_rewind(s->reclist);
1478 while ((r = reclist_read_record(s->reclist)))
1484 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1485 int *num, int *total, int *sumhits, NMEM nmem_show)
1487 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1488 * sizeof(struct record_cluster *));
1489 struct reclist_sortparms *spp;
1492 yaz_timing_t t = yaz_timing_create();
1495 for (spp = sp; spp; spp = spp->next)
1496 if (spp->type == Metadata_sortkey_relevance)
1498 relevance_prepare_read(s->relevance, s->reclist);
1501 reclist_sort(s->reclist, sp);
1503 *total = s->reclist->num_records;
1504 *sumhits = s->total_hits;
1506 for (i = 0; i < start; i++)
1507 if (!reclist_read_record(s->reclist))
1514 for (i = 0; i < *num; i++)
1516 struct record_cluster *r = reclist_read_record(s->reclist);
1526 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1527 yaz_timing_get_real(t), yaz_timing_get_user(t),
1528 yaz_timing_get_sys(t));
1529 yaz_timing_destroy(&t);
1534 void statistics(struct session *se, struct statistics *stat)
1539 memset(stat, 0, sizeof(*stat));
1540 for (cl = se->clients; cl; cl = cl->next)
1542 if (!cl->connection)
1543 stat->num_no_connection++;
1546 case Client_Connecting: stat->num_connecting++; break;
1547 case Client_Initializing: stat->num_initializing++; break;
1548 case Client_Searching: stat->num_searching++; break;
1549 case Client_Presenting: stat->num_presenting++; break;
1550 case Client_Idle: stat->num_idle++; break;
1551 case Client_Failed: stat->num_failed++; break;
1552 case Client_Error: stat->num_error++; break;
1557 stat->num_hits = se->total_hits;
1558 stat->num_records = se->total_records;
1560 stat->num_clients = count;
1563 static CCL_bibset load_cclfile(const char *fn)
1565 CCL_bibset res = ccl_qual_mk();
1566 if (ccl_qual_fname(res, fn) < 0)
1568 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1574 static void start_http_listener(void)
1577 struct conf_server *ser = global_parameters.server;
1579 if (*global_parameters.listener_override)
1580 strcpy(hp, global_parameters.listener_override);
1583 strcpy(hp, ser->host ? ser->host : "");
1588 sprintf(hp + strlen(hp), "%d", ser->port);
1594 static void start_proxy(void)
1597 struct conf_server *ser = global_parameters.server;
1599 if (*global_parameters.proxy_override)
1600 strcpy(hp, global_parameters.proxy_override);
1601 else if (ser->proxy_host || ser->proxy_port)
1603 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1604 if (ser->proxy_port)
1608 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1614 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1617 static void start_zproxy(void)
1619 struct conf_server *ser = global_parameters.server;
1621 if (*global_parameters.zproxy_override){
1622 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1623 global_parameters.zproxy_override);
1627 else if (ser->zproxy_host || ser->zproxy_port)
1631 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1632 if (ser->zproxy_port)
1639 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1641 strcpy(global_parameters.zproxy_override, hp);
1642 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1643 global_parameters.zproxy_override);
1652 int main(int argc, char **argv)
1657 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1658 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1660 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1662 while ((ret = options("f:x:h:p:z:C:s:d", argv, argc, &arg)) != -2)
1666 if (!read_config(arg))
1670 strcpy(global_parameters.listener_override, arg);
1673 global_parameters.ccl_filter = load_cclfile(arg);
1676 strcpy(global_parameters.proxy_override, arg);
1679 strcpy(global_parameters.zproxy_override, arg);
1682 load_simpletargets(arg);
1685 global_parameters.dump_records = 1;
1688 fprintf(stderr, "Usage: pazpar2\n"
1690 " -h [host:]port (REST protocol listener)\n"
1692 " -s simpletargetfile\n"
1693 " -p hostname[:portno] (HTTP proxy)\n"
1694 " -z hostname[:portno] (Z39.50 proxy)\n"
1695 " -d (show internal records)\n");
1702 yaz_log(YLOG_FATAL, "Load config with -f");
1705 global_parameters.server = config->servers;
1707 start_http_listener();
1711 if (!global_parameters.ccl_filter)
1712 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1713 global_parameters.yaz_marc = yaz_marc_create();
1714 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1715 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1716 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1718 event_loop(&channel_list);
1726 * indent-tabs-mode: nil
1728 * vim: shiftwidth=4 tabstop=8 expandtab