1 /* $Id: pazpar2.c,v 1.69 2007-04-10 01:19:56 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 void session_alert_watch(struct session *s, int what);
52 char *session_setting_oneval(struct session *s, struct database *db, int offset);
54 IOCHAN channel_list = 0; // Master list of connections we're handling events to
56 static struct connection *connection_freelist = 0;
57 static struct client *client_freelist = 0;
59 static char *client_states[] = {
63 "Client_Initializing",
68 "Client_Disconnected",
72 // Note: Some things in this structure will eventually move to configuration
73 struct parameters global_parameters =
83 "Index Data PazPar2 (MasterKey)",
93 static int send_apdu(struct client *c, Z_APDU *a)
95 struct connection *co = c->connection;
99 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
101 odr_perror(global_parameters.odr_out, "Encoding APDU");
104 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
105 r = cs_put(co->link, buf, len);
108 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
113 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
116 odr_reset(global_parameters.odr_out); /* release the APDU structure */
117 co->state = Conn_Waiting;
121 // Set authentication token in init if one is set for the client
122 // TODO: Extend this to handle other schemes than open (should be simple)
123 static void init_authentication(struct client *cl, Z_InitRequest *req)
125 struct database *db = cl->database;
126 struct session *se = cl->session;
127 char *auth = session_setting_oneval(se, db, PZ_AUTHENTICATION);
131 Z_IdAuthentication *idAuth = odr_malloc(global_parameters.odr_out,
133 idAuth->which = Z_IdAuthentication_open;
134 idAuth->u.open = auth;
135 req->idAuthentication = idAuth;
139 static void send_init(IOCHAN i)
142 struct connection *co = iochan_getdata(i);
143 struct client *cl = co->client;
144 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
146 a->u.initRequest->implementationId = global_parameters.implementationId;
147 a->u.initRequest->implementationName = global_parameters.implementationName;
148 a->u.initRequest->implementationVersion =
149 global_parameters.implementationVersion;
150 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
151 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
152 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
154 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
155 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
156 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
158 init_authentication(cl, a->u.initRequest);
160 /* add virtual host if tunneling through Z39.50 proxy */
162 if (0 < strlen(global_parameters.zproxy_override)
163 && 0 < strlen(cl->database->url))
164 yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo,
165 global_parameters.odr_out, VAL_PROXY,
166 1, cl->database->url);
168 if (send_apdu(cl, a) >= 0)
170 iochan_setflags(i, EVENT_INPUT);
171 cl->state = Client_Initializing;
174 cl->state = Client_Error;
175 odr_reset(global_parameters.odr_out);
178 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
186 pull_terms(nmem, n->u.p[0], termlist, num);
187 pull_terms(nmem, n->u.p[1], termlist, num);
190 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
197 // Extract terms from query into null-terminated termlist
198 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
202 pull_terms(nmem, query, termlist, &num);
206 static void send_search(IOCHAN i)
208 struct connection *co = iochan_getdata(i);
209 struct client *cl = co->client;
210 struct session *se = cl->session;
211 struct database *db = cl->database;
212 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
213 int ndb, cerror, cpos;
216 struct ccl_rpn_node *cn;
217 int ssub = 0, lslb = 100000, mspn = 10;
221 yaz_log(YLOG_DEBUG, "Sending search");
223 cn = ccl_find_str(db->ccl_map, se->query, &cerror, &cpos);
229 // Initialize relevance structure with query terms
231 extract_terms(se->nmem, cn, p);
232 se->relevance = relevance_create(se->nmem, (const char **) p,
233 se->expected_maxrecs);
236 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
238 zquery->which = Z_Query_type_1;
239 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
242 for (ndb = 0; db->databases[ndb]; ndb++)
244 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
245 for (ndb = 0; db->databases[ndb]; ndb++)
246 databaselist[ndb] = db->databases[ndb];
248 if (!(piggyback = session_setting_oneval(se, db, PZ_PIGGYBACK)) || *piggyback == '1')
250 if ((recsyn = session_setting_oneval(se, db, PZ_REQUESTSYNTAX)))
251 a->u.searchRequest->preferredRecordSyntax =
252 yaz_str_to_z3950oid(global_parameters.odr_out,
253 CLASS_RECSYN, recsyn);
254 a->u.searchRequest->smallSetUpperBound = &ssub;
255 a->u.searchRequest->largeSetLowerBound = &lslb;
256 a->u.searchRequest->mediumSetPresentNumber = &mspn;
258 a->u.searchRequest->resultSetName = "Default";
259 a->u.searchRequest->databaseNames = databaselist;
260 a->u.searchRequest->num_databaseNames = ndb;
262 if (send_apdu(cl, a) >= 0)
264 iochan_setflags(i, EVENT_INPUT);
265 cl->state = Client_Searching;
266 cl->requestid = se->requestid;
269 cl->state = Client_Error;
271 odr_reset(global_parameters.odr_out);
274 static void send_present(IOCHAN i)
276 struct connection *co = iochan_getdata(i);
277 struct client *cl = co->client;
278 struct session *se = cl->session;
279 struct database *db = cl->database;
280 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
282 int start = cl->records + 1;
285 toget = global_parameters.chunk;
286 if (toget > global_parameters.toget - cl->records)
287 toget = global_parameters.toget - cl->records;
288 if (toget > cl->hits - cl->records)
289 toget = cl->hits - cl->records;
291 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
293 a->u.presentRequest->resultSetStartPoint = &start;
294 a->u.presentRequest->numberOfRecordsRequested = &toget;
296 a->u.presentRequest->resultSetId = "Default";
298 if ((recsyn = session_setting_oneval(se, db, PZ_REQUESTSYNTAX)))
299 a->u.presentRequest->preferredRecordSyntax =
300 yaz_str_to_z3950oid(global_parameters.odr_out,
301 CLASS_RECSYN, recsyn);
303 if (send_apdu(cl, a) >= 0)
305 iochan_setflags(i, EVENT_INPUT);
306 cl->state = Client_Presenting;
309 cl->state = Client_Error;
310 odr_reset(global_parameters.odr_out);
313 static void do_initResponse(IOCHAN i, Z_APDU *a)
315 struct connection *co = iochan_getdata(i);
316 struct client *cl = co->client;
317 Z_InitResponse *r = a->u.initResponse;
319 yaz_log(YLOG_DEBUG, "Init response %s", cl->database->url);
323 cl->state = Client_Idle;
326 cl->state = Client_Failed; // FIXME need to do something to the connection
329 static void do_searchResponse(IOCHAN i, Z_APDU *a)
331 struct connection *co = iochan_getdata(i);
332 struct client *cl = co->client;
333 struct session *se = cl->session;
334 Z_SearchResponse *r = a->u.searchResponse;
336 yaz_log(YLOG_DEBUG, "Search response %s (status=%d)",
337 cl->database->url, *r->searchStatus);
339 if (*r->searchStatus)
341 cl->hits = *r->resultCount;
342 se->total_hits += cl->hits;
343 if (r->presentStatus && !*r->presentStatus && r->records)
345 yaz_log(YLOG_DEBUG, "Records in search response %s",
347 ingest_records(cl, r->records);
349 cl->state = Client_Idle;
354 cl->state = Client_Error;
356 Z_Records *recs = r->records;
357 if (recs->which == Z_Records_NSD)
360 "Search response: Non-surrogate diagnostic %s",
362 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
363 cl->state = Client_Error;
369 static void do_closeResponse(IOCHAN i, Z_APDU *a)
371 struct connection *co = iochan_getdata(i);
372 struct client *cl = co->client;
373 /* Z_Close *r = a->u.close; */
375 yaz_log(YLOG_WARN, "Close response %s", cl->database->url);
377 cl->state = Client_Failed;
378 connection_destroy(co);
382 char *normalize_mergekey(char *buf, int skiparticle)
384 char *p = buf, *pout = buf;
389 char articles[] = "the den der die des an a "; // must end in space
391 while (*p && !isalnum(*p))
394 while (*p && *p != ' ' && pout - firstword < 62)
395 *(pout++) = tolower(*(p++));
398 if (!strstr(articles, firstword))
405 while (*p && !isalnum(*p))
408 *(pout++) = tolower(*(p++));
411 while (*p && !isalnum(*p))
418 while (pout > buf && *pout == ' ');
423 static void add_facet(struct session *s, const char *type, const char *value)
429 for (i = 0; i < s->num_termlists; i++)
430 if (!strcmp(s->termlists[i].name, type))
432 if (i == s->num_termlists)
434 if (i == SESSION_MAX_TERMLISTS)
436 yaz_log(YLOG_FATAL, "Too many termlists");
439 s->termlists[i].name = nmem_strdup(s->nmem, type);
440 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
441 s->num_termlists = i + 1;
443 termlist_insert(s->termlists[i].termlist, value);
446 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
448 struct database_retrievalmap *m;
449 struct database *db = cl->database;
453 // First normalize to XML
458 if (rec->which != Z_External_octet)
460 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
464 buf = (char*) rec->u.octet_aligned->buf;
465 len = rec->u.octet_aligned->len;
466 if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
468 yaz_log(YLOG_WARN, "Failed to decode MARC %s",
472 if (yaz_marc_write_xml(db->yaz_marc, &res,
473 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
475 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
479 rdoc = xmlNewDoc((xmlChar *) "1.0");
480 xmlDocSetRootElement(rdoc, res);
484 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
488 if (global_parameters.dump_records)
490 fprintf(stderr, "Input Record (normalized):\n----------------\n");
491 #if LIBXML_VERSION >= 20600
492 xmlDocFormatDump(stderr, rdoc, 1);
494 xmlDocDump(stderr, rdoc);
498 for (m = db->map; m; m = m->next)
501 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
503 yaz_log(YLOG_WARN, "XSLT transformation failed");
509 if (global_parameters.dump_records)
511 fprintf(stderr, "Record:\n----------------\n");
512 #if LIBXML_VERSION >= 20600
513 xmlDocFormatDump(stderr, rdoc, 1);
515 xmlDocDump(stderr, rdoc);
521 // Extract what appears to be years from buf, storing highest and
523 static int extract_years(const char *buf, int *first, int *last)
532 while (*buf && !isdigit(*buf))
535 for (e = buf; *e && isdigit(*e); e++)
539 int value = atoi(buf);
540 if (*first < 0 || value < *first)
542 if (*last < 0 || value > *last)
550 static struct record *ingest_record(struct client *cl, Z_External *rec)
552 xmlDoc *xdoc = normalize_record(cl, rec);
555 struct record_cluster *cluster;
556 struct session *se = cl->session;
557 xmlChar *mergekey, *mergekey_norm;
560 struct conf_service *service = global_parameters.server->service;
565 root = xmlDocGetRootElement(xdoc);
566 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
568 yaz_log(YLOG_WARN, "No mergekey found in record");
573 res = nmem_malloc(se->nmem, sizeof(struct record));
576 res->metadata = nmem_malloc(se->nmem,
577 sizeof(struct record_metadata*) * service->num_metadata);
578 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
580 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
582 normalize_mergekey((char *) mergekey_norm, 0);
584 cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm,
586 if (global_parameters.dump_records)
587 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
588 cl->database->url, cl->records);
591 /* no room for record */
595 relevance_newrec(se->relevance, cluster);
597 for (n = root->children; n; n = n->next)
605 if (n->type != XML_ELEMENT_NODE)
607 if (!strcmp((const char *) n->name, "metadata"))
609 struct conf_metadata *md = 0;
610 struct conf_sortkey *sk = 0;
611 struct record_metadata **wheretoput, *newm;
615 type = xmlGetProp(n, (xmlChar *) "type");
616 value = xmlNodeListGetString(xdoc, n->children, 0);
621 // First, find out what field we're looking at
622 for (imeta = 0; imeta < service->num_metadata; imeta++)
623 if (!strcmp((const char *) type, service->metadata[imeta].name))
625 md = &service->metadata[imeta];
626 if (md->sortkey_offset >= 0)
627 sk = &service->sortkeys[md->sortkey_offset];
632 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
636 // Find out where we are putting it
637 if (md->merge == Metadata_merge_no)
638 wheretoput = &res->metadata[imeta];
640 wheretoput = &cluster->metadata[imeta];
643 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
645 if (md->type == Metadata_type_generic)
648 for (p = (char *) value; *p && isspace(*p); p++)
650 for (pe = p + strlen(p) - 1;
651 pe > p && strchr(" ,/.:([", *pe); pe--)
653 newm->data.text = nmem_strdup(se->nmem, p);
656 else if (md->type == Metadata_type_year)
658 if (extract_years((char *) value, &first, &last) < 0)
663 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
666 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
668 yaz_log(YLOG_WARN, "Only range merging supported for years");
671 if (md->merge == Metadata_merge_unique)
673 struct record_metadata *mnode;
674 for (mnode = *wheretoput; mnode; mnode = mnode->next)
675 if (!strcmp((const char *) mnode->data.text, newm->data.text))
679 newm->next = *wheretoput;
683 else if (md->merge == Metadata_merge_longest)
686 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
691 char *s = nmem_strdup(se->nmem, newm->data.text);
692 if (!cluster->sortkeys[md->sortkey_offset])
693 cluster->sortkeys[md->sortkey_offset] =
694 nmem_malloc(se->nmem, sizeof(union data_types));
695 normalize_mergekey(s,
696 (sk->type == Metadata_sortkey_skiparticle));
697 cluster->sortkeys[md->sortkey_offset]->text = s;
701 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
703 newm->next = *wheretoput;
706 else if (md->merge == Metadata_merge_range)
708 assert(md->type == Metadata_type_year);
712 (*wheretoput)->data.number.min = first;
713 (*wheretoput)->data.number.max = last;
715 cluster->sortkeys[md->sortkey_offset] = &newm->data;
719 if (first < (*wheretoput)->data.number.min)
720 (*wheretoput)->data.number.min = first;
721 if (last > (*wheretoput)->data.number.max)
722 (*wheretoput)->data.number.max = last;
727 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
728 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
733 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
736 relevance_countwords(se->relevance, cluster,
737 (char *) value, md->rank);
740 if (md->type == Metadata_type_year)
743 sprintf(year, "%d", last);
744 add_facet(se, (char *) type, year);
747 sprintf(year, "%d", first);
748 add_facet(se, (char *) type, year);
752 add_facet(se, (char *) type, (char *) value);
759 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
768 relevance_donerecord(se->relevance, cluster);
774 // Retrieve first defined value for 'name' for given database.
775 // Will be extended to take into account user associated with session
776 char *session_setting_oneval(struct session *s, struct database *db, int offset)
778 if (!db->settings[offset])
780 return db->settings[offset]->value;
783 static void ingest_records(struct client *cl, Z_Records *r)
786 yaz_timing_t t = yaz_timing_create();
789 struct session *s = cl->session;
790 Z_NamePlusRecordList *rlist;
793 if (r->which != Z_Records_DBOSD)
795 rlist = r->u.databaseOrSurDiagnostics;
796 for (i = 0; i < rlist->num_records; i++)
798 Z_NamePlusRecord *npr = rlist->records[i];
801 if (npr->which != Z_NamePlusRecord_databaseRecord)
804 "Unexpected record type, probably diagnostic %s",
809 rec = ingest_record(cl, npr->u.databaseRecord);
813 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
814 session_alert_watch(s, SESSION_WATCH_RECORDS);
818 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
819 yaz_timing_get_real(t), yaz_timing_get_user(t),
820 yaz_timing_get_sys(t));
821 yaz_timing_destroy(&t);
825 static void do_presentResponse(IOCHAN i, Z_APDU *a)
827 struct connection *co = iochan_getdata(i);
828 struct client *cl = co->client;
829 Z_PresentResponse *r = a->u.presentResponse;
832 Z_Records *recs = r->records;
833 if (recs->which == Z_Records_NSD)
835 yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
837 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
838 cl->state = Client_Error;
842 if (!*r->presentStatus && cl->state != Client_Error)
844 yaz_log(YLOG_DEBUG, "Good Present response %s",
846 ingest_records(cl, r->records);
847 cl->state = Client_Idle;
849 else if (*r->presentStatus)
851 yaz_log(YLOG_WARN, "Bad Present response %s",
853 cl->state = Client_Error;
857 static void handler(IOCHAN i, int event)
859 struct connection *co = iochan_getdata(i);
860 struct client *cl = co->client;
861 struct session *se = 0;
867 yaz_log(YLOG_WARN, "Destroying orphan connection");
868 connection_destroy(co);
872 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
875 socklen_t errlen = sizeof(errcode);
877 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
878 &errlen) < 0 || errcode != 0)
885 yaz_log(YLOG_DEBUG, "Connect OK");
886 co->state = Conn_Open;
888 cl->state = Client_Connected;
892 else if (event & EVENT_INPUT)
894 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
898 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s",
900 connection_destroy(co);
905 yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->url);
906 connection_destroy(co);
909 else if (len > 1) // We discard input if we have no connection
911 co->state = Conn_Open;
913 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
917 odr_reset(global_parameters.odr_in);
918 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
919 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
926 case Z_APDU_initResponse:
927 do_initResponse(i, a);
929 case Z_APDU_searchResponse:
930 do_searchResponse(i, a);
932 case Z_APDU_presentResponse:
933 do_presentResponse(i, a);
936 do_closeResponse(i, a);
940 "Unexpected Z39.50 response from %s",
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 if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1051 yaz_log(YLOG_WARN|YLOG_ERRNO,
1052 "Lookup of IP address %s failed",
1053 global_parameters.zproxy_override);
1058 res = cs_connect(link, addr);
1061 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
1065 if ((new = connection_freelist))
1066 connection_freelist = new->next;
1069 new = xmalloc(sizeof (struct connection));
1073 new->state = Conn_Connecting;
1074 new->host = cl->database->host;
1075 new->next = new->host->connections;
1076 new->host->connections = new;
1078 cl->connection = new;
1081 new->iochan = iochan_create(cs_fileno(link), handler, 0);
1082 iochan_setdata(new->iochan, new);
1083 new->iochan->next = channel_list;
1084 channel_list = new->iochan;
1088 // Close connection and set state to error
1089 static void client_fatal(struct client *cl)
1091 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
1092 connection_destroy(cl->connection);
1093 cl->state = Client_Error;
1096 // Ensure that client has a connection associated
1097 static int client_prep_connection(struct client *cl)
1099 struct connection *co;
1100 struct session *se = cl->session;
1101 struct host *host = cl->database->host;
1103 co = cl->connection;
1105 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1109 // See if someone else has an idle connection
1110 // We should look at timestamps here to select the longest-idle connection
1111 for (co = host->connections; co; co = co->next)
1112 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1116 connection_release(co);
1117 cl->connection = co;
1121 co = connection_create(cl);
1125 if (co->state == Conn_Connecting)
1127 cl->state = Client_Connecting;
1128 iochan_setflag(co->iochan, EVENT_OUTPUT);
1130 else if (co->state == Conn_Open)
1132 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1133 cl->state = Client_Idle;
1134 iochan_setflag(co->iochan, EVENT_OUTPUT);
1142 static struct client *client_create(void)
1145 if (client_freelist)
1147 r = client_freelist;
1148 client_freelist = client_freelist->next;
1151 r = xmalloc(sizeof(struct client));
1160 r->state = Client_Disconnected;
1165 void client_destroy(struct client *c)
1167 struct session *se = c->session;
1168 if (c == se->clients)
1169 se->clients = c->next;
1173 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1179 connection_release(c->connection);
1180 c->next = client_freelist;
1181 client_freelist = c;
1184 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1186 s->watchlist[what].fun = fun;
1187 s->watchlist[what].data = data;
1190 void session_alert_watch(struct session *s, int what)
1192 if (!s->watchlist[what].fun)
1194 (*s->watchlist[what].fun)(s->watchlist[what].data);
1195 s->watchlist[what].fun = 0;
1196 s->watchlist[what].data = 0;
1199 //callback for grep_databases
1200 static void select_targets_callback(void *context, struct database *db)
1202 struct session *se = (struct session*) context;
1203 struct client *cl = client_create();
1206 cl->next = se->clients;
1210 // Associates a set of clients with a session;
1211 int select_targets(struct session *se, struct database_criterion *crit)
1214 client_destroy(se->clients);
1216 return grep_databases(se, crit, select_targets_callback);
1219 int session_active_clients(struct session *s)
1224 for (c = s->clients; c; c = c->next)
1225 if (c->connection && (c->state == Client_Connecting ||
1226 c->state == Client_Initializing ||
1227 c->state == Client_Searching ||
1228 c->state == Client_Presenting))
1234 // parses crit1=val1,crit2=val2|val3,...
1235 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1237 struct database_criterion *res = 0;
1244 nmem_strsplit(m, ",", buf, &values, &num);
1245 for (i = 0; i < num; i++)
1250 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1251 char *eq = strchr(values[i], '=');
1254 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1258 new->name = values[i];
1259 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1261 for (subi = 0; subi < subnum; subi++)
1263 struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1264 newv->value = subvalues[subi];
1265 newv->next = new->values;
1274 char *search(struct session *se, char *query, char *filter)
1276 int live_channels = 0;
1278 struct database_criterion *criteria;
1280 yaz_log(YLOG_DEBUG, "Search");
1282 nmem_reset(se->nmem);
1283 criteria = parse_filter(se->nmem, filter);
1284 strcpy(se->query, query);
1286 select_targets(se, criteria);
1287 for (cl = se->clients; cl; cl = cl->next)
1289 if (client_prep_connection(cl))
1294 int maxrecs = live_channels * global_parameters.toget;
1295 se->num_termlists = 0;
1296 se->reclist = reclist_create(se->nmem, maxrecs);
1297 // This will be initialized in send_search()
1299 se->total_records = se->total_hits = se->total_merged = 0;
1300 se->expected_maxrecs = maxrecs;
1308 void destroy_session(struct session *s)
1310 yaz_log(YLOG_LOG, "Destroying session");
1312 client_destroy(s->clients);
1313 nmem_destroy(s->nmem);
1314 wrbuf_destroy(s->wrbuf);
1317 struct session *new_session(NMEM nmem)
1320 struct session *session = nmem_malloc(nmem, sizeof(*session));
1322 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1324 session->total_hits = 0;
1325 session->total_records = 0;
1326 session->num_termlists = 0;
1327 session->reclist = 0;
1328 session->requestid = -1;
1329 session->clients = 0;
1330 session->expected_maxrecs = 0;
1331 session->query[0] = '\0';
1332 session->session_nmem = nmem;
1333 session->nmem = nmem_create();
1334 session->wrbuf = wrbuf_alloc();
1335 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1337 session->watchlist[i].data = 0;
1338 session->watchlist[i].fun = 0;
1344 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1346 static struct hitsbytarget res[1000]; // FIXME MM
1350 for (cl = se->clients; cl; cl = cl->next)
1352 res[*count].id = cl->database->url;
1353 res[*count].name = cl->database->name;
1354 res[*count].hits = cl->hits;
1355 res[*count].records = cl->records;
1356 res[*count].diagnostic = cl->diagnostic;
1357 res[*count].state = client_states[cl->state];
1358 res[*count].connected = cl->connection ? 1 : 0;
1365 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1369 for (i = 0; i < s->num_termlists; i++)
1370 if (!strcmp((const char *) s->termlists[i].name, name))
1371 return termlist_highscore(s->termlists[i].termlist, num);
1375 #ifdef MISSING_HEADERS
1376 void report_nmem_stats(void)
1378 size_t in_use, is_free;
1380 nmem_get_memory_in_use(&in_use);
1381 nmem_get_memory_free(&is_free);
1383 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1384 (long) in_use, (long) is_free);
1388 struct record_cluster *show_single(struct session *s, int id)
1390 struct record_cluster *r;
1392 reclist_rewind(s->reclist);
1393 while ((r = reclist_read_record(s->reclist)))
1399 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1400 int *num, int *total, int *sumhits, NMEM nmem_show)
1402 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1403 * sizeof(struct record_cluster *));
1404 struct reclist_sortparms *spp;
1407 yaz_timing_t t = yaz_timing_create();
1410 for (spp = sp; spp; spp = spp->next)
1411 if (spp->type == Metadata_sortkey_relevance)
1413 relevance_prepare_read(s->relevance, s->reclist);
1416 reclist_sort(s->reclist, sp);
1418 *total = s->reclist->num_records;
1419 *sumhits = s->total_hits;
1421 for (i = 0; i < start; i++)
1422 if (!reclist_read_record(s->reclist))
1429 for (i = 0; i < *num; i++)
1431 struct record_cluster *r = reclist_read_record(s->reclist);
1441 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1442 yaz_timing_get_real(t), yaz_timing_get_user(t),
1443 yaz_timing_get_sys(t));
1444 yaz_timing_destroy(&t);
1449 void statistics(struct session *se, struct statistics *stat)
1454 memset(stat, 0, sizeof(*stat));
1455 for (cl = se->clients; cl; cl = cl->next)
1457 if (!cl->connection)
1458 stat->num_no_connection++;
1461 case Client_Connecting: stat->num_connecting++; break;
1462 case Client_Initializing: stat->num_initializing++; break;
1463 case Client_Searching: stat->num_searching++; break;
1464 case Client_Presenting: stat->num_presenting++; break;
1465 case Client_Idle: stat->num_idle++; break;
1466 case Client_Failed: stat->num_failed++; break;
1467 case Client_Error: stat->num_error++; break;
1472 stat->num_hits = se->total_hits;
1473 stat->num_records = se->total_records;
1475 stat->num_clients = count;
1478 static void start_http_listener(void)
1481 struct conf_server *ser = global_parameters.server;
1483 if (*global_parameters.listener_override)
1484 strcpy(hp, global_parameters.listener_override);
1487 strcpy(hp, ser->host ? ser->host : "");
1492 sprintf(hp + strlen(hp), "%d", ser->port);
1498 static void start_proxy(void)
1501 struct conf_server *ser = global_parameters.server;
1503 if (*global_parameters.proxy_override)
1504 strcpy(hp, global_parameters.proxy_override);
1505 else if (ser->proxy_host || ser->proxy_port)
1507 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1508 if (ser->proxy_port)
1512 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1518 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1521 static void start_zproxy(void)
1523 struct conf_server *ser = global_parameters.server;
1525 if (*global_parameters.zproxy_override){
1526 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1527 global_parameters.zproxy_override);
1531 else if (ser->zproxy_host || ser->zproxy_port)
1535 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1536 if (ser->zproxy_port)
1543 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1545 strcpy(global_parameters.zproxy_override, hp);
1546 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
1547 global_parameters.zproxy_override);
1556 int main(int argc, char **argv)
1561 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1562 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1564 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1566 while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1570 if (!read_config(arg))
1574 strcpy(global_parameters.listener_override, arg);
1577 strcpy(global_parameters.proxy_override, arg);
1580 strcpy(global_parameters.zproxy_override, arg);
1583 strcpy(global_parameters.settings_path_override, arg);
1586 load_simpletargets(arg);
1589 global_parameters.dump_records = 1;
1592 fprintf(stderr, "Usage: pazpar2\n"
1594 " -h [host:]port (REST protocol listener)\n"
1596 " -s simpletargetfile\n"
1597 " -p hostname[:portno] (HTTP proxy)\n"
1598 " -z hostname[:portno] (Z39.50 proxy)\n"
1599 " -d (show internal records)\n");
1606 yaz_log(YLOG_FATAL, "Load config with -f");
1609 global_parameters.server = config->servers;
1611 start_http_listener();
1615 if (*global_parameters.settings_path_override)
1616 settings_read(global_parameters.settings_path_override);
1617 else if (global_parameters.server->settings)
1618 settings_read(global_parameters.server->settings);
1620 yaz_log(YLOG_WARN, "No settings-directory specified. Problems may well ensue!");
1621 prepare_databases();
1622 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1623 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1625 event_loop(&channel_list);
1633 * indent-tabs-mode: nil
1635 * vim: shiftwidth=4 tabstop=8 expandtab