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