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