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