Added date support (md-date in show command).
[pazpar2-moved-to-github.git] / src / pazpar2.c
1 /* $Id: pazpar2.c,v 1.21 2007-01-09 18:06:28 quinn 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 "pazpar2.h"
33 #include "eventl.h"
34 #include "http.h"
35 #include "termlists.h"
36 #include "reclists.h"
37 #include "relevance.h"
38 #include "config.h"
39
40 #define MAX_CHUNK 15
41
42 static void client_fatal(struct client *cl);
43 static void connection_destroy(struct connection *co);
44 static int client_prep_connection(struct client *cl);
45 static void ingest_records(struct client *cl, Z_Records *r);
46 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db);
47 void session_alert_watch(struct session *s, int what);
48
49 IOCHAN channel_list = 0;  // Master list of connections we're handling events to
50
51 static struct connection *connection_freelist = 0;
52 static struct client *client_freelist = 0;
53
54 static struct host *hosts = 0;  // The hosts we know about 
55 static struct database *databases = 0; // The databases we know about
56
57 static char *client_states[] = {
58     "Client_Connecting",
59     "Client_Connected",
60     "Client_Idle",
61     "Client_Initializing",
62     "Client_Searching",
63     "Client_Presenting",
64     "Client_Error",
65     "Client_Failed",
66     "Client_Disconnected",
67     "Client_Stopped"
68 };
69
70 // Note: Some things in this structure will eventually move to configuration
71 struct parameters global_parameters = 
72 {
73     0,
74     0,
75     30,
76     "81",
77     "Index Data PazPar2 (MasterKey)",
78     VERSION,
79     600, // 10 minutes
80     60,
81     100,
82     MAX_CHUNK,
83     0,
84     0,
85     0,
86     0
87 };
88
89 static int send_apdu(struct client *c, Z_APDU *a)
90 {
91     struct connection *co = c->connection;
92     char *buf;
93     int len, r;
94
95     if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
96     {
97         odr_perror(global_parameters.odr_out, "Encoding APDU");
98         abort();
99     }
100     buf = odr_getbuf(global_parameters.odr_out, &len, 0);
101     r = cs_put(co->link, buf, len);
102     if (r < 0)
103     {
104         yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
105         return -1;
106     }
107     else if (r == 1)
108     {
109         fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
110         exit(1);
111     }
112     odr_reset(global_parameters.odr_out); /* release the APDU structure  */
113     co->state = Conn_Waiting;
114     return 0;
115 }
116
117
118 static void send_init(IOCHAN i)
119 {
120     struct connection *co = iochan_getdata(i);
121     struct client *cl = co->client;
122     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
123
124     a->u.initRequest->implementationId = global_parameters.implementationId;
125     a->u.initRequest->implementationName = global_parameters.implementationName;
126     a->u.initRequest->implementationVersion =
127         global_parameters.implementationVersion;
128     ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
129     ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
130     ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
131
132     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
133     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
134     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
135     if (send_apdu(cl, a) >= 0)
136     {
137         iochan_setflags(i, EVENT_INPUT);
138         cl->state = Client_Initializing;
139     }
140     else
141         cl->state = Client_Error;
142     odr_reset(global_parameters.odr_out);
143 }
144
145 static void send_search(IOCHAN i)
146 {
147     struct connection *co = iochan_getdata(i);
148     struct client *cl = co->client; 
149     struct session *se = cl->session;
150     struct database *db = cl->database;
151     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
152     int ndb, cerror, cpos;
153     char **databaselist;
154     Z_Query *zquery;
155     struct ccl_rpn_node *cn;
156     int ssub = 0, lslb = 100000, mspn = 10;
157
158     yaz_log(YLOG_DEBUG, "Sending search");
159
160     cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
161     if (!cn)
162         return;
163     a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
164             sizeof(Z_Query));
165     zquery->which = Z_Query_type_1;
166     zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
167     ccl_rpn_delete(cn);
168
169     for (ndb = 0; db->databases[ndb]; ndb++)
170         ;
171     databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
172     for (ndb = 0; db->databases[ndb]; ndb++)
173         databaselist[ndb] = db->databases[ndb];
174
175     a->u.presentRequest->preferredRecordSyntax =
176             yaz_oidval_to_z3950oid(global_parameters.odr_out,
177             CLASS_RECSYN, VAL_USMARC);
178     a->u.searchRequest->smallSetUpperBound = &ssub;
179     a->u.searchRequest->largeSetLowerBound = &lslb;
180     a->u.searchRequest->mediumSetPresentNumber = &mspn;
181     a->u.searchRequest->resultSetName = "Default";
182     a->u.searchRequest->databaseNames = databaselist;
183     a->u.searchRequest->num_databaseNames = ndb;
184
185     if (send_apdu(cl, a) >= 0)
186     {
187         iochan_setflags(i, EVENT_INPUT);
188         cl->state = Client_Searching;
189         cl->requestid = se->requestid;
190     }
191     else
192         cl->state = Client_Error;
193
194     odr_reset(global_parameters.odr_out);
195 }
196
197 static void send_present(IOCHAN i)
198 {
199     struct connection *co = iochan_getdata(i);
200     struct client *cl = co->client; 
201     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
202     int toget;
203     int start = cl->records + 1;
204
205     toget = global_parameters.chunk;
206     if (toget > global_parameters.toget - cl->records)
207         toget = global_parameters.toget - cl->records;
208     if (toget > cl->hits - cl->records)
209         toget = cl->hits - cl->records;
210
211     yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
212
213     a->u.presentRequest->resultSetStartPoint = &start;
214     a->u.presentRequest->numberOfRecordsRequested = &toget;
215
216     a->u.presentRequest->resultSetId = "Default";
217
218     a->u.presentRequest->preferredRecordSyntax =
219             yaz_oidval_to_z3950oid(global_parameters.odr_out,
220             CLASS_RECSYN, VAL_USMARC);
221
222     if (send_apdu(cl, a) >= 0)
223     {
224         iochan_setflags(i, EVENT_INPUT);
225         cl->state = Client_Presenting;
226     }
227     else
228         cl->state = Client_Error;
229     odr_reset(global_parameters.odr_out);
230 }
231
232 static void do_initResponse(IOCHAN i, Z_APDU *a)
233 {
234     struct connection *co = iochan_getdata(i);
235     struct client *cl = co->client;
236     Z_InitResponse *r = a->u.initResponse;
237
238     yaz_log(YLOG_DEBUG, "Received init response");
239
240     if (*r->result)
241     {
242         cl->state = Client_Idle;
243     }
244     else
245         cl->state = Client_Failed; // FIXME need to do something to the connection
246 }
247
248 static void do_searchResponse(IOCHAN i, Z_APDU *a)
249 {
250     struct connection *co = iochan_getdata(i);
251     struct client *cl = co->client;
252     struct session *se = cl->session;
253     Z_SearchResponse *r = a->u.searchResponse;
254
255     yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
256
257     if (*r->searchStatus)
258     {
259         cl->hits = *r->resultCount;
260         se->total_hits += cl->hits;
261         if (r->presentStatus && !*r->presentStatus && r->records)
262         {
263             yaz_log(YLOG_DEBUG, "Records in search response");
264             cl->records += *r->numberOfRecordsReturned;
265             ingest_records(cl, r->records);
266         }
267         cl->state = Client_Idle;
268     }
269     else
270     {          /*"FAILED"*/
271         cl->hits = 0;
272         cl->state = Client_Error;
273         if (r->records) {
274             Z_Records *recs = r->records;
275             if (recs->which == Z_Records_NSD)
276             {
277                 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
278                 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
279                 cl->state = Client_Error;
280             }
281         }
282     }
283 }
284
285 char *normalize_mergekey(char *buf)
286 {
287     char *p = buf, *pout = buf;
288
289     while (*p)
290     {
291         while (*p && !isalnum(*p))
292             p++;
293         while (isalnum(*p))
294             *(pout++) = tolower(*(p++));
295         if (*p)
296             *(pout++) = ' ';
297         while (*p && !isalnum(*p))
298             p++;
299     }
300     if (buf != pout)
301         *pout = '\0';
302
303     return buf;
304 }
305
306
307 #ifdef GAGA
308 // FIXME needs to be generalized. Should flexibly generate X lists per search
309 static void extract_subject(struct session *s, const char *rec)
310 {
311     const char *field, *subfield;
312
313     while ((field = find_field(rec, "650")))
314     {
315         rec = field; 
316         if ((subfield = find_subfield(field, 'a')))
317         {
318             char *e, *ef;
319             char buf[1024];
320             int len;
321
322             ef = index(subfield, '\n');
323             if (!ef)
324                 return;
325             if ((e = index(subfield, '\t')) && e < ef)
326                 ef = e;
327             while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
328                 ef--;
329             len = ef - subfield;
330             assert(len < 1023);
331             memcpy(buf, subfield, len);
332             buf[len] = '\0';
333 #ifdef FIXME
334             if (*buf)
335                 termlist_insert(s->termlist, buf);
336 #endif
337         }
338     }
339 }
340 #endif
341
342 static void add_facet(struct session *s, const char *type, const char *value)
343 {
344     int i;
345
346     for (i = 0; i < s->num_termlists; i++)
347         if (!strcmp(s->termlists[i].name, type))
348             break;
349     if (i == s->num_termlists)
350     {
351         if (i == SESSION_MAX_TERMLISTS)
352         {
353             yaz_log(YLOG_FATAL, "Too many termlists");
354             exit(1);
355         }
356         s->termlists[i].name = nmem_strdup(s->nmem, type);
357         s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
358         s->num_termlists = i + 1;
359     }
360     termlist_insert(s->termlists[i].termlist, value);
361 }
362
363 int yaz_marc_write_xml();
364
365 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
366 {
367     struct conf_retrievalprofile *rprofile = cl->database->rprofile;
368     struct conf_retrievalmap *m;
369     xmlNode *res;
370     xmlDoc *rdoc;
371
372     // First normalize to XML
373     if (rprofile->native_syntax == Nativesyn_iso2709)
374     {
375         char *buf;
376         int len;
377         if (rec->which != Z_External_octet)
378         {
379             yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
380             return 0;
381         }
382         buf = (char*) rec->u.octet_aligned->buf;
383         len = rec->u.octet_aligned->len;
384         if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
385         {
386             yaz_log(YLOG_WARN, "Failed to decode MARC");
387             return 0;
388         }
389         if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
390                     "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
391         {
392             yaz_log(YLOG_WARN, "Failed to encode as XML");
393             return 0;
394         }
395         rdoc = xmlNewDoc("1.0");
396         xmlDocSetRootElement(rdoc, res);
397     }
398     else
399     {
400         yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
401         exit(1);
402     }
403     for (m = rprofile->maplist; m; m = m->next)
404     {
405         xmlDoc *new;
406         if (m->type != Map_xslt)
407         {
408             yaz_log(YLOG_WARN, "Unknown map type");
409             return 0;
410         }
411         if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
412         {
413             yaz_log(YLOG_WARN, "XSLT transformation failed");
414             return 0;
415         }
416         xmlFreeDoc(rdoc);
417         rdoc = new;
418     }
419     if (global_parameters.dump_records)
420     {
421         fprintf(stderr, "Record:\n----------------\n");
422         xmlDocFormatDump(stderr, rdoc, 1);
423     }
424     return rdoc;
425 }
426
427 // Extract what appears to be years from buf, storing highest and
428 // lowest values.
429 static int extract_years(const char *buf, int *first, int *last)
430 {
431     *first = -1;
432     *last = -1;
433     while (*buf)
434     {
435         const char *e;
436         int len;
437
438         while (*buf && !isdigit(*buf))
439             buf++;
440         len = 0;
441         for (e = buf; *e && isdigit(*e); e++)
442             len++;
443         if (len == 4)
444         {
445             int value = atoi(buf);
446             if (*first < 0 || value < *first)
447                 *first = value;
448             if (*last < 0 || value > *last)
449                 *last = value;
450         }
451         buf = e;
452     }
453     return *first;
454 }
455
456 static struct record *ingest_record(struct client *cl, Z_External *rec)
457 {
458     xmlDoc *xdoc = normalize_record(cl, rec);
459     xmlNode *root, *n;
460     struct record *res;
461     struct record_cluster *cluster;
462     struct session *se = cl->session;
463     xmlChar *mergekey, *mergekey_norm;
464     xmlChar *type;
465     xmlChar *value;
466     struct conf_service *service = global_parameters.server->service;
467
468     if (!xdoc)
469         return 0;
470
471     root = xmlDocGetRootElement(xdoc);
472     if (!(mergekey = xmlGetProp(root, "mergekey")))
473     {
474         yaz_log(YLOG_WARN, "No mergekey found in record");
475         xmlFreeDoc(xdoc);
476         return 0;
477     }
478
479     res = nmem_malloc(se->nmem, sizeof(struct record));
480     res->next = 0;
481     res->target_offset = -1;
482     res->term_frequency_vec = 0;
483     res->metadata = nmem_malloc(se->nmem,
484             sizeof(struct record_metadata*) * service->num_metadata);
485     bzero(res->metadata, sizeof(struct record_metadata*) * service->num_metadata);
486     res->relevance = 0;
487
488     mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
489     xmlFree(mergekey);
490     normalize_mergekey(mergekey_norm);
491
492     cluster = reclist_insert(se->reclist, res, mergekey_norm);
493     if (!cluster)
494     {
495         /* no room for record */
496         xmlFreeDoc(xdoc);
497         return 0;
498     }
499     relevance_newrec(se->relevance, cluster);
500
501     type = value = 0;
502     for (n = root->children; n; n = n->next)
503     {
504         if (type)
505             xmlFree(type);
506         if (value)
507             xmlFree(value);
508         type = value = 0;
509
510         if (n->type != XML_ELEMENT_NODE)
511             continue;
512         if (!strcmp(n->name, "metadata"))
513         {
514             type = xmlGetProp(n, "type");
515             value = xmlNodeListGetString(xdoc, n->children, 0);
516             struct conf_metadata *md = 0;
517             struct record_metadata **wheretoput, *newm;
518             int imeta;
519             int first, last;
520
521             // First, find out what field we're looking at
522             for (imeta = 0; imeta < service->num_metadata; imeta++)
523                 if (!strcmp(type, service->metadata[imeta].name))
524                 {
525                     md = &service->metadata[imeta];
526                     break;
527                 }
528             if (!md)
529             {
530                 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
531                 continue;
532             }
533
534             // Find out where we are putting it
535             if (md->merge == Metadata_merge_no)
536                 wheretoput = &res->metadata[imeta];
537             else
538                 wheretoput = &cluster->metadata[imeta];
539             
540             // Put it there
541             newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
542             newm->next = 0;
543             if (md->type == Metadata_type_generic)
544             {
545                 newm->data.text = nmem_strdup(se->nmem, value);
546             }
547             else if (md->type == Metadata_type_year)
548             {
549                 if (extract_years(value, &first, &last) < 0)
550                     continue;
551             }
552             else
553             {
554                 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
555                 continue;
556             }
557             if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
558             {
559                 yaz_log(YLOG_WARN, "Only range merging supported for years");
560                 continue;
561             }
562             if (md->merge == Metadata_merge_unique)
563             {
564                 struct record_metadata *mnode;
565                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
566                     if (!strcmp(mnode->data.text, mnode->data.text))
567                         break;
568                 if (!mnode)
569                 {
570                     newm->next = *wheretoput;
571                     *wheretoput = newm;
572                 }
573             }
574             else if (md->merge == Metadata_merge_longest)
575             {
576                 if (!*wheretoput ||
577                         strlen(newm->data.text) > strlen((*wheretoput)->data.text))
578                 *wheretoput = newm;
579             }
580             else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
581             {
582                 newm->next = *wheretoput;
583                 *wheretoput = newm;
584             }
585             else if (md->merge == Metadata_merge_range)
586             {
587                 assert(md->type == Metadata_type_year);
588                 if (!*wheretoput)
589                 {
590                     *wheretoput = newm;
591                     (*wheretoput)->data.year.year1 = first;
592                     (*wheretoput)->data.year.year2 = last;
593                 }
594                 else
595                 {
596                     if (first < (*wheretoput)->data.year.year1)
597                         (*wheretoput)->data.year.year1 = first;
598                     if (last > (*wheretoput)->data.year.year2)
599                         (*wheretoput)->data.year.year2 = last;
600                 }
601             }
602             else
603                 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
604
605             if (md->rank)
606                 relevance_countwords(se->relevance, cluster, value, md->rank);
607             if (md->termlist)
608                 add_facet(se, type, value);
609             xmlFree(type);
610             xmlFree(value);
611             type = value = 0;
612         }
613         else
614             yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
615     }
616
617     xmlFreeDoc(xdoc);
618
619     relevance_donerecord(se->relevance, cluster);
620     se->total_records++;
621
622     return res;
623 }
624
625 static void ingest_records(struct client *cl, Z_Records *r)
626 {
627 #if USE_TIMING
628     yaz_timing_t t = yaz_timing_create();
629 #endif
630     struct record *rec;
631     struct session *s = cl->session;
632     Z_NamePlusRecordList *rlist;
633     int i;
634
635     if (r->which != Z_Records_DBOSD)
636         return;
637     rlist = r->u.databaseOrSurDiagnostics;
638     for (i = 0; i < rlist->num_records; i++)
639     {
640         Z_NamePlusRecord *npr = rlist->records[i];
641
642         if (npr->which != Z_NamePlusRecord_databaseRecord)
643         {
644             yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
645             continue;
646         }
647
648         rec = ingest_record(cl, npr->u.databaseRecord);
649         if (!rec)
650             continue;
651     }
652     if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
653         session_alert_watch(s, SESSION_WATCH_RECORDS);
654
655 #if USE_TIMING
656     yaz_timing_stop(t);
657     yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f", 
658             yaz_timing_get_real(t), yaz_timing_get_user(t),
659             yaz_timing_get_sys(t));
660     yaz_timing_destroy(&t);
661 #endif
662 }
663
664 static void do_presentResponse(IOCHAN i, Z_APDU *a)
665 {
666     struct connection *co = iochan_getdata(i);
667     struct client *cl = co->client;
668     Z_PresentResponse *r = a->u.presentResponse;
669
670     if (r->records) {
671         Z_Records *recs = r->records;
672         if (recs->which == Z_Records_NSD)
673         {
674             yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
675             cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
676             cl->state = Client_Error;
677         }
678     }
679
680     if (!*r->presentStatus && cl->state != Client_Error)
681     {
682         yaz_log(YLOG_DEBUG, "Good Present response");
683         cl->records += *r->numberOfRecordsReturned;
684         ingest_records(cl, r->records);
685         cl->state = Client_Idle;
686     }
687     else if (*r->presentStatus) 
688     {
689         yaz_log(YLOG_WARN, "Bad Present response");
690         cl->state = Client_Error;
691     }
692 }
693
694 static void handler(IOCHAN i, int event)
695 {
696     struct connection *co = iochan_getdata(i);
697     struct client *cl = co->client;
698     struct session *se = 0;
699
700     if (cl)
701         se = cl->session;
702     else
703     {
704         yaz_log(YLOG_WARN, "Destroying orphan connection");
705         connection_destroy(co);
706         return;
707     }
708
709     if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
710     {
711         int errcode;
712         socklen_t errlen = sizeof(errcode);
713
714         if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
715             &errlen) < 0 || errcode != 0)
716         {
717             client_fatal(cl);
718             return;
719         }
720         else
721         {
722             yaz_log(YLOG_DEBUG, "Connect OK");
723             co->state = Conn_Open;
724             if (cl)
725                 cl->state = Client_Connected;
726         }
727     }
728
729     else if (event & EVENT_INPUT)
730     {
731         int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
732
733         if (len < 0)
734         {
735             yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
736             connection_destroy(co);
737             return;
738         }
739         else if (len == 0)
740         {
741             yaz_log(YLOG_WARN, "EOF reading from Z server");
742             connection_destroy(co);
743             return;
744         }
745         else if (len > 1) // We discard input if we have no connection
746         {
747             co->state = Conn_Open;
748
749             if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
750             {
751                 Z_APDU *a;
752
753                 odr_reset(global_parameters.odr_in);
754                 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
755                 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
756                 {
757                     client_fatal(cl);
758                     return;
759                 }
760                 switch (a->which)
761                 {
762                     case Z_APDU_initResponse:
763                         do_initResponse(i, a);
764                         break;
765                     case Z_APDU_searchResponse:
766                         do_searchResponse(i, a);
767                         break;
768                     case Z_APDU_presentResponse:
769                         do_presentResponse(i, a);
770                         break;
771                     default:
772                         yaz_log(YLOG_WARN, "Unexpected result from server");
773                         client_fatal(cl);
774                         return;
775                 }
776                 // We aren't expecting staggered output from target
777                 // if (cs_more(t->link))
778                 //    iochan_setevent(i, EVENT_INPUT);
779             }
780             else  // we throw away response and go to idle mode
781             {
782                 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
783                 cl->state = Client_Idle;
784             }
785         }
786         /* if len==1 we do nothing but wait for more input */
787     }
788
789     if (cl->state == Client_Connected) {
790         send_init(i);
791     }
792
793     if (cl->state == Client_Idle)
794     {
795         if (cl->requestid != se->requestid && *se->query) {
796             send_search(i);
797         }
798         else if (cl->hits > 0 && cl->records < global_parameters.toget &&
799             cl->records < cl->hits) {
800             send_present(i);
801         }
802     }
803 }
804
805 // Disassociate connection from client
806 static void connection_release(struct connection *co)
807 {
808     struct client *cl = co->client;
809
810     yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
811     if (!cl)
812         return;
813     cl->connection = 0;
814     co->client = 0;
815 }
816
817 // Close connection and recycle structure
818 static void connection_destroy(struct connection *co)
819 {
820     struct host *h = co->host;
821     cs_close(co->link);
822     iochan_destroy(co->iochan);
823
824     yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
825     if (h->connections == co)
826         h->connections = co->next;
827     else
828     {
829         struct connection *pco;
830         for (pco = h->connections; pco && pco->next != co; pco = pco->next)
831             ;
832         if (pco)
833             pco->next = co->next;
834         else
835             abort();
836     }
837     if (co->client)
838     {
839         if (co->client->state != Client_Idle)
840             co->client->state = Client_Disconnected;
841         co->client->connection = 0;
842     }
843     co->next = connection_freelist;
844     connection_freelist = co;
845 }
846
847 // Creates a new connection for client, associated with the host of 
848 // client's database
849 static struct connection *connection_create(struct client *cl)
850 {
851     struct connection *new;
852     COMSTACK link; 
853     int res;
854     void *addr;
855
856     yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
857     if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
858     {
859         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
860         exit(1);
861     }
862
863     if (!(addr = cs_straddr(link, cl->database->host->ipport)))
864     {
865         yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
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, "%hhd.%hhd.%hhd.%hhd:%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 = 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(struct session *s, int start, int *num, int *total,
1308                      int *sumhits, NMEM nmem_show)
1309 {
1310     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
1311                                        * sizeof(struct record_cluster *));
1312     int i;
1313 #if USE_TIMING    
1314     yaz_timing_t t = yaz_timing_create();
1315 #endif
1316     relevance_prepare_read(s->relevance, s->reclist);
1317
1318     *total = s->reclist->num_records;
1319     *sumhits = s->total_hits;
1320
1321     for (i = 0; i < start; i++)
1322         if (!reclist_read_record(s->reclist))
1323         {
1324             *num = 0;
1325             recs = 0;
1326             break;
1327         }
1328
1329     for (i = 0; i < *num; i++)
1330     {
1331         struct record_cluster *r = reclist_read_record(s->reclist);
1332         if (!r)
1333         {
1334             *num = i;
1335             break;
1336         }
1337         recs[i] = r;
1338     }
1339 #if USE_TIMING
1340     yaz_timing_stop(t);
1341     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1342             yaz_timing_get_real(t), yaz_timing_get_user(t),
1343             yaz_timing_get_sys(t));
1344     yaz_timing_destroy(&t);
1345 #endif
1346     return recs;
1347 }
1348
1349 void statistics(struct session *se, struct statistics *stat)
1350 {
1351     struct client *cl;
1352     int count = 0;
1353
1354     bzero(stat, sizeof(*stat));
1355     for (cl = se->clients; cl; cl = cl->next)
1356     {
1357         if (!cl->connection)
1358             stat->num_no_connection++;
1359         switch (cl->state)
1360         {
1361             case Client_Connecting: stat->num_connecting++; break;
1362             case Client_Initializing: stat->num_initializing++; break;
1363             case Client_Searching: stat->num_searching++; break;
1364             case Client_Presenting: stat->num_presenting++; break;
1365             case Client_Idle: stat->num_idle++; break;
1366             case Client_Failed: stat->num_failed++; break;
1367             case Client_Error: stat->num_error++; break;
1368             default: break;
1369         }
1370         count++;
1371     }
1372     stat->num_hits = se->total_hits;
1373     stat->num_records = se->total_records;
1374
1375     stat->num_clients = count;
1376 }
1377
1378 static CCL_bibset load_cclfile(const char *fn)
1379 {
1380     CCL_bibset res = ccl_qual_mk();
1381     if (ccl_qual_fname(res, fn) < 0)
1382     {
1383         yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1384         exit(1);
1385     }
1386     return res;
1387 }
1388
1389 int main(int argc, char **argv)
1390 {
1391     int ret;
1392     char *arg;
1393     int setport = 0;
1394
1395     if (signal(SIGPIPE, SIG_IGN) < 0)
1396         yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1397
1398     yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1399
1400     while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1401     {
1402         switch (ret) {
1403             case 'f':
1404                 if (!read_config(arg))
1405                     exit(1);
1406                 break;
1407             case 'h':
1408                 http_init(arg);
1409                 setport++;
1410                 break;
1411             case 'C':
1412                 global_parameters.ccl_filter = load_cclfile(arg);
1413                 break;
1414             case 'p':
1415                 http_set_proxyaddr(arg);
1416                 break;
1417             case 's':
1418                 load_simpletargets(arg);
1419                 break;
1420             case 'd':
1421                 global_parameters.dump_records = 1;
1422                 break;
1423             default:
1424                 fprintf(stderr, "Usage: pazpar2\n"
1425                         "    -f configfile\n"
1426                         "    -h [host:]port          (REST protocol listener)\n"
1427                         "    -C cclconfig\n"
1428                         "    -s simpletargetfile\n"
1429                         "    -p hostname[:portno]    (HTTP proxy)\n");
1430                 exit(1);
1431         }
1432     }
1433
1434     if (!config)
1435     {
1436         yaz_log(YLOG_FATAL, "Load config with -f");
1437         exit(1);
1438     }
1439     global_parameters.server = config->servers;
1440
1441     if (!setport)
1442     {
1443         fprintf(stderr, "Set command port with -h\n");
1444         exit(1);
1445     }
1446
1447     global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1448     global_parameters.yaz_marc = yaz_marc_create();
1449     yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1450     global_parameters.odr_in = odr_createmem(ODR_DECODE);
1451     global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1452
1453     event_loop(&channel_list);
1454
1455     return 0;
1456 }
1457
1458 /*
1459  * Local variables:
1460  * c-basic-offset: 4
1461  * indent-tabs-mode: nil
1462  * End:
1463  * vim: shiftwidth=4 tabstop=8 expandtab
1464  */