Added the most basic level of support for authentication. The setting
[pazpar2-moved-to-github.git] / src / pazpar2.c
1 /* $Id: pazpar2.c,v 1.65 2007-04-08 21:51: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/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/otherinfo.h>
21 #include <yaz/yaz-util.h>
22 #include <yaz/nmem.h>
23
24 #if HAVE_CONFIG_H
25 #include "cconfig.h"
26 #endif
27
28 #define USE_TIMING 0
29 #if USE_TIMING
30 #include <yaz/timing.h>
31 #endif
32
33 #include <netinet/in.h>
34
35 #include "pazpar2.h"
36 #include "eventl.h"
37 #include "http.h"
38 #include "termlists.h"
39 #include "reclists.h"
40 #include "relevance.h"
41 #include "config.h"
42 #include "database.h"
43 #include "settings.h"
44
45 #define MAX_CHUNK 15
46
47 static void client_fatal(struct client *cl);
48 static void connection_destroy(struct connection *co);
49 static int client_prep_connection(struct client *cl);
50 static void ingest_records(struct client *cl, Z_Records *r);
51 void session_alert_watch(struct session *s, int what);
52 char *session_setting_oneval(struct session *s, struct database *db, int offset);
53
54 IOCHAN channel_list = 0;  // Master list of connections we're handling events to
55
56 static struct connection *connection_freelist = 0;
57 static struct client *client_freelist = 0;
58
59 static char *client_states[] = {
60     "Client_Connecting",
61     "Client_Connected",
62     "Client_Idle",
63     "Client_Initializing",
64     "Client_Searching",
65     "Client_Presenting",
66     "Client_Error",
67     "Client_Failed",
68     "Client_Disconnected",
69     "Client_Stopped"
70 };
71
72 // Note: Some things in this structure will eventually move to configuration
73 struct parameters global_parameters = 
74 {
75     "",
76     "",
77     "",
78     "",
79     0,
80     0,
81     30,
82     "81",
83     "Index Data PazPar2 (MasterKey)",
84     VERSION,
85     600, // 10 minutes
86     60,
87     100,
88     MAX_CHUNK,
89     0,
90     0
91 };
92
93 static int send_apdu(struct client *c, Z_APDU *a)
94 {
95     struct connection *co = c->connection;
96     char *buf;
97     int len, r;
98
99     if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
100     {
101         odr_perror(global_parameters.odr_out, "Encoding APDU");
102         abort();
103     }
104     buf = odr_getbuf(global_parameters.odr_out, &len, 0);
105     r = cs_put(co->link, buf, len);
106     if (r < 0)
107     {
108         yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
109         return -1;
110     }
111     else if (r == 1)
112     {
113         fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
114         exit(1);
115     }
116     odr_reset(global_parameters.odr_out); /* release the APDU structure  */
117     co->state = Conn_Waiting;
118     return 0;
119 }
120
121 // Set authentication token in init if one is set for the client
122 // TODO: Extend this to handle other schemes than open (should be simple)
123 static void init_authentication(struct client *cl, Z_InitRequest *req)
124 {
125     struct database *db = cl->database;
126     struct session *se = cl->session;
127     char *auth = session_setting_oneval(se, db, PZ_AUTHENTICATION);
128
129     if (auth)
130     {
131         Z_IdAuthentication *idAuth = odr_malloc(global_parameters.odr_out,
132                 sizeof(*idAuth));
133         idAuth->which = Z_IdAuthentication_open;
134         idAuth->u.open = auth;
135         req->idAuthentication = idAuth;
136     }
137 }
138
139 static void send_init(IOCHAN i)
140 {
141
142     struct connection *co = iochan_getdata(i);
143     struct client *cl = co->client;
144     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
145
146     a->u.initRequest->implementationId = global_parameters.implementationId;
147     a->u.initRequest->implementationName = global_parameters.implementationName;
148     a->u.initRequest->implementationVersion =
149         global_parameters.implementationVersion;
150     ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
151     ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
152     ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
153
154     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
155     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
156     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
157
158     init_authentication(cl, a->u.initRequest);
159
160     /* add virtual host if tunneling through Z39.50 proxy */
161     
162     if (0 < strlen(global_parameters.zproxy_override) 
163         && 0 < strlen(cl->database->url))
164         yaz_oi_set_string_oidval(&a->u.initRequest->otherInfo, 
165                                  global_parameters.odr_out, VAL_PROXY,
166                                  1, cl->database->url);
167
168     if (send_apdu(cl, a) >= 0)
169     {
170         iochan_setflags(i, EVENT_INPUT);
171         cl->state = Client_Initializing;
172     }
173     else
174         cl->state = Client_Error;
175     odr_reset(global_parameters.odr_out);
176 }
177
178 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
179 {
180     switch (n->kind)
181     {
182         case CCL_RPN_AND:
183         case CCL_RPN_OR:
184         case CCL_RPN_NOT:
185         case CCL_RPN_PROX:
186             pull_terms(nmem, n->u.p[0], termlist, num);
187             pull_terms(nmem, n->u.p[1], termlist, num);
188             break;
189         case CCL_RPN_TERM:
190             termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
191             break;
192         default: // NOOP
193             break;
194     }
195 }
196
197 // Extract terms from query into null-terminated termlist
198 static void extract_terms(NMEM nmem, struct ccl_rpn_node *query, char **termlist)
199 {
200     int num = 0;
201
202     pull_terms(nmem, query, termlist, &num);
203     termlist[num] = 0;
204 }
205
206 static void send_search(IOCHAN i)
207 {
208     struct connection *co = iochan_getdata(i);
209     struct client *cl = co->client; 
210     struct session *se = cl->session;
211     struct database *db = cl->database;
212     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
213     int ndb, cerror, cpos;
214     char **databaselist;
215     Z_Query *zquery;
216     struct ccl_rpn_node *cn;
217     int ssub = 0, lslb = 100000, mspn = 10;
218     char *recsyn;
219     char *piggyback;
220
221     yaz_log(YLOG_DEBUG, "Sending search");
222
223     cn = ccl_find_str(db->ccl_map, se->query, &cerror, &cpos);
224     if (!cn)
225         return;
226
227     if (!se->relevance)
228     {
229         // Initialize relevance structure with query terms
230         char *p[512];
231         extract_terms(se->nmem, cn, p);
232         se->relevance = relevance_create(se->nmem, (const char **) p,
233                 se->expected_maxrecs);
234     }
235
236     a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
237             sizeof(Z_Query));
238     zquery->which = Z_Query_type_1;
239     zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
240     ccl_rpn_delete(cn);
241
242     for (ndb = 0; db->databases[ndb]; ndb++)
243         ;
244     databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
245     for (ndb = 0; db->databases[ndb]; ndb++)
246         databaselist[ndb] = db->databases[ndb];
247
248     if (!(piggyback = session_setting_oneval(se, db, PZ_PIGGYBACK)) || *piggyback == '1')
249     {
250         if ((recsyn = session_setting_oneval(se, db, PZ_NATIVESYNTAX)))
251             a->u.searchRequest->preferredRecordSyntax =
252                     yaz_str_to_z3950oid(global_parameters.odr_out,
253                     CLASS_RECSYN, recsyn);
254         a->u.searchRequest->smallSetUpperBound = &ssub;
255         a->u.searchRequest->largeSetLowerBound = &lslb;
256         a->u.searchRequest->mediumSetPresentNumber = &mspn;
257     }
258     a->u.searchRequest->resultSetName = "Default";
259     a->u.searchRequest->databaseNames = databaselist;
260     a->u.searchRequest->num_databaseNames = ndb;
261
262     if (send_apdu(cl, a) >= 0)
263     {
264         iochan_setflags(i, EVENT_INPUT);
265         cl->state = Client_Searching;
266         cl->requestid = se->requestid;
267     }
268     else
269         cl->state = Client_Error;
270
271     odr_reset(global_parameters.odr_out);
272 }
273
274 static void send_present(IOCHAN i)
275 {
276     struct connection *co = iochan_getdata(i);
277     struct client *cl = co->client; 
278     struct session *se = cl->session;
279     struct database *db = cl->database;
280     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
281     int toget;
282     int start = cl->records + 1;
283     char *recsyn;
284
285     toget = global_parameters.chunk;
286     if (toget > global_parameters.toget - cl->records)
287         toget = global_parameters.toget - cl->records;
288     if (toget > cl->hits - cl->records)
289         toget = cl->hits - cl->records;
290
291     yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
292
293     a->u.presentRequest->resultSetStartPoint = &start;
294     a->u.presentRequest->numberOfRecordsRequested = &toget;
295
296     a->u.presentRequest->resultSetId = "Default";
297
298     if ((recsyn = session_setting_oneval(se, db, PZ_NATIVESYNTAX)))
299         a->u.presentRequest->preferredRecordSyntax =
300                 yaz_str_to_z3950oid(global_parameters.odr_out,
301                 CLASS_RECSYN, recsyn);
302
303     if (send_apdu(cl, a) >= 0)
304     {
305         iochan_setflags(i, EVENT_INPUT);
306         cl->state = Client_Presenting;
307     }
308     else
309         cl->state = Client_Error;
310     odr_reset(global_parameters.odr_out);
311 }
312
313 static void do_initResponse(IOCHAN i, Z_APDU *a)
314 {
315     struct connection *co = iochan_getdata(i);
316     struct client *cl = co->client;
317     Z_InitResponse *r = a->u.initResponse;
318
319     yaz_log(YLOG_DEBUG, "Init response %s", cl->database->url);
320
321     if (*r->result)
322     {
323         cl->state = Client_Idle;
324     }
325     else
326         cl->state = Client_Failed; // FIXME need to do something to the connection
327 }
328
329 static void do_searchResponse(IOCHAN i, Z_APDU *a)
330 {
331     struct connection *co = iochan_getdata(i);
332     struct client *cl = co->client;
333     struct session *se = cl->session;
334     Z_SearchResponse *r = a->u.searchResponse;
335
336     yaz_log(YLOG_DEBUG, "Search response %s (status=%d)", 
337             cl->database->url, *r->searchStatus);
338
339     if (*r->searchStatus)
340     {
341         cl->hits = *r->resultCount;
342         se->total_hits += cl->hits;
343         if (r->presentStatus && !*r->presentStatus && r->records)
344         {
345             yaz_log(YLOG_DEBUG, "Records in search response %s", 
346                     cl->database->url);
347             ingest_records(cl, r->records);
348         }
349         cl->state = Client_Idle;
350     }
351     else
352     {          /*"FAILED"*/
353         cl->hits = 0;
354         cl->state = Client_Error;
355         if (r->records) {
356             Z_Records *recs = r->records;
357             if (recs->which == Z_Records_NSD)
358             {
359                 yaz_log(YLOG_WARN, 
360                         "Search response: Non-surrogate diagnostic %s",
361                         cl->database->url);
362                 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
363                 cl->state = Client_Error;
364             }
365         }
366     }
367 }
368
369 static void do_closeResponse(IOCHAN i, Z_APDU *a)
370 {
371     struct connection *co = iochan_getdata(i);
372     struct client *cl = co->client;
373     /* Z_Close *r = a->u.close; */
374
375     yaz_log(YLOG_WARN, "Close response %s", cl->database->url);
376
377     cl->state = Client_Failed;
378     connection_destroy(co);
379 }
380
381
382 char *normalize_mergekey(char *buf, int skiparticle)
383 {
384     char *p = buf, *pout = buf;
385
386     if (skiparticle)
387     {
388         char firstword[64];
389         char articles[] = "the den der die des an a "; // must end in space
390
391         while (*p && !isalnum(*p))
392             p++;
393         pout = firstword;
394         while (*p && *p != ' ' && pout - firstword < 62)
395             *(pout++) = tolower(*(p++));
396         *(pout++) = ' ';
397         *(pout++) = '\0';
398         if (!strstr(articles, firstword))
399             p = buf;
400         pout = buf;
401     }
402
403     while (*p)
404     {
405         while (*p && !isalnum(*p))
406             p++;
407         while (isalnum(*p))
408             *(pout++) = tolower(*(p++));
409         if (*p)
410             *(pout++) = ' ';
411         while (*p && !isalnum(*p))
412             p++;
413     }
414     if (buf != pout)
415         do {
416             *(pout--) = '\0';
417         }
418         while (pout > buf && *pout == ' ');
419
420     return buf;
421 }
422
423 static void add_facet(struct session *s, const char *type, const char *value)
424 {
425     int i;
426
427     if (!*value)
428         return;
429     for (i = 0; i < s->num_termlists; i++)
430         if (!strcmp(s->termlists[i].name, type))
431             break;
432     if (i == s->num_termlists)
433     {
434         if (i == SESSION_MAX_TERMLISTS)
435         {
436             yaz_log(YLOG_FATAL, "Too many termlists");
437             exit(1);
438         }
439         s->termlists[i].name = nmem_strdup(s->nmem, type);
440         s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
441         s->num_termlists = i + 1;
442     }
443     termlist_insert(s->termlists[i].termlist, value);
444 }
445
446 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
447 {
448     struct database_retrievalmap *m;
449     struct database *db = cl->database;
450     xmlNode *res;
451     xmlDoc *rdoc;
452
453     // First normalize to XML
454     if (db->yaz_marc)
455     {
456         char *buf;
457         int len;
458         if (rec->which != Z_External_octet)
459         {
460             yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
461                     cl->database->url);
462             return 0;
463         }
464         buf = (char*) rec->u.octet_aligned->buf;
465         len = rec->u.octet_aligned->len;
466         if (yaz_marc_read_iso2709(db->yaz_marc, buf, len) < 0)
467         {
468             yaz_log(YLOG_WARN, "Failed to decode MARC %s",
469                     cl->database->url);
470             return 0;
471         }
472         if (yaz_marc_write_xml(db->yaz_marc, &res,
473                     "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
474         {
475             yaz_log(YLOG_WARN, "Failed to encode as XML %s",
476                     cl->database->url);
477             return 0;
478         }
479         rdoc = xmlNewDoc((xmlChar *) "1.0");
480         xmlDocSetRootElement(rdoc, res);
481     }
482     else
483     {
484         yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
485         exit(1);
486     }
487
488     if (global_parameters.dump_records)
489     {
490         fprintf(stderr, "Input Record (normalized):\n----------------\n");
491 #if LIBXML_VERSION >= 20600
492         xmlDocFormatDump(stderr, rdoc, 1);
493 #else
494         xmlDocDump(stderr, rdoc);
495 #endif
496     }
497
498     for (m = db->map; m; m = m->next)
499     {
500         xmlDoc *new;
501         if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
502         {
503             yaz_log(YLOG_WARN, "XSLT transformation failed");
504             return 0;
505         }
506         xmlFreeDoc(rdoc);
507         rdoc = new;
508     }
509     if (global_parameters.dump_records)
510     {
511         fprintf(stderr, "Record:\n----------------\n");
512 #if LIBXML_VERSION >= 20600
513         xmlDocFormatDump(stderr, rdoc, 1);
514 #else
515         xmlDocDump(stderr, rdoc);
516 #endif
517     }
518     return rdoc;
519 }
520
521 // Extract what appears to be years from buf, storing highest and
522 // lowest values.
523 static int extract_years(const char *buf, int *first, int *last)
524 {
525     *first = -1;
526     *last = -1;
527     while (*buf)
528     {
529         const char *e;
530         int len;
531
532         while (*buf && !isdigit(*buf))
533             buf++;
534         len = 0;
535         for (e = buf; *e && isdigit(*e); e++)
536             len++;
537         if (len == 4)
538         {
539             int value = atoi(buf);
540             if (*first < 0 || value < *first)
541                 *first = value;
542             if (*last < 0 || value > *last)
543                 *last = value;
544         }
545         buf = e;
546     }
547     return *first;
548 }
549
550 static struct record *ingest_record(struct client *cl, Z_External *rec)
551 {
552     xmlDoc *xdoc = normalize_record(cl, rec);
553     xmlNode *root, *n;
554     struct record *res;
555     struct record_cluster *cluster;
556     struct session *se = cl->session;
557     xmlChar *mergekey, *mergekey_norm;
558     xmlChar *type = 0;
559     xmlChar *value = 0;
560     struct conf_service *service = global_parameters.server->service;
561
562     if (!xdoc)
563         return 0;
564
565     root = xmlDocGetRootElement(xdoc);
566     if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
567     {
568         yaz_log(YLOG_WARN, "No mergekey found in record");
569         xmlFreeDoc(xdoc);
570         return 0;
571     }
572
573     res = nmem_malloc(se->nmem, sizeof(struct record));
574     res->next = 0;
575     res->client = cl;
576     res->metadata = nmem_malloc(se->nmem,
577             sizeof(struct record_metadata*) * service->num_metadata);
578     memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
579
580     mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
581     xmlFree(mergekey);
582     normalize_mergekey((char *) mergekey_norm, 0);
583
584     cluster = reclist_insert(se->reclist, res, (char *) mergekey_norm, 
585                              &se->total_merged);
586     if (global_parameters.dump_records)
587         yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
588                 cl->database->url, cl->records);
589     if (!cluster)
590     {
591         /* no room for record */
592         xmlFreeDoc(xdoc);
593         return 0;
594     }
595     relevance_newrec(se->relevance, cluster);
596
597     for (n = root->children; n; n = n->next)
598     {
599         if (type)
600             xmlFree(type);
601         if (value)
602             xmlFree(value);
603         type = value = 0;
604
605         if (n->type != XML_ELEMENT_NODE)
606             continue;
607         if (!strcmp((const char *) n->name, "metadata"))
608         {
609             struct conf_metadata *md = 0;
610             struct conf_sortkey *sk = 0;
611             struct record_metadata **wheretoput, *newm;
612             int imeta;
613             int first, last;
614
615             type = xmlGetProp(n, (xmlChar *) "type");
616             value = xmlNodeListGetString(xdoc, n->children, 0);
617
618             if (!type || !value)
619                 continue;
620
621             // First, find out what field we're looking at
622             for (imeta = 0; imeta < service->num_metadata; imeta++)
623                 if (!strcmp((const char *) type, service->metadata[imeta].name))
624                 {
625                     md = &service->metadata[imeta];
626                     if (md->sortkey_offset >= 0)
627                         sk = &service->sortkeys[md->sortkey_offset];
628                     break;
629                 }
630             if (!md)
631             {
632                 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
633                 continue;
634             }
635
636             // Find out where we are putting it
637             if (md->merge == Metadata_merge_no)
638                 wheretoput = &res->metadata[imeta];
639             else
640                 wheretoput = &cluster->metadata[imeta];
641             
642             // Put it there
643             newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
644             newm->next = 0;
645             if (md->type == Metadata_type_generic)
646             {
647                 char *p, *pe;
648                 for (p = (char *) value; *p && isspace(*p); p++)
649                     ;
650                 for (pe = p + strlen(p) - 1;
651                         pe > p && strchr(" ,/.:([", *pe); pe--)
652                     *pe = '\0';
653                 newm->data.text = nmem_strdup(se->nmem, p);
654
655             }
656             else if (md->type == Metadata_type_year)
657             {
658                 if (extract_years((char *) value, &first, &last) < 0)
659                     continue;
660             }
661             else
662             {
663                 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
664                 continue;
665             }
666             if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
667             {
668                 yaz_log(YLOG_WARN, "Only range merging supported for years");
669                 continue;
670             }
671             if (md->merge == Metadata_merge_unique)
672             {
673                 struct record_metadata *mnode;
674                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
675                     if (!strcmp((const char *) mnode->data.text, newm->data.text))
676                         break;
677                 if (!mnode)
678                 {
679                     newm->next = *wheretoput;
680                     *wheretoput = newm;
681                 }
682             }
683             else if (md->merge == Metadata_merge_longest)
684             {
685                 if (!*wheretoput ||
686                         strlen(newm->data.text) > strlen((*wheretoput)->data.text))
687                 {
688                     *wheretoput = newm;
689                     if (sk)
690                     {
691                         char *s = nmem_strdup(se->nmem, newm->data.text);
692                         if (!cluster->sortkeys[md->sortkey_offset])
693                             cluster->sortkeys[md->sortkey_offset] = 
694                                 nmem_malloc(se->nmem, sizeof(union data_types));
695                         normalize_mergekey(s,
696                                 (sk->type == Metadata_sortkey_skiparticle));
697                         cluster->sortkeys[md->sortkey_offset]->text = s;
698                     }
699                 }
700             }
701             else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
702             {
703                 newm->next = *wheretoput;
704                 *wheretoput = newm;
705             }
706             else if (md->merge == Metadata_merge_range)
707             {
708                 assert(md->type == Metadata_type_year);
709                 if (!*wheretoput)
710                 {
711                     *wheretoput = newm;
712                     (*wheretoput)->data.number.min = first;
713                     (*wheretoput)->data.number.max = last;
714                     if (sk)
715                         cluster->sortkeys[md->sortkey_offset] = &newm->data;
716                 }
717                 else
718                 {
719                     if (first < (*wheretoput)->data.number.min)
720                         (*wheretoput)->data.number.min = first;
721                     if (last > (*wheretoput)->data.number.max)
722                         (*wheretoput)->data.number.max = last;
723                 }
724 #ifdef GAGA
725                 if (sk)
726                 {
727                     union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
728                     yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
729                 }
730 #endif
731             }
732             else
733                 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
734
735             if (md->rank)
736                 relevance_countwords(se->relevance, cluster, 
737                                      (char *) value, md->rank);
738             if (md->termlist)
739             {
740                 if (md->type == Metadata_type_year)
741                 {
742                     char year[64];
743                     sprintf(year, "%d", last);
744                     add_facet(se, (char *) type, year);
745                     if (first != last)
746                     {
747                         sprintf(year, "%d", first);
748                         add_facet(se, (char *) type, year);
749                     }
750                 }
751                 else
752                     add_facet(se, (char *) type, (char *) value);
753             }
754             xmlFree(type);
755             xmlFree(value);
756             type = value = 0;
757         }
758         else
759             yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
760     }
761     if (type)
762         xmlFree(type);
763     if (value)
764         xmlFree(value);
765
766     xmlFreeDoc(xdoc);
767
768     relevance_donerecord(se->relevance, cluster);
769     se->total_records++;
770
771     return res;
772 }
773
774 // Retrieve first defined value for 'name' for given database.
775 // Will be extended to take into account user associated with session
776 char *session_setting_oneval(struct session *s, struct database *db, int offset)
777 {
778     if (!db->settings[offset])
779         return 0;
780     return db->settings[offset]->value;
781 }
782
783 static void ingest_records(struct client *cl, Z_Records *r)
784 {
785 #if USE_TIMING
786     yaz_timing_t t = yaz_timing_create();
787 #endif
788     struct record *rec;
789     struct session *s = cl->session;
790     Z_NamePlusRecordList *rlist;
791     int i;
792
793     if (r->which != Z_Records_DBOSD)
794         return;
795     rlist = r->u.databaseOrSurDiagnostics;
796     for (i = 0; i < rlist->num_records; i++)
797     {
798         Z_NamePlusRecord *npr = rlist->records[i];
799
800         cl->records++;
801         if (npr->which != Z_NamePlusRecord_databaseRecord)
802         {
803             yaz_log(YLOG_WARN, 
804                     "Unexpected record type, probably diagnostic %s",
805                     cl->database->url);
806             continue;
807         }
808
809         rec = ingest_record(cl, npr->u.databaseRecord);
810         if (!rec)
811             continue;
812     }
813     if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
814         session_alert_watch(s, SESSION_WATCH_RECORDS);
815
816 #if USE_TIMING
817     yaz_timing_stop(t);
818     yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f", 
819             yaz_timing_get_real(t), yaz_timing_get_user(t),
820             yaz_timing_get_sys(t));
821     yaz_timing_destroy(&t);
822 #endif
823 }
824
825 static void do_presentResponse(IOCHAN i, Z_APDU *a)
826 {
827     struct connection *co = iochan_getdata(i);
828     struct client *cl = co->client;
829     Z_PresentResponse *r = a->u.presentResponse;
830
831     if (r->records) {
832         Z_Records *recs = r->records;
833         if (recs->which == Z_Records_NSD)
834         {
835             yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
836                     cl->database->url);
837             cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
838             cl->state = Client_Error;
839         }
840     }
841
842     if (!*r->presentStatus && cl->state != Client_Error)
843     {
844         yaz_log(YLOG_DEBUG, "Good Present response %s",
845                 cl->database->url);
846         ingest_records(cl, r->records);
847         cl->state = Client_Idle;
848     }
849     else if (*r->presentStatus) 
850     {
851         yaz_log(YLOG_WARN, "Bad Present response %s",
852                 cl->database->url);
853         cl->state = Client_Error;
854     }
855 }
856
857 static void handler(IOCHAN i, int event)
858 {
859     struct connection *co = iochan_getdata(i);
860     struct client *cl = co->client;
861     struct session *se = 0;
862
863     if (cl)
864         se = cl->session;
865     else
866     {
867         yaz_log(YLOG_WARN, "Destroying orphan connection");
868         connection_destroy(co);
869         return;
870     }
871
872     if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
873     {
874         int errcode;
875         socklen_t errlen = sizeof(errcode);
876
877         if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
878             &errlen) < 0 || errcode != 0)
879         {
880             client_fatal(cl);
881             return;
882         }
883         else
884         {
885             yaz_log(YLOG_DEBUG, "Connect OK");
886             co->state = Conn_Open;
887             if (cl)
888                 cl->state = Client_Connected;
889         }
890     }
891
892     else if (event & EVENT_INPUT)
893     {
894         int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
895
896         if (len < 0)
897         {
898             yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s", 
899                     cl->database->url);
900             connection_destroy(co);
901             return;
902         }
903         else if (len == 0)
904         {
905             yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->url);
906             connection_destroy(co);
907             return;
908         }
909         else if (len > 1) // We discard input if we have no connection
910         {
911             co->state = Conn_Open;
912
913             if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
914             {
915                 Z_APDU *a;
916
917                 odr_reset(global_parameters.odr_in);
918                 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
919                 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
920                 {
921                     client_fatal(cl);
922                     return;
923                 }
924                 switch (a->which)
925                 {
926                     case Z_APDU_initResponse:
927                         do_initResponse(i, a);
928                         break;
929                     case Z_APDU_searchResponse:
930                         do_searchResponse(i, a);
931                         break;
932                     case Z_APDU_presentResponse:
933                         do_presentResponse(i, a);
934                         break;
935                     case Z_APDU_close:
936                         do_closeResponse(i, a);
937                         break;
938                     default:
939                         yaz_log(YLOG_WARN, 
940                                 "Unexpected Z39.50 response from %s",  
941                                 cl->database->url);
942                         client_fatal(cl);
943                         return;
944                 }
945                 // We aren't expecting staggered output from target
946                 // if (cs_more(t->link))
947                 //    iochan_setevent(i, EVENT_INPUT);
948             }
949             else  // we throw away response and go to idle mode
950             {
951                 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
952                 cl->state = Client_Idle;
953             }
954         }
955         /* if len==1 we do nothing but wait for more input */
956     }
957
958     if (cl->state == Client_Connected) {
959         send_init(i);
960     }
961
962     if (cl->state == Client_Idle)
963     {
964         if (cl->requestid != se->requestid && *se->query) {
965             send_search(i);
966         }
967         else if (cl->hits > 0 && cl->records < global_parameters.toget &&
968             cl->records < cl->hits) {
969             send_present(i);
970         }
971     }
972 }
973
974 // Disassociate connection from client
975 static void connection_release(struct connection *co)
976 {
977     struct client *cl = co->client;
978
979     yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
980     if (!cl)
981         return;
982     cl->connection = 0;
983     co->client = 0;
984 }
985
986 // Close connection and recycle structure
987 static void connection_destroy(struct connection *co)
988 {
989     struct host *h = co->host;
990     cs_close(co->link);
991     iochan_destroy(co->iochan);
992
993     yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
994     if (h->connections == co)
995         h->connections = co->next;
996     else
997     {
998         struct connection *pco;
999         for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1000             ;
1001         if (pco)
1002             pco->next = co->next;
1003         else
1004             abort();
1005     }
1006     if (co->client)
1007     {
1008         if (co->client->state != Client_Idle)
1009             co->client->state = Client_Disconnected;
1010         co->client->connection = 0;
1011     }
1012     co->next = connection_freelist;
1013     connection_freelist = co;
1014 }
1015
1016 // Creates a new connection for client, associated with the host of 
1017 // client's database
1018 static struct connection *connection_create(struct client *cl)
1019 {
1020     struct connection *new;
1021     COMSTACK link; 
1022     int res;
1023     void *addr;
1024
1025
1026     if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1027         {
1028             yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1029             exit(1);
1030         }
1031     
1032     if (0 == strlen(global_parameters.zproxy_override)){
1033         /* no Z39.50 proxy needed - direct connect */
1034         yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
1035         
1036         if (!(addr = cs_straddr(link, cl->database->host->ipport)))
1037             {
1038                 yaz_log(YLOG_WARN|YLOG_ERRNO, 
1039                         "Lookup of IP address %s failed", 
1040                         cl->database->host->ipport);
1041                 return 0;
1042             }
1043     
1044     } else {
1045         /* Z39.50 proxy connect */
1046         yaz_log(YLOG_DEBUG, "Connection create %s proxy %s", 
1047                 cl->database->url, global_parameters.zproxy_override);
1048
1049         if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1050             {
1051                 yaz_log(YLOG_WARN|YLOG_ERRNO, 
1052                         "Lookup of IP address %s failed", 
1053                         global_parameters.zproxy_override);
1054                 return 0;
1055             }
1056     }
1057
1058     res = cs_connect(link, addr);
1059     if (res < 0)
1060     {
1061         yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
1062         return 0;
1063     }
1064
1065     if ((new = connection_freelist))
1066         connection_freelist = new->next;
1067     else
1068     {
1069         new = xmalloc(sizeof (struct connection));
1070         new->ibuf = 0;
1071         new->ibufsize = 0;
1072     }
1073     new->state = Conn_Connecting;
1074     new->host = cl->database->host;
1075     new->next = new->host->connections;
1076     new->host->connections = new;
1077     new->client = cl;
1078     cl->connection = new;
1079     new->link = link;
1080
1081     new->iochan = iochan_create(cs_fileno(link), 0, handler, 0);
1082     iochan_setdata(new->iochan, new);
1083     new->iochan->next = channel_list;
1084     channel_list = new->iochan;
1085     return new;
1086 }
1087
1088 // Close connection and set state to error
1089 static void client_fatal(struct client *cl)
1090 {
1091     yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
1092     connection_destroy(cl->connection);
1093     cl->state = Client_Error;
1094 }
1095
1096 // Ensure that client has a connection associated
1097 static int client_prep_connection(struct client *cl)
1098 {
1099     struct connection *co;
1100     struct session *se = cl->session;
1101     struct host *host = cl->database->host;
1102
1103     co = cl->connection;
1104
1105     yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1106
1107     if (!co)
1108     {
1109         // See if someone else has an idle connection
1110         // We should look at timestamps here to select the longest-idle connection
1111         for (co = host->connections; co; co = co->next)
1112             if (co->state == Conn_Open && (!co->client || co->client->session != se))
1113                 break;
1114         if (co)
1115         {
1116             connection_release(co);
1117             cl->connection = co;
1118             co->client = cl;
1119         }
1120         else
1121             co = connection_create(cl);
1122     }
1123     if (co)
1124     {
1125         if (co->state == Conn_Connecting)
1126         {
1127             cl->state = Client_Connecting;
1128             iochan_setflag(co->iochan, EVENT_OUTPUT);
1129         }
1130         else if (co->state == Conn_Open)
1131         {
1132             if (cl->state == Client_Error || cl->state == Client_Disconnected)
1133                 cl->state = Client_Idle;
1134             iochan_setflag(co->iochan, EVENT_OUTPUT);
1135         }
1136         return 1;
1137     }
1138     else
1139         return 0;
1140 }
1141
1142 #ifdef GAGA // Moved to database.c
1143
1144 // This function will most likely vanish when a proper target profile mechanism is
1145 // introduced.
1146 void load_simpletargets(const char *fn)
1147 {
1148     FILE *f = fopen(fn, "r");
1149     char line[256];
1150
1151     if (!f)
1152     {
1153         yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1154         exit(1);
1155     }
1156
1157     while (fgets(line, 255, f))
1158     {
1159         char *url, *db;
1160         char *name;
1161         struct host *host;
1162         struct database *database;
1163
1164         if (strncmp(line, "target ", 7))
1165             continue;
1166         line[strlen(line) - 1] = '\0';
1167
1168         if ((name = strchr(line, ';')))
1169             *(name++) = '\0';
1170
1171         url = line + 7;
1172         if ((db = strchr(url, '/')))
1173             *(db++) = '\0';
1174         else
1175             db = "Default";
1176
1177         yaz_log(YLOG_LOG, "Target: %s, '%s'", url, db);
1178         for (host = hosts; host; host = host->next)
1179             if (!strcmp((const char *) url, host->hostport))
1180                 break;
1181         if (!host)
1182         {
1183             struct addrinfo *addrinfo, hints;
1184             char *port;
1185             char ipport[128];
1186             unsigned char addrbuf[4];
1187             int res;
1188
1189             host = xmalloc(sizeof(struct host));
1190             host->hostport = xstrdup(url);
1191             host->connections = 0;
1192
1193             if ((port = strchr(url, ':')))
1194                 *(port++) = '\0';
1195             else
1196                 port = "210";
1197
1198             hints.ai_flags = 0;
1199             hints.ai_family = PF_INET;
1200             hints.ai_socktype = SOCK_STREAM;
1201             hints.ai_protocol = IPPROTO_TCP;
1202             hints.ai_addrlen = 0;
1203             hints.ai_addr = 0;
1204             hints.ai_canonname = 0;
1205             hints.ai_next = 0;
1206             // This is not robust code. It assumes that getaddrinfo returns AF_INET
1207             // address.
1208             if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1209             {
1210                 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1211                 xfree(host->hostport);
1212                 xfree(host);
1213                 continue;
1214             }
1215             assert(addrinfo->ai_family == PF_INET);
1216             memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1217             sprintf(ipport, "%u.%u.%u.%u:%s",
1218                     addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1219             host->ipport = xstrdup(ipport);
1220             freeaddrinfo(addrinfo);
1221             host->next = hosts;
1222             hosts = host;
1223         }
1224         database = xmalloc(sizeof(struct database));
1225         database->host = host;
1226         database->url = xmalloc(strlen(url) + strlen(db) + 2);
1227         strcpy(database->url, url);
1228         strcat(database->url, "/");
1229         strcat(database->url, db);
1230         if (name)
1231             database->name = xstrdup(name);
1232         else
1233             database->name = 0;
1234         
1235         database->databases = xmalloc(2 * sizeof(char *));
1236         database->databases[0] = xstrdup(db);
1237         database->databases[1] = 0;
1238         database->errors = 0;
1239         database->qprofile = 0;
1240         database->rprofile = database_retrieval_profile(database);
1241         database->next = databases;
1242         databases = database;
1243
1244     }
1245     fclose(f);
1246 }
1247
1248 #endif
1249
1250 static struct client *client_create(void)
1251 {
1252     struct client *r;
1253     if (client_freelist)
1254     {
1255         r = client_freelist;
1256         client_freelist = client_freelist->next;
1257     }
1258     else
1259         r = xmalloc(sizeof(struct client));
1260     r->database = 0;
1261     r->connection = 0;
1262     r->session = 0;
1263     r->hits = 0;
1264     r->records = 0;
1265     r->setno = 0;
1266     r->requestid = -1;
1267     r->diagnostic = 0;
1268     r->state = Client_Disconnected;
1269     r->next = 0;
1270     return r;
1271 }
1272
1273 void client_destroy(struct client *c)
1274 {
1275     struct session *se = c->session;
1276     if (c == se->clients)
1277         se->clients = c->next;
1278     else
1279     {
1280         struct client *cc;
1281         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1282             ;
1283         if (cc)
1284             cc->next = c->next;
1285     }
1286     if (c->connection)
1287         connection_release(c->connection);
1288     c->next = client_freelist;
1289     client_freelist = c;
1290 }
1291
1292 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1293 {
1294     s->watchlist[what].fun = fun;
1295     s->watchlist[what].data = data;
1296 }
1297
1298 void session_alert_watch(struct session *s, int what)
1299 {
1300     if (!s->watchlist[what].fun)
1301         return;
1302     (*s->watchlist[what].fun)(s->watchlist[what].data);
1303     s->watchlist[what].fun = 0;
1304     s->watchlist[what].data = 0;
1305 }
1306
1307 //callback for grep_databases
1308 static void select_targets_callback(void *context, struct database *db)
1309 {
1310     struct session *se = (struct session*) context;
1311     struct client *cl = client_create();
1312     cl->database = db;
1313     cl->session = se;
1314     cl->next = se->clients;
1315     se->clients = cl;
1316 }
1317
1318 // This should be extended with parameters to control selection criteria
1319 // Associates a set of clients with a session;
1320 int select_targets(struct session *se, struct database_criterion *crit)
1321 {
1322     while (se->clients)
1323         client_destroy(se->clients);
1324
1325     return grep_databases(se, crit, select_targets_callback);
1326 }
1327
1328 int session_active_clients(struct session *s)
1329 {
1330     struct client *c;
1331     int res = 0;
1332
1333     for (c = s->clients; c; c = c->next)
1334         if (c->connection && (c->state == Client_Connecting ||
1335                     c->state == Client_Initializing ||
1336                     c->state == Client_Searching ||
1337                     c->state == Client_Presenting))
1338             res++;
1339
1340     return res;
1341 }
1342
1343 // parses crit1=val1,crit2=val2|val3,...
1344 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1345 {
1346     struct database_criterion *res = 0;
1347     char **values;
1348     int num;
1349     int i;
1350
1351     if (!buf || !*buf)
1352         return 0;
1353     nmem_strsplit(m, ",", buf,  &values, &num);
1354     for (i = 0; i < num; i++)
1355     {
1356         char **subvalues;
1357         int subnum;
1358         int subi;
1359         struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1360         char *eq = strchr(values[i], '=');
1361         if (!eq)
1362         {
1363             yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1364             return 0;
1365         }
1366         *(eq++) = '\0';
1367         new->name = values[i];
1368         nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1369         new->values = 0;
1370         for (subi = 0; subi < subnum; subi++)
1371         {
1372             struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1373             newv->value = subvalues[subi];
1374             newv->next = new->values;
1375             new->values = newv;
1376         }
1377         new->next = res;
1378         res = new;
1379     }
1380     return res;
1381 }
1382
1383 char *search(struct session *se, char *query, char *filter)
1384 {
1385     int live_channels = 0;
1386     struct client *cl;
1387     struct database_criterion *criteria;
1388
1389     yaz_log(YLOG_DEBUG, "Search");
1390
1391     nmem_reset(se->nmem);
1392     criteria = parse_filter(se->nmem, filter);
1393     strcpy(se->query, query);
1394     se->requestid++;
1395     // Release any existing clients
1396     select_targets(se, criteria);
1397     for (cl = se->clients; cl; cl = cl->next)
1398     {
1399         if (client_prep_connection(cl))
1400             live_channels++;
1401     }
1402     if (live_channels)
1403     {
1404         int maxrecs = live_channels * global_parameters.toget;
1405         se->num_termlists = 0;
1406         se->reclist = reclist_create(se->nmem, maxrecs);
1407         // This will be initialized in send_search()
1408         se->relevance = 0;
1409         se->total_records = se->total_hits = se->total_merged = 0;
1410         se->expected_maxrecs = maxrecs;
1411     }
1412     else
1413         return "NOTARGETS";
1414
1415     return 0;
1416 }
1417
1418 void destroy_session(struct session *s)
1419 {
1420     yaz_log(YLOG_LOG, "Destroying session");
1421     while (s->clients)
1422         client_destroy(s->clients);
1423     nmem_destroy(s->nmem);
1424     wrbuf_destroy(s->wrbuf);
1425 }
1426
1427 struct session *new_session() 
1428 {
1429     int i;
1430     struct session *session = xmalloc(sizeof(*session));
1431
1432     yaz_log(YLOG_DEBUG, "New pazpar2 session");
1433     
1434     session->total_hits = 0;
1435     session->total_records = 0;
1436     session->num_termlists = 0;
1437     session->reclist = 0;
1438     session->requestid = -1;
1439     session->clients = 0;
1440     session->expected_maxrecs = 0;
1441     session->query[0] = '\0';
1442     session->nmem = nmem_create();
1443     session->wrbuf = wrbuf_alloc();
1444     for (i = 0; i <= SESSION_WATCH_MAX; i++)
1445     {
1446         session->watchlist[i].data = 0;
1447         session->watchlist[i].fun = 0;
1448     }
1449
1450     return session;
1451 }
1452
1453 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1454 {
1455     static struct hitsbytarget res[1000]; // FIXME MM
1456     struct client *cl;
1457
1458     *count = 0;
1459     for (cl = se->clients; cl; cl = cl->next)
1460     {
1461         res[*count].id = cl->database->url;
1462         res[*count].name = cl->database->name;
1463         res[*count].hits = cl->hits;
1464         res[*count].records = cl->records;
1465         res[*count].diagnostic = cl->diagnostic;
1466         res[*count].state = client_states[cl->state];
1467         res[*count].connected  = cl->connection ? 1 : 0;
1468         (*count)++;
1469     }
1470
1471     return res;
1472 }
1473
1474 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1475 {
1476     int i;
1477
1478     for (i = 0; i < s->num_termlists; i++)
1479         if (!strcmp((const char *) s->termlists[i].name, name))
1480             return termlist_highscore(s->termlists[i].termlist, num);
1481     return 0;
1482 }
1483
1484 #ifdef MISSING_HEADERS
1485 void report_nmem_stats(void)
1486 {
1487     size_t in_use, is_free;
1488
1489     nmem_get_memory_in_use(&in_use);
1490     nmem_get_memory_free(&is_free);
1491
1492     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1493             (long) in_use, (long) is_free);
1494 }
1495 #endif
1496
1497 struct record_cluster *show_single(struct session *s, int id)
1498 {
1499     struct record_cluster *r;
1500
1501     reclist_rewind(s->reclist);
1502     while ((r = reclist_read_record(s->reclist)))
1503         if (r->recid == id)
1504             return r;
1505     return 0;
1506 }
1507
1508 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1509         int *num, int *total, int *sumhits, NMEM nmem_show)
1510 {
1511     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
1512                                        * sizeof(struct record_cluster *));
1513     struct reclist_sortparms *spp;
1514     int i;
1515 #if USE_TIMING    
1516     yaz_timing_t t = yaz_timing_create();
1517 #endif
1518
1519     for (spp = sp; spp; spp = spp->next)
1520         if (spp->type == Metadata_sortkey_relevance)
1521         {
1522             relevance_prepare_read(s->relevance, s->reclist);
1523             break;
1524         }
1525     reclist_sort(s->reclist, sp);
1526
1527     *total = s->reclist->num_records;
1528     *sumhits = s->total_hits;
1529
1530     for (i = 0; i < start; i++)
1531         if (!reclist_read_record(s->reclist))
1532         {
1533             *num = 0;
1534             recs = 0;
1535             break;
1536         }
1537
1538     for (i = 0; i < *num; i++)
1539     {
1540         struct record_cluster *r = reclist_read_record(s->reclist);
1541         if (!r)
1542         {
1543             *num = i;
1544             break;
1545         }
1546         recs[i] = r;
1547     }
1548 #if USE_TIMING
1549     yaz_timing_stop(t);
1550     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1551             yaz_timing_get_real(t), yaz_timing_get_user(t),
1552             yaz_timing_get_sys(t));
1553     yaz_timing_destroy(&t);
1554 #endif
1555     return recs;
1556 }
1557
1558 void statistics(struct session *se, struct statistics *stat)
1559 {
1560     struct client *cl;
1561     int count = 0;
1562
1563     memset(stat, 0, sizeof(*stat));
1564     for (cl = se->clients; cl; cl = cl->next)
1565     {
1566         if (!cl->connection)
1567             stat->num_no_connection++;
1568         switch (cl->state)
1569         {
1570             case Client_Connecting: stat->num_connecting++; break;
1571             case Client_Initializing: stat->num_initializing++; break;
1572             case Client_Searching: stat->num_searching++; break;
1573             case Client_Presenting: stat->num_presenting++; break;
1574             case Client_Idle: stat->num_idle++; break;
1575             case Client_Failed: stat->num_failed++; break;
1576             case Client_Error: stat->num_error++; break;
1577             default: break;
1578         }
1579         count++;
1580     }
1581     stat->num_hits = se->total_hits;
1582     stat->num_records = se->total_records;
1583
1584     stat->num_clients = count;
1585 }
1586
1587 static void start_http_listener(void)
1588 {
1589     char hp[128] = "";
1590     struct conf_server *ser = global_parameters.server;
1591
1592     if (*global_parameters.listener_override)
1593         strcpy(hp, global_parameters.listener_override);
1594     else
1595     {
1596         strcpy(hp, ser->host ? ser->host : "");
1597         if (ser->port)
1598         {
1599             if (*hp)
1600                 strcat(hp, ":");
1601             sprintf(hp + strlen(hp), "%d", ser->port);
1602         }
1603     }
1604     http_init(hp);
1605 }
1606
1607 static void start_proxy(void)
1608 {
1609     char hp[128] = "";
1610     struct conf_server *ser = global_parameters.server;
1611
1612     if (*global_parameters.proxy_override)
1613         strcpy(hp, global_parameters.proxy_override);
1614     else if (ser->proxy_host || ser->proxy_port)
1615     {
1616         strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1617         if (ser->proxy_port)
1618         {
1619             if (*hp)
1620                 strcat(hp, ":");
1621             sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1622         }
1623     }
1624     else
1625         return;
1626
1627     http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1628 }
1629
1630 static void start_zproxy(void)
1631 {
1632     struct conf_server *ser = global_parameters.server;
1633
1634     if (*global_parameters.zproxy_override){
1635         yaz_log(YLOG_LOG, "Z39.50 proxy  %s", 
1636                 global_parameters.zproxy_override);
1637         return;
1638     }
1639
1640     else if (ser->zproxy_host || ser->zproxy_port)
1641     {
1642         char hp[128] = "";
1643
1644         strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1645         if (ser->zproxy_port)
1646         {
1647             if (*hp)
1648                 strcat(hp, ":");
1649             else
1650                 strcat(hp, "@:");
1651
1652             sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1653         }
1654         strcpy(global_parameters.zproxy_override, hp);
1655         yaz_log(YLOG_LOG, "Z39.50 proxy  %s", 
1656                 global_parameters.zproxy_override);
1657
1658     }
1659     else
1660         return;
1661 }
1662
1663
1664
1665 int main(int argc, char **argv)
1666 {
1667     int ret;
1668     char *arg;
1669
1670     if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1671         yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1672
1673     yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1674
1675     while ((ret = options("t:f:x:h:p:z:s:d", argv, argc, &arg)) != -2)
1676     {
1677         switch (ret) {
1678             case 'f':
1679                 if (!read_config(arg))
1680                     exit(1);
1681                 break;
1682             case 'h':
1683                 strcpy(global_parameters.listener_override, arg);
1684                 break;
1685             case 'p':
1686                 strcpy(global_parameters.proxy_override, arg);
1687                 break;
1688             case 'z':
1689                 strcpy(global_parameters.zproxy_override, arg);
1690                 break;
1691             case 't':
1692                 strcpy(global_parameters.settings_path_override, arg);
1693                 break;
1694             case 's':
1695                 load_simpletargets(arg);
1696                 break;
1697             case 'd':
1698                 global_parameters.dump_records = 1;
1699                 break;
1700             default:
1701                 fprintf(stderr, "Usage: pazpar2\n"
1702                         "    -f configfile\n"
1703                         "    -h [host:]port          (REST protocol listener)\n"
1704                         "    -C cclconfig\n"
1705                         "    -s simpletargetfile\n"
1706                         "    -p hostname[:portno]    (HTTP proxy)\n"
1707                         "    -z hostname[:portno]    (Z39.50 proxy)\n"
1708                         "    -d                      (show internal records)\n");
1709                 exit(1);
1710         }
1711     }
1712
1713     if (!config)
1714     {
1715         yaz_log(YLOG_FATAL, "Load config with -f");
1716         exit(1);
1717     }
1718     global_parameters.server = config->servers;
1719
1720     start_http_listener();
1721     start_proxy();
1722     start_zproxy();
1723
1724     if (*global_parameters.settings_path_override)
1725         settings_read(global_parameters.settings_path_override);
1726     else if (global_parameters.server->settings)
1727         settings_read(global_parameters.server->settings);
1728     else
1729         yaz_log(YLOG_WARN, "No settings-directory specified. Problems may well ensue!");
1730     prepare_databases();
1731     global_parameters.odr_in = odr_createmem(ODR_DECODE);
1732     global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1733
1734     event_loop(&channel_list);
1735
1736     return 0;
1737 }
1738
1739 /*
1740  * Local variables:
1741  * c-basic-offset: 4
1742  * indent-tabs-mode: nil
1743  * End:
1744  * vim: shiftwidth=4 tabstop=8 expandtab
1745  */