fd5ebf5403666d185877a802286f5d7fdee77c66
[pazpar2-moved-to-github.git] / src / pazpar2.c
1 /* $Id: pazpar2.c,v 1.7 2007-01-03 06:23:44 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             cl->state = Client_Connecting;
782         else if (co->state == Conn_Open)
783         {
784             if (cl->state == Client_Error || cl->state == Client_Disconnected)
785                 cl->state = Client_Idle;
786         }
787         iochan_setflag(co->iochan, EVENT_OUTPUT);
788         return 1;
789     }
790     else
791         return 0;
792 }
793
794 // This function will most likely vanish when a proper target profile mechanism is
795 // introduced.
796 void load_simpletargets(const char *fn)
797 {
798     FILE *f = fopen(fn, "r");
799     char line[256];
800
801     if (!f)
802     {
803         yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
804         exit(1);
805     }
806
807     while (fgets(line, 255, f))
808     {
809         char *url, *db;
810         struct host *host;
811         struct database *database;
812
813         if (strncmp(line, "target ", 7))
814             continue;
815         url = line + 7;
816         url[strlen(url) - 1] = '\0';
817         yaz_log(YLOG_DEBUG, "Target: %s", url);
818         if ((db = strchr(url, '/')))
819             *(db++) = '\0';
820         else
821             db = "Default";
822
823         for (host = hosts; host; host = host->next)
824             if (!strcmp(url, host->hostport))
825                 break;
826         if (!host)
827         {
828             struct addrinfo *addrinfo, hints;
829             char *port;
830             char ipport[128];
831             unsigned char addrbuf[4];
832             int res;
833
834             host = xmalloc(sizeof(struct host));
835             host->hostport = xstrdup(url);
836             host->connections = 0;
837
838             if ((port = strchr(url, ':')))
839                 *(port++) = '\0';
840             else
841                 port = "210";
842
843             hints.ai_flags = 0;
844             hints.ai_family = PF_INET;
845             hints.ai_socktype = SOCK_STREAM;
846             hints.ai_protocol = IPPROTO_TCP;
847             hints.ai_addrlen = 0;
848             hints.ai_addr = 0;
849             hints.ai_canonname = 0;
850             hints.ai_next = 0;
851             // This is not robust code. It assumes that getaddrinfo returns AF_INET
852             // address.
853             if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
854             {
855                 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
856                 xfree(host->hostport);
857                 xfree(host);
858                 continue;
859             }
860             assert(addrinfo->ai_family == PF_INET);
861             memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
862             sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
863                     addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
864             host->ipport = xstrdup(ipport);
865             freeaddrinfo(addrinfo);
866             host->next = hosts;
867             hosts = host;
868         }
869         database = xmalloc(sizeof(struct database));
870         database->host = host;
871         database->url = xmalloc(strlen(url) + strlen(db) + 2);
872         strcpy(database->url, url);
873         strcat(database->url, "/");
874         strcat(database->url, db);
875         
876         database->databases = xmalloc(2 * sizeof(char *));
877         database->databases[0] = xstrdup(db);
878         database->databases[1] = 0;
879         database->errors = 0;
880         database->qprofile = 0;
881         database->rprofile = database_retrieval_profile(database);
882         database->next = databases;
883         databases = database;
884
885     }
886     fclose(f);
887 }
888
889 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
890 {
891     switch (n->kind)
892     {
893         case CCL_RPN_AND:
894         case CCL_RPN_OR:
895         case CCL_RPN_NOT:
896         case CCL_RPN_PROX:
897             pull_terms(nmem, n->u.p[0], termlist, num);
898             pull_terms(nmem, n->u.p[1], termlist, num);
899             break;
900         case CCL_RPN_TERM:
901             termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
902             break;
903         default: // NOOP
904             break;
905     }
906 }
907
908 // Extract terms from query into null-terminated termlist
909 static int extract_terms(NMEM nmem, char *query, char **termlist)
910 {
911     int error, pos;
912     struct ccl_rpn_node *n;
913     int num = 0;
914
915     n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
916     if (!n)
917         return -1;
918     pull_terms(nmem, n, termlist, &num);
919     termlist[num] = 0;
920     ccl_rpn_delete(n);
921     return 0;
922 }
923
924 static struct client *client_create(void)
925 {
926     struct client *r;
927     if (client_freelist)
928     {
929         r = client_freelist;
930         client_freelist = client_freelist->next;
931     }
932     else
933         r = xmalloc(sizeof(struct client));
934     r->database = 0;
935     r->connection = 0;
936     r->session = 0;
937     r->hits = 0;
938     r->records = 0;
939     r->setno = 0;
940     r->requestid = -1;
941     r->diagnostic = 0;
942     r->state = Client_Disconnected;
943     r->next = 0;
944     return r;
945 }
946
947 void client_destroy(struct client *c)
948 {
949     struct session *se = c->session;
950     if (c == se->clients)
951         se->clients = c->next;
952     else
953     {
954         struct client *cc;
955         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
956             ;
957         if (cc)
958             cc->next = c->next;
959     }
960     if (c->connection)
961         connection_release(c->connection);
962     c->next = client_freelist;
963     client_freelist = c;
964 }
965
966 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
967 {
968     s->watchlist[what].fun = fun;
969     s->watchlist[what].data = data;
970 }
971
972 void session_alert_watch(struct session *s, int what)
973 {
974     if (!s->watchlist[what].fun)
975         return;
976     (*s->watchlist[what].fun)(s->watchlist[what].data);
977     s->watchlist[what].fun = 0;
978     s->watchlist[what].data = 0;
979 }
980
981 // This needs to be extended with selection criteria
982 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
983 {
984     if (!config)
985     {
986         yaz_log(YLOG_FATAL, "Must load configuration (-f)");
987         exit(1);
988     }
989     if (!config->retrievalprofiles)
990     {
991         yaz_log(YLOG_FATAL, "No retrieval profiles defined");
992     }
993     return config->retrievalprofiles;
994 }
995
996 // This should be extended with parameters to control selection criteria
997 // Associates a set of clients with a session;
998 int select_targets(struct session *se)
999 {
1000     struct database *db;
1001     int c = 0;
1002
1003     while (se->clients)
1004         client_destroy(se->clients);
1005     for (db = databases; db; db = db->next)
1006     {
1007         struct client *cl = client_create();
1008         cl->database = db;
1009         cl->session = se;
1010         cl->next = se->clients;
1011         se->clients = cl;
1012         c++;
1013     }
1014     return c;
1015 }
1016
1017 char *search(struct session *se, char *query)
1018 {
1019     int live_channels = 0;
1020     struct client *cl;
1021
1022     yaz_log(YLOG_DEBUG, "Search");
1023
1024     strcpy(se->query, query);
1025     se->requestid++;
1026     nmem_reset(se->nmem);
1027     for (cl = se->clients; cl; cl = cl->next)
1028     {
1029         cl->hits = -1;
1030         cl->records = 0;
1031         cl->diagnostic = 0;
1032
1033         if (client_prep_connection(cl))
1034             live_channels++;
1035     }
1036     if (live_channels)
1037     {
1038         char *p[512];
1039         int maxrecs = live_channels * global_parameters.toget;
1040         se->num_termlists = 0;
1041         se->reclist = reclist_create(se->nmem, maxrecs);
1042         extract_terms(se->nmem, query, p);
1043         se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1044         se->total_records = se->total_hits = 0;
1045         se->expected_maxrecs = maxrecs;
1046     }
1047     else
1048         return "NOTARGETS";
1049
1050     return 0;
1051 }
1052
1053 void destroy_session(struct session *s)
1054 {
1055     yaz_log(YLOG_LOG, "Destroying session");
1056     while (s->clients)
1057         client_destroy(s->clients);
1058     nmem_destroy(s->nmem);
1059     wrbuf_free(s->wrbuf, 1);
1060 }
1061
1062 struct session *new_session() 
1063 {
1064     int i;
1065     struct session *session = xmalloc(sizeof(*session));
1066
1067     yaz_log(YLOG_DEBUG, "New pazpar2 session");
1068     
1069     session->total_hits = 0;
1070     session->total_records = 0;
1071     session->num_termlists = 0;
1072     session->reclist = 0;
1073     session->requestid = -1;
1074     session->clients = 0;
1075     session->expected_maxrecs = 0;
1076     session->query[0] = '\0';
1077     session->nmem = nmem_create();
1078     session->wrbuf = wrbuf_alloc();
1079     for (i = 0; i <= SESSION_WATCH_MAX; i++)
1080     {
1081         session->watchlist[i].data = 0;
1082         session->watchlist[i].fun = 0;
1083     }
1084
1085     select_targets(session);
1086
1087     return session;
1088 }
1089
1090 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1091 {
1092     static struct hitsbytarget res[1000]; // FIXME MM
1093     struct client *cl;
1094
1095     *count = 0;
1096     for (cl = se->clients; cl; cl = cl->next)
1097     {
1098         strcpy(res[*count].id, cl->database->host->hostport);
1099         res[*count].hits = cl->hits;
1100         res[*count].records = cl->records;
1101         res[*count].diagnostic = cl->diagnostic;
1102         res[*count].state = client_states[cl->state];
1103         res[*count].connected  = cl->connection ? 1 : 0;
1104         (*count)++;
1105     }
1106
1107     return res;
1108 }
1109
1110 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1111 {
1112     int i;
1113
1114     for (i = 0; i < s->num_termlists; i++)
1115         if (!strcmp(s->termlists[i].name, name))
1116             return termlist_highscore(s->termlists[i].termlist, num);
1117     return 0;
1118 }
1119
1120 #ifdef REPORT_NMEM
1121 // conditional compilation by SH: This lead to a warning with currently installed
1122 // YAZ header files on us1
1123 void report_nmem_stats(void)
1124 {
1125     size_t in_use, is_free;
1126
1127     nmem_get_memory_in_use(&in_use);
1128     nmem_get_memory_free(&is_free);
1129
1130     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1131             (long) in_use, (long) is_free);
1132 }
1133 #endif
1134
1135 struct record **show(struct session *s, int start, int *num, int *total,
1136                      int *sumhits, NMEM nmem_show)
1137 {
1138     struct record **recs = nmem_malloc(nmem_show, *num 
1139                                        * sizeof(struct record *));
1140     int i;
1141
1142     relevance_prepare_read(s->relevance, s->reclist);
1143
1144     *total = s->reclist->num_records;
1145     *sumhits = s->total_hits;
1146
1147     for (i = 0; i < start; i++)
1148         if (!reclist_read_record(s->reclist))
1149         {
1150             *num = 0;
1151             return 0;
1152         }
1153
1154     for (i = 0; i < *num; i++)
1155     {
1156         struct record *r = reclist_read_record(s->reclist);
1157         if (!r)
1158         {
1159             *num = i;
1160             break;
1161         }
1162         recs[i] = r;
1163     }
1164     return recs;
1165 }
1166
1167 void statistics(struct session *se, struct statistics *stat)
1168 {
1169     struct client *cl;
1170     int count = 0;
1171
1172     bzero(stat, sizeof(*stat));
1173     for (cl = se->clients; cl; cl = cl->next)
1174     {
1175         if (!cl->connection)
1176             stat->num_no_connection++;
1177         switch (cl->state)
1178         {
1179             case Client_Connecting: stat->num_connecting++; break;
1180             case Client_Initializing: stat->num_initializing++; break;
1181             case Client_Searching: stat->num_searching++; break;
1182             case Client_Presenting: stat->num_presenting++; break;
1183             case Client_Idle: stat->num_idle++; break;
1184             case Client_Failed: stat->num_failed++; break;
1185             case Client_Error: stat->num_error++; break;
1186             default: break;
1187         }
1188         count++;
1189     }
1190     stat->num_hits = se->total_hits;
1191     stat->num_records = se->total_records;
1192
1193     stat->num_clients = count;
1194 }
1195
1196 static CCL_bibset load_cclfile(const char *fn)
1197 {
1198     CCL_bibset res = ccl_qual_mk();
1199     if (ccl_qual_fname(res, fn) < 0)
1200     {
1201         yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1202         exit(1);
1203     }
1204     return res;
1205 }
1206
1207 int main(int argc, char **argv)
1208 {
1209     int ret;
1210     char *arg;
1211     int setport = 0;
1212
1213     if (signal(SIGPIPE, SIG_IGN) < 0)
1214         yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1215
1216     yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1217
1218     while ((ret = options("f:x:c:h:p:C:s:d", argv, argc, &arg)) != -2)
1219     {
1220         switch (ret) {
1221             case 'f':
1222                 if (!read_config(arg))
1223                     exit(1);
1224                 break;
1225             case 'c':
1226                 command_init(atoi(arg));
1227                 setport++;
1228                 break;
1229             case 'h':
1230                 http_init(arg);
1231                 setport++;
1232                 break;
1233             case 'C':
1234                 global_parameters.ccl_filter = load_cclfile(arg);
1235                 break;
1236             case 'p':
1237                 http_set_proxyaddr(arg);
1238                 break;
1239             case 's':
1240                 load_simpletargets(arg);
1241                 break;
1242             case 'd':
1243                 global_parameters.dump_records = 1;
1244                 break;
1245             default:
1246                 fprintf(stderr, "Usage: pazpar2\n"
1247                         "    -f configfile\n"
1248                         "    -h [host:]port          (REST protocol listener)\n"
1249                         "    -c cmdport              (telnet-style)\n"
1250                         "    -C cclconfig\n"
1251                         "    -s simpletargetfile\n"
1252                         "    -p hostname[:portno]    (HTTP proxy)\n");
1253                 exit(1);
1254         }
1255     }
1256
1257     if (!setport)
1258     {
1259         fprintf(stderr, "Set command port with -h or -c\n");
1260         exit(1);
1261     }
1262
1263     global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1264     global_parameters.yaz_marc = yaz_marc_create();
1265     yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1266     global_parameters.odr_in = odr_createmem(ODR_DECODE);
1267     global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1268
1269     event_loop(&channel_list);
1270
1271     return 0;
1272 }
1273
1274 /*
1275  * Local variables:
1276  * c-basic-offset: 4
1277  * indent-tabs-mode: nil
1278  * End:
1279  * vim: shiftwidth=4 tabstop=8 expandtab
1280  */