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