b5a0ee71719a7047a332ef2ca58028b7cc27d88c
[pazpar2-moved-to-github.git] / src / pazpar2.c
1 /* $Id: pazpar2.c,v 1.22 2007-01-09 22:06:49 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->metadata = nmem_malloc(se->nmem,
482             sizeof(struct record_metadata*) * service->num_metadata);
483     bzero(res->metadata, sizeof(struct record_metadata*) * service->num_metadata);
484
485     mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
486     xmlFree(mergekey);
487     normalize_mergekey(mergekey_norm);
488
489     cluster = reclist_insert(se->reclist, res, mergekey_norm, &se->total_merged);
490     if (!cluster)
491     {
492         /* no room for record */
493         xmlFreeDoc(xdoc);
494         return 0;
495     }
496     relevance_newrec(se->relevance, cluster);
497
498     type = value = 0;
499     for (n = root->children; n; n = n->next)
500     {
501         if (type)
502             xmlFree(type);
503         if (value)
504             xmlFree(value);
505         type = value = 0;
506
507         if (n->type != XML_ELEMENT_NODE)
508             continue;
509         if (!strcmp(n->name, "metadata"))
510         {
511             type = xmlGetProp(n, "type");
512             value = xmlNodeListGetString(xdoc, n->children, 0);
513             struct conf_metadata *md = 0;
514             struct record_metadata **wheretoput, *newm;
515             int imeta;
516             int first, last;
517
518             // First, find out what field we're looking at
519             for (imeta = 0; imeta < service->num_metadata; imeta++)
520                 if (!strcmp(type, service->metadata[imeta].name))
521                 {
522                     md = &service->metadata[imeta];
523                     break;
524                 }
525             if (!md)
526             {
527                 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
528                 continue;
529             }
530
531             // Find out where we are putting it
532             if (md->merge == Metadata_merge_no)
533                 wheretoput = &res->metadata[imeta];
534             else
535                 wheretoput = &cluster->metadata[imeta];
536             
537             // Put it there
538             newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
539             newm->next = 0;
540             if (md->type == Metadata_type_generic)
541             {
542                 newm->data.text = nmem_strdup(se->nmem, value);
543             }
544             else if (md->type == Metadata_type_year)
545             {
546                 if (extract_years(value, &first, &last) < 0)
547                     continue;
548             }
549             else
550             {
551                 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
552                 continue;
553             }
554             if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
555             {
556                 yaz_log(YLOG_WARN, "Only range merging supported for years");
557                 continue;
558             }
559             if (md->merge == Metadata_merge_unique)
560             {
561                 struct record_metadata *mnode;
562                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
563                     if (!strcmp(mnode->data.text, mnode->data.text))
564                         break;
565                 if (!mnode)
566                 {
567                     newm->next = *wheretoput;
568                     *wheretoput = newm;
569                 }
570             }
571             else if (md->merge == Metadata_merge_longest)
572             {
573                 if (!*wheretoput ||
574                         strlen(newm->data.text) > strlen((*wheretoput)->data.text))
575                 *wheretoput = newm;
576             }
577             else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
578             {
579                 newm->next = *wheretoput;
580                 *wheretoput = newm;
581             }
582             else if (md->merge == Metadata_merge_range)
583             {
584                 assert(md->type == Metadata_type_year);
585                 if (!*wheretoput)
586                 {
587                     *wheretoput = newm;
588                     (*wheretoput)->data.year.year1 = first;
589                     (*wheretoput)->data.year.year2 = last;
590                 }
591                 else
592                 {
593                     if (first < (*wheretoput)->data.year.year1)
594                         (*wheretoput)->data.year.year1 = first;
595                     if (last > (*wheretoput)->data.year.year2)
596                         (*wheretoput)->data.year.year2 = last;
597                 }
598             }
599             else
600                 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
601
602             if (md->rank)
603                 relevance_countwords(se->relevance, cluster, value, md->rank);
604             if (md->termlist)
605                 add_facet(se, type, value);
606             xmlFree(type);
607             xmlFree(value);
608             type = value = 0;
609         }
610         else
611             yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
612     }
613
614     xmlFreeDoc(xdoc);
615
616     relevance_donerecord(se->relevance, cluster);
617     se->total_records++;
618
619     return res;
620 }
621
622 static void ingest_records(struct client *cl, Z_Records *r)
623 {
624 #if USE_TIMING
625     yaz_timing_t t = yaz_timing_create();
626 #endif
627     struct record *rec;
628     struct session *s = cl->session;
629     Z_NamePlusRecordList *rlist;
630     int i;
631
632     if (r->which != Z_Records_DBOSD)
633         return;
634     rlist = r->u.databaseOrSurDiagnostics;
635     for (i = 0; i < rlist->num_records; i++)
636     {
637         Z_NamePlusRecord *npr = rlist->records[i];
638
639         if (npr->which != Z_NamePlusRecord_databaseRecord)
640         {
641             yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
642             continue;
643         }
644
645         rec = ingest_record(cl, npr->u.databaseRecord);
646         if (!rec)
647             continue;
648     }
649     if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
650         session_alert_watch(s, SESSION_WATCH_RECORDS);
651
652 #if USE_TIMING
653     yaz_timing_stop(t);
654     yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f", 
655             yaz_timing_get_real(t), yaz_timing_get_user(t),
656             yaz_timing_get_sys(t));
657     yaz_timing_destroy(&t);
658 #endif
659 }
660
661 static void do_presentResponse(IOCHAN i, Z_APDU *a)
662 {
663     struct connection *co = iochan_getdata(i);
664     struct client *cl = co->client;
665     Z_PresentResponse *r = a->u.presentResponse;
666
667     if (r->records) {
668         Z_Records *recs = r->records;
669         if (recs->which == Z_Records_NSD)
670         {
671             yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
672             cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
673             cl->state = Client_Error;
674         }
675     }
676
677     if (!*r->presentStatus && cl->state != Client_Error)
678     {
679         yaz_log(YLOG_DEBUG, "Good Present response");
680         cl->records += *r->numberOfRecordsReturned;
681         ingest_records(cl, r->records);
682         cl->state = Client_Idle;
683     }
684     else if (*r->presentStatus) 
685     {
686         yaz_log(YLOG_WARN, "Bad Present response");
687         cl->state = Client_Error;
688     }
689 }
690
691 static void handler(IOCHAN i, int event)
692 {
693     struct connection *co = iochan_getdata(i);
694     struct client *cl = co->client;
695     struct session *se = 0;
696
697     if (cl)
698         se = cl->session;
699     else
700     {
701         yaz_log(YLOG_WARN, "Destroying orphan connection");
702         connection_destroy(co);
703         return;
704     }
705
706     if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
707     {
708         int errcode;
709         socklen_t errlen = sizeof(errcode);
710
711         if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
712             &errlen) < 0 || errcode != 0)
713         {
714             client_fatal(cl);
715             return;
716         }
717         else
718         {
719             yaz_log(YLOG_DEBUG, "Connect OK");
720             co->state = Conn_Open;
721             if (cl)
722                 cl->state = Client_Connected;
723         }
724     }
725
726     else if (event & EVENT_INPUT)
727     {
728         int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
729
730         if (len < 0)
731         {
732             yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
733             connection_destroy(co);
734             return;
735         }
736         else if (len == 0)
737         {
738             yaz_log(YLOG_WARN, "EOF reading from Z server");
739             connection_destroy(co);
740             return;
741         }
742         else if (len > 1) // We discard input if we have no connection
743         {
744             co->state = Conn_Open;
745
746             if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
747             {
748                 Z_APDU *a;
749
750                 odr_reset(global_parameters.odr_in);
751                 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
752                 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
753                 {
754                     client_fatal(cl);
755                     return;
756                 }
757                 switch (a->which)
758                 {
759                     case Z_APDU_initResponse:
760                         do_initResponse(i, a);
761                         break;
762                     case Z_APDU_searchResponse:
763                         do_searchResponse(i, a);
764                         break;
765                     case Z_APDU_presentResponse:
766                         do_presentResponse(i, a);
767                         break;
768                     default:
769                         yaz_log(YLOG_WARN, "Unexpected result from server");
770                         client_fatal(cl);
771                         return;
772                 }
773                 // We aren't expecting staggered output from target
774                 // if (cs_more(t->link))
775                 //    iochan_setevent(i, EVENT_INPUT);
776             }
777             else  // we throw away response and go to idle mode
778             {
779                 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
780                 cl->state = Client_Idle;
781             }
782         }
783         /* if len==1 we do nothing but wait for more input */
784     }
785
786     if (cl->state == Client_Connected) {
787         send_init(i);
788     }
789
790     if (cl->state == Client_Idle)
791     {
792         if (cl->requestid != se->requestid && *se->query) {
793             send_search(i);
794         }
795         else if (cl->hits > 0 && cl->records < global_parameters.toget &&
796             cl->records < cl->hits) {
797             send_present(i);
798         }
799     }
800 }
801
802 // Disassociate connection from client
803 static void connection_release(struct connection *co)
804 {
805     struct client *cl = co->client;
806
807     yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
808     if (!cl)
809         return;
810     cl->connection = 0;
811     co->client = 0;
812 }
813
814 // Close connection and recycle structure
815 static void connection_destroy(struct connection *co)
816 {
817     struct host *h = co->host;
818     cs_close(co->link);
819     iochan_destroy(co->iochan);
820
821     yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
822     if (h->connections == co)
823         h->connections = co->next;
824     else
825     {
826         struct connection *pco;
827         for (pco = h->connections; pco && pco->next != co; pco = pco->next)
828             ;
829         if (pco)
830             pco->next = co->next;
831         else
832             abort();
833     }
834     if (co->client)
835     {
836         if (co->client->state != Client_Idle)
837             co->client->state = Client_Disconnected;
838         co->client->connection = 0;
839     }
840     co->next = connection_freelist;
841     connection_freelist = co;
842 }
843
844 // Creates a new connection for client, associated with the host of 
845 // client's database
846 static struct connection *connection_create(struct client *cl)
847 {
848     struct connection *new;
849     COMSTACK link; 
850     int res;
851     void *addr;
852
853     yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
854     if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
855     {
856         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
857         exit(1);
858     }
859
860     if (!(addr = cs_straddr(link, cl->database->host->ipport)))
861     {
862         yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
863         return 0;
864     }
865
866     res = cs_connect(link, addr);
867     if (res < 0)
868     {
869         yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
870         return 0;
871     }
872
873     if ((new = connection_freelist))
874         connection_freelist = new->next;
875     else
876     {
877         new = xmalloc(sizeof (struct connection));
878         new->ibuf = 0;
879         new->ibufsize = 0;
880     }
881     new->state = Conn_Connecting;
882     new->host = cl->database->host;
883     new->next = new->host->connections;
884     new->host->connections = new;
885     new->client = cl;
886     cl->connection = new;
887     new->link = link;
888
889     new->iochan = iochan_create(cs_fileno(link), handler, 0);
890     iochan_setdata(new->iochan, new);
891     new->iochan->next = channel_list;
892     channel_list = new->iochan;
893     return new;
894 }
895
896 // Close connection and set state to error
897 static void client_fatal(struct client *cl)
898 {
899     yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
900     connection_destroy(cl->connection);
901     cl->state = Client_Error;
902 }
903
904 // Ensure that client has a connection associated
905 static int client_prep_connection(struct client *cl)
906 {
907     struct connection *co;
908     struct session *se = cl->session;
909     struct host *host = cl->database->host;
910
911     co = cl->connection;
912
913     yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
914
915     if (!co)
916     {
917         // See if someone else has an idle connection
918         // We should look at timestamps here to select the longest-idle connection
919         for (co = host->connections; co; co = co->next)
920             if (co->state == Conn_Open && (!co->client || co->client->session != se))
921                 break;
922         if (co)
923         {
924             connection_release(co);
925             cl->connection = co;
926             co->client = cl;
927         }
928         else
929             co = connection_create(cl);
930     }
931     if (co)
932     {
933         if (co->state == Conn_Connecting)
934         {
935             cl->state = Client_Connecting;
936             iochan_setflag(co->iochan, EVENT_OUTPUT);
937         }
938         else if (co->state == Conn_Open)
939         {
940             if (cl->state == Client_Error || cl->state == Client_Disconnected)
941                 cl->state = Client_Idle;
942             iochan_setflag(co->iochan, EVENT_OUTPUT);
943         }
944         return 1;
945     }
946     else
947         return 0;
948 }
949
950 // This function will most likely vanish when a proper target profile mechanism is
951 // introduced.
952 void load_simpletargets(const char *fn)
953 {
954     FILE *f = fopen(fn, "r");
955     char line[256];
956
957     if (!f)
958     {
959         yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
960         exit(1);
961     }
962
963     while (fgets(line, 255, f))
964     {
965         char *url, *db;
966         struct host *host;
967         struct database *database;
968
969         if (strncmp(line, "target ", 7))
970             continue;
971         url = line + 7;
972         url[strlen(url) - 1] = '\0';
973         yaz_log(YLOG_DEBUG, "Target: %s", url);
974         if ((db = strchr(url, '/')))
975             *(db++) = '\0';
976         else
977             db = "Default";
978
979         for (host = hosts; host; host = host->next)
980             if (!strcmp(url, host->hostport))
981                 break;
982         if (!host)
983         {
984             struct addrinfo *addrinfo, hints;
985             char *port;
986             char ipport[128];
987             unsigned char addrbuf[4];
988             int res;
989
990             host = xmalloc(sizeof(struct host));
991             host->hostport = xstrdup(url);
992             host->connections = 0;
993
994             if ((port = strchr(url, ':')))
995                 *(port++) = '\0';
996             else
997                 port = "210";
998
999             hints.ai_flags = 0;
1000             hints.ai_family = PF_INET;
1001             hints.ai_socktype = SOCK_STREAM;
1002             hints.ai_protocol = IPPROTO_TCP;
1003             hints.ai_addrlen = 0;
1004             hints.ai_addr = 0;
1005             hints.ai_canonname = 0;
1006             hints.ai_next = 0;
1007             // This is not robust code. It assumes that getaddrinfo returns AF_INET
1008             // address.
1009             if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1010             {
1011                 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1012                 xfree(host->hostport);
1013                 xfree(host);
1014                 continue;
1015             }
1016             assert(addrinfo->ai_family == PF_INET);
1017             memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1018             sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
1019                     addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1020             host->ipport = xstrdup(ipport);
1021             freeaddrinfo(addrinfo);
1022             host->next = hosts;
1023             hosts = host;
1024         }
1025         database = xmalloc(sizeof(struct database));
1026         database->host = host;
1027         database->url = xmalloc(strlen(url) + strlen(db) + 2);
1028         strcpy(database->url, url);
1029         strcat(database->url, "/");
1030         strcat(database->url, db);
1031         
1032         database->databases = xmalloc(2 * sizeof(char *));
1033         database->databases[0] = xstrdup(db);
1034         database->databases[1] = 0;
1035         database->errors = 0;
1036         database->qprofile = 0;
1037         database->rprofile = database_retrieval_profile(database);
1038         database->next = databases;
1039         databases = database;
1040
1041     }
1042     fclose(f);
1043 }
1044
1045 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1046 {
1047     switch (n->kind)
1048     {
1049         case CCL_RPN_AND:
1050         case CCL_RPN_OR:
1051         case CCL_RPN_NOT:
1052         case CCL_RPN_PROX:
1053             pull_terms(nmem, n->u.p[0], termlist, num);
1054             pull_terms(nmem, n->u.p[1], termlist, num);
1055             break;
1056         case CCL_RPN_TERM:
1057             termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1058             break;
1059         default: // NOOP
1060             break;
1061     }
1062 }
1063
1064 // Extract terms from query into null-terminated termlist
1065 static int extract_terms(NMEM nmem, char *query, char **termlist)
1066 {
1067     int error, pos;
1068     struct ccl_rpn_node *n;
1069     int num = 0;
1070
1071     n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1072     if (!n)
1073         return -1;
1074     pull_terms(nmem, n, termlist, &num);
1075     termlist[num] = 0;
1076     ccl_rpn_delete(n);
1077     return 0;
1078 }
1079
1080 static struct client *client_create(void)
1081 {
1082     struct client *r;
1083     if (client_freelist)
1084     {
1085         r = client_freelist;
1086         client_freelist = client_freelist->next;
1087     }
1088     else
1089         r = xmalloc(sizeof(struct client));
1090     r->database = 0;
1091     r->connection = 0;
1092     r->session = 0;
1093     r->hits = 0;
1094     r->records = 0;
1095     r->setno = 0;
1096     r->requestid = -1;
1097     r->diagnostic = 0;
1098     r->state = Client_Disconnected;
1099     r->next = 0;
1100     return r;
1101 }
1102
1103 void client_destroy(struct client *c)
1104 {
1105     struct session *se = c->session;
1106     if (c == se->clients)
1107         se->clients = c->next;
1108     else
1109     {
1110         struct client *cc;
1111         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1112             ;
1113         if (cc)
1114             cc->next = c->next;
1115     }
1116     if (c->connection)
1117         connection_release(c->connection);
1118     c->next = client_freelist;
1119     client_freelist = c;
1120 }
1121
1122 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1123 {
1124     s->watchlist[what].fun = fun;
1125     s->watchlist[what].data = data;
1126 }
1127
1128 void session_alert_watch(struct session *s, int what)
1129 {
1130     if (!s->watchlist[what].fun)
1131         return;
1132     (*s->watchlist[what].fun)(s->watchlist[what].data);
1133     s->watchlist[what].fun = 0;
1134     s->watchlist[what].data = 0;
1135 }
1136
1137 // This needs to be extended with selection criteria
1138 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1139 {
1140     if (!config)
1141     {
1142         yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1143         exit(1);
1144     }
1145     if (!config->retrievalprofiles)
1146     {
1147         yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1148     }
1149     return config->retrievalprofiles;
1150 }
1151
1152 // This should be extended with parameters to control selection criteria
1153 // Associates a set of clients with a session;
1154 int select_targets(struct session *se)
1155 {
1156     struct database *db;
1157     int c = 0;
1158
1159     while (se->clients)
1160         client_destroy(se->clients);
1161     for (db = databases; db; db = db->next)
1162     {
1163         struct client *cl = client_create();
1164         cl->database = db;
1165         cl->session = se;
1166         cl->next = se->clients;
1167         se->clients = cl;
1168         c++;
1169     }
1170     return c;
1171 }
1172
1173 int session_active_clients(struct session *s)
1174 {
1175     struct client *c;
1176     int res = 0;
1177
1178     for (c = s->clients; c; c = c->next)
1179         if (c->connection && (c->state == Client_Connecting ||
1180                     c->state == Client_Initializing ||
1181                     c->state == Client_Searching ||
1182                     c->state == Client_Presenting))
1183             res++;
1184
1185     return res;
1186 }
1187
1188 char *search(struct session *se, char *query)
1189 {
1190     int live_channels = 0;
1191     struct client *cl;
1192
1193     yaz_log(YLOG_DEBUG, "Search");
1194
1195     strcpy(se->query, query);
1196     se->requestid++;
1197     nmem_reset(se->nmem);
1198     for (cl = se->clients; cl; cl = cl->next)
1199     {
1200         cl->hits = -1;
1201         cl->records = 0;
1202         cl->diagnostic = 0;
1203
1204         if (client_prep_connection(cl))
1205             live_channels++;
1206     }
1207     if (live_channels)
1208     {
1209         char *p[512];
1210         int maxrecs = live_channels * global_parameters.toget;
1211         se->num_termlists = 0;
1212         se->reclist = reclist_create(se->nmem, maxrecs);
1213         extract_terms(se->nmem, query, p);
1214         se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1215         se->total_records = se->total_hits = se->total_merged = 0;
1216         se->expected_maxrecs = maxrecs;
1217     }
1218     else
1219         return "NOTARGETS";
1220
1221     return 0;
1222 }
1223
1224 void destroy_session(struct session *s)
1225 {
1226     yaz_log(YLOG_LOG, "Destroying session");
1227     while (s->clients)
1228         client_destroy(s->clients);
1229     nmem_destroy(s->nmem);
1230     wrbuf_free(s->wrbuf, 1);
1231 }
1232
1233 struct session *new_session() 
1234 {
1235     int i;
1236     struct session *session = xmalloc(sizeof(*session));
1237
1238     yaz_log(YLOG_DEBUG, "New pazpar2 session");
1239     
1240     session->total_hits = 0;
1241     session->total_records = 0;
1242     session->num_termlists = 0;
1243     session->reclist = 0;
1244     session->requestid = -1;
1245     session->clients = 0;
1246     session->expected_maxrecs = 0;
1247     session->query[0] = '\0';
1248     session->nmem = nmem_create();
1249     session->wrbuf = wrbuf_alloc();
1250     for (i = 0; i <= SESSION_WATCH_MAX; i++)
1251     {
1252         session->watchlist[i].data = 0;
1253         session->watchlist[i].fun = 0;
1254     }
1255
1256     select_targets(session);
1257
1258     return session;
1259 }
1260
1261 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1262 {
1263     static struct hitsbytarget res[1000]; // FIXME MM
1264     struct client *cl;
1265
1266     *count = 0;
1267     for (cl = se->clients; cl; cl = cl->next)
1268     {
1269         strcpy(res[*count].id, cl->database->host->hostport);
1270         res[*count].hits = cl->hits;
1271         res[*count].records = cl->records;
1272         res[*count].diagnostic = cl->diagnostic;
1273         res[*count].state = client_states[cl->state];
1274         res[*count].connected  = cl->connection ? 1 : 0;
1275         (*count)++;
1276     }
1277
1278     return res;
1279 }
1280
1281 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1282 {
1283     int i;
1284
1285     for (i = 0; i < s->num_termlists; i++)
1286         if (!strcmp(s->termlists[i].name, name))
1287             return termlist_highscore(s->termlists[i].termlist, num);
1288     return 0;
1289 }
1290
1291 #ifdef MISSING_HEADERS
1292 void report_nmem_stats(void)
1293 {
1294     size_t in_use, is_free;
1295
1296     nmem_get_memory_in_use(&in_use);
1297     nmem_get_memory_free(&is_free);
1298
1299     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1300             (long) in_use, (long) is_free);
1301 }
1302 #endif
1303
1304 struct record_cluster *show_single(struct session *s, int id)
1305 {
1306     struct record_cluster *r;
1307
1308     reclist_rewind(s->reclist);
1309     while ((r = reclist_read_record(s->reclist)))
1310         if (r->recid == id)
1311             return r;
1312     return 0;
1313 }
1314
1315 struct record_cluster **show(struct session *s, int start, int *num, int *total,
1316                      int *sumhits, NMEM nmem_show)
1317 {
1318     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
1319                                        * sizeof(struct record_cluster *));
1320     int i;
1321 #if USE_TIMING    
1322     yaz_timing_t t = yaz_timing_create();
1323 #endif
1324     relevance_prepare_read(s->relevance, s->reclist);
1325
1326     *total = s->reclist->num_records;
1327     *sumhits = s->total_hits;
1328
1329     for (i = 0; i < start; i++)
1330         if (!reclist_read_record(s->reclist))
1331         {
1332             *num = 0;
1333             recs = 0;
1334             break;
1335         }
1336
1337     for (i = 0; i < *num; i++)
1338     {
1339         struct record_cluster *r = reclist_read_record(s->reclist);
1340         if (!r)
1341         {
1342             *num = i;
1343             break;
1344         }
1345         recs[i] = r;
1346     }
1347 #if USE_TIMING
1348     yaz_timing_stop(t);
1349     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1350             yaz_timing_get_real(t), yaz_timing_get_user(t),
1351             yaz_timing_get_sys(t));
1352     yaz_timing_destroy(&t);
1353 #endif
1354     return recs;
1355 }
1356
1357 void statistics(struct session *se, struct statistics *stat)
1358 {
1359     struct client *cl;
1360     int count = 0;
1361
1362     bzero(stat, sizeof(*stat));
1363     for (cl = se->clients; cl; cl = cl->next)
1364     {
1365         if (!cl->connection)
1366             stat->num_no_connection++;
1367         switch (cl->state)
1368         {
1369             case Client_Connecting: stat->num_connecting++; break;
1370             case Client_Initializing: stat->num_initializing++; break;
1371             case Client_Searching: stat->num_searching++; break;
1372             case Client_Presenting: stat->num_presenting++; break;
1373             case Client_Idle: stat->num_idle++; break;
1374             case Client_Failed: stat->num_failed++; break;
1375             case Client_Error: stat->num_error++; break;
1376             default: break;
1377         }
1378         count++;
1379     }
1380     stat->num_hits = se->total_hits;
1381     stat->num_records = se->total_records;
1382
1383     stat->num_clients = count;
1384 }
1385
1386 static CCL_bibset load_cclfile(const char *fn)
1387 {
1388     CCL_bibset res = ccl_qual_mk();
1389     if (ccl_qual_fname(res, fn) < 0)
1390     {
1391         yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1392         exit(1);
1393     }
1394     return res;
1395 }
1396
1397 int main(int argc, char **argv)
1398 {
1399     int ret;
1400     char *arg;
1401     int setport = 0;
1402
1403     if (signal(SIGPIPE, SIG_IGN) < 0)
1404         yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1405
1406     yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1407
1408     while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1409     {
1410         switch (ret) {
1411             case 'f':
1412                 if (!read_config(arg))
1413                     exit(1);
1414                 break;
1415             case 'h':
1416                 http_init(arg);
1417                 setport++;
1418                 break;
1419             case 'C':
1420                 global_parameters.ccl_filter = load_cclfile(arg);
1421                 break;
1422             case 'p':
1423                 http_set_proxyaddr(arg);
1424                 break;
1425             case 's':
1426                 load_simpletargets(arg);
1427                 break;
1428             case 'd':
1429                 global_parameters.dump_records = 1;
1430                 break;
1431             default:
1432                 fprintf(stderr, "Usage: pazpar2\n"
1433                         "    -f configfile\n"
1434                         "    -h [host:]port          (REST protocol listener)\n"
1435                         "    -C cclconfig\n"
1436                         "    -s simpletargetfile\n"
1437                         "    -p hostname[:portno]    (HTTP proxy)\n");
1438                 exit(1);
1439         }
1440     }
1441
1442     if (!config)
1443     {
1444         yaz_log(YLOG_FATAL, "Load config with -f");
1445         exit(1);
1446     }
1447     global_parameters.server = config->servers;
1448
1449     if (!setport)
1450     {
1451         fprintf(stderr, "Set command port with -h\n");
1452         exit(1);
1453     }
1454
1455     global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1456     global_parameters.yaz_marc = yaz_marc_create();
1457     yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1458     global_parameters.odr_in = odr_createmem(ODR_DECODE);
1459     global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1460
1461     event_loop(&channel_list);
1462
1463     return 0;
1464 }
1465
1466 /*
1467  * Local variables:
1468  * c-basic-offset: 4
1469  * indent-tabs-mode: nil
1470  * End:
1471  * vim: shiftwidth=4 tabstop=8 expandtab
1472  */