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