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