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