1 /* $Id: pazpar2.c,v 1.64 2007-04-08 20:52:09 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, int offset);
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)",
94 static int send_apdu(struct client *c, Z_APDU *a)
96 struct connection *co = c->connection;
100 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
102 odr_perror(global_parameters.odr_out, "Encoding APDU");
105 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
106 r = cs_put(co->link, buf, len);
109 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
114 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
117 odr_reset(global_parameters.odr_out); /* release the APDU structure */
118 co->state = Conn_Waiting;
123 static void send_init(IOCHAN i)
126 struct connection *co = iochan_getdata(i);
127 struct client *cl = co->client;
128 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
130 a->u.initRequest->implementationId = global_parameters.implementationId;
131 a->u.initRequest->implementationName = global_parameters.implementationName;
132 a->u.initRequest->implementationVersion =
133 global_parameters.implementationVersion;
134 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
135 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
136 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
138 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
139 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
140 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
143 /* add virtual host if tunneling through Z39.50 proxy */
145 if (0 < strlen(global_parameters.zproxy_override)
146 && 0 < strlen(cl->database->url))
147 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
148 global_parameters.odr_out, VAL_PROXY,
149 1, cl->database->url);
153 if (send_apdu(cl, a) >= 0)
155 iochan_setflags(i, EVENT_INPUT);
156 cl->state = Client_Initializing;
159 cl->state = Client_Error;
160 odr_reset(global_parameters.odr_out);
163 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
171 pull_terms(nmem, n->u.p[0], termlist, num);
172 pull_terms(nmem, n->u.p[1], termlist, num);
175 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
182 // Extract terms from query into null-terminated termlist
183 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
187 pull_terms(nmem, query, termlist, &num);
191 static void send_search(IOCHAN i)
193 struct connection *co = iochan_getdata(i);
194 struct client *cl = co->client;
195 struct session *se = cl->session;
196 struct database *db = cl->database;
197 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
198 int ndb, cerror, cpos;
201 struct ccl_rpn_node *cn;
202 int ssub = 0, lslb = 100000, mspn = 10;
206 yaz_log(YLOG_DEBUG, "Sending search");
208 cn = ccl_find_str(db->ccl_map, se->query, &cerror, &cpos);
214 // Initialize relevance structure with query terms
216 extract_terms(se->nmem, cn, p);
217 se->relevance = relevance_create(se->nmem, (const char **) p,
218 se->expected_maxrecs);
221 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
223 zquery->which = Z_Query_type_1;
224 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
227 for (ndb = 0; db->databases[ndb]; ndb++)
229 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
230 for (ndb = 0; db->databases[ndb]; ndb++)
231 databaselist[ndb] = db->databases[ndb];
233 if (!(piggyback = session_setting_oneval(se, db, PZ_PIGGYBACK)) || *piggyback == '1')
235 if ((recsyn = session_setting_oneval(se, db, PZ_NATIVESYNTAX)))
236 a->u.searchRequest->preferredRecordSyntax =
237 yaz_str_to_z3950oid(global_parameters.odr_out,
238 CLASS_RECSYN, recsyn);
239 a->u.searchRequest->smallSetUpperBound = &ssub;
240 a->u.searchRequest->largeSetLowerBound = &lslb;
241 a->u.searchRequest->mediumSetPresentNumber = &mspn;
243 a->u.searchRequest->resultSetName = "Default";
244 a->u.searchRequest->databaseNames = databaselist;
245 a->u.searchRequest->num_databaseNames = ndb;
247 if (send_apdu(cl, a) >= 0)
249 iochan_setflags(i, EVENT_INPUT);
250 cl->state = Client_Searching;
251 cl->requestid = se->requestid;
254 cl->state = Client_Error;
256 odr_reset(global_parameters.odr_out);
259 static void send_present(IOCHAN i)
261 struct connection *co = iochan_getdata(i);
262 struct client *cl = co->client;
263 struct session *se = cl->session;
264 struct database *db = cl->database;
265 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
267 int start = cl->records + 1;
270 toget = global_parameters.chunk;
271 if (toget > global_parameters.toget - cl->records)
272 toget = global_parameters.toget - cl->records;
273 if (toget > cl->hits - cl->records)
274 toget = cl->hits - cl->records;
276 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
278 a->u.presentRequest->resultSetStartPoint = &start;
279 a->u.presentRequest->numberOfRecordsRequested = &toget;
281 a->u.presentRequest->resultSetId = "Default";
283 if ((recsyn = session_setting_oneval(se, db, PZ_NATIVESYNTAX)))
284 a->u.presentRequest->preferredRecordSyntax =
285 yaz_str_to_z3950oid(global_parameters.odr_out,
286 CLASS_RECSYN, recsyn);
288 if (send_apdu(cl, a) >= 0)
290 iochan_setflags(i, EVENT_INPUT);
291 cl->state = Client_Presenting;
294 cl->state = Client_Error;
295 odr_reset(global_parameters.odr_out);
298 static void do_initResponse(IOCHAN i, Z_APDU *a)
300 struct connection *co = iochan_getdata(i);
301 struct client *cl = co->client;
302 Z_InitResponse *r = a->u.initResponse;
304 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->url);
308 cl->state = Client_Idle;
311 cl->state = Client_Failed; // FIXME need to do something to the connection
314 static void do_searchResponse(IOCHAN i, Z_APDU *a)
316 struct connection *co = iochan_getdata(i);
317 struct client *cl = co->client;
318 struct session *se = cl->session;
319 Z_SearchResponse *r = a->u.searchResponse;
321 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
322 cl->database->url, *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 %s",
332 ingest_records(cl, r->records);
334 cl->state = Client_Idle;
339 cl->state = Client_Error;
341 Z_Records *recs = r->records;
342 if (recs->which == Z_Records_NSD)
345 "Search response: Non-surrogate diagnostic %s",
347 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
348 cl->state = Client_Error;
354 static void do_closeResponse(IOCHAN i, Z_APDU *a)
356 struct connection *co = iochan_getdata(i);
357 struct client *cl = co->client;
358 /* Z_Close *r = a->u.close; */
360 yaz_log(YLOG_WARN, "Close response %s", cl->database->url);
362 cl->state = Client_Failed;
363 connection_destroy(co);
367 char *normalize_mergekey(char *buf, int skiparticle)
369 char *p = buf, *pout = buf;
374 char articles[] = "the den der die des an a "; // must end in space
376 while (*p && !isalnum(*p))
379 while (*p && *p != ' ' && pout - firstword < 62)
380 *(pout++) = tolower(*(p++));
383 if (!strstr(articles, firstword))
390 while (*p && !isalnum(*p))
393 *(pout++) = tolower(*(p++));
396 while (*p && !isalnum(*p))
403 while (pout > buf && *pout == ' ');
408 static void add_facet(struct session *s, const char *type, const char *value)
414 for (i = 0; i < s->num_termlists; i++)
415 if (!strcmp(s->termlists[i].name, type))
417 if (i == s->num_termlists)
419 if (i == SESSION_MAX_TERMLISTS)
421 yaz_log(YLOG_FATAL, "Too many termlists");
424 s->termlists[i].name = nmem_strdup(s->nmem, type);
425 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
426 s->num_termlists = i + 1;
428 termlist_insert(s->termlists[i].termlist, value);
431 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
433 struct database_retrievalmap *m;
434 struct database *db = cl->database;
438 // First normalize to XML
443 if (rec->which != Z_External_octet)
445 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
449 buf = (char*) rec->u.octet_aligned->buf;
450 len = rec->u.octet_aligned->len;
451 if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
453 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
457 if (yaz_marc_write_xml(db->yaz_marc, &res,
458 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
460 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
464 rdoc = xmlNewDoc((xmlChar *) "1.0");
465 xmlDocSetRootElement(rdoc, res);
469 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
473 if (global_parameters.dump_records)
475 fprintf(stderr, "Input Record (normalized):\n----------------\n");
476 #if LIBXML_VERSION >= 20600
477 xmlDocFormatDump(stderr, rdoc, 1);
479 xmlDocDump(stderr, rdoc);
483 for (m = db->map; m; m = m->next)
486 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
488 yaz_log(YLOG_WARN, "XSLT transformation failed");
494 if (global_parameters.dump_records)
496 fprintf(stderr, "Record:\n----------------\n");
497 #if LIBXML_VERSION >= 20600
498 xmlDocFormatDump(stderr, rdoc, 1);
500 xmlDocDump(stderr, rdoc);
506 // Extract what appears to be years from buf, storing highest and
508 static int extract_years(const char *buf, int *first, int *last)
517 while (*buf && !isdigit(*buf))
520 for (e = buf; *e && isdigit(*e); e++)
524 int value = atoi(buf);
525 if (*first < 0 || value < *first)
527 if (*last < 0 || value > *last)
535 static struct record *ingest_record(struct client *cl, Z_External *rec)
537 xmlDoc *xdoc = normalize_record(cl, rec);
540 struct record_cluster *cluster;
541 struct session *se = cl->session;
542 xmlChar *mergekey, *mergekey_norm;
545 struct conf_service *service = global_parameters.server->service;
550 root = xmlDocGetRootElement(xdoc);
551 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
553 yaz_log(YLOG_WARN, "No mergekey found in record");
558 res = nmem_malloc(se->nmem, sizeof(struct record));
561 res->metadata = nmem_malloc(se->nmem,
562 sizeof(struct record_metadata*) * service->num_metadata);
563 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
565 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
567 normalize_mergekey((char *) mergekey_norm, 0);
569 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
571 if (global_parameters.dump_records)
572 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
573 cl->database->url, cl->records);
576 /* no room for record */
580 relevance_newrec(se->relevance, cluster);
582 for (n = root->children; n; n = n->next)
590 if (n->type != XML_ELEMENT_NODE)
592 if (!strcmp((const char *) n->name, "metadata"))
594 struct conf_metadata *md = 0;
595 struct conf_sortkey *sk = 0;
596 struct record_metadata **wheretoput, *newm;
600 type = xmlGetProp(n, (xmlChar *) "type");
601 value = xmlNodeListGetString(xdoc, n->children, 0);
606 // First, find out what field we're looking at
607 for (imeta = 0; imeta < service->num_metadata; imeta++)
608 if (!strcmp((const char *) type, service->metadata[imeta].name))
610 md = &service->metadata[imeta];
611 if (md->sortkey_offset >= 0)
612 sk = &service->sortkeys[md->sortkey_offset];
617 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
621 // Find out where we are putting it
622 if (md->merge == Metadata_merge_no)
623 wheretoput = &res->metadata[imeta];
625 wheretoput = &cluster->metadata[imeta];
628 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
630 if (md->type == Metadata_type_generic)
633 for (p = (char *) value; *p && isspace(*p); p++)
635 for (pe = p + strlen(p) - 1;
636 pe > p && strchr(" ,/.:([", *pe); pe--)
638 newm->data.text = nmem_strdup(se->nmem, p);
641 else if (md->type == Metadata_type_year)
643 if (extract_years((char *) value, &first, &last) < 0)
648 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
651 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
653 yaz_log(YLOG_WARN, "Only range merging supported for years");
656 if (md->merge == Metadata_merge_unique)
658 struct record_metadata *mnode;
659 for (mnode = *wheretoput; mnode; mnode = mnode->next)
660 if (!strcmp((const char *) mnode->data.text, newm->data.text))
664 newm->next = *wheretoput;
668 else if (md->merge == Metadata_merge_longest)
671 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
676 char *s = nmem_strdup(se->nmem, newm->data.text);
677 if (!cluster->sortkeys[md->sortkey_offset])
678 cluster->sortkeys[md->sortkey_offset] =
679 nmem_malloc(se->nmem, sizeof(union data_types));
680 normalize_mergekey(s,
681 (sk->type == Metadata_sortkey_skiparticle));
682 cluster->sortkeys[md->sortkey_offset]->text = s;
686 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
688 newm->next = *wheretoput;
691 else if (md->merge == Metadata_merge_range)
693 assert(md->type == Metadata_type_year);
697 (*wheretoput)->data.number.min = first;
698 (*wheretoput)->data.number.max = last;
700 cluster->sortkeys[md->sortkey_offset] = &newm->data;
704 if (first < (*wheretoput)->data.number.min)
705 (*wheretoput)->data.number.min = first;
706 if (last > (*wheretoput)->data.number.max)
707 (*wheretoput)->data.number.max = last;
712 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
713 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
718 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
721 relevance_countwords(se->relevance, cluster,
722 (char *) value, md->rank);
725 if (md->type == Metadata_type_year)
728 sprintf(year, "%d", last);
729 add_facet(se, (char *) type, year);
732 sprintf(year, "%d", first);
733 add_facet(se, (char *) type, year);
737 add_facet(se, (char *) type, (char *) value);
744 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
753 relevance_donerecord(se->relevance, cluster);
759 // Retrieve first defined value for 'name' for given database.
760 // Will be extended to take into account user associated with session
761 char *session_setting_oneval(struct session *s, struct database *db, int offset)
763 if (!db->settings[offset])
765 return db->settings[offset]->value;
768 static void ingest_records(struct client *cl, Z_Records *r)
771 yaz_timing_t t = yaz_timing_create();
774 struct session *s = cl->session;
775 Z_NamePlusRecordList *rlist;
778 if (r->which != Z_Records_DBOSD)
780 rlist = r->u.databaseOrSurDiagnostics;
781 for (i = 0; i < rlist->num_records; i++)
783 Z_NamePlusRecord *npr = rlist->records[i];
786 if (npr->which != Z_NamePlusRecord_databaseRecord)
789 "Unexpected record type, probably diagnostic %s",
794 rec = ingest_record(cl, npr->u.databaseRecord);
798 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
799 session_alert_watch(s, SESSION_WATCH_RECORDS);
803 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
804 yaz_timing_get_real(t), yaz_timing_get_user(t),
805 yaz_timing_get_sys(t));
806 yaz_timing_destroy(&t);
810 static void do_presentResponse(IOCHAN i, Z_APDU *a)
812 struct connection *co = iochan_getdata(i);
813 struct client *cl = co->client;
814 Z_PresentResponse *r = a->u.presentResponse;
817 Z_Records *recs = r->records;
818 if (recs->which == Z_Records_NSD)
820 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
822 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
823 cl->state = Client_Error;
827 if (!*r->presentStatus && cl->state != Client_Error)
829 yaz_log(YLOG_DEBUG, "Good Present response %s",
831 ingest_records(cl, r->records);
832 cl->state = Client_Idle;
834 else if (*r->presentStatus)
836 yaz_log(YLOG_WARN, "Bad Present response %s",
838 cl->state = Client_Error;
842 static void handler(IOCHAN i, int event)
844 struct connection *co = iochan_getdata(i);
845 struct client *cl = co->client;
846 struct session *se = 0;
852 yaz_log(YLOG_WARN, "Destroying orphan connection");
853 connection_destroy(co);
857 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
860 socklen_t errlen = sizeof(errcode);
862 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
863 &errlen) < 0 || errcode != 0)
870 yaz_log(YLOG_DEBUG, "Connect OK");
871 co->state = Conn_Open;
873 cl->state = Client_Connected;
877 else if (event & EVENT_INPUT)
879 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
883 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
885 connection_destroy(co);
890 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->url);
891 connection_destroy(co);
894 else if (len > 1) // We discard input if we have no connection
896 co->state = Conn_Open;
898 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
902 odr_reset(global_parameters.odr_in);
903 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
904 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
911 case Z_APDU_initResponse:
912 do_initResponse(i, a);
914 case Z_APDU_searchResponse:
915 do_searchResponse(i, a);
917 case Z_APDU_presentResponse:
918 do_presentResponse(i, a);
921 do_closeResponse(i, a);
925 "Unexpected Z39.50 response from %s",
930 // We aren't expecting staggered output from target
931 // if (cs_more(t->link))
932 // iochan_setevent(i, EVENT_INPUT);
934 else // we throw away response and go to idle mode
936 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
937 cl->state = Client_Idle;
940 /* if len==1 we do nothing but wait for more input */
943 if (cl->state == Client_Connected) {
947 if (cl->state == Client_Idle)
949 if (cl->requestid != se->requestid && *se->query) {
952 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
953 cl->records < cl->hits) {
959 // Disassociate connection from client
960 static void connection_release(struct connection *co)
962 struct client *cl = co->client;
964 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
971 // Close connection and recycle structure
972 static void connection_destroy(struct connection *co)
974 struct host *h = co->host;
976 iochan_destroy(co->iochan);
978 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
979 if (h->connections == co)
980 h->connections = co->next;
983 struct connection *pco;
984 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
987 pco->next = co->next;
993 if (co->client->state != Client_Idle)
994 co->client->state = Client_Disconnected;
995 co->client->connection = 0;
997 co->next = connection_freelist;
998 connection_freelist = co;
1001 // Creates a new connection for client, associated with the host of
1002 // client's database
1003 static struct connection *connection_create(struct client *cl)
1005 struct connection *new;
1011 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1013 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1017 if (0 == strlen(global_parameters.zproxy_override)){
1018 /* no Z39.50 proxy needed - direct connect */
1019 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
1021 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
1023 yaz_log(YLOG_WARN|YLOG_ERRNO,
1024 "Lookup of IP address %s failed",
1025 cl->database->host->ipport);
1030 /* Z39.50 proxy connect */
1031 yaz_log(YLOG_DEBUG, "Connection create %s proxy %s",
1032 cl->database->url, global_parameters.zproxy_override);
1034 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1036 yaz_log(YLOG_WARN|YLOG_ERRNO,
1037 "Lookup of IP address %s failed",
1038 global_parameters.zproxy_override);
1043 res = cs_connect(link, addr);
1046 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
1050 if ((new = connection_freelist))
1051 connection_freelist = new->next;
1054 new = xmalloc(sizeof (struct connection));
1058 new->state = Conn_Connecting;
1059 new->host = cl->database->host;
1060 new->next = new->host->connections;
1061 new->host->connections = new;
1063 cl->connection = new;
1066 new->iochan = iochan_create(cs_fileno(link), 0, handler, 0);
1067 iochan_setdata(new->iochan, new);
1068 new->iochan->next = channel_list;
1069 channel_list = new->iochan;
1073 // Close connection and set state to error
1074 static void client_fatal(struct client *cl)
1076 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
1077 connection_destroy(cl->connection);
1078 cl->state = Client_Error;
1081 // Ensure that client has a connection associated
1082 static int client_prep_connection(struct client *cl)
1084 struct connection *co;
1085 struct session *se = cl->session;
1086 struct host *host = cl->database->host;
1088 co = cl->connection;
1090 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1094 // See if someone else has an idle connection
1095 // We should look at timestamps here to select the longest-idle connection
1096 for (co = host->connections; co; co = co->next)
1097 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1101 connection_release(co);
1102 cl->connection = co;
1106 co = connection_create(cl);
1110 if (co->state == Conn_Connecting)
1112 cl->state = Client_Connecting;
1113 iochan_setflag(co->iochan, EVENT_OUTPUT);
1115 else if (co->state == Conn_Open)
1117 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1118 cl->state = Client_Idle;
1119 iochan_setflag(co->iochan, EVENT_OUTPUT);
1127 #ifdef GAGA // Moved to database.c
1129 // This function will most likely vanish when a proper target profile mechanism is
1131 void load_simpletargets(const char *fn)
1133 FILE *f = fopen(fn, "r");
1138 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1142 while (fgets(line, 255, f))
1147 struct database *database;
1149 if (strncmp(line, "target ", 7))
1151 line[strlen(line) - 1] = '\0';
1153 if ((name = strchr(line, ';')))
1157 if ((db = strchr(url, '/')))
1162 yaz_log(YLOG_LOG, "Target: %s, '%s'", url, db);
1163 for (host = hosts; host; host = host->next)
1164 if (!strcmp((const char *) url, host->hostport))
1168 struct addrinfo *addrinfo, hints;
1171 unsigned char addrbuf[4];
1174 host = xmalloc(sizeof(struct host));
1175 host->hostport = xstrdup(url);
1176 host->connections = 0;
1178 if ((port = strchr(url, ':')))
1184 hints.ai_family = PF_INET;
1185 hints.ai_socktype = SOCK_STREAM;
1186 hints.ai_protocol = IPPROTO_TCP;
1187 hints.ai_addrlen = 0;
1189 hints.ai_canonname = 0;
1191 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1193 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1195 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1196 xfree(host->hostport);
1200 assert(addrinfo->ai_family == PF_INET);
1201 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1202 sprintf(ipport, "%u.%u.%u.%u:%s",
1203 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1204 host->ipport = xstrdup(ipport);
1205 freeaddrinfo(addrinfo);
1209 database = xmalloc(sizeof(struct database));
1210 database->host = host;
1211 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1212 strcpy(database->url, url);
1213 strcat(database->url, "/");
1214 strcat(database->url, db);
1216 database->name = xstrdup(name);
1220 database->databases = xmalloc(2 * sizeof(char *));
1221 database->databases[0] = xstrdup(db);
1222 database->databases[1] = 0;
1223 database->errors = 0;
1224 database->qprofile = 0;
1225 database->rprofile = database_retrieval_profile(database);
1226 database->next = databases;
1227 databases = database;
1235 static struct client *client_create(void)
1238 if (client_freelist)
1240 r = client_freelist;
1241 client_freelist = client_freelist->next;
1244 r = xmalloc(sizeof(struct client));
1253 r->state = Client_Disconnected;
1258 void client_destroy(struct client *c)
1260 struct session *se = c->session;
1261 if (c == se->clients)
1262 se->clients = c->next;
1266 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1272 connection_release(c->connection);
1273 c->next = client_freelist;
1274 client_freelist = c;
1277 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1279 s->watchlist[what].fun = fun;
1280 s->watchlist[what].data = data;
1283 void session_alert_watch(struct session *s, int what)
1285 if (!s->watchlist[what].fun)
1287 (*s->watchlist[what].fun)(s->watchlist[what].data);
1288 s->watchlist[what].fun = 0;
1289 s->watchlist[what].data = 0;
1292 //callback for grep_databases
1293 static void select_targets_callback(void *context, struct database *db)
1295 struct session *se = (struct session*) context;
1296 struct client *cl = client_create();
1299 cl->next = se->clients;
1303 // This should be extended with parameters to control selection criteria
1304 // Associates a set of clients with a session;
1305 int select_targets(struct session *se, struct database_criterion *crit)
1308 client_destroy(se->clients);
1310 return grep_databases(se, crit, select_targets_callback);
1313 int session_active_clients(struct session *s)
1318 for (c = s->clients; c; c = c->next)
1319 if (c->connection && (c->state == Client_Connecting ||
1320 c->state == Client_Initializing ||
1321 c->state == Client_Searching ||
1322 c->state == Client_Presenting))
1328 // parses crit1=val1,crit2=val2|val3,...
1329 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1331 struct database_criterion *res = 0;
1338 nmem_strsplit(m, ",", buf, &values, &num);
1339 for (i = 0; i < num; i++)
1344 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1345 char *eq = strchr(values[i], '=');
1348 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1352 new->name = values[i];
1353 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1355 for (subi = 0; subi < subnum; subi++)
1357 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1358 newv->value = subvalues[subi];
1359 newv->next = new->values;
1368 char *search(struct session *se, char *query, char *filter)
1370 int live_channels = 0;
1372 struct database_criterion *criteria;
1374 yaz_log(YLOG_DEBUG, "Search");
1376 nmem_reset(se->nmem);
1377 criteria = parse_filter(se->nmem, filter);
1378 strcpy(se->query, query);
1380 // Release any existing clients
1381 select_targets(se, criteria);
1382 for (cl = se->clients; cl; cl = cl->next)
1384 if (client_prep_connection(cl))
1389 int maxrecs = live_channels * global_parameters.toget;
1390 se->num_termlists = 0;
1391 se->reclist = reclist_create(se->nmem, maxrecs);
1392 // This will be initialized in send_search()
1394 se->total_records = se->total_hits = se->total_merged = 0;
1395 se->expected_maxrecs = maxrecs;
1403 void destroy_session(struct session *s)
1405 yaz_log(YLOG_LOG, "Destroying session");
1407 client_destroy(s->clients);
1408 nmem_destroy(s->nmem);
1409 wrbuf_destroy(s->wrbuf);
1412 struct session *new_session()
1415 struct session *session = xmalloc(sizeof(*session));
1417 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1419 session->total_hits = 0;
1420 session->total_records = 0;
1421 session->num_termlists = 0;
1422 session->reclist = 0;
1423 session->requestid = -1;
1424 session->clients = 0;
1425 session->expected_maxrecs = 0;
1426 session->query[0] = '\0';
1427 session->nmem = nmem_create();
1428 session->wrbuf = wrbuf_alloc();
1429 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1431 session->watchlist[i].data = 0;
1432 session->watchlist[i].fun = 0;
1438 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1440 static struct hitsbytarget res[1000]; // FIXME MM
1444 for (cl = se->clients; cl; cl = cl->next)
1446 res[*count].id = cl->database->url;
1447 res[*count].name = cl->database->name;
1448 res[*count].hits = cl->hits;
1449 res[*count].records = cl->records;
1450 res[*count].diagnostic = cl->diagnostic;
1451 res[*count].state = client_states[cl->state];
1452 res[*count].connected = cl->connection ? 1 : 0;
1459 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1463 for (i = 0; i < s->num_termlists; i++)
1464 if (!strcmp((const char *) s->termlists[i].name, name))
1465 return termlist_highscore(s->termlists[i].termlist, num);
1469 #ifdef MISSING_HEADERS
1470 void report_nmem_stats(void)
1472 size_t in_use, is_free;
1474 nmem_get_memory_in_use(&in_use);
1475 nmem_get_memory_free(&is_free);
1477 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1478 (long) in_use, (long) is_free);
1482 struct record_cluster *show_single(struct session *s, int id)
1484 struct record_cluster *r;
1486 reclist_rewind(s->reclist);
1487 while ((r = reclist_read_record(s->reclist)))
1493 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1494 int *num, int *total, int *sumhits, NMEM nmem_show)
1496 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1497 * sizeof(struct record_cluster *));
1498 struct reclist_sortparms *spp;
1501 yaz_timing_t t = yaz_timing_create();
1504 for (spp = sp; spp; spp = spp->next)
1505 if (spp->type == Metadata_sortkey_relevance)
1507 relevance_prepare_read(s->relevance, s->reclist);
1510 reclist_sort(s->reclist, sp);
1512 *total = s->reclist->num_records;
1513 *sumhits = s->total_hits;
1515 for (i = 0; i < start; i++)
1516 if (!reclist_read_record(s->reclist))
1523 for (i = 0; i < *num; i++)
1525 struct record_cluster *r = reclist_read_record(s->reclist);
1535 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1536 yaz_timing_get_real(t), yaz_timing_get_user(t),
1537 yaz_timing_get_sys(t));
1538 yaz_timing_destroy(&t);
1543 void statistics(struct session *se, struct statistics *stat)
1548 memset(stat, 0, sizeof(*stat));
1549 for (cl = se->clients; cl; cl = cl->next)
1551 if (!cl->connection)
1552 stat->num_no_connection++;
1555 case Client_Connecting: stat->num_connecting++; break;
1556 case Client_Initializing: stat->num_initializing++; break;
1557 case Client_Searching: stat->num_searching++; break;
1558 case Client_Presenting: stat->num_presenting++; break;
1559 case Client_Idle: stat->num_idle++; break;
1560 case Client_Failed: stat->num_failed++; break;
1561 case Client_Error: stat->num_error++; break;
1566 stat->num_hits = se->total_hits;
1567 stat->num_records = se->total_records;
1569 stat->num_clients = count;
1572 static void start_http_listener(void)
1575 struct conf_server *ser = global_parameters.server;
1577 if (*global_parameters.listener_override)
1578 strcpy(hp, global_parameters.listener_override);
1581 strcpy(hp, ser->host ? ser->host : "");
1586 sprintf(hp + strlen(hp), "%d", ser->port);
1592 static void start_proxy(void)
1595 struct conf_server *ser = global_parameters.server;
1597 if (*global_parameters.proxy_override)
1598 strcpy(hp, global_parameters.proxy_override);
1599 else if (ser->proxy_host || ser->proxy_port)
1601 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1602 if (ser->proxy_port)
1606 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1612 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1615 static void start_zproxy(void)
1617 struct conf_server *ser = global_parameters.server;
1619 if (*global_parameters.zproxy_override){
1620 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1621 global_parameters.zproxy_override);
1625 else if (ser->zproxy_host || ser->zproxy_port)
1629 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1630 if (ser->zproxy_port)
1637 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1639 strcpy(global_parameters.zproxy_override, hp);
1640 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1641 global_parameters.zproxy_override);
1650 int main(int argc, char **argv)
1655 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1656 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1658 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1660 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1664 if (!read_config(arg))
1668 strcpy(global_parameters.listener_override, arg);
1671 strcpy(global_parameters.proxy_override, arg);
1674 strcpy(global_parameters.zproxy_override, arg);
1677 strcpy(global_parameters.settings_path_override, arg);
1680 load_simpletargets(arg);
1683 global_parameters.dump_records = 1;
1686 fprintf(stderr, "Usage: pazpar2\n"
1688 " -h [host:]port (REST protocol listener)\n"
1690 " -s simpletargetfile\n"
1691 " -p hostname[:portno] (HTTP proxy)\n"
1692 " -z hostname[:portno] (Z39.50 proxy)\n"
1693 " -d (show internal records)\n");
1700 yaz_log(YLOG_FATAL, "Load config with -f");
1703 global_parameters.server = config->servers;
1705 start_http_listener();
1709 if (*global_parameters.settings_path_override)
1710 settings_read(global_parameters.settings_path_override);
1711 else if (global_parameters.server->settings)
1712 settings_read(global_parameters.server->settings);
1714 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may well ensue!");
1715 prepare_databases();
1716 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1717 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1719 event_loop(&channel_list);
1727 * indent-tabs-mode: nil
1729 * vim: shiftwidth=4 tabstop=8 expandtab