1 /* $Id: pazpar2.c,v 1.60 2007-04-03 03:55:12 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);
53 char *session_setting_oneval(struct session *s, struct database *db, const char *name);
55 IOCHAN channel_list = 0; // Master list of connections we're handling events to
57 static struct connection *connection_freelist = 0;
58 static struct client *client_freelist = 0;
60 static char *client_states[] = {
64 "Client_Initializing",
69 "Client_Disconnected",
73 // Note: Some things in this structure will eventually move to configuration
74 struct parameters global_parameters =
84 "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 pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
172 pull_terms(nmem, n->u.p[0], termlist, num);
173 pull_terms(nmem, n->u.p[1], termlist, num);
176 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
183 // Extract terms from query into null-terminated termlist
184 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
188 pull_terms(nmem, query, termlist, &num);
192 static void send_search(IOCHAN i)
194 struct connection *co = iochan_getdata(i);
195 struct client *cl = co->client;
196 struct session *se = cl->session;
197 struct database *db = cl->database;
198 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
199 int ndb, cerror, cpos;
202 struct ccl_rpn_node *cn;
203 int ssub = 0, lslb = 100000, mspn = 10;
207 yaz_log(YLOG_DEBUG, "Sending search");
209 cn = ccl_find_str(db->ccl_map, se->query, &cerror, &cpos);
215 // Initialize relevance structure with query terms
217 extract_terms(se->nmem, cn, p);
218 se->relevance = relevance_create(se->nmem, (const char **) p,
219 se->expected_maxrecs);
222 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
224 zquery->which = Z_Query_type_1;
225 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
228 for (ndb = 0; db->databases[ndb]; ndb++)
230 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
231 for (ndb = 0; db->databases[ndb]; ndb++)
232 databaselist[ndb] = db->databases[ndb];
234 if (!(piggyback = session_setting_oneval(se, db, "pz:piggyback")) || *piggyback == '1')
236 if ((recsyn = session_setting_oneval(se, db, "pz:syntax")))
237 a->u.searchRequest->preferredRecordSyntax =
238 yaz_str_to_z3950oid(global_parameters.odr_out,
239 CLASS_RECSYN, recsyn);
240 a->u.searchRequest->smallSetUpperBound = &ssub;
241 a->u.searchRequest->largeSetLowerBound = &lslb;
242 a->u.searchRequest->mediumSetPresentNumber = &mspn;
244 a->u.searchRequest->resultSetName = "Default";
245 a->u.searchRequest->databaseNames = databaselist;
246 a->u.searchRequest->num_databaseNames = ndb;
248 if (send_apdu(cl, a) >= 0)
250 iochan_setflags(i, EVENT_INPUT);
251 cl->state = Client_Searching;
252 cl->requestid = se->requestid;
255 cl->state = Client_Error;
257 odr_reset(global_parameters.odr_out);
260 static void send_present(IOCHAN i)
262 struct connection *co = iochan_getdata(i);
263 struct client *cl = co->client;
264 struct session *se = cl->session;
265 struct database *db = cl->database;
266 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
268 int start = cl->records + 1;
271 toget = global_parameters.chunk;
272 if (toget > global_parameters.toget - cl->records)
273 toget = global_parameters.toget - cl->records;
274 if (toget > cl->hits - cl->records)
275 toget = cl->hits - cl->records;
277 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
279 a->u.presentRequest->resultSetStartPoint = &start;
280 a->u.presentRequest->numberOfRecordsRequested = &toget;
282 a->u.presentRequest->resultSetId = "Default";
284 if ((recsyn = session_setting_oneval(se, db, "pz:syntax")))
285 a->u.presentRequest->preferredRecordSyntax =
286 yaz_str_to_z3950oid(global_parameters.odr_out,
287 CLASS_RECSYN, recsyn);
289 if (send_apdu(cl, a) >= 0)
291 iochan_setflags(i, EVENT_INPUT);
292 cl->state = Client_Presenting;
295 cl->state = Client_Error;
296 odr_reset(global_parameters.odr_out);
299 static void do_initResponse(IOCHAN i, Z_APDU *a)
301 struct connection *co = iochan_getdata(i);
302 struct client *cl = co->client;
303 Z_InitResponse *r = a->u.initResponse;
305 yaz_log(YLOG_DEBUG, "Received init response");
309 cl->state = Client_Idle;
312 cl->state = Client_Failed; // FIXME need to do something to the connection
315 static void do_searchResponse(IOCHAN i, Z_APDU *a)
317 struct connection *co = iochan_getdata(i);
318 struct client *cl = co->client;
319 struct session *se = cl->session;
320 Z_SearchResponse *r = a->u.searchResponse;
322 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
324 if (*r->searchStatus)
326 cl->hits = *r->resultCount;
327 se->total_hits += cl->hits;
328 if (r->presentStatus && !*r->presentStatus && r->records)
330 yaz_log(YLOG_DEBUG, "Records in search response");
331 ingest_records(cl, r->records);
333 cl->state = Client_Idle;
338 cl->state = Client_Error;
340 Z_Records *recs = r->records;
341 if (recs->which == Z_Records_NSD)
343 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
344 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
345 cl->state = Client_Error;
351 char *normalize_mergekey(char *buf, int skiparticle)
353 char *p = buf, *pout = buf;
358 char articles[] = "the den der die des an a "; // must end in space
360 while (*p && !isalnum(*p))
363 while (*p && *p != ' ' && pout - firstword < 62)
364 *(pout++) = tolower(*(p++));
367 if (!strstr(articles, firstword))
374 while (*p && !isalnum(*p))
377 *(pout++) = tolower(*(p++));
380 while (*p && !isalnum(*p))
387 while (pout > buf && *pout == ' ');
394 // FIXME needs to be generalized. Should flexibly generate X lists per search
395 static void extract_subject(struct session *s, const char *rec)
397 const char *field, *subfield;
399 while ((field = find_field(rec, "650")))
402 if ((subfield = find_subfield(field, 'a')))
408 ef = index(subfield, '\n');
411 if ((e = index(subfield, '\t')) && e < ef)
413 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
417 memcpy(buf, subfield, len);
421 termlist_insert(s->termlist, buf);
428 static void add_facet(struct session *s, const char *type, const char *value)
434 for (i = 0; i < s->num_termlists; i++)
435 if (!strcmp(s->termlists[i].name, type))
437 if (i == s->num_termlists)
439 if (i == SESSION_MAX_TERMLISTS)
441 yaz_log(YLOG_FATAL, "Too many termlists");
444 s->termlists[i].name = nmem_strdup(s->nmem, type);
445 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
446 s->num_termlists = i + 1;
448 termlist_insert(s->termlists[i].termlist, value);
451 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
453 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
454 struct conf_retrievalmap *m;
458 // First normalize to XML
459 if (rprofile->native_syntax == Nativesyn_iso2709)
463 if (rec->which != Z_External_octet)
465 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
468 buf = (char*) rec->u.octet_aligned->buf;
469 len = rec->u.octet_aligned->len;
470 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
472 yaz_log(YLOG_WARN, "Failed to decode MARC");
475 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
476 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
478 yaz_log(YLOG_WARN, "Failed to encode as XML");
481 rdoc = xmlNewDoc((xmlChar *) "1.0");
482 xmlDocSetRootElement(rdoc, res);
486 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
490 if (global_parameters.dump_records)
492 fprintf(stderr, "Input Record (normalized):\n----------------\n");
493 #if LIBXML_VERSION >= 20600
494 xmlDocFormatDump(stderr, rdoc, 1);
496 xmlDocDump(stderr, rdoc);
500 for (m = rprofile->maplist; m; m = m->next)
503 if (m->type != Map_xslt)
505 yaz_log(YLOG_WARN, "Unknown map type");
508 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
510 yaz_log(YLOG_WARN, "XSLT transformation failed");
516 if (global_parameters.dump_records)
518 fprintf(stderr, "Record:\n----------------\n");
519 #if LIBXML_VERSION >= 20600
520 xmlDocFormatDump(stderr, rdoc, 1);
522 xmlDocDump(stderr, rdoc);
528 // Extract what appears to be years from buf, storing highest and
530 static int extract_years(const char *buf, int *first, int *last)
539 while (*buf && !isdigit(*buf))
542 for (e = buf; *e && isdigit(*e); e++)
546 int value = atoi(buf);
547 if (*first < 0 || value < *first)
549 if (*last < 0 || value > *last)
557 static struct record *ingest_record(struct client *cl, Z_External *rec)
559 xmlDoc *xdoc = normalize_record(cl, rec);
562 struct record_cluster *cluster;
563 struct session *se = cl->session;
564 xmlChar *mergekey, *mergekey_norm;
567 struct conf_service *service = global_parameters.server->service;
572 root = xmlDocGetRootElement(xdoc);
573 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
575 yaz_log(YLOG_WARN, "No mergekey found in record");
580 res = nmem_malloc(se->nmem, sizeof(struct record));
583 res->metadata = nmem_malloc(se->nmem,
584 sizeof(struct record_metadata*) * service->num_metadata);
585 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
587 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
589 normalize_mergekey((char *) mergekey_norm, 0);
591 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
593 if (global_parameters.dump_records)
594 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
595 cl->database->url, cl->records);
598 /* no room for record */
602 relevance_newrec(se->relevance, cluster);
604 for (n = root->children; n; n = n->next)
612 if (n->type != XML_ELEMENT_NODE)
614 if (!strcmp((const char *) n->name, "metadata"))
616 struct conf_metadata *md = 0;
617 struct conf_sortkey *sk = 0;
618 struct record_metadata **wheretoput, *newm;
622 type = xmlGetProp(n, (xmlChar *) "type");
623 value = xmlNodeListGetString(xdoc, n->children, 0);
628 // First, find out what field we're looking at
629 for (imeta = 0; imeta < service->num_metadata; imeta++)
630 if (!strcmp((const char *) type, service->metadata[imeta].name))
632 md = &service->metadata[imeta];
633 if (md->sortkey_offset >= 0)
634 sk = &service->sortkeys[md->sortkey_offset];
639 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
643 // Find out where we are putting it
644 if (md->merge == Metadata_merge_no)
645 wheretoput = &res->metadata[imeta];
647 wheretoput = &cluster->metadata[imeta];
650 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
652 if (md->type == Metadata_type_generic)
655 for (p = (char *) value; *p && isspace(*p); p++)
657 for (pe = p + strlen(p) - 1;
658 pe > p && strchr(" ,/.:([", *pe); pe--)
660 newm->data.text = nmem_strdup(se->nmem, p);
663 else if (md->type == Metadata_type_year)
665 if (extract_years((char *) value, &first, &last) < 0)
670 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
673 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
675 yaz_log(YLOG_WARN, "Only range merging supported for years");
678 if (md->merge == Metadata_merge_unique)
680 struct record_metadata *mnode;
681 for (mnode = *wheretoput; mnode; mnode = mnode->next)
682 if (!strcmp((const char *) mnode->data.text, newm->data.text))
686 newm->next = *wheretoput;
690 else if (md->merge == Metadata_merge_longest)
693 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
698 char *s = nmem_strdup(se->nmem, newm->data.text);
699 if (!cluster->sortkeys[md->sortkey_offset])
700 cluster->sortkeys[md->sortkey_offset] =
701 nmem_malloc(se->nmem, sizeof(union data_types));
702 normalize_mergekey(s,
703 (sk->type == Metadata_sortkey_skiparticle));
704 cluster->sortkeys[md->sortkey_offset]->text = s;
708 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
710 newm->next = *wheretoput;
713 else if (md->merge == Metadata_merge_range)
715 assert(md->type == Metadata_type_year);
719 (*wheretoput)->data.number.min = first;
720 (*wheretoput)->data.number.max = last;
722 cluster->sortkeys[md->sortkey_offset] = &newm->data;
726 if (first < (*wheretoput)->data.number.min)
727 (*wheretoput)->data.number.min = first;
728 if (last > (*wheretoput)->data.number.max)
729 (*wheretoput)->data.number.max = last;
734 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
735 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
740 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
743 relevance_countwords(se->relevance, cluster,
744 (char *) value, md->rank);
747 if (md->type == Metadata_type_year)
750 sprintf(year, "%d", last);
751 add_facet(se, (char *) type, year);
754 sprintf(year, "%d", first);
755 add_facet(se, (char *) type, year);
759 add_facet(se, (char *) type, (char *) value);
766 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
775 relevance_donerecord(se->relevance, cluster);
781 // Retrieve first defined value for 'name' for given database.
782 // Will be extended to take into account user associated with session
783 char *session_setting_oneval(struct session *s, struct database *db, const char *name)
785 int offset = settings_offset(name);
789 if (!db->settings[offset])
791 return db->settings[offset]->value;
794 static void ingest_records(struct client *cl, Z_Records *r)
797 yaz_timing_t t = yaz_timing_create();
800 struct session *s = cl->session;
801 Z_NamePlusRecordList *rlist;
804 if (r->which != Z_Records_DBOSD)
806 rlist = r->u.databaseOrSurDiagnostics;
807 for (i = 0; i < rlist->num_records; i++)
809 Z_NamePlusRecord *npr = rlist->records[i];
812 if (npr->which != Z_NamePlusRecord_databaseRecord)
814 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
818 rec = ingest_record(cl, npr->u.databaseRecord);
822 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
823 session_alert_watch(s, SESSION_WATCH_RECORDS);
827 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
828 yaz_timing_get_real(t), yaz_timing_get_user(t),
829 yaz_timing_get_sys(t));
830 yaz_timing_destroy(&t);
834 static void do_presentResponse(IOCHAN i, Z_APDU *a)
836 struct connection *co = iochan_getdata(i);
837 struct client *cl = co->client;
838 Z_PresentResponse *r = a->u.presentResponse;
841 Z_Records *recs = r->records;
842 if (recs->which == Z_Records_NSD)
844 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
845 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
846 cl->state = Client_Error;
850 if (!*r->presentStatus && cl->state != Client_Error)
852 yaz_log(YLOG_DEBUG, "Good Present response");
853 ingest_records(cl, r->records);
854 cl->state = Client_Idle;
856 else if (*r->presentStatus)
858 yaz_log(YLOG_WARN, "Bad Present response");
859 cl->state = Client_Error;
863 static void handler(IOCHAN i, int event)
865 struct connection *co = iochan_getdata(i);
866 struct client *cl = co->client;
867 struct session *se = 0;
873 yaz_log(YLOG_WARN, "Destroying orphan connection");
874 connection_destroy(co);
878 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
881 socklen_t errlen = sizeof(errcode);
883 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
884 &errlen) < 0 || errcode != 0)
891 yaz_log(YLOG_DEBUG, "Connect OK");
892 co->state = Conn_Open;
894 cl->state = Client_Connected;
898 else if (event & EVENT_INPUT)
900 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
904 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
905 connection_destroy(co);
910 yaz_log(YLOG_WARN, "EOF reading from Z server");
911 connection_destroy(co);
914 else if (len > 1) // We discard input if we have no connection
916 co->state = Conn_Open;
918 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
922 odr_reset(global_parameters.odr_in);
923 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
924 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
931 case Z_APDU_initResponse:
932 do_initResponse(i, a);
934 case Z_APDU_searchResponse:
935 do_searchResponse(i, a);
937 case Z_APDU_presentResponse:
938 do_presentResponse(i, a);
941 yaz_log(YLOG_WARN, "Unexpected result from server");
945 // We aren't expecting staggered output from target
946 // if (cs_more(t->link))
947 // iochan_setevent(i, EVENT_INPUT);
949 else // we throw away response and go to idle mode
951 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
952 cl->state = Client_Idle;
955 /* if len==1 we do nothing but wait for more input */
958 if (cl->state == Client_Connected) {
962 if (cl->state == Client_Idle)
964 if (cl->requestid != se->requestid && *se->query) {
967 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
968 cl->records < cl->hits) {
974 // Disassociate connection from client
975 static void connection_release(struct connection *co)
977 struct client *cl = co->client;
979 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
986 // Close connection and recycle structure
987 static void connection_destroy(struct connection *co)
989 struct host *h = co->host;
991 iochan_destroy(co->iochan);
993 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
994 if (h->connections == co)
995 h->connections = co->next;
998 struct connection *pco;
999 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1002 pco->next = co->next;
1008 if (co->client->state != Client_Idle)
1009 co->client->state = Client_Disconnected;
1010 co->client->connection = 0;
1012 co->next = connection_freelist;
1013 connection_freelist = co;
1016 // Creates a new connection for client, associated with the host of
1017 // client's database
1018 static struct connection *connection_create(struct client *cl)
1020 struct connection *new;
1026 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1028 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1032 if (0 == strlen(global_parameters.zproxy_override)){
1033 /* no Z39.50 proxy needed - direct connect */
1034 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
1036 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
1038 yaz_log(YLOG_WARN|YLOG_ERRNO,
1039 "Lookup of IP address %s failed",
1040 cl->database->host->ipport);
1045 /* Z39.50 proxy connect */
1046 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1047 cl->database->url, global_parameters.zproxy_override);
1049 yaz_log(YLOG_LOG, "Connection cs_create_host %s proxy %s",
1050 cl->database->url, global_parameters.zproxy_override);
1052 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1054 yaz_log(YLOG_WARN|YLOG_ERRNO,
1055 "Lookup of IP address %s failed",
1056 global_parameters.zproxy_override);
1061 res = cs_connect(link, addr);
1064 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
1068 if ((new = connection_freelist))
1069 connection_freelist = new->next;
1072 new = xmalloc(sizeof (struct connection));
1076 new->state = Conn_Connecting;
1077 new->host = cl->database->host;
1078 new->next = new->host->connections;
1079 new->host->connections = new;
1081 cl->connection = new;
1084 new->iochan = iochan_create(cs_fileno(link), 0, handler, 0);
1085 iochan_setdata(new->iochan, new);
1086 new->iochan->next = channel_list;
1087 channel_list = new->iochan;
1091 // Close connection and set state to error
1092 static void client_fatal(struct client *cl)
1094 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
1095 connection_destroy(cl->connection);
1096 cl->state = Client_Error;
1099 // Ensure that client has a connection associated
1100 static int client_prep_connection(struct client *cl)
1102 struct connection *co;
1103 struct session *se = cl->session;
1104 struct host *host = cl->database->host;
1106 co = cl->connection;
1108 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1112 // See if someone else has an idle connection
1113 // We should look at timestamps here to select the longest-idle connection
1114 for (co = host->connections; co; co = co->next)
1115 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1119 connection_release(co);
1120 cl->connection = co;
1124 co = connection_create(cl);
1128 if (co->state == Conn_Connecting)
1130 cl->state = Client_Connecting;
1131 iochan_setflag(co->iochan, EVENT_OUTPUT);
1133 else if (co->state == Conn_Open)
1135 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1136 cl->state = Client_Idle;
1137 iochan_setflag(co->iochan, EVENT_OUTPUT);
1145 #ifdef GAGA // Moved to database.c
1147 // This function will most likely vanish when a proper target profile mechanism is
1149 void load_simpletargets(const char *fn)
1151 FILE *f = fopen(fn, "r");
1156 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1160 while (fgets(line, 255, f))
1165 struct database *database;
1167 if (strncmp(line, "target ", 7))
1169 line[strlen(line) - 1] = '\0';
1171 if ((name = strchr(line, ';')))
1175 if ((db = strchr(url, '/')))
1180 yaz_log(YLOG_LOG, "Target: %s, '%s'", url, db);
1181 for (host = hosts; host; host = host->next)
1182 if (!strcmp((const char *) url, host->hostport))
1186 struct addrinfo *addrinfo, hints;
1189 unsigned char addrbuf[4];
1192 host = xmalloc(sizeof(struct host));
1193 host->hostport = xstrdup(url);
1194 host->connections = 0;
1196 if ((port = strchr(url, ':')))
1202 hints.ai_family = PF_INET;
1203 hints.ai_socktype = SOCK_STREAM;
1204 hints.ai_protocol = IPPROTO_TCP;
1205 hints.ai_addrlen = 0;
1207 hints.ai_canonname = 0;
1209 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1211 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1213 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1214 xfree(host->hostport);
1218 assert(addrinfo->ai_family == PF_INET);
1219 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1220 sprintf(ipport, "%u.%u.%u.%u:%s",
1221 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1222 host->ipport = xstrdup(ipport);
1223 freeaddrinfo(addrinfo);
1227 database = xmalloc(sizeof(struct database));
1228 database->host = host;
1229 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1230 strcpy(database->url, url);
1231 strcat(database->url, "/");
1232 strcat(database->url, db);
1234 database->name = xstrdup(name);
1238 database->databases = xmalloc(2 * sizeof(char *));
1239 database->databases[0] = xstrdup(db);
1240 database->databases[1] = 0;
1241 database->errors = 0;
1242 database->qprofile = 0;
1243 database->rprofile = database_retrieval_profile(database);
1244 database->next = databases;
1245 databases = database;
1253 static struct client *client_create(void)
1256 if (client_freelist)
1258 r = client_freelist;
1259 client_freelist = client_freelist->next;
1262 r = xmalloc(sizeof(struct client));
1271 r->state = Client_Disconnected;
1276 void client_destroy(struct client *c)
1278 struct session *se = c->session;
1279 if (c == se->clients)
1280 se->clients = c->next;
1284 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1290 connection_release(c->connection);
1291 c->next = client_freelist;
1292 client_freelist = c;
1295 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1297 s->watchlist[what].fun = fun;
1298 s->watchlist[what].data = data;
1301 void session_alert_watch(struct session *s, int what)
1303 if (!s->watchlist[what].fun)
1305 (*s->watchlist[what].fun)(s->watchlist[what].data);
1306 s->watchlist[what].fun = 0;
1307 s->watchlist[what].data = 0;
1310 //callback for grep_databases
1311 static void select_targets_callback(void *context, struct database *db)
1313 struct session *se = (struct session*) context;
1314 struct client *cl = client_create();
1317 cl->next = se->clients;
1321 // This should be extended with parameters to control selection criteria
1322 // Associates a set of clients with a session;
1323 int select_targets(struct session *se, struct database_criterion *crit)
1326 client_destroy(se->clients);
1328 return grep_databases(se, crit, select_targets_callback);
1331 int session_active_clients(struct session *s)
1336 for (c = s->clients; c; c = c->next)
1337 if (c->connection && (c->state == Client_Connecting ||
1338 c->state == Client_Initializing ||
1339 c->state == Client_Searching ||
1340 c->state == Client_Presenting))
1346 // parses crit1=val1,crit2=val2|val3,...
1347 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1349 struct database_criterion *res = 0;
1356 nmem_strsplit(m, ",", buf, &values, &num);
1357 for (i = 0; i < num; i++)
1362 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1363 char *eq = strchr(values[i], '=');
1366 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1370 new->name = values[i];
1371 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1373 for (subi = 0; subi < subnum; subi++)
1375 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1376 newv->value = subvalues[subi];
1377 newv->next = new->values;
1386 char *search(struct session *se, char *query, char *filter)
1388 int live_channels = 0;
1390 struct database_criterion *criteria;
1392 yaz_log(YLOG_DEBUG, "Search");
1394 nmem_reset(se->nmem);
1395 criteria = parse_filter(se->nmem, filter);
1396 strcpy(se->query, query);
1398 // Release any existing clients
1399 select_targets(se, criteria);
1400 for (cl = se->clients; cl; cl = cl->next)
1402 if (client_prep_connection(cl))
1407 int maxrecs = live_channels * global_parameters.toget;
1408 se->num_termlists = 0;
1409 se->reclist = reclist_create(se->nmem, maxrecs);
1410 // This will be initialized in send_search()
1412 se->total_records = se->total_hits = se->total_merged = 0;
1413 se->expected_maxrecs = maxrecs;
1421 void destroy_session(struct session *s)
1423 yaz_log(YLOG_LOG, "Destroying session");
1425 client_destroy(s->clients);
1426 nmem_destroy(s->nmem);
1427 wrbuf_destroy(s->wrbuf);
1430 struct session *new_session()
1433 struct session *session = xmalloc(sizeof(*session));
1435 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1437 session->total_hits = 0;
1438 session->total_records = 0;
1439 session->num_termlists = 0;
1440 session->reclist = 0;
1441 session->requestid = -1;
1442 session->clients = 0;
1443 session->expected_maxrecs = 0;
1444 session->query[0] = '\0';
1445 session->nmem = nmem_create();
1446 session->wrbuf = wrbuf_alloc();
1447 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1449 session->watchlist[i].data = 0;
1450 session->watchlist[i].fun = 0;
1456 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1458 static struct hitsbytarget res[1000]; // FIXME MM
1462 for (cl = se->clients; cl; cl = cl->next)
1464 res[*count].id = cl->database->url;
1465 res[*count].name = cl->database->name;
1466 res[*count].hits = cl->hits;
1467 res[*count].records = cl->records;
1468 res[*count].diagnostic = cl->diagnostic;
1469 res[*count].state = client_states[cl->state];
1470 res[*count].connected = cl->connection ? 1 : 0;
1477 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1481 for (i = 0; i < s->num_termlists; i++)
1482 if (!strcmp((const char *) s->termlists[i].name, name))
1483 return termlist_highscore(s->termlists[i].termlist, num);
1487 #ifdef MISSING_HEADERS
1488 void report_nmem_stats(void)
1490 size_t in_use, is_free;
1492 nmem_get_memory_in_use(&in_use);
1493 nmem_get_memory_free(&is_free);
1495 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1496 (long) in_use, (long) is_free);
1500 struct record_cluster *show_single(struct session *s, int id)
1502 struct record_cluster *r;
1504 reclist_rewind(s->reclist);
1505 while ((r = reclist_read_record(s->reclist)))
1511 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1512 int *num, int *total, int *sumhits, NMEM nmem_show)
1514 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1515 * sizeof(struct record_cluster *));
1516 struct reclist_sortparms *spp;
1519 yaz_timing_t t = yaz_timing_create();
1522 for (spp = sp; spp; spp = spp->next)
1523 if (spp->type == Metadata_sortkey_relevance)
1525 relevance_prepare_read(s->relevance, s->reclist);
1528 reclist_sort(s->reclist, sp);
1530 *total = s->reclist->num_records;
1531 *sumhits = s->total_hits;
1533 for (i = 0; i < start; i++)
1534 if (!reclist_read_record(s->reclist))
1541 for (i = 0; i < *num; i++)
1543 struct record_cluster *r = reclist_read_record(s->reclist);
1553 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1554 yaz_timing_get_real(t), yaz_timing_get_user(t),
1555 yaz_timing_get_sys(t));
1556 yaz_timing_destroy(&t);
1561 void statistics(struct session *se, struct statistics *stat)
1566 memset(stat, 0, sizeof(*stat));
1567 for (cl = se->clients; cl; cl = cl->next)
1569 if (!cl->connection)
1570 stat->num_no_connection++;
1573 case Client_Connecting: stat->num_connecting++; break;
1574 case Client_Initializing: stat->num_initializing++; break;
1575 case Client_Searching: stat->num_searching++; break;
1576 case Client_Presenting: stat->num_presenting++; break;
1577 case Client_Idle: stat->num_idle++; break;
1578 case Client_Failed: stat->num_failed++; break;
1579 case Client_Error: stat->num_error++; break;
1584 stat->num_hits = se->total_hits;
1585 stat->num_records = se->total_records;
1587 stat->num_clients = count;
1590 static void start_http_listener(void)
1593 struct conf_server *ser = global_parameters.server;
1595 if (*global_parameters.listener_override)
1596 strcpy(hp, global_parameters.listener_override);
1599 strcpy(hp, ser->host ? ser->host : "");
1604 sprintf(hp + strlen(hp), "%d", ser->port);
1610 // Initialize CCL map for a target
1611 // Note: This approach ignores user-specific CCL maps, for which I
1612 // don't presently see any application.
1613 static void prepare_cclmap(void *context, struct database *db)
1619 db->ccl_map = ccl_qual_mk();
1620 for (s = db->settings[PZ_CCLMAP]; s; s = s->next)
1623 char *p = strchr(s->name + 3, ':');
1626 yaz_log(YLOG_FATAL, "Malformed cclmap name: %s", s->name);
1630 ccl_qual_fitem(db->ccl_map, s->value, p);
1634 // Read settings for each database, and prepare a CCL map for that database
1635 static void prepare_cclmaps(void)
1637 grep_databases(0, 0, prepare_cclmap);
1640 static void start_proxy(void)
1643 struct conf_server *ser = global_parameters.server;
1645 if (*global_parameters.proxy_override)
1646 strcpy(hp, global_parameters.proxy_override);
1647 else if (ser->proxy_host || ser->proxy_port)
1649 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1650 if (ser->proxy_port)
1654 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1660 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1663 static void start_zproxy(void)
1665 struct conf_server *ser = global_parameters.server;
1667 if (*global_parameters.zproxy_override){
1668 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1669 global_parameters.zproxy_override);
1673 else if (ser->zproxy_host || ser->zproxy_port)
1677 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1678 if (ser->zproxy_port)
1685 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1687 strcpy(global_parameters.zproxy_override, hp);
1688 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1689 global_parameters.zproxy_override);
1698 int main(int argc, char **argv)
1703 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1704 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1706 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1708 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1712 if (!read_config(arg))
1716 strcpy(global_parameters.listener_override, arg);
1719 strcpy(global_parameters.proxy_override, arg);
1722 strcpy(global_parameters.zproxy_override, arg);
1725 strcpy(global_parameters.settings_path_override, arg);
1728 load_simpletargets(arg);
1731 global_parameters.dump_records = 1;
1734 fprintf(stderr, "Usage: pazpar2\n"
1736 " -h [host:]port (REST protocol listener)\n"
1738 " -s simpletargetfile\n"
1739 " -p hostname[:portno] (HTTP proxy)\n"
1740 " -z hostname[:portno] (Z39.50 proxy)\n"
1741 " -d (show internal records)\n");
1748 yaz_log(YLOG_FATAL, "Load config with -f");
1751 global_parameters.server = config->servers;
1753 start_http_listener();
1757 if (*global_parameters.settings_path_override)
1758 settings_read(global_parameters.settings_path_override);
1759 else if (global_parameters.server->settings)
1760 settings_read(global_parameters.server->settings);
1762 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may ensue!");
1764 global_parameters.yaz_marc = yaz_marc_create();
1765 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1766 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1767 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1769 event_loop(&channel_list);
1777 * indent-tabs-mode: nil
1779 * vim: shiftwidth=4 tabstop=8 expandtab