1fe17a8a79b390fb4b05d1f08d2fd402fd57cd2e
[pazpar2-moved-to-github.git] / src / pazpar2.c
1 /* $Id: pazpar2.c,v 1.26 2007-01-10 11:56:10 adam Exp $ */
2
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <sys/time.h>
7 #include <unistd.h>
8 #include <sys/socket.h>
9 #include <netdb.h>
10 #include <signal.h>
11 #include <ctype.h>
12 #include <assert.h>
13
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/yaz-util.h>
21 #include <yaz/nmem.h>
22
23 #if HAVE_CONFIG_H
24 #include "cconfig.h"
25 #endif
26
27 #define USE_TIMING 0
28 #if USE_TIMING
29 #include <yaz/timing.h>
30 #endif
31
32 #include <netinet/in.h>
33
34 #include "pazpar2.h"
35 #include "eventl.h"
36 #include "http.h"
37 #include "termlists.h"
38 #include "reclists.h"
39 #include "relevance.h"
40 #include "config.h"
41
42 #define MAX_CHUNK 15
43
44 static void client_fatal(struct client *cl);
45 static void connection_destroy(struct connection *co);
46 static int client_prep_connection(struct client *cl);
47 static void ingest_records(struct client *cl, Z_Records *r);
48 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db);
49 void session_alert_watch(struct session *s, int what);
50
51 IOCHAN channel_list = 0;  // Master list of connections we're handling events to
52
53 static struct connection *connection_freelist = 0;
54 static struct client *client_freelist = 0;
55
56 static struct host *hosts = 0;  // The hosts we know about 
57 static struct database *databases = 0; // The databases we know about
58
59 static char *client_states[] = {
60     "Client_Connecting",
61     "Client_Connected",
62     "Client_Idle",
63     "Client_Initializing",
64     "Client_Searching",
65     "Client_Presenting",
66     "Client_Error",
67     "Client_Failed",
68     "Client_Disconnected",
69     "Client_Stopped"
70 };
71
72 // Note: Some things in this structure will eventually move to configuration
73 struct parameters global_parameters = 
74 {
75     0,
76     0,
77     30,
78     "81",
79     "Index Data PazPar2 (MasterKey)",
80     VERSION,
81     600, // 10 minutes
82     60,
83     100,
84     MAX_CHUNK,
85     0,
86     0,
87     0,
88     0
89 };
90
91 static int send_apdu(struct client *c, Z_APDU *a)
92 {
93     struct connection *co = c->connection;
94     char *buf;
95     int len, r;
96
97     if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
98     {
99         odr_perror(global_parameters.odr_out, "Encoding APDU");
100         abort();
101     }
102     buf = odr_getbuf(global_parameters.odr_out, &len, 0);
103     r = cs_put(co->link, buf, len);
104     if (r < 0)
105     {
106         yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
107         return -1;
108     }
109     else if (r == 1)
110     {
111         fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
112         exit(1);
113     }
114     odr_reset(global_parameters.odr_out); /* release the APDU structure  */
115     co->state = Conn_Waiting;
116     return 0;
117 }
118
119
120 static void send_init(IOCHAN i)
121 {
122     struct connection *co = iochan_getdata(i);
123     struct client *cl = co->client;
124     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
125
126     a->u.initRequest->implementationId = global_parameters.implementationId;
127     a->u.initRequest->implementationName = global_parameters.implementationName;
128     a->u.initRequest->implementationVersion =
129         global_parameters.implementationVersion;
130     ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
131     ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
132     ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
133
134     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
135     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
136     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
137     if (send_apdu(cl, a) >= 0)
138     {
139         iochan_setflags(i, EVENT_INPUT);
140         cl->state = Client_Initializing;
141     }
142     else
143         cl->state = Client_Error;
144     odr_reset(global_parameters.odr_out);
145 }
146
147 static void send_search(IOCHAN i)
148 {
149     struct connection *co = iochan_getdata(i);
150     struct client *cl = co->client; 
151     struct session *se = cl->session;
152     struct database *db = cl->database;
153     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
154     int ndb, cerror, cpos;
155     char **databaselist;
156     Z_Query *zquery;
157     struct ccl_rpn_node *cn;
158     int ssub = 0, lslb = 100000, mspn = 10;
159
160     yaz_log(YLOG_DEBUG, "Sending search");
161
162     cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
163     if (!cn)
164         return;
165     a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
166             sizeof(Z_Query));
167     zquery->which = Z_Query_type_1;
168     zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
169     ccl_rpn_delete(cn);
170
171     for (ndb = 0; db->databases[ndb]; ndb++)
172         ;
173     databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
174     for (ndb = 0; db->databases[ndb]; ndb++)
175         databaselist[ndb] = db->databases[ndb];
176
177     a->u.presentRequest->preferredRecordSyntax =
178             yaz_oidval_to_z3950oid(global_parameters.odr_out,
179             CLASS_RECSYN, VAL_USMARC);
180     a->u.searchRequest->smallSetUpperBound = &ssub;
181     a->u.searchRequest->largeSetLowerBound = &lslb;
182     a->u.searchRequest->mediumSetPresentNumber = &mspn;
183     a->u.searchRequest->resultSetName = "Default";
184     a->u.searchRequest->databaseNames = databaselist;
185     a->u.searchRequest->num_databaseNames = ndb;
186
187     if (send_apdu(cl, a) >= 0)
188     {
189         iochan_setflags(i, EVENT_INPUT);
190         cl->state = Client_Searching;
191         cl->requestid = se->requestid;
192     }
193     else
194         cl->state = Client_Error;
195
196     odr_reset(global_parameters.odr_out);
197 }
198
199 static void send_present(IOCHAN i)
200 {
201     struct connection *co = iochan_getdata(i);
202     struct client *cl = co->client; 
203     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
204     int toget;
205     int start = cl->records + 1;
206
207     toget = global_parameters.chunk;
208     if (toget > global_parameters.toget - cl->records)
209         toget = global_parameters.toget - cl->records;
210     if (toget > cl->hits - cl->records)
211         toget = cl->hits - cl->records;
212
213     yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
214
215     a->u.presentRequest->resultSetStartPoint = &start;
216     a->u.presentRequest->numberOfRecordsRequested = &toget;
217
218     a->u.presentRequest->resultSetId = "Default";
219
220     a->u.presentRequest->preferredRecordSyntax =
221             yaz_oidval_to_z3950oid(global_parameters.odr_out,
222             CLASS_RECSYN, VAL_USMARC);
223
224     if (send_apdu(cl, a) >= 0)
225     {
226         iochan_setflags(i, EVENT_INPUT);
227         cl->state = Client_Presenting;
228     }
229     else
230         cl->state = Client_Error;
231     odr_reset(global_parameters.odr_out);
232 }
233
234 static void do_initResponse(IOCHAN i, Z_APDU *a)
235 {
236     struct connection *co = iochan_getdata(i);
237     struct client *cl = co->client;
238     Z_InitResponse *r = a->u.initResponse;
239
240     yaz_log(YLOG_DEBUG, "Received init response");
241
242     if (*r->result)
243     {
244         cl->state = Client_Idle;
245     }
246     else
247         cl->state = Client_Failed; // FIXME need to do something to the connection
248 }
249
250 static void do_searchResponse(IOCHAN i, Z_APDU *a)
251 {
252     struct connection *co = iochan_getdata(i);
253     struct client *cl = co->client;
254     struct session *se = cl->session;
255     Z_SearchResponse *r = a->u.searchResponse;
256
257     yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
258
259     if (*r->searchStatus)
260     {
261         cl->hits = *r->resultCount;
262         se->total_hits += cl->hits;
263         if (r->presentStatus && !*r->presentStatus && r->records)
264         {
265             yaz_log(YLOG_DEBUG, "Records in search response");
266             cl->records += *r->numberOfRecordsReturned;
267             ingest_records(cl, r->records);
268         }
269         cl->state = Client_Idle;
270     }
271     else
272     {          /*"FAILED"*/
273         cl->hits = 0;
274         cl->state = Client_Error;
275         if (r->records) {
276             Z_Records *recs = r->records;
277             if (recs->which == Z_Records_NSD)
278             {
279                 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
280                 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
281                 cl->state = Client_Error;
282             }
283         }
284     }
285 }
286
287 char *normalize_mergekey(char *buf)
288 {
289     char *p = buf, *pout = buf;
290
291     while (*p)
292     {
293         while (*p && !isalnum(*p))
294             p++;
295         while (isalnum(*p))
296             *(pout++) = tolower(*(p++));
297         if (*p)
298             *(pout++) = ' ';
299         while (*p && !isalnum(*p))
300             p++;
301     }
302     if (buf != pout)
303         *pout = '\0';
304
305     return buf;
306 }
307
308
309 #ifdef GAGA
310 // FIXME needs to be generalized. Should flexibly generate X lists per search
311 static void extract_subject(struct session *s, const char *rec)
312 {
313     const char *field, *subfield;
314
315     while ((field = find_field(rec, "650")))
316     {
317         rec = field; 
318         if ((subfield = find_subfield(field, 'a')))
319         {
320             char *e, *ef;
321             char buf[1024];
322             int len;
323
324             ef = index(subfield, '\n');
325             if (!ef)
326                 return;
327             if ((e = index(subfield, '\t')) && e < ef)
328                 ef = e;
329             while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
330                 ef--;
331             len = ef - subfield;
332             assert(len < 1023);
333             memcpy(buf, subfield, len);
334             buf[len] = '\0';
335 #ifdef FIXME
336             if (*buf)
337                 termlist_insert(s->termlist, buf);
338 #endif
339         }
340     }
341 }
342 #endif
343
344 static void add_facet(struct session *s, const char *type, const char *value)
345 {
346     int i;
347
348     for (i = 0; i < s->num_termlists; i++)
349         if (!strcmp(s->termlists[i].name, type))
350             break;
351     if (i == s->num_termlists)
352     {
353         if (i == SESSION_MAX_TERMLISTS)
354         {
355             yaz_log(YLOG_FATAL, "Too many termlists");
356             exit(1);
357         }
358         s->termlists[i].name = nmem_strdup(s->nmem, type);
359         s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
360         s->num_termlists = i + 1;
361     }
362     termlist_insert(s->termlists[i].termlist, value);
363 }
364
365 int yaz_marc_write_xml();
366
367 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
368 {
369     struct conf_retrievalprofile *rprofile = cl->database->rprofile;
370     struct conf_retrievalmap *m;
371     xmlNode *res;
372     xmlDoc *rdoc;
373
374     // First normalize to XML
375     if (rprofile->native_syntax == Nativesyn_iso2709)
376     {
377         char *buf;
378         int len;
379         if (rec->which != Z_External_octet)
380         {
381             yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
382             return 0;
383         }
384         buf = (char*) rec->u.octet_aligned->buf;
385         len = rec->u.octet_aligned->len;
386         if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
387         {
388             yaz_log(YLOG_WARN, "Failed to decode MARC");
389             return 0;
390         }
391         if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
392                     "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
393         {
394             yaz_log(YLOG_WARN, "Failed to encode as XML");
395             return 0;
396         }
397         rdoc = xmlNewDoc("1.0");
398         xmlDocSetRootElement(rdoc, res);
399     }
400     else
401     {
402         yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
403         exit(1);
404     }
405     for (m = rprofile->maplist; m; m = m->next)
406     {
407         xmlDoc *new;
408         if (m->type != Map_xslt)
409         {
410             yaz_log(YLOG_WARN, "Unknown map type");
411             return 0;
412         }
413         if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
414         {
415             yaz_log(YLOG_WARN, "XSLT transformation failed");
416             return 0;
417         }
418         xmlFreeDoc(rdoc);
419         rdoc = new;
420     }
421     if (global_parameters.dump_records)
422     {
423         fprintf(stderr, "Record:\n----------------\n");
424         xmlDocFormatDump(stderr, rdoc, 1);
425     }
426     return rdoc;
427 }
428
429 // Extract what appears to be years from buf, storing highest and
430 // lowest values.
431 static int extract_years(const char *buf, int *first, int *last)
432 {
433     *first = -1;
434     *last = -1;
435     while (*buf)
436     {
437         const char *e;
438         int len;
439
440         while (*buf && !isdigit(*buf))
441             buf++;
442         len = 0;
443         for (e = buf; *e && isdigit(*e); e++)
444             len++;
445         if (len == 4)
446         {
447             int value = atoi(buf);
448             if (*first < 0 || value < *first)
449                 *first = value;
450             if (*last < 0 || value > *last)
451                 *last = value;
452         }
453         buf = e;
454     }
455     return *first;
456 }
457
458 static struct record *ingest_record(struct client *cl, Z_External *rec)
459 {
460     xmlDoc *xdoc = normalize_record(cl, rec);
461     xmlNode *root, *n;
462     struct record *res;
463     struct record_cluster *cluster;
464     struct session *se = cl->session;
465     xmlChar *mergekey, *mergekey_norm;
466     xmlChar *type;
467     xmlChar *value;
468     struct conf_service *service = global_parameters.server->service;
469
470     if (!xdoc)
471         return 0;
472
473     root = xmlDocGetRootElement(xdoc);
474     if (!(mergekey = xmlGetProp(root, "mergekey")))
475     {
476         yaz_log(YLOG_WARN, "No mergekey found in record");
477         xmlFreeDoc(xdoc);
478         return 0;
479     }
480
481     res = nmem_malloc(se->nmem, sizeof(struct record));
482     res->next = 0;
483     res->metadata = nmem_malloc(se->nmem,
484             sizeof(struct record_metadata*) * service->num_metadata);
485     memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
486
487     mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
488     xmlFree(mergekey);
489     normalize_mergekey(mergekey_norm);
490
491     cluster = reclist_insert(se->reclist, res, mergekey_norm, &se->total_merged);
492     if (!cluster)
493     {
494         /* no room for record */
495         xmlFreeDoc(xdoc);
496         return 0;
497     }
498     relevance_newrec(se->relevance, cluster);
499
500     type = value = 0;
501     for (n = root->children; n; n = n->next)
502     {
503         if (type)
504             xmlFree(type);
505         if (value)
506             xmlFree(value);
507         type = value = 0;
508
509         if (n->type != XML_ELEMENT_NODE)
510             continue;
511         if (!strcmp(n->name, "metadata"))
512         {
513             type = xmlGetProp(n, "type");
514             value = xmlNodeListGetString(xdoc, n->children, 0);
515             struct conf_metadata *md = 0;
516             struct record_metadata **wheretoput, *newm;
517             int imeta;
518             int first, last;
519
520             // First, find out what field we're looking at
521             for (imeta = 0; imeta < service->num_metadata; imeta++)
522                 if (!strcmp(type, service->metadata[imeta].name))
523                 {
524                     md = &service->metadata[imeta];
525                     break;
526                 }
527             if (!md)
528             {
529                 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
530                 continue;
531             }
532
533             // Find out where we are putting it
534             if (md->merge == Metadata_merge_no)
535                 wheretoput = &res->metadata[imeta];
536             else
537                 wheretoput = &cluster->metadata[imeta];
538             
539             // Put it there
540             newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
541             newm->next = 0;
542             if (md->type == Metadata_type_generic)
543             {
544                 newm->data.text = nmem_strdup(se->nmem, value);
545             }
546             else if (md->type == Metadata_type_year)
547             {
548                 if (extract_years(value, &first, &last) < 0)
549                     continue;
550             }
551             else
552             {
553                 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
554                 continue;
555             }
556             if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
557             {
558                 yaz_log(YLOG_WARN, "Only range merging supported for years");
559                 continue;
560             }
561             if (md->merge == Metadata_merge_unique)
562             {
563                 struct record_metadata *mnode;
564                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
565                     if (!strcmp(mnode->data.text, mnode->data.text))
566                         break;
567                 if (!mnode)
568                 {
569                     newm->next = *wheretoput;
570                     *wheretoput = newm;
571                 }
572             }
573             else if (md->merge == Metadata_merge_longest)
574             {
575                 if (!*wheretoput ||
576                         strlen(newm->data.text) > strlen((*wheretoput)->data.text))
577                 *wheretoput = newm;
578             }
579             else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
580             {
581                 newm->next = *wheretoput;
582                 *wheretoput = newm;
583             }
584             else if (md->merge == Metadata_merge_range)
585             {
586                 assert(md->type == Metadata_type_year);
587                 if (!*wheretoput)
588                 {
589                     *wheretoput = newm;
590                     (*wheretoput)->data.year.year1 = first;
591                     (*wheretoput)->data.year.year2 = last;
592                 }
593                 else
594                 {
595                     if (first < (*wheretoput)->data.year.year1)
596                         (*wheretoput)->data.year.year1 = first;
597                     if (last > (*wheretoput)->data.year.year2)
598                         (*wheretoput)->data.year.year2 = last;
599                 }
600             }
601             else
602                 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
603
604             if (md->rank)
605                 relevance_countwords(se->relevance, cluster, value, md->rank);
606             if (md->termlist)
607                 add_facet(se, type, value);
608             xmlFree(type);
609             xmlFree(value);
610             type = value = 0;
611         }
612         else
613             yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
614     }
615
616     xmlFreeDoc(xdoc);
617
618     relevance_donerecord(se->relevance, cluster);
619     se->total_records++;
620
621     return res;
622 }
623
624 static void ingest_records(struct client *cl, Z_Records *r)
625 {
626 #if USE_TIMING
627     yaz_timing_t t = yaz_timing_create();
628 #endif
629     struct record *rec;
630     struct session *s = cl->session;
631     Z_NamePlusRecordList *rlist;
632     int i;
633
634     if (r->which != Z_Records_DBOSD)
635         return;
636     rlist = r->u.databaseOrSurDiagnostics;
637     for (i = 0; i < rlist->num_records; i++)
638     {
639         Z_NamePlusRecord *npr = rlist->records[i];
640
641         if (npr->which != Z_NamePlusRecord_databaseRecord)
642         {
643             yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
644             continue;
645         }
646
647         rec = ingest_record(cl, npr->u.databaseRecord);
648         if (!rec)
649             continue;
650     }
651     if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
652         session_alert_watch(s, SESSION_WATCH_RECORDS);
653
654 #if USE_TIMING
655     yaz_timing_stop(t);
656     yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f", 
657             yaz_timing_get_real(t), yaz_timing_get_user(t),
658             yaz_timing_get_sys(t));
659     yaz_timing_destroy(&t);
660 #endif
661 }
662
663 static void do_presentResponse(IOCHAN i, Z_APDU *a)
664 {
665     struct connection *co = iochan_getdata(i);
666     struct client *cl = co->client;
667     Z_PresentResponse *r = a->u.presentResponse;
668
669     if (r->records) {
670         Z_Records *recs = r->records;
671         if (recs->which == Z_Records_NSD)
672         {
673             yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
674             cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
675             cl->state = Client_Error;
676         }
677     }
678
679     if (!*r->presentStatus && cl->state != Client_Error)
680     {
681         yaz_log(YLOG_DEBUG, "Good Present response");
682         cl->records += *r->numberOfRecordsReturned;
683         ingest_records(cl, r->records);
684         cl->state = Client_Idle;
685     }
686     else if (*r->presentStatus) 
687     {
688         yaz_log(YLOG_WARN, "Bad Present response");
689         cl->state = Client_Error;
690     }
691 }
692
693 static void handler(IOCHAN i, int event)
694 {
695     struct connection *co = iochan_getdata(i);
696     struct client *cl = co->client;
697     struct session *se = 0;
698
699     if (cl)
700         se = cl->session;
701     else
702     {
703         yaz_log(YLOG_WARN, "Destroying orphan connection");
704         connection_destroy(co);
705         return;
706     }
707
708     if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
709     {
710         int errcode;
711         socklen_t errlen = sizeof(errcode);
712
713         if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
714             &errlen) < 0 || errcode != 0)
715         {
716             client_fatal(cl);
717             return;
718         }
719         else
720         {
721             yaz_log(YLOG_DEBUG, "Connect OK");
722             co->state = Conn_Open;
723             if (cl)
724                 cl->state = Client_Connected;
725         }
726     }
727
728     else if (event & EVENT_INPUT)
729     {
730         int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
731
732         if (len < 0)
733         {
734             yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
735             connection_destroy(co);
736             return;
737         }
738         else if (len == 0)
739         {
740             yaz_log(YLOG_WARN, "EOF reading from Z server");
741             connection_destroy(co);
742             return;
743         }
744         else if (len > 1) // We discard input if we have no connection
745         {
746             co->state = Conn_Open;
747
748             if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
749             {
750                 Z_APDU *a;
751
752                 odr_reset(global_parameters.odr_in);
753                 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
754                 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
755                 {
756                     client_fatal(cl);
757                     return;
758                 }
759                 switch (a->which)
760                 {
761                     case Z_APDU_initResponse:
762                         do_initResponse(i, a);
763                         break;
764                     case Z_APDU_searchResponse:
765                         do_searchResponse(i, a);
766                         break;
767                     case Z_APDU_presentResponse:
768                         do_presentResponse(i, a);
769                         break;
770                     default:
771                         yaz_log(YLOG_WARN, "Unexpected result from server");
772                         client_fatal(cl);
773                         return;
774                 }
775                 // We aren't expecting staggered output from target
776                 // if (cs_more(t->link))
777                 //    iochan_setevent(i, EVENT_INPUT);
778             }
779             else  // we throw away response and go to idle mode
780             {
781                 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
782                 cl->state = Client_Idle;
783             }
784         }
785         /* if len==1 we do nothing but wait for more input */
786     }
787
788     if (cl->state == Client_Connected) {
789         send_init(i);
790     }
791
792     if (cl->state == Client_Idle)
793     {
794         if (cl->requestid != se->requestid && *se->query) {
795             send_search(i);
796         }
797         else if (cl->hits > 0 && cl->records < global_parameters.toget &&
798             cl->records < cl->hits) {
799             send_present(i);
800         }
801     }
802 }
803
804 // Disassociate connection from client
805 static void connection_release(struct connection *co)
806 {
807     struct client *cl = co->client;
808
809     yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
810     if (!cl)
811         return;
812     cl->connection = 0;
813     co->client = 0;
814 }
815
816 // Close connection and recycle structure
817 static void connection_destroy(struct connection *co)
818 {
819     struct host *h = co->host;
820     cs_close(co->link);
821     iochan_destroy(co->iochan);
822
823     yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
824     if (h->connections == co)
825         h->connections = co->next;
826     else
827     {
828         struct connection *pco;
829         for (pco = h->connections; pco && pco->next != co; pco = pco->next)
830             ;
831         if (pco)
832             pco->next = co->next;
833         else
834             abort();
835     }
836     if (co->client)
837     {
838         if (co->client->state != Client_Idle)
839             co->client->state = Client_Disconnected;
840         co->client->connection = 0;
841     }
842     co->next = connection_freelist;
843     connection_freelist = co;
844 }
845
846 // Creates a new connection for client, associated with the host of 
847 // client's database
848 static struct connection *connection_create(struct client *cl)
849 {
850     struct connection *new;
851     COMSTACK link; 
852     int res;
853     void *addr;
854
855     yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
856     if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
857     {
858         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
859         exit(1);
860     }
861
862     if (!(addr = cs_straddr(link, cl->database->host->ipport)))
863     {
864         yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address %s failed?", 
865             cl->database->host->ipport);
866         return 0;
867     }
868
869     res = cs_connect(link, addr);
870     if (res < 0)
871     {
872         yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
873         return 0;
874     }
875
876     if ((new = connection_freelist))
877         connection_freelist = new->next;
878     else
879     {
880         new = xmalloc(sizeof (struct connection));
881         new->ibuf = 0;
882         new->ibufsize = 0;
883     }
884     new->state = Conn_Connecting;
885     new->host = cl->database->host;
886     new->next = new->host->connections;
887     new->host->connections = new;
888     new->client = cl;
889     cl->connection = new;
890     new->link = link;
891
892     new->iochan = iochan_create(cs_fileno(link), handler, 0);
893     iochan_setdata(new->iochan, new);
894     new->iochan->next = channel_list;
895     channel_list = new->iochan;
896     return new;
897 }
898
899 // Close connection and set state to error
900 static void client_fatal(struct client *cl)
901 {
902     yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
903     connection_destroy(cl->connection);
904     cl->state = Client_Error;
905 }
906
907 // Ensure that client has a connection associated
908 static int client_prep_connection(struct client *cl)
909 {
910     struct connection *co;
911     struct session *se = cl->session;
912     struct host *host = cl->database->host;
913
914     co = cl->connection;
915
916     yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
917
918     if (!co)
919     {
920         // See if someone else has an idle connection
921         // We should look at timestamps here to select the longest-idle connection
922         for (co = host->connections; co; co = co->next)
923             if (co->state == Conn_Open && (!co->client || co->client->session != se))
924                 break;
925         if (co)
926         {
927             connection_release(co);
928             cl->connection = co;
929             co->client = cl;
930         }
931         else
932             co = connection_create(cl);
933     }
934     if (co)
935     {
936         if (co->state == Conn_Connecting)
937         {
938             cl->state = Client_Connecting;
939             iochan_setflag(co->iochan, EVENT_OUTPUT);
940         }
941         else if (co->state == Conn_Open)
942         {
943             if (cl->state == Client_Error || cl->state == Client_Disconnected)
944                 cl->state = Client_Idle;
945             iochan_setflag(co->iochan, EVENT_OUTPUT);
946         }
947         return 1;
948     }
949     else
950         return 0;
951 }
952
953 // This function will most likely vanish when a proper target profile mechanism is
954 // introduced.
955 void load_simpletargets(const char *fn)
956 {
957     FILE *f = fopen(fn, "r");
958     char line[256];
959
960     if (!f)
961     {
962         yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
963         exit(1);
964     }
965
966     while (fgets(line, 255, f))
967     {
968         char *url, *db;
969         struct host *host;
970         struct database *database;
971
972         if (strncmp(line, "target ", 7))
973             continue;
974         url = line + 7;
975         url[strlen(url) - 1] = '\0';
976         yaz_log(YLOG_DEBUG, "Target: %s", url);
977         if ((db = strchr(url, '/')))
978             *(db++) = '\0';
979         else
980             db = "Default";
981
982         for (host = hosts; host; host = host->next)
983             if (!strcmp(url, host->hostport))
984                 break;
985         if (!host)
986         {
987             struct addrinfo *addrinfo, hints;
988             char *port;
989             char ipport[128];
990             unsigned char addrbuf[4];
991             int res;
992
993             host = xmalloc(sizeof(struct host));
994             host->hostport = xstrdup(url);
995             host->connections = 0;
996
997             if ((port = strchr(url, ':')))
998                 *(port++) = '\0';
999             else
1000                 port = "210";
1001
1002             hints.ai_flags = 0;
1003             hints.ai_family = PF_INET;
1004             hints.ai_socktype = SOCK_STREAM;
1005             hints.ai_protocol = IPPROTO_TCP;
1006             hints.ai_addrlen = 0;
1007             hints.ai_addr = 0;
1008             hints.ai_canonname = 0;
1009             hints.ai_next = 0;
1010             // This is not robust code. It assumes that getaddrinfo returns AF_INET
1011             // address.
1012             if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1013             {
1014                 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1015                 xfree(host->hostport);
1016                 xfree(host);
1017                 continue;
1018             }
1019             assert(addrinfo->ai_family == PF_INET);
1020             memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1021             sprintf(ipport, "%u.%u.%u.%u:%s",
1022                     addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1023             host->ipport = xstrdup(ipport);
1024             freeaddrinfo(addrinfo);
1025             host->next = hosts;
1026             hosts = host;
1027         }
1028         database = xmalloc(sizeof(struct database));
1029         database->host = host;
1030         database->url = xmalloc(strlen(url) + strlen(db) + 2);
1031         strcpy(database->url, url);
1032         strcat(database->url, "/");
1033         strcat(database->url, db);
1034         
1035         database->databases = xmalloc(2 * sizeof(char *));
1036         database->databases[0] = xstrdup(db);
1037         database->databases[1] = 0;
1038         database->errors = 0;
1039         database->qprofile = 0;
1040         database->rprofile = database_retrieval_profile(database);
1041         database->next = databases;
1042         databases = database;
1043
1044     }
1045     fclose(f);
1046 }
1047
1048 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1049 {
1050     switch (n->kind)
1051     {
1052         case CCL_RPN_AND:
1053         case CCL_RPN_OR:
1054         case CCL_RPN_NOT:
1055         case CCL_RPN_PROX:
1056             pull_terms(nmem, n->u.p[0], termlist, num);
1057             pull_terms(nmem, n->u.p[1], termlist, num);
1058             break;
1059         case CCL_RPN_TERM:
1060             termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1061             break;
1062         default: // NOOP
1063             break;
1064     }
1065 }
1066
1067 // Extract terms from query into null-terminated termlist
1068 static int extract_terms(NMEM nmem, char *query, char **termlist)
1069 {
1070     int error, pos;
1071     struct ccl_rpn_node *n;
1072     int num = 0;
1073
1074     n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1075     if (!n)
1076         return -1;
1077     pull_terms(nmem, n, termlist, &num);
1078     termlist[num] = 0;
1079     ccl_rpn_delete(n);
1080     return 0;
1081 }
1082
1083 static struct client *client_create(void)
1084 {
1085     struct client *r;
1086     if (client_freelist)
1087     {
1088         r = client_freelist;
1089         client_freelist = client_freelist->next;
1090     }
1091     else
1092         r = xmalloc(sizeof(struct client));
1093     r->database = 0;
1094     r->connection = 0;
1095     r->session = 0;
1096     r->hits = 0;
1097     r->records = 0;
1098     r->setno = 0;
1099     r->requestid = -1;
1100     r->diagnostic = 0;
1101     r->state = Client_Disconnected;
1102     r->next = 0;
1103     return r;
1104 }
1105
1106 void client_destroy(struct client *c)
1107 {
1108     struct session *se = c->session;
1109     if (c == se->clients)
1110         se->clients = c->next;
1111     else
1112     {
1113         struct client *cc;
1114         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1115             ;
1116         if (cc)
1117             cc->next = c->next;
1118     }
1119     if (c->connection)
1120         connection_release(c->connection);
1121     c->next = client_freelist;
1122     client_freelist = c;
1123 }
1124
1125 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1126 {
1127     s->watchlist[what].fun = fun;
1128     s->watchlist[what].data = data;
1129 }
1130
1131 void session_alert_watch(struct session *s, int what)
1132 {
1133     if (!s->watchlist[what].fun)
1134         return;
1135     (*s->watchlist[what].fun)(s->watchlist[what].data);
1136     s->watchlist[what].fun = 0;
1137     s->watchlist[what].data = 0;
1138 }
1139
1140 // This needs to be extended with selection criteria
1141 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1142 {
1143     if (!config)
1144     {
1145         yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1146         exit(1);
1147     }
1148     if (!config->retrievalprofiles)
1149     {
1150         yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1151     }
1152     return config->retrievalprofiles;
1153 }
1154
1155 // This should be extended with parameters to control selection criteria
1156 // Associates a set of clients with a session;
1157 int select_targets(struct session *se)
1158 {
1159     struct database *db;
1160     int c = 0;
1161
1162     while (se->clients)
1163         client_destroy(se->clients);
1164     for (db = databases; db; db = db->next)
1165     {
1166         struct client *cl = client_create();
1167         cl->database = db;
1168         cl->session = se;
1169         cl->next = se->clients;
1170         se->clients = cl;
1171         c++;
1172     }
1173     return c;
1174 }
1175
1176 int session_active_clients(struct session *s)
1177 {
1178     struct client *c;
1179     int res = 0;
1180
1181     for (c = s->clients; c; c = c->next)
1182         if (c->connection && (c->state == Client_Connecting ||
1183                     c->state == Client_Initializing ||
1184                     c->state == Client_Searching ||
1185                     c->state == Client_Presenting))
1186             res++;
1187
1188     return res;
1189 }
1190
1191 char *search(struct session *se, char *query)
1192 {
1193     int live_channels = 0;
1194     struct client *cl;
1195
1196     yaz_log(YLOG_DEBUG, "Search");
1197
1198     strcpy(se->query, query);
1199     se->requestid++;
1200     nmem_reset(se->nmem);
1201     for (cl = se->clients; cl; cl = cl->next)
1202     {
1203         cl->hits = -1;
1204         cl->records = 0;
1205         cl->diagnostic = 0;
1206
1207         if (client_prep_connection(cl))
1208             live_channels++;
1209     }
1210     if (live_channels)
1211     {
1212         char *p[512];
1213         int maxrecs = live_channels * global_parameters.toget;
1214         se->num_termlists = 0;
1215         se->reclist = reclist_create(se->nmem, maxrecs);
1216         extract_terms(se->nmem, query, p);
1217         se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1218         se->total_records = se->total_hits = se->total_merged = 0;
1219         se->expected_maxrecs = maxrecs;
1220     }
1221     else
1222         return "NOTARGETS";
1223
1224     return 0;
1225 }
1226
1227 void destroy_session(struct session *s)
1228 {
1229     yaz_log(YLOG_LOG, "Destroying session");
1230     while (s->clients)
1231         client_destroy(s->clients);
1232     nmem_destroy(s->nmem);
1233     wrbuf_free(s->wrbuf, 1);
1234 }
1235
1236 struct session *new_session() 
1237 {
1238     int i;
1239     struct session *session = xmalloc(sizeof(*session));
1240
1241     yaz_log(YLOG_DEBUG, "New pazpar2 session");
1242     
1243     session->total_hits = 0;
1244     session->total_records = 0;
1245     session->num_termlists = 0;
1246     session->reclist = 0;
1247     session->requestid = -1;
1248     session->clients = 0;
1249     session->expected_maxrecs = 0;
1250     session->query[0] = '\0';
1251     session->nmem = nmem_create();
1252     session->wrbuf = wrbuf_alloc();
1253     for (i = 0; i <= SESSION_WATCH_MAX; i++)
1254     {
1255         session->watchlist[i].data = 0;
1256         session->watchlist[i].fun = 0;
1257     }
1258
1259     select_targets(session);
1260
1261     return session;
1262 }
1263
1264 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1265 {
1266     static struct hitsbytarget res[1000]; // FIXME MM
1267     struct client *cl;
1268
1269     *count = 0;
1270     for (cl = se->clients; cl; cl = cl->next)
1271     {
1272         strcpy(res[*count].id, cl->database->host->hostport);
1273         res[*count].hits = cl->hits;
1274         res[*count].records = cl->records;
1275         res[*count].diagnostic = cl->diagnostic;
1276         res[*count].state = client_states[cl->state];
1277         res[*count].connected  = cl->connection ? 1 : 0;
1278         (*count)++;
1279     }
1280
1281     return res;
1282 }
1283
1284 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1285 {
1286     int i;
1287
1288     for (i = 0; i < s->num_termlists; i++)
1289         if (!strcmp(s->termlists[i].name, name))
1290             return termlist_highscore(s->termlists[i].termlist, num);
1291     return 0;
1292 }
1293
1294 #ifdef MISSING_HEADERS
1295 void report_nmem_stats(void)
1296 {
1297     size_t in_use, is_free;
1298
1299     nmem_get_memory_in_use(&in_use);
1300     nmem_get_memory_free(&is_free);
1301
1302     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1303             (long) in_use, (long) is_free);
1304 }
1305 #endif
1306
1307 struct record_cluster *show_single(struct session *s, int id)
1308 {
1309     struct record_cluster *r;
1310
1311     reclist_rewind(s->reclist);
1312     while ((r = reclist_read_record(s->reclist)))
1313         if (r->recid == id)
1314             return r;
1315     return 0;
1316 }
1317
1318 struct record_cluster **show(struct session *s, int start, int *num, int *total,
1319                      int *sumhits, NMEM nmem_show)
1320 {
1321     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
1322                                        * sizeof(struct record_cluster *));
1323     int i;
1324 #if USE_TIMING    
1325     yaz_timing_t t = yaz_timing_create();
1326 #endif
1327     relevance_prepare_read(s->relevance, s->reclist);
1328
1329     *total = s->reclist->num_records;
1330     *sumhits = s->total_hits;
1331
1332     for (i = 0; i < start; i++)
1333         if (!reclist_read_record(s->reclist))
1334         {
1335             *num = 0;
1336             recs = 0;
1337             break;
1338         }
1339
1340     for (i = 0; i < *num; i++)
1341     {
1342         struct record_cluster *r = reclist_read_record(s->reclist);
1343         if (!r)
1344         {
1345             *num = i;
1346             break;
1347         }
1348         recs[i] = r;
1349     }
1350 #if USE_TIMING
1351     yaz_timing_stop(t);
1352     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1353             yaz_timing_get_real(t), yaz_timing_get_user(t),
1354             yaz_timing_get_sys(t));
1355     yaz_timing_destroy(&t);
1356 #endif
1357     return recs;
1358 }
1359
1360 void statistics(struct session *se, struct statistics *stat)
1361 {
1362     struct client *cl;
1363     int count = 0;
1364
1365     memset(stat, 0, sizeof(*stat));
1366     for (cl = se->clients; cl; cl = cl->next)
1367     {
1368         if (!cl->connection)
1369             stat->num_no_connection++;
1370         switch (cl->state)
1371         {
1372             case Client_Connecting: stat->num_connecting++; break;
1373             case Client_Initializing: stat->num_initializing++; break;
1374             case Client_Searching: stat->num_searching++; break;
1375             case Client_Presenting: stat->num_presenting++; break;
1376             case Client_Idle: stat->num_idle++; break;
1377             case Client_Failed: stat->num_failed++; break;
1378             case Client_Error: stat->num_error++; break;
1379             default: break;
1380         }
1381         count++;
1382     }
1383     stat->num_hits = se->total_hits;
1384     stat->num_records = se->total_records;
1385
1386     stat->num_clients = count;
1387 }
1388
1389 static CCL_bibset load_cclfile(const char *fn)
1390 {
1391     CCL_bibset res = ccl_qual_mk();
1392     if (ccl_qual_fname(res, fn) < 0)
1393     {
1394         yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1395         exit(1);
1396     }
1397     return res;
1398 }
1399
1400 int main(int argc, char **argv)
1401 {
1402     int ret;
1403     char *arg;
1404     int setport = 0;
1405
1406     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1407         yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1408
1409     yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1410
1411     while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1412     {
1413         switch (ret) {
1414             case 'f':
1415                 if (!read_config(arg))
1416                     exit(1);
1417                 break;
1418             case 'h':
1419                 http_init(arg);
1420                 setport++;
1421                 break;
1422             case 'C':
1423                 global_parameters.ccl_filter = load_cclfile(arg);
1424                 break;
1425             case 'p':
1426                 http_set_proxyaddr(arg);
1427                 break;
1428             case 's':
1429                 load_simpletargets(arg);
1430                 break;
1431             case 'd':
1432                 global_parameters.dump_records = 1;
1433                 break;
1434             default:
1435                 fprintf(stderr, "Usage: pazpar2\n"
1436                         "    -f configfile\n"
1437                         "    -h [host:]port          (REST protocol listener)\n"
1438                         "    -C cclconfig\n"
1439                         "    -s simpletargetfile\n"
1440                         "    -p hostname[:portno]    (HTTP proxy)\n");
1441                 exit(1);
1442         }
1443     }
1444
1445     if (!config)
1446     {
1447         yaz_log(YLOG_FATAL, "Load config with -f");
1448         exit(1);
1449     }
1450     global_parameters.server = config->servers;
1451
1452     if (!setport)
1453     {
1454         fprintf(stderr, "Set command port with -h\n");
1455         exit(1);
1456     }
1457
1458     global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1459     global_parameters.yaz_marc = yaz_marc_create();
1460     yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1461     global_parameters.odr_in = odr_createmem(ODR_DECODE);
1462     global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1463
1464     event_loop(&channel_list);
1465
1466     return 0;
1467 }
1468
1469 /*
1470  * Local variables:
1471  * c-basic-offset: 4
1472  * indent-tabs-mode: nil
1473  * End:
1474  * vim: shiftwidth=4 tabstop=8 expandtab
1475  */