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