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