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