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