1 /* $Id: pazpar2.c,v 1.6 2006-12-27 21:11:10 quinn Exp $ */;
8 #include <sys/socket.h>
14 #include <yaz/comstack.h>
15 #include <yaz/tcpip.h>
16 #include <yaz/proto.h>
17 #include <yaz/readconf.h>
18 #include <yaz/pquery.h>
19 #include <yaz/yaz-util.h>
26 #include "termlists.h"
28 #include "relevance.h"
31 #define PAZPAR2_VERSION "0.1"
34 static void client_fatal(struct client *cl);
35 static void connection_destroy(struct connection *co);
36 static int client_prep_connection(struct client *cl);
37 static void ingest_records(struct client *cl, Z_Records *r);
38 void session_alert_watch(struct session *s, int what);
40 IOCHAN channel_list = 0; // Master list of connections we're handling events to
42 static struct connection *connection_freelist = 0;
43 static struct client *client_freelist = 0;
45 static struct host *hosts = 0; // The hosts we know about
46 static struct database *databases = 0; // The databases we know about
48 static char *client_states[] = {
52 "Client_Initializing",
57 "Client_Disconnected",
61 struct parameters global_parameters =
65 "Index Data PazPar2 (MasterKey)",
79 static int send_apdu(struct client *c, Z_APDU *a)
81 struct connection *co = c->connection;
85 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
87 odr_perror(global_parameters.odr_out, "Encoding APDU");
90 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
91 r = cs_put(co->link, buf, len);
94 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
99 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
102 odr_reset(global_parameters.odr_out); /* release the APDU structure */
103 co->state = Conn_Waiting;
108 static void send_init(IOCHAN i)
110 struct connection *co = iochan_getdata(i);
111 struct client *cl = co->client;
112 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
114 a->u.initRequest->implementationId = global_parameters.implementationId;
115 a->u.initRequest->implementationName = global_parameters.implementationName;
116 a->u.initRequest->implementationVersion =
117 global_parameters.implementationVersion;
118 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
119 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
120 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
122 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
123 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
124 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
125 if (send_apdu(cl, a) >= 0)
127 iochan_setflags(i, EVENT_INPUT);
128 cl->state = Client_Initializing;
131 cl->state = Client_Error;
132 odr_reset(global_parameters.odr_out);
135 static void send_search(IOCHAN i)
137 struct connection *co = iochan_getdata(i);
138 struct client *cl = co->client;
139 struct session *se = cl->session;
140 struct database *db = cl->database;
141 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
142 int ndb, cerror, cpos;
145 struct ccl_rpn_node *cn;
146 int ssub = 0, lslb = 100000, mspn = 10;
148 yaz_log(YLOG_DEBUG, "Sending search");
150 cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
153 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
155 zquery->which = Z_Query_type_1;
156 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
159 for (ndb = 0; db->databases[ndb]; ndb++)
161 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
162 for (ndb = 0; db->databases[ndb]; ndb++)
163 databaselist[ndb] = db->databases[ndb];
165 a->u.presentRequest->preferredRecordSyntax =
166 yaz_oidval_to_z3950oid(global_parameters.odr_out,
167 CLASS_RECSYN, VAL_USMARC);
168 a->u.searchRequest->smallSetUpperBound = &ssub;
169 a->u.searchRequest->largeSetLowerBound = &lslb;
170 a->u.searchRequest->mediumSetPresentNumber = &mspn;
171 a->u.searchRequest->resultSetName = "Default";
172 a->u.searchRequest->databaseNames = databaselist;
173 a->u.searchRequest->num_databaseNames = ndb;
175 if (send_apdu(cl, a) >= 0)
177 iochan_setflags(i, EVENT_INPUT);
178 cl->state = Client_Searching;
179 cl->requestid = se->requestid;
182 cl->state = Client_Error;
184 odr_reset(global_parameters.odr_out);
187 static void send_present(IOCHAN i)
189 struct connection *co = iochan_getdata(i);
190 struct client *cl = co->client;
191 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
193 int start = cl->records + 1;
195 toget = global_parameters.chunk;
196 if (toget > cl->hits - cl->records)
197 toget = cl->hits - cl->records;
199 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
201 a->u.presentRequest->resultSetStartPoint = &start;
202 a->u.presentRequest->numberOfRecordsRequested = &toget;
204 a->u.presentRequest->resultSetId = "Default";
206 a->u.presentRequest->preferredRecordSyntax =
207 yaz_oidval_to_z3950oid(global_parameters.odr_out,
208 CLASS_RECSYN, VAL_USMARC);
210 if (send_apdu(cl, a) >= 0)
212 iochan_setflags(i, EVENT_INPUT);
213 cl->state = Client_Presenting;
216 cl->state = Client_Error;
217 odr_reset(global_parameters.odr_out);
220 static void do_initResponse(IOCHAN i, Z_APDU *a)
222 struct connection *co = iochan_getdata(i);
223 struct client *cl = co->client;
224 Z_InitResponse *r = a->u.initResponse;
226 yaz_log(YLOG_DEBUG, "Received init response");
230 cl->state = Client_Idle;
233 cl->state = Client_Failed; // FIXME need to do something to the connection
236 static void do_searchResponse(IOCHAN i, Z_APDU *a)
238 struct connection *co = iochan_getdata(i);
239 struct client *cl = co->client;
240 struct session *se = cl->session;
241 Z_SearchResponse *r = a->u.searchResponse;
243 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
245 if (*r->searchStatus)
247 cl->hits = *r->resultCount;
248 se->total_hits += cl->hits;
249 if (r->presentStatus && !*r->presentStatus && r->records)
251 yaz_log(YLOG_DEBUG, "Records in search response");
252 cl->records += *r->numberOfRecordsReturned;
253 ingest_records(cl, r->records);
255 cl->state = Client_Idle;
260 cl->state = Client_Error;
262 Z_Records *recs = r->records;
263 if (recs->which == Z_Records_NSD)
265 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
266 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
267 cl->state = Client_Error;
273 const char *find_field(const char *rec, const char *field)
279 strcpy(lbuf + 1, field);
281 if ((line = strstr(rec, lbuf)))
287 const char *find_subfield(const char *field, char subfield)
289 const char *p = field;
291 while (*p && *p != '\n')
293 while (*p != '\n' && *p != '\t')
295 if (*p == '\t' && *(++p) == subfield) {
307 // Extract 245 $a $b 100 $a
308 char *extract_title(struct session *s, const char *rec)
310 const char *field, *subfield;
312 unsigned char *obuf, *p;
314 wrbuf_rewind(s->wrbuf);
316 if (!(field = find_field(rec, "245")))
318 if (!(subfield = find_subfield(field, 'a')))
320 ef = index(subfield, '\n');
321 if ((e = index(subfield, '\t')) && e < ef)
325 wrbuf_write(s->wrbuf, subfield, ef - subfield);
326 if ((subfield = find_subfield(field, 'b')))
328 ef = index(subfield, '\n');
329 if ((e = index(subfield, '\t')) && e < ef)
333 wrbuf_putc(s->wrbuf, ' ');
334 wrbuf_write(s->wrbuf, subfield, ef - subfield);
338 if ((field = find_field(rec, "100")))
340 if ((subfield = find_subfield(field, 'a')))
342 ef = index(subfield, '\n');
343 if ((e = index(subfield, '\t')) && e < ef)
347 wrbuf_puts(s->wrbuf, ", by ");
348 wrbuf_write(s->wrbuf, subfield, ef - subfield);
352 wrbuf_putc(s->wrbuf, '\0');
353 obuf = (unsigned char*) nmem_strdup(s->nmem, wrbuf_buf(s->wrbuf));
354 for (p = obuf; *p; p++)
355 if (*p == '&' || *p == '<' || *p > 122 || *p < ' ')
360 // Extract 245 $a $b 100 $a
361 char *extract_mergekey(struct session *s, const char *rec)
363 const char *field, *subfield;
365 char *out, *p, *pout;
367 wrbuf_rewind(s->wrbuf);
369 if (!(field = find_field(rec, "245")))
371 if (!(subfield = find_subfield(field, 'a')))
373 ef = index(subfield, '\n');
374 if ((e = index(subfield, '\t')) && e < ef)
378 wrbuf_write(s->wrbuf, subfield, ef - subfield);
379 if ((subfield = find_subfield(field, 'b')))
381 ef = index(subfield, '\n');
382 if ((e = index(subfield, '\t')) && e < ef)
386 wrbuf_puts(s->wrbuf, " field ");
387 wrbuf_write(s->wrbuf, subfield, ef - subfield);
391 if ((field = find_field(rec, "100")))
393 if ((subfield = find_subfield(field, 'a')))
395 ef = index(subfield, '\n');
396 if ((e = index(subfield, '\t')) && e < ef)
400 wrbuf_puts(s->wrbuf, " field ");
401 wrbuf_write(s->wrbuf, subfield, ef - subfield);
405 wrbuf_putc(s->wrbuf, '\0');
406 p = wrbuf_buf(s->wrbuf);
407 out = pout = nmem_malloc(s->nmem, strlen(p) + 1);
412 *(pout++) = tolower(*(p++));
413 while (*p && !isalnum(*p))
424 static void push_record(struct session *s, struct record *r)
427 assert(s->recheap_max + 1 < s->recheap_size);
429 s->recheap[p = ++s->recheap_max] = r;
432 int parent = (p - 1) >> 1;
433 if (strcmp(s->recheap[p]->merge_key, s->recheap[parent]->merge_key) < 0)
436 tmp = s->recheap[parent];
437 s->recheap[parent] = s->recheap[p];
446 static struct record *top_record(struct session *s)
448 return s-> recheap_max >= 0 ? s->recheap[0] : 0;
451 static struct record *pop_record(struct session *s)
455 int lastnonleaf = (s->recheap_max - 1) >> 1;
457 if (s->recheap_max < 0)
462 s->recheap[p] = s->recheap[s->recheap_max--];
464 while (p <= lastnonleaf)
466 int right = (p + 1) << 1;
467 int left = right - 1;
470 if (right < s->recheap_max &&
471 strcmp(s->recheap[right]->merge_key, s->recheap[left]->merge_key) < 0)
473 if (strcmp(s->recheap[min]->merge_key, s->recheap[p]->merge_key) < 0)
475 struct record *tmp = s->recheap[min];
476 s->recheap[min] = s->recheap[p];
486 // Like pop_record but collapses identical (merge_key) records
487 // The heap will contain multiple independent matching records and possibly
488 // one cluster, created the last time the list was scanned
489 static struct record *pop_mrecord(struct session *s)
494 if (!(this = pop_record(s)))
497 // Collapse identical records
498 while ((next = top_record(s)))
500 struct record *p, *tmpnext;
501 if (strcmp(this->merge_key, next->merge_key))
503 // Absorb record (and clustersiblings) into a supercluster
504 for (p = next; p; p = tmpnext) {
505 tmpnext = p->next_cluster;
506 p->next_cluster = this->next_cluster;
507 this->next_cluster = p;
515 // Reads records in sort order. Store records in top of heapspace until rewind is called.
516 static struct record *read_recheap(struct session *s)
518 struct record *r = pop_mrecord(s);
522 if (s->recheap_scratch < 0)
523 s->recheap_scratch = s->recheap_size;
524 s->recheap[--s->recheap_scratch] = r;
530 // Return records to heap after read
531 static void rewind_recheap(struct session *s)
533 while (s->recheap_scratch >= 0) {
534 push_record(s, s->recheap[s->recheap_scratch++]);
535 if (s->recheap_scratch >= s->recheap_size)
536 s->recheap_scratch = -1;
542 // FIXME needs to be generalized. Should flexibly generate X lists per search
543 static void extract_subject(struct session *s, const char *rec)
545 const char *field, *subfield;
547 while ((field = find_field(rec, "650")))
550 if ((subfield = find_subfield(field, 'a')))
556 ef = index(subfield, '\n');
559 if ((e = index(subfield, '\t')) && e < ef)
561 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
565 memcpy(buf, subfield, len);
568 termlist_insert(s->termlist, buf);
573 static void pull_relevance_field(struct session *s, struct record *head, const char *rec,
574 char *field, int mult)
577 while ((fb = find_field(rec, field)))
579 char *ffield = strchr(fb, '\t');
582 char *eol = strchr(ffield, '\n');
585 relevance_countwords(s->relevance, head, ffield, eol - ffield, mult);
586 rec = field + 1; // Crude way to cause a loop through repeating fields
590 static void pull_relevance_keys(struct session *s, struct record *head, struct record *rec)
592 relevance_newrec(s->relevance, head);
593 pull_relevance_field(s, head, rec->buf, "100", 2);
594 pull_relevance_field(s, head, rec->buf, "245", 4);
595 //pull_relevance_field(s, head, rec->buf, "530", 1);
596 pull_relevance_field(s, head, rec->buf, "630", 1);
597 pull_relevance_field(s, head, rec->buf, "650", 1);
598 pull_relevance_field(s, head, rec->buf, "700", 1);
599 relevance_donerecord(s->relevance, head);
602 static struct record *ingest_record(struct client *cl, char *buf, int len)
604 struct session *se = cl->session;
609 wrbuf_rewind(se->wrbuf);
610 yaz_marc_xml(global_parameters.yaz_marc, YAZ_MARC_LINE);
611 if (yaz_marc_decode_wrbuf(global_parameters.yaz_marc, buf, len, se->wrbuf) < 0)
613 yaz_log(YLOG_WARN, "Failed to decode MARC record");
616 wrbuf_putc(se->wrbuf, '\0');
617 recbuf = wrbuf_buf(se->wrbuf);
619 res = nmem_malloc(se->nmem, sizeof(struct record));
620 res->buf = nmem_strdup(se->nmem, recbuf);
622 extract_subject(se, res->buf);
624 res->title = extract_title(se, res->buf);
625 res->merge_key = extract_mergekey(se, res->buf);
629 res->next_cluster = 0;
630 res->target_offset = -1;
631 res->term_frequency_vec = 0;
633 head = reclist_insert(se->reclist, res);
635 pull_relevance_keys(se, head, res);
642 static void ingest_records(struct client *cl, Z_Records *r)
645 struct session *s = cl->session;
646 Z_NamePlusRecordList *rlist;
649 if (r->which != Z_Records_DBOSD)
651 rlist = r->u.databaseOrSurDiagnostics;
652 for (i = 0; i < rlist->num_records; i++)
654 Z_NamePlusRecord *npr = rlist->records[i];
659 if (npr->which != Z_NamePlusRecord_databaseRecord)
661 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
664 e = npr->u.databaseRecord;
665 if (e->which != Z_External_octet)
667 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
670 buf = (char*) e->u.octet_aligned->buf;
671 len = e->u.octet_aligned->len;
673 rec = ingest_record(cl, buf, len);
677 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
678 session_alert_watch(s, SESSION_WATCH_RECORDS);
681 xsltStylesheetPtr load_stylesheet(const char *fname)
683 xsltStylesheetPtr ret;
684 if (!(ret = xsltParseStylesheetFile((const xmlChar *) fname)))
686 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to load stylesheet %s", fname);
692 static void do_presentResponse(IOCHAN i, Z_APDU *a)
694 struct connection *co = iochan_getdata(i);
695 struct client *cl = co->client;
696 Z_PresentResponse *r = a->u.presentResponse;
699 Z_Records *recs = r->records;
700 if (recs->which == Z_Records_NSD)
702 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
703 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
704 cl->state = Client_Error;
708 if (!*r->presentStatus && cl->state != Client_Error)
710 yaz_log(YLOG_DEBUG, "Good Present response");
711 cl->records += *r->numberOfRecordsReturned;
712 ingest_records(cl, r->records);
713 cl->state = Client_Idle;
715 else if (*r->presentStatus)
717 yaz_log(YLOG_WARN, "Bad Present response");
718 cl->state = Client_Error;
722 static void handler(IOCHAN i, int event)
724 struct connection *co = iochan_getdata(i);
725 struct client *cl = co->client;
726 struct session *se = 0;
732 yaz_log(YLOG_WARN, "Destroying orphan connection");
733 connection_destroy(co);
737 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
740 socklen_t errlen = sizeof(errcode);
742 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
743 &errlen) < 0 || errcode != 0)
750 yaz_log(YLOG_DEBUG, "Connect OK");
751 co->state = Conn_Open;
753 cl->state = Client_Connected;
757 else if (event & EVENT_INPUT)
759 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
763 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
764 connection_destroy(co);
769 yaz_log(YLOG_WARN, "EOF reading from Z server");
770 connection_destroy(co);
773 else if (len > 1) // We discard input if we have no connection
775 co->state = Conn_Open;
777 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
781 odr_reset(global_parameters.odr_in);
782 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
783 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
790 case Z_APDU_initResponse:
791 do_initResponse(i, a);
793 case Z_APDU_searchResponse:
794 do_searchResponse(i, a);
796 case Z_APDU_presentResponse:
797 do_presentResponse(i, a);
800 yaz_log(YLOG_WARN, "Unexpected result from server");
804 // We aren't expecting staggered output from target
805 // if (cs_more(t->link))
806 // iochan_setevent(i, EVENT_INPUT);
808 else // we throw away response and go to idle mode
810 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
811 cl->state = Client_Idle;
814 /* if len==1 we do nothing but wait for more input */
817 if (cl->state == Client_Connected) {
821 if (cl->state == Client_Idle)
823 if (cl->requestid != se->requestid && *se->query) {
826 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
827 cl->records < cl->hits) {
833 // Disassociate connection from client
834 static void connection_release(struct connection *co)
836 struct client *cl = co->client;
838 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
845 // Close connection and recycle structure
846 static void connection_destroy(struct connection *co)
848 struct host *h = co->host;
850 iochan_destroy(co->iochan);
852 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
853 if (h->connections == co)
854 h->connections = co->next;
857 struct connection *pco;
858 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
861 pco->next = co->next;
867 if (co->client->state != Client_Idle)
868 co->client->state = Client_Disconnected;
869 co->client->connection = 0;
871 co->next = connection_freelist;
872 connection_freelist = co;
875 // Creates a new connection for client, associated with the host of
877 static struct connection *connection_create(struct client *cl)
879 struct connection *new;
884 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
885 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
887 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
891 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
893 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
897 res = cs_connect(link, addr);
900 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
904 if ((new = connection_freelist))
905 connection_freelist = new->next;
908 new = xmalloc(sizeof (struct connection));
912 new->state = Conn_Connecting;
913 new->host = cl->database->host;
914 new->next = new->host->connections;
915 new->host->connections = new;
917 cl->connection = new;
920 new->iochan = iochan_create(cs_fileno(link), handler, 0);
921 iochan_setdata(new->iochan, new);
922 new->iochan->next = channel_list;
923 channel_list = new->iochan;
927 // Close connection and set state to error
928 static void client_fatal(struct client *cl)
930 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
931 connection_destroy(cl->connection);
932 cl->state = Client_Error;
935 // Ensure that client has a connection associated
936 static int client_prep_connection(struct client *cl)
938 struct connection *co;
939 struct session *se = cl->session;
940 struct host *host = cl->database->host;
944 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
948 // See if someone else has an idle connection
949 // We should look at timestamps here to select the longest-idle connection
950 for (co = host->connections; co; co = co->next)
951 if (co->state == Conn_Open && (!co->client || co->client->session != se))
955 connection_release(co);
960 co = connection_create(cl);
964 if (co->state == Conn_Connecting)
965 cl->state = Client_Connecting;
966 else if (co->state == Conn_Open)
968 if (cl->state == Client_Error || cl->state == Client_Disconnected)
969 cl->state = Client_Idle;
971 iochan_setflag(co->iochan, EVENT_OUTPUT);
978 void load_simpletargets(const char *fn)
980 FILE *f = fopen(fn, "r");
985 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
989 while (fgets(line, 255, f))
993 struct database *database;
995 if (strncmp(line, "target ", 7))
998 url[strlen(url) - 1] = '\0';
999 yaz_log(YLOG_DEBUG, "Target: %s", url);
1000 if ((db = strchr(url, '/')))
1005 for (host = hosts; host; host = host->next)
1006 if (!strcmp(url, host->hostport))
1010 struct addrinfo *addrinfo, hints;
1013 unsigned char addrbuf[4];
1016 host = xmalloc(sizeof(struct host));
1017 host->hostport = xstrdup(url);
1018 host->connections = 0;
1020 if ((port = strchr(url, ':')))
1026 hints.ai_family = PF_INET;
1027 hints.ai_socktype = SOCK_STREAM;
1028 hints.ai_protocol = IPPROTO_TCP;
1029 hints.ai_addrlen = 0;
1031 hints.ai_canonname = 0;
1033 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1035 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1037 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1038 xfree(host->hostport);
1042 assert(addrinfo->ai_family == PF_INET);
1043 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1044 sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
1045 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1046 host->ipport = xstrdup(ipport);
1047 freeaddrinfo(addrinfo);
1051 database = xmalloc(sizeof(struct database));
1052 database->host = host;
1053 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1054 strcpy(database->url, url);
1055 strcat(database->url, "/");
1056 strcat(database->url, db);
1058 database->databases = xmalloc(2 * sizeof(char *));
1059 database->databases[0] = xstrdup(db);
1060 database->databases[1] = 0;
1061 database->errors = 0;
1062 database->next = databases;
1063 databases = database;
1069 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1077 pull_terms(nmem, n->u.p[0], termlist, num);
1078 pull_terms(nmem, n->u.p[1], termlist, num);
1081 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1088 // Extract terms from query into null-terminated termlist
1089 static int extract_terms(NMEM nmem, char *query, char **termlist)
1092 struct ccl_rpn_node *n;
1095 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1098 pull_terms(nmem, n, termlist, &num);
1104 static struct client *client_create(void)
1107 if (client_freelist)
1109 r = client_freelist;
1110 client_freelist = client_freelist->next;
1113 r = xmalloc(sizeof(struct client));
1122 r->state = Client_Disconnected;
1127 void client_destroy(struct client *c)
1129 struct session *se = c->session;
1130 if (c == se->clients)
1131 se->clients = c->next;
1135 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1141 connection_release(c->connection);
1142 c->next = client_freelist;
1143 client_freelist = c;
1146 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1148 s->watchlist[what].fun = fun;
1149 s->watchlist[what].data = data;
1152 void session_alert_watch(struct session *s, int what)
1154 if (!s->watchlist[what].fun)
1156 (*s->watchlist[what].fun)(s->watchlist[what].data);
1157 s->watchlist[what].fun = 0;
1158 s->watchlist[what].data = 0;
1161 // This should be extended with parameters to control selection criteria
1162 // Associates a set of clients with a session;
1163 int select_targets(struct session *se)
1165 struct database *db;
1169 client_destroy(se->clients);
1170 for (db = databases; db; db = db->next)
1172 struct client *cl = client_create();
1175 cl->next = se->clients;
1182 char *search(struct session *se, char *query)
1184 int live_channels = 0;
1187 yaz_log(YLOG_DEBUG, "Search");
1189 strcpy(se->query, query);
1191 nmem_reset(se->nmem);
1192 for (cl = se->clients; cl; cl = cl->next)
1198 if (client_prep_connection(cl))
1204 int maxrecs = live_channels * global_parameters.toget;
1205 se->termlist = termlist_create(se->nmem, maxrecs, 15);
1206 se->reclist = reclist_create(se->nmem, maxrecs);
1207 extract_terms(se->nmem, query, p);
1208 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1209 se->total_records = se->total_hits = 0;
1217 void destroy_session(struct session *s)
1219 yaz_log(YLOG_LOG, "Destroying session");
1221 client_destroy(s->clients);
1222 nmem_destroy(s->nmem);
1223 wrbuf_free(s->wrbuf, 1);
1226 struct session *new_session()
1229 struct session *session = xmalloc(sizeof(*session));
1231 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1233 session->total_hits = 0;
1234 session->total_records = 0;
1235 session->termlist = 0;
1236 session->reclist = 0;
1237 session->requestid = -1;
1238 session->clients = 0;
1239 session->query[0] = '\0';
1240 session->nmem = nmem_create();
1241 session->wrbuf = wrbuf_alloc();
1242 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1244 session->watchlist[i].data = 0;
1245 session->watchlist[i].fun = 0;
1248 select_targets(session);
1253 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1255 static struct hitsbytarget res[1000]; // FIXME MM
1259 for (cl = se->clients; cl; cl = cl->next)
1261 strcpy(res[*count].id, cl->database->host->hostport);
1262 res[*count].hits = cl->hits;
1263 res[*count].records = cl->records;
1264 res[*count].diagnostic = cl->diagnostic;
1265 res[*count].state = client_states[cl->state];
1266 res[*count].connected = cl->connection ? 1 : 0;
1273 struct termlist_score **termlist(struct session *s, int *num)
1275 return termlist_highscore(s->termlist, num);
1279 // conditional compilation by SH: This lead to a warning with currently installed
1280 // YAZ header files on us1
1281 void report_nmem_stats(void)
1283 size_t in_use, is_free;
1285 nmem_get_memory_in_use(&in_use);
1286 nmem_get_memory_free(&is_free);
1288 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1289 (long) in_use, (long) is_free);
1293 struct record **show(struct session *s, int start, int *num, int *total,
1294 int *sumhits, NMEM nmem_show)
1296 struct record **recs = nmem_malloc(nmem_show, *num
1297 * sizeof(struct record *));
1300 relevance_prepare_read(s->relevance, s->reclist);
1302 *total = s->reclist->num_records;
1303 *sumhits = s->total_hits;
1305 for (i = 0; i < start; i++)
1306 if (!reclist_read_record(s->reclist))
1312 for (i = 0; i < *num; i++)
1314 struct record *r = reclist_read_record(s->reclist);
1325 void statistics(struct session *se, struct statistics *stat)
1330 bzero(stat, sizeof(*stat));
1331 for (cl = se->clients; cl; cl = cl->next)
1333 if (!cl->connection)
1334 stat->num_no_connection++;
1337 case Client_Connecting: stat->num_connecting++; break;
1338 case Client_Initializing: stat->num_initializing++; break;
1339 case Client_Searching: stat->num_searching++; break;
1340 case Client_Presenting: stat->num_presenting++; break;
1341 case Client_Idle: stat->num_idle++; break;
1342 case Client_Failed: stat->num_failed++; break;
1343 case Client_Error: stat->num_error++; break;
1348 stat->num_hits = se->total_hits;
1349 stat->num_records = se->total_records;
1351 stat->num_clients = count;
1354 static CCL_bibset load_cclfile(const char *fn)
1356 CCL_bibset res = ccl_qual_mk();
1357 if (ccl_qual_fname(res, fn) < 0)
1359 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1365 int main(int argc, char **argv)
1371 if (signal(SIGPIPE, SIG_IGN) < 0)
1372 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1374 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1376 while ((ret = options("f:x:c:h:p:C:s:", argv, argc, &arg)) != -2)
1380 if (!read_config(arg))
1384 command_init(atoi(arg));
1392 global_parameters.ccl_filter = load_cclfile(arg);
1395 http_set_proxyaddr(arg);
1398 load_simpletargets(arg);
1401 global_parameters.xsl = load_stylesheet(arg);
1404 fprintf(stderr, "Usage: pazpar2\n"
1406 " -h [host:]port (REST protocol listener)\n"
1407 " -c cmdport (telnet-style)\n"
1409 " -s simpletargetfile\n"
1410 " -p hostname[:portno] (HTTP proxy)\n");
1417 fprintf(stderr, "Set command port with -h or -c\n");
1421 if (!global_parameters.xsl)
1422 global_parameters.xsl = load_stylesheet("../etc/default.xsl");
1423 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1424 global_parameters.yaz_marc = yaz_marc_create();
1425 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1426 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1427 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1429 event_loop(&channel_list);
1437 * indent-tabs-mode: nil
1439 * vim: shiftwidth=4 tabstop=8 expandtab