1 /* $Id: pazpar2.c,v 1.5 2006-12-22 04:43:11 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"
30 #define PAZPAR2_VERSION "0.1"
33 static void client_fatal(struct client *cl);
34 static void connection_destroy(struct connection *co);
35 static int client_prep_connection(struct client *cl);
36 static void ingest_records(struct client *cl, Z_Records *r);
37 void session_alert_watch(struct session *s, int what);
39 IOCHAN channel_list = 0; // Master list of connections we're handling events to
41 static struct connection *connection_freelist = 0;
42 static struct client *client_freelist = 0;
44 static struct host *hosts = 0; // The hosts we know about
45 static struct database *databases = 0; // The databases we know about
47 static char *client_states[] = {
51 "Client_Initializing",
56 "Client_Disconnected",
60 struct parameters global_parameters =
64 "Index Data PazPar2 (MasterKey)",
78 static int send_apdu(struct client *c, Z_APDU *a)
80 struct connection *co = c->connection;
84 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
86 odr_perror(global_parameters.odr_out, "Encoding APDU");
89 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
90 r = cs_put(co->link, buf, len);
93 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
98 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
101 odr_reset(global_parameters.odr_out); /* release the APDU structure */
102 co->state = Conn_Waiting;
107 static void send_init(IOCHAN i)
109 struct connection *co = iochan_getdata(i);
110 struct client *cl = co->client;
111 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
113 a->u.initRequest->implementationId = global_parameters.implementationId;
114 a->u.initRequest->implementationName = global_parameters.implementationName;
115 a->u.initRequest->implementationVersion =
116 global_parameters.implementationVersion;
117 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
118 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
119 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
121 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
122 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
123 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
124 if (send_apdu(cl, a) >= 0)
126 iochan_setflags(i, EVENT_INPUT);
127 cl->state = Client_Initializing;
130 cl->state = Client_Error;
131 odr_reset(global_parameters.odr_out);
134 static void send_search(IOCHAN i)
136 struct connection *co = iochan_getdata(i);
137 struct client *cl = co->client;
138 struct session *se = cl->session;
139 struct database *db = cl->database;
140 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
141 int ndb, cerror, cpos;
144 struct ccl_rpn_node *cn;
145 int ssub = 0, lslb = 100000, mspn = 10;
147 yaz_log(YLOG_DEBUG, "Sending search");
149 cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
152 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
154 zquery->which = Z_Query_type_1;
155 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
158 for (ndb = 0; db->databases[ndb]; ndb++)
160 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
161 for (ndb = 0; db->databases[ndb]; ndb++)
162 databaselist[ndb] = db->databases[ndb];
164 a->u.presentRequest->preferredRecordSyntax =
165 yaz_oidval_to_z3950oid(global_parameters.odr_out,
166 CLASS_RECSYN, VAL_USMARC);
167 a->u.searchRequest->smallSetUpperBound = &ssub;
168 a->u.searchRequest->largeSetLowerBound = &lslb;
169 a->u.searchRequest->mediumSetPresentNumber = &mspn;
170 a->u.searchRequest->resultSetName = "Default";
171 a->u.searchRequest->databaseNames = databaselist;
172 a->u.searchRequest->num_databaseNames = ndb;
174 if (send_apdu(cl, a) >= 0)
176 iochan_setflags(i, EVENT_INPUT);
177 cl->state = Client_Searching;
178 cl->requestid = se->requestid;
181 cl->state = Client_Error;
183 odr_reset(global_parameters.odr_out);
186 static void send_present(IOCHAN i)
188 struct connection *co = iochan_getdata(i);
189 struct client *cl = co->client;
190 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
192 int start = cl->records + 1;
194 toget = global_parameters.chunk;
195 if (toget > cl->hits - cl->records)
196 toget = cl->hits - cl->records;
198 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
200 a->u.presentRequest->resultSetStartPoint = &start;
201 a->u.presentRequest->numberOfRecordsRequested = &toget;
203 a->u.presentRequest->resultSetId = "Default";
205 a->u.presentRequest->preferredRecordSyntax =
206 yaz_oidval_to_z3950oid(global_parameters.odr_out,
207 CLASS_RECSYN, VAL_USMARC);
209 if (send_apdu(cl, a) >= 0)
211 iochan_setflags(i, EVENT_INPUT);
212 cl->state = Client_Presenting;
215 cl->state = Client_Error;
216 odr_reset(global_parameters.odr_out);
219 static void do_initResponse(IOCHAN i, Z_APDU *a)
221 struct connection *co = iochan_getdata(i);
222 struct client *cl = co->client;
223 Z_InitResponse *r = a->u.initResponse;
225 yaz_log(YLOG_DEBUG, "Received init response");
229 cl->state = Client_Idle;
232 cl->state = Client_Failed; // FIXME need to do something to the connection
235 static void do_searchResponse(IOCHAN i, Z_APDU *a)
237 struct connection *co = iochan_getdata(i);
238 struct client *cl = co->client;
239 struct session *se = cl->session;
240 Z_SearchResponse *r = a->u.searchResponse;
242 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
244 if (*r->searchStatus)
246 cl->hits = *r->resultCount;
247 se->total_hits += cl->hits;
248 if (r->presentStatus && !*r->presentStatus && r->records)
250 yaz_log(YLOG_DEBUG, "Records in search response");
251 cl->records += *r->numberOfRecordsReturned;
252 ingest_records(cl, r->records);
254 cl->state = Client_Idle;
259 cl->state = Client_Error;
261 Z_Records *recs = r->records;
262 if (recs->which == Z_Records_NSD)
264 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
265 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
266 cl->state = Client_Error;
272 const char *find_field(const char *rec, const char *field)
278 strcpy(lbuf + 1, field);
280 if ((line = strstr(rec, lbuf)))
286 const char *find_subfield(const char *field, char subfield)
288 const char *p = field;
290 while (*p && *p != '\n')
292 while (*p != '\n' && *p != '\t')
294 if (*p == '\t' && *(++p) == subfield) {
306 // Extract 245 $a $b 100 $a
307 char *extract_title(struct session *s, const char *rec)
309 const char *field, *subfield;
311 unsigned char *obuf, *p;
313 wrbuf_rewind(s->wrbuf);
315 if (!(field = find_field(rec, "245")))
317 if (!(subfield = find_subfield(field, 'a')))
319 ef = index(subfield, '\n');
320 if ((e = index(subfield, '\t')) && e < ef)
324 wrbuf_write(s->wrbuf, subfield, ef - subfield);
325 if ((subfield = find_subfield(field, 'b')))
327 ef = index(subfield, '\n');
328 if ((e = index(subfield, '\t')) && e < ef)
332 wrbuf_putc(s->wrbuf, ' ');
333 wrbuf_write(s->wrbuf, subfield, ef - subfield);
337 if ((field = find_field(rec, "100")))
339 if ((subfield = find_subfield(field, 'a')))
341 ef = index(subfield, '\n');
342 if ((e = index(subfield, '\t')) && e < ef)
346 wrbuf_puts(s->wrbuf, ", by ");
347 wrbuf_write(s->wrbuf, subfield, ef - subfield);
351 wrbuf_putc(s->wrbuf, '\0');
352 obuf = (unsigned char*) nmem_strdup(s->nmem, wrbuf_buf(s->wrbuf));
353 for (p = obuf; *p; p++)
354 if (*p == '&' || *p == '<' || *p > 122 || *p < ' ')
359 // Extract 245 $a $b 100 $a
360 char *extract_mergekey(struct session *s, const char *rec)
362 const char *field, *subfield;
364 char *out, *p, *pout;
366 wrbuf_rewind(s->wrbuf);
368 if (!(field = find_field(rec, "245")))
370 if (!(subfield = find_subfield(field, 'a')))
372 ef = index(subfield, '\n');
373 if ((e = index(subfield, '\t')) && e < ef)
377 wrbuf_write(s->wrbuf, subfield, ef - subfield);
378 if ((subfield = find_subfield(field, 'b')))
380 ef = index(subfield, '\n');
381 if ((e = index(subfield, '\t')) && e < ef)
385 wrbuf_puts(s->wrbuf, " field ");
386 wrbuf_write(s->wrbuf, subfield, ef - subfield);
390 if ((field = find_field(rec, "100")))
392 if ((subfield = find_subfield(field, 'a')))
394 ef = index(subfield, '\n');
395 if ((e = index(subfield, '\t')) && e < ef)
399 wrbuf_puts(s->wrbuf, " field ");
400 wrbuf_write(s->wrbuf, subfield, ef - subfield);
404 wrbuf_putc(s->wrbuf, '\0');
405 p = wrbuf_buf(s->wrbuf);
406 out = pout = nmem_malloc(s->nmem, strlen(p) + 1);
411 *(pout++) = tolower(*(p++));
412 while (*p && !isalnum(*p))
423 static void push_record(struct session *s, struct record *r)
426 assert(s->recheap_max + 1 < s->recheap_size);
428 s->recheap[p = ++s->recheap_max] = r;
431 int parent = (p - 1) >> 1;
432 if (strcmp(s->recheap[p]->merge_key, s->recheap[parent]->merge_key) < 0)
435 tmp = s->recheap[parent];
436 s->recheap[parent] = s->recheap[p];
445 static struct record *top_record(struct session *s)
447 return s-> recheap_max >= 0 ? s->recheap[0] : 0;
450 static struct record *pop_record(struct session *s)
454 int lastnonleaf = (s->recheap_max - 1) >> 1;
456 if (s->recheap_max < 0)
461 s->recheap[p] = s->recheap[s->recheap_max--];
463 while (p <= lastnonleaf)
465 int right = (p + 1) << 1;
466 int left = right - 1;
469 if (right < s->recheap_max &&
470 strcmp(s->recheap[right]->merge_key, s->recheap[left]->merge_key) < 0)
472 if (strcmp(s->recheap[min]->merge_key, s->recheap[p]->merge_key) < 0)
474 struct record *tmp = s->recheap[min];
475 s->recheap[min] = s->recheap[p];
485 // Like pop_record but collapses identical (merge_key) records
486 // The heap will contain multiple independent matching records and possibly
487 // one cluster, created the last time the list was scanned
488 static struct record *pop_mrecord(struct session *s)
493 if (!(this = pop_record(s)))
496 // Collapse identical records
497 while ((next = top_record(s)))
499 struct record *p, *tmpnext;
500 if (strcmp(this->merge_key, next->merge_key))
502 // Absorb record (and clustersiblings) into a supercluster
503 for (p = next; p; p = tmpnext) {
504 tmpnext = p->next_cluster;
505 p->next_cluster = this->next_cluster;
506 this->next_cluster = p;
514 // Reads records in sort order. Store records in top of heapspace until rewind is called.
515 static struct record *read_recheap(struct session *s)
517 struct record *r = pop_mrecord(s);
521 if (s->recheap_scratch < 0)
522 s->recheap_scratch = s->recheap_size;
523 s->recheap[--s->recheap_scratch] = r;
529 // Return records to heap after read
530 static void rewind_recheap(struct session *s)
532 while (s->recheap_scratch >= 0) {
533 push_record(s, s->recheap[s->recheap_scratch++]);
534 if (s->recheap_scratch >= s->recheap_size)
535 s->recheap_scratch = -1;
541 // FIXME needs to be generalized. Should flexibly generate X lists per search
542 static void extract_subject(struct session *s, const char *rec)
544 const char *field, *subfield;
546 while ((field = find_field(rec, "650")))
549 if ((subfield = find_subfield(field, 'a')))
555 ef = index(subfield, '\n');
558 if ((e = index(subfield, '\t')) && e < ef)
560 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
564 memcpy(buf, subfield, len);
567 termlist_insert(s->termlist, buf);
572 static void pull_relevance_field(struct session *s, struct record *head, const char *rec,
573 char *field, int mult)
576 while ((fb = find_field(rec, field)))
578 char *ffield = strchr(fb, '\t');
581 char *eol = strchr(ffield, '\n');
584 relevance_countwords(s->relevance, head, ffield, eol - ffield, mult);
585 rec = field + 1; // Crude way to cause a loop through repeating fields
589 static void pull_relevance_keys(struct session *s, struct record *head, struct record *rec)
591 relevance_newrec(s->relevance, head);
592 pull_relevance_field(s, head, rec->buf, "100", 2);
593 pull_relevance_field(s, head, rec->buf, "245", 4);
594 //pull_relevance_field(s, head, rec->buf, "530", 1);
595 pull_relevance_field(s, head, rec->buf, "630", 1);
596 pull_relevance_field(s, head, rec->buf, "650", 1);
597 pull_relevance_field(s, head, rec->buf, "700", 1);
598 relevance_donerecord(s->relevance, head);
601 static struct record *ingest_record(struct client *cl, char *buf, int len)
603 struct session *se = cl->session;
608 wrbuf_rewind(se->wrbuf);
609 yaz_marc_xml(global_parameters.yaz_marc, YAZ_MARC_LINE);
610 if (yaz_marc_decode_wrbuf(global_parameters.yaz_marc, buf, len, se->wrbuf) < 0)
612 yaz_log(YLOG_WARN, "Failed to decode MARC record");
615 wrbuf_putc(se->wrbuf, '\0');
616 recbuf = wrbuf_buf(se->wrbuf);
618 res = nmem_malloc(se->nmem, sizeof(struct record));
619 res->buf = nmem_strdup(se->nmem, recbuf);
621 extract_subject(se, res->buf);
623 res->title = extract_title(se, res->buf);
624 res->merge_key = extract_mergekey(se, res->buf);
628 res->next_cluster = 0;
629 res->target_offset = -1;
630 res->term_frequency_vec = 0;
632 head = reclist_insert(se->reclist, res);
634 pull_relevance_keys(se, head, res);
641 static void ingest_records(struct client *cl, Z_Records *r)
644 struct session *s = cl->session;
645 Z_NamePlusRecordList *rlist;
648 if (r->which != Z_Records_DBOSD)
650 rlist = r->u.databaseOrSurDiagnostics;
651 for (i = 0; i < rlist->num_records; i++)
653 Z_NamePlusRecord *npr = rlist->records[i];
658 if (npr->which != Z_NamePlusRecord_databaseRecord)
660 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
663 e = npr->u.databaseRecord;
664 if (e->which != Z_External_octet)
666 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
669 buf = (char*) e->u.octet_aligned->buf;
670 len = e->u.octet_aligned->len;
672 rec = ingest_record(cl, buf, len);
676 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
677 session_alert_watch(s, SESSION_WATCH_RECORDS);
680 xsltStylesheetPtr load_stylesheet(const char *fname)
682 xsltStylesheetPtr ret;
683 if (!(ret = xsltParseStylesheetFile((const xmlChar *) fname)))
685 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to load stylesheet %s", fname);
691 static void do_presentResponse(IOCHAN i, Z_APDU *a)
693 struct connection *co = iochan_getdata(i);
694 struct client *cl = co->client;
695 Z_PresentResponse *r = a->u.presentResponse;
698 Z_Records *recs = r->records;
699 if (recs->which == Z_Records_NSD)
701 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
702 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
703 cl->state = Client_Error;
707 if (!*r->presentStatus && cl->state != Client_Error)
709 yaz_log(YLOG_DEBUG, "Good Present response");
710 cl->records += *r->numberOfRecordsReturned;
711 ingest_records(cl, r->records);
712 cl->state = Client_Idle;
714 else if (*r->presentStatus)
716 yaz_log(YLOG_WARN, "Bad Present response");
717 cl->state = Client_Error;
721 static void handler(IOCHAN i, int event)
723 struct connection *co = iochan_getdata(i);
724 struct client *cl = co->client;
725 struct session *se = 0;
731 yaz_log(YLOG_WARN, "Destroying orphan connection");
732 connection_destroy(co);
736 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
739 socklen_t errlen = sizeof(errcode);
741 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
742 &errlen) < 0 || errcode != 0)
749 yaz_log(YLOG_DEBUG, "Connect OK");
750 co->state = Conn_Open;
752 cl->state = Client_Connected;
756 else if (event & EVENT_INPUT)
758 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
762 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
763 connection_destroy(co);
768 yaz_log(YLOG_WARN, "EOF reading from Z server");
769 connection_destroy(co);
772 else if (len > 1) // We discard input if we have no connection
774 co->state = Conn_Open;
776 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
780 odr_reset(global_parameters.odr_in);
781 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
782 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
789 case Z_APDU_initResponse:
790 do_initResponse(i, a);
792 case Z_APDU_searchResponse:
793 do_searchResponse(i, a);
795 case Z_APDU_presentResponse:
796 do_presentResponse(i, a);
799 yaz_log(YLOG_WARN, "Unexpected result from server");
803 // We aren't expecting staggered output from target
804 // if (cs_more(t->link))
805 // iochan_setevent(i, EVENT_INPUT);
807 else // we throw away response and go to idle mode
809 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
810 cl->state = Client_Idle;
813 /* if len==1 we do nothing but wait for more input */
816 if (cl->state == Client_Connected) {
820 if (cl->state == Client_Idle)
822 if (cl->requestid != se->requestid && *se->query) {
825 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
826 cl->records < cl->hits) {
832 // Disassociate connection from client
833 static void connection_release(struct connection *co)
835 struct client *cl = co->client;
837 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
844 // Close connection and recycle structure
845 static void connection_destroy(struct connection *co)
847 struct host *h = co->host;
849 iochan_destroy(co->iochan);
851 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
852 if (h->connections == co)
853 h->connections = co->next;
856 struct connection *pco;
857 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
860 pco->next = co->next;
866 if (co->client->state != Client_Idle)
867 co->client->state = Client_Disconnected;
868 co->client->connection = 0;
870 co->next = connection_freelist;
871 connection_freelist = co;
874 // Creates a new connection for client, associated with the host of
876 static struct connection *connection_create(struct client *cl)
878 struct connection *new;
883 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
884 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
886 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
890 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
892 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
896 res = cs_connect(link, addr);
899 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
903 if ((new = connection_freelist))
904 connection_freelist = new->next;
907 new = xmalloc(sizeof (struct connection));
911 new->state = Conn_Connecting;
912 new->host = cl->database->host;
913 new->next = new->host->connections;
914 new->host->connections = new;
916 cl->connection = new;
919 new->iochan = iochan_create(cs_fileno(link), handler, 0);
920 iochan_setdata(new->iochan, new);
921 new->iochan->next = channel_list;
922 channel_list = new->iochan;
926 // Close connection and set state to error
927 static void client_fatal(struct client *cl)
929 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
930 connection_destroy(cl->connection);
931 cl->state = Client_Error;
934 // Ensure that client has a connection associated
935 static int client_prep_connection(struct client *cl)
937 struct connection *co;
938 struct session *se = cl->session;
939 struct host *host = cl->database->host;
943 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
947 // See if someone else has an idle connection
948 // We should look at timestamps here to select the longest-idle connection
949 for (co = host->connections; co; co = co->next)
950 if (co->state == Conn_Open && (!co->client || co->client->session != se))
954 connection_release(co);
959 co = connection_create(cl);
963 if (co->state == Conn_Connecting)
964 cl->state = Client_Connecting;
965 else if (co->state == Conn_Open)
967 if (cl->state == Client_Error || cl->state == Client_Disconnected)
968 cl->state = Client_Idle;
970 iochan_setflag(co->iochan, EVENT_OUTPUT);
977 void load_simpletargets(const char *fn)
979 FILE *f = fopen(fn, "r");
984 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
988 while (fgets(line, 255, f))
992 struct database *database;
994 if (strncmp(line, "target ", 7))
997 url[strlen(url) - 1] = '\0';
998 yaz_log(YLOG_DEBUG, "Target: %s", url);
999 if ((db = strchr(url, '/')))
1004 for (host = hosts; host; host = host->next)
1005 if (!strcmp(url, host->hostport))
1009 struct addrinfo *addrinfo, hints;
1012 unsigned char addrbuf[4];
1015 host = xmalloc(sizeof(struct host));
1016 host->hostport = xstrdup(url);
1017 host->connections = 0;
1019 if ((port = strchr(url, ':')))
1025 hints.ai_family = PF_INET;
1026 hints.ai_socktype = SOCK_STREAM;
1027 hints.ai_protocol = IPPROTO_TCP;
1028 hints.ai_addrlen = 0;
1030 hints.ai_canonname = 0;
1032 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1034 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1036 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1037 xfree(host->hostport);
1041 assert(addrinfo->ai_family == PF_INET);
1042 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1043 sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
1044 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1045 host->ipport = xstrdup(ipport);
1046 freeaddrinfo(addrinfo);
1050 database = xmalloc(sizeof(struct database));
1051 database->host = host;
1052 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1053 strcpy(database->url, url);
1054 strcat(database->url, "/");
1055 strcat(database->url, db);
1057 database->databases = xmalloc(2 * sizeof(char *));
1058 database->databases[0] = xstrdup(db);
1059 database->databases[1] = 0;
1060 database->errors = 0;
1061 database->next = databases;
1062 databases = database;
1068 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1076 pull_terms(nmem, n->u.p[0], termlist, num);
1077 pull_terms(nmem, n->u.p[1], termlist, num);
1080 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1087 // Extract terms from query into null-terminated termlist
1088 static int extract_terms(NMEM nmem, char *query, char **termlist)
1091 struct ccl_rpn_node *n;
1094 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1097 pull_terms(nmem, n, termlist, &num);
1103 static struct client *client_create(void)
1106 if (client_freelist)
1108 r = client_freelist;
1109 client_freelist = client_freelist->next;
1112 r = xmalloc(sizeof(struct client));
1121 r->state = Client_Disconnected;
1126 void client_destroy(struct client *c)
1128 struct session *se = c->session;
1129 if (c == se->clients)
1130 se->clients = c->next;
1134 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1140 connection_release(c->connection);
1141 c->next = client_freelist;
1142 client_freelist = c;
1145 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1147 s->watchlist[what].fun = fun;
1148 s->watchlist[what].data = data;
1151 void session_alert_watch(struct session *s, int what)
1153 if (!s->watchlist[what].fun)
1155 (*s->watchlist[what].fun)(s->watchlist[what].data);
1156 s->watchlist[what].fun = 0;
1157 s->watchlist[what].data = 0;
1160 // This should be extended with parameters to control selection criteria
1161 // Associates a set of clients with a session;
1162 int select_targets(struct session *se)
1164 struct database *db;
1168 client_destroy(se->clients);
1169 for (db = databases; db; db = db->next)
1171 struct client *cl = client_create();
1174 cl->next = se->clients;
1181 char *search(struct session *se, char *query)
1183 int live_channels = 0;
1186 yaz_log(YLOG_DEBUG, "Search");
1188 strcpy(se->query, query);
1190 nmem_reset(se->nmem);
1191 for (cl = se->clients; cl; cl = cl->next)
1197 if (client_prep_connection(cl))
1203 int maxrecs = live_channels * global_parameters.toget;
1204 se->termlist = termlist_create(se->nmem, maxrecs, 15);
1205 se->reclist = reclist_create(se->nmem, maxrecs);
1206 extract_terms(se->nmem, query, p);
1207 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1208 se->total_records = se->total_hits = 0;
1216 void destroy_session(struct session *s)
1218 yaz_log(YLOG_LOG, "Destroying session");
1220 client_destroy(s->clients);
1221 nmem_destroy(s->nmem);
1222 wrbuf_free(s->wrbuf, 1);
1225 struct session *new_session()
1228 struct session *session = xmalloc(sizeof(*session));
1230 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1232 session->total_hits = 0;
1233 session->total_records = 0;
1234 session->termlist = 0;
1235 session->reclist = 0;
1236 session->requestid = -1;
1237 session->clients = 0;
1238 session->query[0] = '\0';
1239 session->nmem = nmem_create();
1240 session->wrbuf = wrbuf_alloc();
1241 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1243 session->watchlist[i].data = 0;
1244 session->watchlist[i].fun = 0;
1247 select_targets(session);
1252 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1254 static struct hitsbytarget res[1000]; // FIXME MM
1258 for (cl = se->clients; cl; cl = cl->next)
1260 strcpy(res[*count].id, cl->database->host->hostport);
1261 res[*count].hits = cl->hits;
1262 res[*count].records = cl->records;
1263 res[*count].diagnostic = cl->diagnostic;
1264 res[*count].state = client_states[cl->state];
1265 res[*count].connected = cl->connection ? 1 : 0;
1272 struct termlist_score **termlist(struct session *s, int *num)
1274 return termlist_highscore(s->termlist, num);
1278 // conditional compilation by SH: This lead to a warning with currently installed
1279 // YAZ header files on us1
1280 void report_nmem_stats(void)
1282 size_t in_use, is_free;
1284 nmem_get_memory_in_use(&in_use);
1285 nmem_get_memory_free(&is_free);
1287 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1288 (long) in_use, (long) is_free);
1292 struct record **show(struct session *s, int start, int *num, int *total,
1293 int *sumhits, NMEM nmem_show)
1295 struct record **recs = nmem_malloc(nmem_show, *num
1296 * sizeof(struct record *));
1299 relevance_prepare_read(s->relevance, s->reclist);
1301 *total = s->reclist->num_records;
1302 *sumhits = s->total_hits;
1304 for (i = 0; i < start; i++)
1305 if (!reclist_read_record(s->reclist))
1311 for (i = 0; i < *num; i++)
1313 struct record *r = reclist_read_record(s->reclist);
1324 void statistics(struct session *se, struct statistics *stat)
1329 bzero(stat, sizeof(*stat));
1330 for (cl = se->clients; cl; cl = cl->next)
1332 if (!cl->connection)
1333 stat->num_no_connection++;
1336 case Client_Connecting: stat->num_connecting++; break;
1337 case Client_Initializing: stat->num_initializing++; break;
1338 case Client_Searching: stat->num_searching++; break;
1339 case Client_Presenting: stat->num_presenting++; break;
1340 case Client_Idle: stat->num_idle++; break;
1341 case Client_Failed: stat->num_failed++; break;
1342 case Client_Error: stat->num_error++; break;
1347 stat->num_hits = se->total_hits;
1348 stat->num_records = se->total_records;
1350 stat->num_clients = count;
1353 static CCL_bibset load_cclfile(const char *fn)
1355 CCL_bibset res = ccl_qual_mk();
1356 if (ccl_qual_fname(res, fn) < 0)
1358 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1364 int main(int argc, char **argv)
1370 if (signal(SIGPIPE, SIG_IGN) < 0)
1371 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1373 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1375 while ((ret = options("x:c:h:p:C:s:", argv, argc, &arg)) != -2)
1379 command_init(atoi(arg));
1387 global_parameters.ccl_filter = load_cclfile(arg);
1390 http_set_proxyaddr(arg);
1393 load_simpletargets(arg);
1396 global_parameters.xsl = load_stylesheet(arg);
1399 fprintf(stderr, "Usage: pazpar2\n"
1400 " -h [host:]port (REST protocol listener)\n"
1401 " -c cmdport (telnet-style)\n"
1403 " -s simpletargetfile\n"
1404 " -p hostname[:portno] (HTTP proxy)\n");
1411 fprintf(stderr, "Set command port with -h or -c\n");
1415 if (!global_parameters.xsl)
1416 global_parameters.xsl = load_stylesheet("../etc/default.xsl");
1417 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1418 global_parameters.yaz_marc = yaz_marc_create();
1419 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1420 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1421 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1423 event_loop(&channel_list);
1431 * indent-tabs-mode: nil
1433 * vim: shiftwidth=4 tabstop=8 expandtab