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