1 /* $Id: pazpar2.c,v 1.63 2007-04-04 22:43:10 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"
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, "Init response %s", cl->database->url);
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, "Search response %s (status=%d)",
323 cl->database->url, *r->searchStatus);
325 if (*r->searchStatus)
327 cl->hits = *r->resultCount;
328 se->total_hits += cl->hits;
329 if (r->presentStatus && !*r->presentStatus && r->records)
331 yaz_log(YLOG_DEBUG, "Records in search response %s",
333 ingest_records(cl, r->records);
335 cl->state = Client_Idle;
340 cl->state = Client_Error;
342 Z_Records *recs = r->records;
343 if (recs->which == Z_Records_NSD)
346 "Search response: Non-surrogate diagnostic %s",
348 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
349 cl->state = Client_Error;
355 static void do_closeResponse(IOCHAN i, Z_APDU *a)
357 struct connection *co = iochan_getdata(i);
358 struct client *cl = co->client;
359 /* Z_Close *r = a->u.close; */
361 yaz_log(YLOG_WARN, "Close response %s", cl->database->url);
363 cl->state = Client_Failed;
364 connection_destroy(co);
368 char *normalize_mergekey(char *buf, int skiparticle)
370 char *p = buf, *pout = buf;
375 char articles[] = "the den der die des an a "; // must end in space
377 while (*p && !isalnum(*p))
380 while (*p && *p != ' ' && pout - firstword < 62)
381 *(pout++) = tolower(*(p++));
384 if (!strstr(articles, firstword))
391 while (*p && !isalnum(*p))
394 *(pout++) = tolower(*(p++));
397 while (*p && !isalnum(*p))
404 while (pout > buf && *pout == ' ');
409 static void add_facet(struct session *s, const char *type, const char *value)
415 for (i = 0; i < s->num_termlists; i++)
416 if (!strcmp(s->termlists[i].name, type))
418 if (i == s->num_termlists)
420 if (i == SESSION_MAX_TERMLISTS)
422 yaz_log(YLOG_FATAL, "Too many termlists");
425 s->termlists[i].name = nmem_strdup(s->nmem, type);
426 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
427 s->num_termlists = i + 1;
429 termlist_insert(s->termlists[i].termlist, value);
432 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
434 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
435 struct conf_retrievalmap *m;
439 // First normalize to XML
440 if (rprofile->native_syntax == Nativesyn_iso2709)
444 if (rec->which != Z_External_octet)
446 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
450 buf = (char*) rec->u.octet_aligned->buf;
451 len = rec->u.octet_aligned->len;
452 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
454 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
458 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
459 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
461 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
465 rdoc = xmlNewDoc((xmlChar *) "1.0");
466 xmlDocSetRootElement(rdoc, res);
470 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
474 if (global_parameters.dump_records)
476 fprintf(stderr, "Input Record (normalized):\n----------------\n");
477 #if LIBXML_VERSION >= 20600
478 xmlDocFormatDump(stderr, rdoc, 1);
480 xmlDocDump(stderr, rdoc);
484 for (m = rprofile->maplist; m; m = m->next)
487 if (m->type != Map_xslt)
489 yaz_log(YLOG_WARN, "Unknown map type");
492 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
494 yaz_log(YLOG_WARN, "XSLT transformation failed");
500 if (global_parameters.dump_records)
502 fprintf(stderr, "Record:\n----------------\n");
503 #if LIBXML_VERSION >= 20600
504 xmlDocFormatDump(stderr, rdoc, 1);
506 xmlDocDump(stderr, rdoc);
512 // Extract what appears to be years from buf, storing highest and
514 static int extract_years(const char *buf, int *first, int *last)
523 while (*buf && !isdigit(*buf))
526 for (e = buf; *e && isdigit(*e); e++)
530 int value = atoi(buf);
531 if (*first < 0 || value < *first)
533 if (*last < 0 || value > *last)
541 static struct record *ingest_record(struct client *cl, Z_External *rec)
543 xmlDoc *xdoc = normalize_record(cl, rec);
546 struct record_cluster *cluster;
547 struct session *se = cl->session;
548 xmlChar *mergekey, *mergekey_norm;
551 struct conf_service *service = global_parameters.server->service;
556 root = xmlDocGetRootElement(xdoc);
557 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
559 yaz_log(YLOG_WARN, "No mergekey found in record");
564 res = nmem_malloc(se->nmem, sizeof(struct record));
567 res->metadata = nmem_malloc(se->nmem,
568 sizeof(struct record_metadata*) * service->num_metadata);
569 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
571 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
573 normalize_mergekey((char *) mergekey_norm, 0);
575 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
577 if (global_parameters.dump_records)
578 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
579 cl->database->url, cl->records);
582 /* no room for record */
586 relevance_newrec(se->relevance, cluster);
588 for (n = root->children; n; n = n->next)
596 if (n->type != XML_ELEMENT_NODE)
598 if (!strcmp((const char *) n->name, "metadata"))
600 struct conf_metadata *md = 0;
601 struct conf_sortkey *sk = 0;
602 struct record_metadata **wheretoput, *newm;
606 type = xmlGetProp(n, (xmlChar *) "type");
607 value = xmlNodeListGetString(xdoc, n->children, 0);
612 // First, find out what field we're looking at
613 for (imeta = 0; imeta < service->num_metadata; imeta++)
614 if (!strcmp((const char *) type, service->metadata[imeta].name))
616 md = &service->metadata[imeta];
617 if (md->sortkey_offset >= 0)
618 sk = &service->sortkeys[md->sortkey_offset];
623 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
627 // Find out where we are putting it
628 if (md->merge == Metadata_merge_no)
629 wheretoput = &res->metadata[imeta];
631 wheretoput = &cluster->metadata[imeta];
634 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
636 if (md->type == Metadata_type_generic)
639 for (p = (char *) value; *p && isspace(*p); p++)
641 for (pe = p + strlen(p) - 1;
642 pe > p && strchr(" ,/.:([", *pe); pe--)
644 newm->data.text = nmem_strdup(se->nmem, p);
647 else if (md->type == Metadata_type_year)
649 if (extract_years((char *) value, &first, &last) < 0)
654 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
657 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
659 yaz_log(YLOG_WARN, "Only range merging supported for years");
662 if (md->merge == Metadata_merge_unique)
664 struct record_metadata *mnode;
665 for (mnode = *wheretoput; mnode; mnode = mnode->next)
666 if (!strcmp((const char *) mnode->data.text, newm->data.text))
670 newm->next = *wheretoput;
674 else if (md->merge == Metadata_merge_longest)
677 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
682 char *s = nmem_strdup(se->nmem, newm->data.text);
683 if (!cluster->sortkeys[md->sortkey_offset])
684 cluster->sortkeys[md->sortkey_offset] =
685 nmem_malloc(se->nmem, sizeof(union data_types));
686 normalize_mergekey(s,
687 (sk->type == Metadata_sortkey_skiparticle));
688 cluster->sortkeys[md->sortkey_offset]->text = s;
692 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
694 newm->next = *wheretoput;
697 else if (md->merge == Metadata_merge_range)
699 assert(md->type == Metadata_type_year);
703 (*wheretoput)->data.number.min = first;
704 (*wheretoput)->data.number.max = last;
706 cluster->sortkeys[md->sortkey_offset] = &newm->data;
710 if (first < (*wheretoput)->data.number.min)
711 (*wheretoput)->data.number.min = first;
712 if (last > (*wheretoput)->data.number.max)
713 (*wheretoput)->data.number.max = last;
718 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
719 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
724 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
727 relevance_countwords(se->relevance, cluster,
728 (char *) value, md->rank);
731 if (md->type == Metadata_type_year)
734 sprintf(year, "%d", last);
735 add_facet(se, (char *) type, year);
738 sprintf(year, "%d", first);
739 add_facet(se, (char *) type, year);
743 add_facet(se, (char *) type, (char *) value);
750 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
759 relevance_donerecord(se->relevance, cluster);
765 // Retrieve first defined value for 'name' for given database.
766 // Will be extended to take into account user associated with session
767 char *session_setting_oneval(struct session *s, struct database *db, const char *name)
769 int offset = settings_offset(name);
773 if (!db->settings[offset])
775 return db->settings[offset]->value;
778 static void ingest_records(struct client *cl, Z_Records *r)
781 yaz_timing_t t = yaz_timing_create();
784 struct session *s = cl->session;
785 Z_NamePlusRecordList *rlist;
788 if (r->which != Z_Records_DBOSD)
790 rlist = r->u.databaseOrSurDiagnostics;
791 for (i = 0; i < rlist->num_records; i++)
793 Z_NamePlusRecord *npr = rlist->records[i];
796 if (npr->which != Z_NamePlusRecord_databaseRecord)
799 "Unexpected record type, probably diagnostic %s",
804 rec = ingest_record(cl, npr->u.databaseRecord);
808 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
809 session_alert_watch(s, SESSION_WATCH_RECORDS);
813 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
814 yaz_timing_get_real(t), yaz_timing_get_user(t),
815 yaz_timing_get_sys(t));
816 yaz_timing_destroy(&t);
820 static void do_presentResponse(IOCHAN i, Z_APDU *a)
822 struct connection *co = iochan_getdata(i);
823 struct client *cl = co->client;
824 Z_PresentResponse *r = a->u.presentResponse;
827 Z_Records *recs = r->records;
828 if (recs->which == Z_Records_NSD)
830 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
832 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
833 cl->state = Client_Error;
837 if (!*r->presentStatus && cl->state != Client_Error)
839 yaz_log(YLOG_DEBUG, "Good Present response %s",
841 ingest_records(cl, r->records);
842 cl->state = Client_Idle;
844 else if (*r->presentStatus)
846 yaz_log(YLOG_WARN, "Bad Present response %s",
848 cl->state = Client_Error;
852 static void handler(IOCHAN i, int event)
854 struct connection *co = iochan_getdata(i);
855 struct client *cl = co->client;
856 struct session *se = 0;
862 yaz_log(YLOG_WARN, "Destroying orphan connection");
863 connection_destroy(co);
867 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
870 socklen_t errlen = sizeof(errcode);
872 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
873 &errlen) < 0 || errcode != 0)
880 yaz_log(YLOG_DEBUG, "Connect OK");
881 co->state = Conn_Open;
883 cl->state = Client_Connected;
887 else if (event & EVENT_INPUT)
889 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
893 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
895 connection_destroy(co);
900 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->url);
901 connection_destroy(co);
904 else if (len > 1) // We discard input if we have no connection
906 co->state = Conn_Open;
908 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
912 odr_reset(global_parameters.odr_in);
913 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
914 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
921 case Z_APDU_initResponse:
922 do_initResponse(i, a);
924 case Z_APDU_searchResponse:
925 do_searchResponse(i, a);
927 case Z_APDU_presentResponse:
928 do_presentResponse(i, a);
931 do_closeResponse(i, a);
935 "Unexpected Z39.50 response from %s",
940 // We aren't expecting staggered output from target
941 // if (cs_more(t->link))
942 // iochan_setevent(i, EVENT_INPUT);
944 else // we throw away response and go to idle mode
946 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
947 cl->state = Client_Idle;
950 /* if len==1 we do nothing but wait for more input */
953 if (cl->state == Client_Connected) {
957 if (cl->state == Client_Idle)
959 if (cl->requestid != se->requestid && *se->query) {
962 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
963 cl->records < cl->hits) {
969 // Disassociate connection from client
970 static void connection_release(struct connection *co)
972 struct client *cl = co->client;
974 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
981 // Close connection and recycle structure
982 static void connection_destroy(struct connection *co)
984 struct host *h = co->host;
986 iochan_destroy(co->iochan);
988 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
989 if (h->connections == co)
990 h->connections = co->next;
993 struct connection *pco;
994 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
997 pco->next = co->next;
1003 if (co->client->state != Client_Idle)
1004 co->client->state = Client_Disconnected;
1005 co->client->connection = 0;
1007 co->next = connection_freelist;
1008 connection_freelist = co;
1011 // Creates a new connection for client, associated with the host of
1012 // client's database
1013 static struct connection *connection_create(struct client *cl)
1015 struct connection *new;
1021 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1023 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1027 if (0 == strlen(global_parameters.zproxy_override)){
1028 /* no Z39.50 proxy needed - direct connect */
1029 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
1031 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
1033 yaz_log(YLOG_WARN|YLOG_ERRNO,
1034 "Lookup of IP address %s failed",
1035 cl->database->host->ipport);
1040 /* Z39.50 proxy connect */
1041 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1042 cl->database->url, global_parameters.zproxy_override);
1044 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1046 yaz_log(YLOG_WARN|YLOG_ERRNO,
1047 "Lookup of IP address %s failed",
1048 global_parameters.zproxy_override);
1053 res = cs_connect(link, addr);
1056 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
1060 if ((new = connection_freelist))
1061 connection_freelist = new->next;
1064 new = xmalloc(sizeof (struct connection));
1068 new->state = Conn_Connecting;
1069 new->host = cl->database->host;
1070 new->next = new->host->connections;
1071 new->host->connections = new;
1073 cl->connection = new;
1076 new->iochan = iochan_create(cs_fileno(link), 0, handler, 0);
1077 iochan_setdata(new->iochan, new);
1078 new->iochan->next = channel_list;
1079 channel_list = new->iochan;
1083 // Close connection and set state to error
1084 static void client_fatal(struct client *cl)
1086 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
1087 connection_destroy(cl->connection);
1088 cl->state = Client_Error;
1091 // Ensure that client has a connection associated
1092 static int client_prep_connection(struct client *cl)
1094 struct connection *co;
1095 struct session *se = cl->session;
1096 struct host *host = cl->database->host;
1098 co = cl->connection;
1100 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1104 // See if someone else has an idle connection
1105 // We should look at timestamps here to select the longest-idle connection
1106 for (co = host->connections; co; co = co->next)
1107 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1111 connection_release(co);
1112 cl->connection = co;
1116 co = connection_create(cl);
1120 if (co->state == Conn_Connecting)
1122 cl->state = Client_Connecting;
1123 iochan_setflag(co->iochan, EVENT_OUTPUT);
1125 else if (co->state == Conn_Open)
1127 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1128 cl->state = Client_Idle;
1129 iochan_setflag(co->iochan, EVENT_OUTPUT);
1137 #ifdef GAGA // Moved to database.c
1139 // This function will most likely vanish when a proper target profile mechanism is
1141 void load_simpletargets(const char *fn)
1143 FILE *f = fopen(fn, "r");
1148 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1152 while (fgets(line, 255, f))
1157 struct database *database;
1159 if (strncmp(line, "target ", 7))
1161 line[strlen(line) - 1] = '\0';
1163 if ((name = strchr(line, ';')))
1167 if ((db = strchr(url, '/')))
1172 yaz_log(YLOG_LOG, "Target: %s, '%s'", url, db);
1173 for (host = hosts; host; host = host->next)
1174 if (!strcmp((const char *) url, host->hostport))
1178 struct addrinfo *addrinfo, hints;
1181 unsigned char addrbuf[4];
1184 host = xmalloc(sizeof(struct host));
1185 host->hostport = xstrdup(url);
1186 host->connections = 0;
1188 if ((port = strchr(url, ':')))
1194 hints.ai_family = PF_INET;
1195 hints.ai_socktype = SOCK_STREAM;
1196 hints.ai_protocol = IPPROTO_TCP;
1197 hints.ai_addrlen = 0;
1199 hints.ai_canonname = 0;
1201 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1203 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1205 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1206 xfree(host->hostport);
1210 assert(addrinfo->ai_family == PF_INET);
1211 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1212 sprintf(ipport, "%u.%u.%u.%u:%s",
1213 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1214 host->ipport = xstrdup(ipport);
1215 freeaddrinfo(addrinfo);
1219 database = xmalloc(sizeof(struct database));
1220 database->host = host;
1221 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1222 strcpy(database->url, url);
1223 strcat(database->url, "/");
1224 strcat(database->url, db);
1226 database->name = xstrdup(name);
1230 database->databases = xmalloc(2 * sizeof(char *));
1231 database->databases[0] = xstrdup(db);
1232 database->databases[1] = 0;
1233 database->errors = 0;
1234 database->qprofile = 0;
1235 database->rprofile = database_retrieval_profile(database);
1236 database->next = databases;
1237 databases = database;
1245 static struct client *client_create(void)
1248 if (client_freelist)
1250 r = client_freelist;
1251 client_freelist = client_freelist->next;
1254 r = xmalloc(sizeof(struct client));
1263 r->state = Client_Disconnected;
1268 void client_destroy(struct client *c)
1270 struct session *se = c->session;
1271 if (c == se->clients)
1272 se->clients = c->next;
1276 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1282 connection_release(c->connection);
1283 c->next = client_freelist;
1284 client_freelist = c;
1287 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1289 s->watchlist[what].fun = fun;
1290 s->watchlist[what].data = data;
1293 void session_alert_watch(struct session *s, int what)
1295 if (!s->watchlist[what].fun)
1297 (*s->watchlist[what].fun)(s->watchlist[what].data);
1298 s->watchlist[what].fun = 0;
1299 s->watchlist[what].data = 0;
1302 //callback for grep_databases
1303 static void select_targets_callback(void *context, struct database *db)
1305 struct session *se = (struct session*) context;
1306 struct client *cl = client_create();
1309 cl->next = se->clients;
1313 // This should be extended with parameters to control selection criteria
1314 // Associates a set of clients with a session;
1315 int select_targets(struct session *se, struct database_criterion *crit)
1318 client_destroy(se->clients);
1320 return grep_databases(se, crit, select_targets_callback);
1323 int session_active_clients(struct session *s)
1328 for (c = s->clients; c; c = c->next)
1329 if (c->connection && (c->state == Client_Connecting ||
1330 c->state == Client_Initializing ||
1331 c->state == Client_Searching ||
1332 c->state == Client_Presenting))
1338 // parses crit1=val1,crit2=val2|val3,...
1339 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1341 struct database_criterion *res = 0;
1348 nmem_strsplit(m, ",", buf, &values, &num);
1349 for (i = 0; i < num; i++)
1354 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1355 char *eq = strchr(values[i], '=');
1358 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1362 new->name = values[i];
1363 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1365 for (subi = 0; subi < subnum; subi++)
1367 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1368 newv->value = subvalues[subi];
1369 newv->next = new->values;
1378 char *search(struct session *se, char *query, char *filter)
1380 int live_channels = 0;
1382 struct database_criterion *criteria;
1384 yaz_log(YLOG_DEBUG, "Search");
1386 nmem_reset(se->nmem);
1387 criteria = parse_filter(se->nmem, filter);
1388 strcpy(se->query, query);
1390 // Release any existing clients
1391 select_targets(se, criteria);
1392 for (cl = se->clients; cl; cl = cl->next)
1394 if (client_prep_connection(cl))
1399 int maxrecs = live_channels * global_parameters.toget;
1400 se->num_termlists = 0;
1401 se->reclist = reclist_create(se->nmem, maxrecs);
1402 // This will be initialized in send_search()
1404 se->total_records = se->total_hits = se->total_merged = 0;
1405 se->expected_maxrecs = maxrecs;
1413 void destroy_session(struct session *s)
1415 yaz_log(YLOG_LOG, "Destroying session");
1417 client_destroy(s->clients);
1418 nmem_destroy(s->nmem);
1419 wrbuf_destroy(s->wrbuf);
1422 struct session *new_session()
1425 struct session *session = xmalloc(sizeof(*session));
1427 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1429 session->total_hits = 0;
1430 session->total_records = 0;
1431 session->num_termlists = 0;
1432 session->reclist = 0;
1433 session->requestid = -1;
1434 session->clients = 0;
1435 session->expected_maxrecs = 0;
1436 session->query[0] = '\0';
1437 session->nmem = nmem_create();
1438 session->wrbuf = wrbuf_alloc();
1439 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1441 session->watchlist[i].data = 0;
1442 session->watchlist[i].fun = 0;
1448 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1450 static struct hitsbytarget res[1000]; // FIXME MM
1454 for (cl = se->clients; cl; cl = cl->next)
1456 res[*count].id = cl->database->url;
1457 res[*count].name = cl->database->name;
1458 res[*count].hits = cl->hits;
1459 res[*count].records = cl->records;
1460 res[*count].diagnostic = cl->diagnostic;
1461 res[*count].state = client_states[cl->state];
1462 res[*count].connected = cl->connection ? 1 : 0;
1469 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1473 for (i = 0; i < s->num_termlists; i++)
1474 if (!strcmp((const char *) s->termlists[i].name, name))
1475 return termlist_highscore(s->termlists[i].termlist, num);
1479 #ifdef MISSING_HEADERS
1480 void report_nmem_stats(void)
1482 size_t in_use, is_free;
1484 nmem_get_memory_in_use(&in_use);
1485 nmem_get_memory_free(&is_free);
1487 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1488 (long) in_use, (long) is_free);
1492 struct record_cluster *show_single(struct session *s, int id)
1494 struct record_cluster *r;
1496 reclist_rewind(s->reclist);
1497 while ((r = reclist_read_record(s->reclist)))
1503 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1504 int *num, int *total, int *sumhits, NMEM nmem_show)
1506 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1507 * sizeof(struct record_cluster *));
1508 struct reclist_sortparms *spp;
1511 yaz_timing_t t = yaz_timing_create();
1514 for (spp = sp; spp; spp = spp->next)
1515 if (spp->type == Metadata_sortkey_relevance)
1517 relevance_prepare_read(s->relevance, s->reclist);
1520 reclist_sort(s->reclist, sp);
1522 *total = s->reclist->num_records;
1523 *sumhits = s->total_hits;
1525 for (i = 0; i < start; i++)
1526 if (!reclist_read_record(s->reclist))
1533 for (i = 0; i < *num; i++)
1535 struct record_cluster *r = reclist_read_record(s->reclist);
1545 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1546 yaz_timing_get_real(t), yaz_timing_get_user(t),
1547 yaz_timing_get_sys(t));
1548 yaz_timing_destroy(&t);
1553 void statistics(struct session *se, struct statistics *stat)
1558 memset(stat, 0, sizeof(*stat));
1559 for (cl = se->clients; cl; cl = cl->next)
1561 if (!cl->connection)
1562 stat->num_no_connection++;
1565 case Client_Connecting: stat->num_connecting++; break;
1566 case Client_Initializing: stat->num_initializing++; break;
1567 case Client_Searching: stat->num_searching++; break;
1568 case Client_Presenting: stat->num_presenting++; break;
1569 case Client_Idle: stat->num_idle++; break;
1570 case Client_Failed: stat->num_failed++; break;
1571 case Client_Error: stat->num_error++; break;
1576 stat->num_hits = se->total_hits;
1577 stat->num_records = se->total_records;
1579 stat->num_clients = count;
1582 static void start_http_listener(void)
1585 struct conf_server *ser = global_parameters.server;
1587 if (*global_parameters.listener_override)
1588 strcpy(hp, global_parameters.listener_override);
1591 strcpy(hp, ser->host ? ser->host : "");
1596 sprintf(hp + strlen(hp), "%d", ser->port);
1602 // Initialize CCL map for a target
1603 // Note: This approach ignores user-specific CCL maps, for which I
1604 // don't presently see any application.
1605 static void prepare_cclmap(void *context, struct database *db)
1611 db->ccl_map = ccl_qual_mk();
1612 for (s = db->settings[PZ_CCLMAP]; s; s = s->next)
1615 char *p = strchr(s->name + 3, ':');
1618 yaz_log(YLOG_FATAL, "Malformed cclmap name: %s", s->name);
1622 ccl_qual_fitem(db->ccl_map, s->value, p);
1626 // Read settings for each database, and prepare a CCL map for that database
1627 static void prepare_cclmaps(void)
1629 grep_databases(0, 0, prepare_cclmap);
1632 static void start_proxy(void)
1635 struct conf_server *ser = global_parameters.server;
1637 if (*global_parameters.proxy_override)
1638 strcpy(hp, global_parameters.proxy_override);
1639 else if (ser->proxy_host || ser->proxy_port)
1641 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1642 if (ser->proxy_port)
1646 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1652 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1655 static void start_zproxy(void)
1657 struct conf_server *ser = global_parameters.server;
1659 if (*global_parameters.zproxy_override){
1660 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1661 global_parameters.zproxy_override);
1665 else if (ser->zproxy_host || ser->zproxy_port)
1669 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1670 if (ser->zproxy_port)
1677 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1679 strcpy(global_parameters.zproxy_override, hp);
1680 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1681 global_parameters.zproxy_override);
1690 int main(int argc, char **argv)
1695 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1696 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1698 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1700 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1704 if (!read_config(arg))
1708 strcpy(global_parameters.listener_override, arg);
1711 strcpy(global_parameters.proxy_override, arg);
1714 strcpy(global_parameters.zproxy_override, arg);
1717 strcpy(global_parameters.settings_path_override, arg);
1720 load_simpletargets(arg);
1723 global_parameters.dump_records = 1;
1726 fprintf(stderr, "Usage: pazpar2\n"
1728 " -h [host:]port (REST protocol listener)\n"
1730 " -s simpletargetfile\n"
1731 " -p hostname[:portno] (HTTP proxy)\n"
1732 " -z hostname[:portno] (Z39.50 proxy)\n"
1733 " -d (show internal records)\n");
1740 yaz_log(YLOG_FATAL, "Load config with -f");
1743 global_parameters.server = config->servers;
1745 start_http_listener();
1749 if (*global_parameters.settings_path_override)
1750 settings_read(global_parameters.settings_path_override);
1751 else if (global_parameters.server->settings)
1752 settings_read(global_parameters.server->settings);
1754 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may ensue!");
1756 global_parameters.yaz_marc = yaz_marc_create();
1757 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1758 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1759 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1761 event_loop(&channel_list);
1769 * indent-tabs-mode: nil
1771 * vim: shiftwidth=4 tabstop=8 expandtab