changed order of arguments of reclist_insert such that struct reclist *tl
[pazpar2-moved-to-github.git] / src / logic.c
1 /* $Id: logic.c,v 1.4 2007-04-17 07:52:03 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/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(se->reclist, 
703                              global_parameters.server->service, 
704                              res, (char *) mergekey_norm, 
705                              &se->total_merged);
706     if (global_parameters.dump_records)
707         yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
708                 cl->database->database->url, cl->records);
709     if (!cluster)
710     {
711         /* no room for record */
712         xmlFreeDoc(xdoc);
713         return 0;
714     }
715     relevance_newrec(se->relevance, cluster);
716
717     for (n = root->children; n; n = n->next)
718     {
719         if (type)
720             xmlFree(type);
721         if (value)
722             xmlFree(value);
723         type = value = 0;
724
725         if (n->type != XML_ELEMENT_NODE)
726             continue;
727         if (!strcmp((const char *) n->name, "metadata"))
728         {
729             struct conf_metadata *md = 0;
730             struct conf_sortkey *sk = 0;
731             struct record_metadata **wheretoput, *newm;
732             int imeta;
733             int first, last;
734
735             type = xmlGetProp(n, (xmlChar *) "type");
736             value = xmlNodeListGetString(xdoc, n->children, 0);
737
738             if (!type || !value)
739                 continue;
740
741             // First, find out what field we're looking at
742             for (imeta = 0; imeta < service->num_metadata; imeta++)
743                 if (!strcmp((const char *) type, service->metadata[imeta].name))
744                 {
745                     md = &service->metadata[imeta];
746                     if (md->sortkey_offset >= 0)
747                         sk = &service->sortkeys[md->sortkey_offset];
748                     break;
749                 }
750             if (!md)
751             {
752                 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
753                 continue;
754             }
755
756             // Find out where we are putting it
757             if (md->merge == Metadata_merge_no)
758                 wheretoput = &res->metadata[imeta];
759             else
760                 wheretoput = &cluster->metadata[imeta];
761             
762             // Put it there
763             newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
764             newm->next = 0;
765             if (md->type == Metadata_type_generic)
766             {
767                 char *p, *pe;
768                 for (p = (char *) value; *p && isspace(*p); p++)
769                     ;
770                 for (pe = p + strlen(p) - 1;
771                         pe > p && strchr(" ,/.:([", *pe); pe--)
772                     *pe = '\0';
773                 newm->data.text = nmem_strdup(se->nmem, p);
774
775             }
776             else if (md->type == Metadata_type_year)
777             {
778                 if (extract_years((char *) value, &first, &last) < 0)
779                     continue;
780             }
781             else
782             {
783                 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
784                 continue;
785             }
786             if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
787             {
788                 yaz_log(YLOG_WARN, "Only range merging supported for years");
789                 continue;
790             }
791             if (md->merge == Metadata_merge_unique)
792             {
793                 struct record_metadata *mnode;
794                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
795                     if (!strcmp((const char *) mnode->data.text, newm->data.text))
796                         break;
797                 if (!mnode)
798                 {
799                     newm->next = *wheretoput;
800                     *wheretoput = newm;
801                 }
802             }
803             else if (md->merge == Metadata_merge_longest)
804             {
805                 if (!*wheretoput ||
806                         strlen(newm->data.text) > strlen((*wheretoput)->data.text))
807                 {
808                     *wheretoput = newm;
809                     if (sk)
810                     {
811                         char *s = nmem_strdup(se->nmem, newm->data.text);
812                         if (!cluster->sortkeys[md->sortkey_offset])
813                             cluster->sortkeys[md->sortkey_offset] = 
814                                 nmem_malloc(se->nmem, sizeof(union data_types));
815                         normalize_mergekey(s,
816                                 (sk->type == Metadata_sortkey_skiparticle));
817                         cluster->sortkeys[md->sortkey_offset]->text = s;
818                     }
819                 }
820             }
821             else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
822             {
823                 newm->next = *wheretoput;
824                 *wheretoput = newm;
825             }
826             else if (md->merge == Metadata_merge_range)
827             {
828                 assert(md->type == Metadata_type_year);
829                 if (!*wheretoput)
830                 {
831                     *wheretoput = newm;
832                     (*wheretoput)->data.number.min = first;
833                     (*wheretoput)->data.number.max = last;
834                     if (sk)
835                         cluster->sortkeys[md->sortkey_offset] = &newm->data;
836                 }
837                 else
838                 {
839                     if (first < (*wheretoput)->data.number.min)
840                         (*wheretoput)->data.number.min = first;
841                     if (last > (*wheretoput)->data.number.max)
842                         (*wheretoput)->data.number.max = last;
843                 }
844 #ifdef GAGA
845                 if (sk)
846                 {
847                     union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
848                     yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
849                 }
850 #endif
851             }
852             else
853                 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
854
855             if (md->rank)
856                 relevance_countwords(se->relevance, cluster, 
857                                      (char *) value, md->rank);
858             if (md->termlist)
859             {
860                 if (md->type == Metadata_type_year)
861                 {
862                     char year[64];
863                     sprintf(year, "%d", last);
864                     add_facet(se, (char *) type, year);
865                     if (first != last)
866                     {
867                         sprintf(year, "%d", first);
868                         add_facet(se, (char *) type, year);
869                     }
870                 }
871                 else
872                     add_facet(se, (char *) type, (char *) value);
873             }
874             xmlFree(type);
875             xmlFree(value);
876             type = value = 0;
877         }
878         else
879             yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
880     }
881     if (type)
882         xmlFree(type);
883     if (value)
884         xmlFree(value);
885
886     xmlFreeDoc(xdoc);
887
888     relevance_donerecord(se->relevance, cluster);
889     se->total_records++;
890
891     return res;
892 }
893
894 // Retrieve first defined value for 'name' for given database.
895 // Will be extended to take into account user associated with session
896 char *session_setting_oneval(struct session_database *db, int offset)
897 {
898     if (!db->settings[offset])
899         return "";
900     return db->settings[offset]->value;
901 }
902
903 static void ingest_records(struct client *cl, Z_Records *r)
904 {
905 #if USE_TIMING
906     yaz_timing_t t = yaz_timing_create();
907 #endif
908     struct record *rec;
909     struct session *s = cl->session;
910     Z_NamePlusRecordList *rlist;
911     int i;
912
913     if (r->which != Z_Records_DBOSD)
914         return;
915     rlist = r->u.databaseOrSurDiagnostics;
916     for (i = 0; i < rlist->num_records; i++)
917     {
918         Z_NamePlusRecord *npr = rlist->records[i];
919
920         cl->records++;
921         if (npr->which != Z_NamePlusRecord_databaseRecord)
922         {
923             yaz_log(YLOG_WARN, 
924                     "Unexpected record type, probably diagnostic %s",
925                     cl->database->database->url);
926             continue;
927         }
928
929         rec = ingest_record(cl, npr->u.databaseRecord);
930         if (!rec)
931             continue;
932     }
933     if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
934         session_alert_watch(s, SESSION_WATCH_RECORDS);
935
936 #if USE_TIMING
937     yaz_timing_stop(t);
938     yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f", 
939             yaz_timing_get_real(t), yaz_timing_get_user(t),
940             yaz_timing_get_sys(t));
941     yaz_timing_destroy(&t);
942 #endif
943 }
944
945 static void do_presentResponse(IOCHAN i, Z_APDU *a)
946 {
947     struct connection *co = iochan_getdata(i);
948     struct client *cl = co->client;
949     Z_PresentResponse *r = a->u.presentResponse;
950
951     if (r->records) {
952         Z_Records *recs = r->records;
953         if (recs->which == Z_Records_NSD)
954         {
955             yaz_log(YLOG_WARN, "Non-surrogate diagnostic %s",
956                     cl->database->database->url);
957             cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
958             cl->state = Client_Error;
959         }
960     }
961
962     if (!*r->presentStatus && cl->state != Client_Error)
963     {
964         yaz_log(YLOG_DEBUG, "Good Present response %s",
965                 cl->database->database->url);
966         ingest_records(cl, r->records);
967         cl->state = Client_Idle;
968     }
969     else if (*r->presentStatus) 
970     {
971         yaz_log(YLOG_WARN, "Bad Present response %s",
972                 cl->database->database->url);
973         cl->state = Client_Error;
974     }
975 }
976
977 static void handler(IOCHAN i, int event)
978 {
979     struct connection *co = iochan_getdata(i);
980     struct client *cl = co->client;
981     struct session *se = 0;
982
983     if (cl)
984         se = cl->session;
985     else
986     {
987         yaz_log(YLOG_WARN, "Destroying orphan connection");
988         connection_destroy(co);
989         return;
990     }
991
992     if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
993     {
994         int errcode;
995         socklen_t errlen = sizeof(errcode);
996
997         if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
998             &errlen) < 0 || errcode != 0)
999         {
1000             client_fatal(cl);
1001             return;
1002         }
1003         else
1004         {
1005             yaz_log(YLOG_DEBUG, "Connect OK");
1006             co->state = Conn_Open;
1007             if (cl)
1008                 cl->state = Client_Connected;
1009         }
1010     }
1011
1012     else if (event & EVENT_INPUT)
1013     {
1014         int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
1015
1016         if (len < 0)
1017         {
1018             yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from %s", 
1019                     cl->database->database->url);
1020             connection_destroy(co);
1021             return;
1022         }
1023         else if (len == 0)
1024         {
1025             yaz_log(YLOG_WARN, "EOF reading from %s", cl->database->database->url);
1026             connection_destroy(co);
1027             return;
1028         }
1029         else if (len > 1) // We discard input if we have no connection
1030         {
1031             co->state = Conn_Open;
1032
1033             if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
1034             {
1035                 Z_APDU *a;
1036
1037                 odr_reset(global_parameters.odr_in);
1038                 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
1039                 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
1040                 {
1041                     client_fatal(cl);
1042                     return;
1043                 }
1044                 switch (a->which)
1045                 {
1046                     case Z_APDU_initResponse:
1047                         do_initResponse(i, a);
1048                         break;
1049                     case Z_APDU_searchResponse:
1050                         do_searchResponse(i, a);
1051                         break;
1052                     case Z_APDU_presentResponse:
1053                         do_presentResponse(i, a);
1054                         break;
1055                     case Z_APDU_close:
1056                         do_closeResponse(i, a);
1057                         break;
1058                     default:
1059                         yaz_log(YLOG_WARN, 
1060                                 "Unexpected Z39.50 response from %s",  
1061                                 cl->database->database->url);
1062                         client_fatal(cl);
1063                         return;
1064                 }
1065                 // We aren't expecting staggered output from target
1066                 // if (cs_more(t->link))
1067                 //    iochan_setevent(i, EVENT_INPUT);
1068             }
1069             else  // we throw away response and go to idle mode
1070             {
1071                 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
1072                 cl->state = Client_Idle;
1073             }
1074         }
1075         /* if len==1 we do nothing but wait for more input */
1076     }
1077
1078     if (cl->state == Client_Connected) {
1079         send_init(i);
1080     }
1081
1082     if (cl->state == Client_Idle)
1083     {
1084         if (cl->requestid != se->requestid && *se->query) {
1085             send_search(i);
1086         }
1087         else if (cl->hits > 0 && cl->records < global_parameters.toget &&
1088             cl->records < cl->hits) {
1089             send_present(i);
1090         }
1091     }
1092 }
1093
1094 // Disassociate connection from client
1095 static void connection_release(struct connection *co)
1096 {
1097     struct client *cl = co->client;
1098
1099     yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
1100     if (!cl)
1101         return;
1102     cl->connection = 0;
1103     co->client = 0;
1104 }
1105
1106 // Close connection and recycle structure
1107 static void connection_destroy(struct connection *co)
1108 {
1109     struct host *h = co->host;
1110     cs_close(co->link);
1111     iochan_destroy(co->iochan);
1112
1113     yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
1114     if (h->connections == co)
1115         h->connections = co->next;
1116     else
1117     {
1118         struct connection *pco;
1119         for (pco = h->connections; pco && pco->next != co; pco = pco->next)
1120             ;
1121         if (pco)
1122             pco->next = co->next;
1123         else
1124             abort();
1125     }
1126     if (co->client)
1127     {
1128         if (co->client->state != Client_Idle)
1129             co->client->state = Client_Disconnected;
1130         co->client->connection = 0;
1131     }
1132     co->next = connection_freelist;
1133     connection_freelist = co;
1134 }
1135
1136 // Creates a new connection for client, associated with the host of 
1137 // client's database
1138 static struct connection *connection_create(struct client *cl)
1139 {
1140     struct connection *new;
1141     COMSTACK link; 
1142     int res;
1143     void *addr;
1144
1145
1146     if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
1147         {
1148             yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
1149             exit(1);
1150         }
1151     
1152     if (0 == strlen(global_parameters.zproxy_override)){
1153         /* no Z39.50 proxy needed - direct connect */
1154         yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->database->url);
1155         
1156         if (!(addr = cs_straddr(link, cl->database->database->host->ipport)))
1157             {
1158                 yaz_log(YLOG_WARN|YLOG_ERRNO, 
1159                         "Lookup of IP address %s failed", 
1160                         cl->database->database->host->ipport);
1161                 return 0;
1162             }
1163     
1164     } else {
1165         /* Z39.50 proxy connect */
1166         yaz_log(YLOG_DEBUG, "Connection create %s proxy %s", 
1167                 cl->database->database->url, global_parameters.zproxy_override);
1168
1169         if (!(addr = cs_straddr(link, global_parameters.zproxy_override)))
1170             {
1171                 yaz_log(YLOG_WARN|YLOG_ERRNO, 
1172                         "Lookup of IP address %s failed", 
1173                         global_parameters.zproxy_override);
1174                 return 0;
1175             }
1176     }
1177
1178     res = cs_connect(link, addr);
1179     if (res < 0)
1180     {
1181         yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->database->url);
1182         return 0;
1183     }
1184
1185     if ((new = connection_freelist))
1186         connection_freelist = new->next;
1187     else
1188     {
1189         new = xmalloc(sizeof (struct connection));
1190         new->ibuf = 0;
1191         new->ibufsize = 0;
1192     }
1193     new->state = Conn_Connecting;
1194     new->host = cl->database->database->host;
1195     new->next = new->host->connections;
1196     new->host->connections = new;
1197     new->client = cl;
1198     cl->connection = new;
1199     new->link = link;
1200
1201     new->iochan = iochan_create(cs_fileno(link), handler, 0);
1202     iochan_setdata(new->iochan, new);
1203     new->iochan->next = channel_list;
1204     channel_list = new->iochan;
1205     return new;
1206 }
1207
1208 // Close connection and set state to error
1209 static void client_fatal(struct client *cl)
1210 {
1211     yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->database->url);
1212     connection_destroy(cl->connection);
1213     cl->state = Client_Error;
1214 }
1215
1216 // Ensure that client has a connection associated
1217 static int client_prep_connection(struct client *cl)
1218 {
1219     struct connection *co;
1220     struct session *se = cl->session;
1221     struct host *host = cl->database->database->host;
1222
1223     co = cl->connection;
1224
1225     yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->database->url);
1226
1227     if (!co)
1228     {
1229         // See if someone else has an idle connection
1230         // We should look at timestamps here to select the longest-idle connection
1231         for (co = host->connections; co; co = co->next)
1232             if (co->state == Conn_Open && (!co->client || co->client->session != se))
1233                 break;
1234         if (co)
1235         {
1236             connection_release(co);
1237             cl->connection = co;
1238             co->client = cl;
1239         }
1240         else
1241             co = connection_create(cl);
1242     }
1243     if (co)
1244     {
1245         if (co->state == Conn_Connecting)
1246         {
1247             cl->state = Client_Connecting;
1248             iochan_setflag(co->iochan, EVENT_OUTPUT);
1249         }
1250         else if (co->state == Conn_Open)
1251         {
1252             if (cl->state == Client_Error || cl->state == Client_Disconnected)
1253                 cl->state = Client_Idle;
1254             iochan_setflag(co->iochan, EVENT_OUTPUT);
1255         }
1256         return 1;
1257     }
1258     else
1259         return 0;
1260 }
1261
1262 static struct client *client_create(void)
1263 {
1264     struct client *r;
1265     if (client_freelist)
1266     {
1267         r = client_freelist;
1268         client_freelist = client_freelist->next;
1269     }
1270     else
1271         r = xmalloc(sizeof(struct client));
1272     r->database = 0;
1273     r->connection = 0;
1274     r->session = 0;
1275     r->hits = 0;
1276     r->records = 0;
1277     r->setno = 0;
1278     r->requestid = -1;
1279     r->diagnostic = 0;
1280     r->state = Client_Disconnected;
1281     r->next = 0;
1282     return r;
1283 }
1284
1285 void client_destroy(struct client *c)
1286 {
1287     struct session *se = c->session;
1288     if (c == se->clients)
1289         se->clients = c->next;
1290     else
1291     {
1292         struct client *cc;
1293         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1294             ;
1295         if (cc)
1296             cc->next = c->next;
1297     }
1298     if (c->connection)
1299         connection_release(c->connection);
1300     c->next = client_freelist;
1301     client_freelist = c;
1302 }
1303
1304 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1305 {
1306     s->watchlist[what].fun = fun;
1307     s->watchlist[what].data = data;
1308 }
1309
1310 void session_alert_watch(struct session *s, int what)
1311 {
1312     if (!s->watchlist[what].fun)
1313         return;
1314     (*s->watchlist[what].fun)(s->watchlist[what].data);
1315     s->watchlist[what].fun = 0;
1316     s->watchlist[what].data = 0;
1317 }
1318
1319 //callback for grep_databases
1320 static void select_targets_callback(void *context, struct session_database *db)
1321 {
1322     struct session *se = (struct session*) context;
1323     struct client *cl = client_create();
1324     cl->database = db;
1325     cl->session = se;
1326     cl->next = se->clients;
1327     se->clients = cl;
1328 }
1329
1330 // Associates a set of clients with a session;
1331 // Note: Session-databases represent databases with per-session setting overrides
1332 int select_targets(struct session *se, struct database_criterion *crit)
1333 {
1334     while (se->clients)
1335         client_destroy(se->clients);
1336
1337     return session_grep_databases(se, crit, select_targets_callback);
1338 }
1339
1340 int session_active_clients(struct session *s)
1341 {
1342     struct client *c;
1343     int res = 0;
1344
1345     for (c = s->clients; c; c = c->next)
1346         if (c->connection && (c->state == Client_Connecting ||
1347                     c->state == Client_Initializing ||
1348                     c->state == Client_Searching ||
1349                     c->state == Client_Presenting))
1350             res++;
1351
1352     return res;
1353 }
1354
1355 // parses crit1=val1,crit2=val2|val3,...
1356 static struct database_criterion *parse_filter(NMEM m, const char *buf)
1357 {
1358     struct database_criterion *res = 0;
1359     char **values;
1360     int num;
1361     int i;
1362
1363     if (!buf || !*buf)
1364         return 0;
1365     nmem_strsplit(m, ",", buf,  &values, &num);
1366     for (i = 0; i < num; i++)
1367     {
1368         char **subvalues;
1369         int subnum;
1370         int subi;
1371         struct database_criterion *new = nmem_malloc(m, sizeof(*new));
1372         char *eq = strchr(values[i], '=');
1373         if (!eq)
1374         {
1375             yaz_log(YLOG_WARN, "Missing equal-sign in filter");
1376             return 0;
1377         }
1378         *(eq++) = '\0';
1379         new->name = values[i];
1380         nmem_strsplit(m, "|", eq, &subvalues, &subnum);
1381         new->values = 0;
1382         for (subi = 0; subi < subnum; subi++)
1383         {
1384             struct database_criterion_value *newv = nmem_malloc(m, sizeof(*newv));
1385             newv->value = subvalues[subi];
1386             newv->next = new->values;
1387             new->values = newv;
1388         }
1389         new->next = res;
1390         res = new;
1391     }
1392     return res;
1393 }
1394
1395 char *search(struct session *se, char *query, char *filter)
1396 {
1397     int live_channels = 0;
1398     struct client *cl;
1399     struct database_criterion *criteria;
1400
1401     yaz_log(YLOG_DEBUG, "Search");
1402
1403     nmem_reset(se->nmem);
1404     criteria = parse_filter(se->nmem, filter);
1405     strcpy(se->query, query);
1406     se->requestid++;
1407     select_targets(se, criteria);
1408     for (cl = se->clients; cl; cl = cl->next)
1409     {
1410         if (client_prep_connection(cl))
1411             live_channels++;
1412     }
1413     if (live_channels)
1414     {
1415         int maxrecs = live_channels * global_parameters.toget;
1416         se->num_termlists = 0;
1417         se->reclist = reclist_create(se->nmem, maxrecs);
1418         // This will be initialized in send_search()
1419         se->relevance = 0;
1420         se->total_records = se->total_hits = se->total_merged = 0;
1421         se->expected_maxrecs = maxrecs;
1422     }
1423     else
1424         return "NOTARGETS";
1425
1426     return 0;
1427 }
1428
1429 // Apply a session override to a database
1430 void session_apply_setting(struct session *se, char *dbname, char *setting, char *value)
1431 {
1432     struct session_database *sdb;
1433
1434     for (sdb = se->databases; sdb; sdb = sdb->next)
1435         if (!strcmp(dbname, sdb->database->url))
1436         {
1437             struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
1438             int offset = settings_offset(setting);
1439
1440             if (offset < 0)
1441             {
1442                 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
1443                 return;
1444             }
1445             new->precedence = 0;
1446             new->target = dbname;
1447             new->name = setting;
1448             new->value = value;
1449             new->next = sdb->settings[offset];
1450             sdb->settings[offset] = new;
1451             break;
1452         }
1453     if (!sdb)
1454         yaz_log(YLOG_WARN, "Unknown database in setting override: %s", dbname);
1455 }
1456
1457 void session_init_databases_fun(void *context, struct database *db)
1458 {
1459     struct session *se = (struct session *) context;
1460     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
1461     int num = settings_num();
1462     int i;
1463
1464     new->database = db;
1465     new->settings = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
1466     for (i = 0; i < num; i++)
1467         new->settings[i] = db->settings[i];
1468     new->next = se->databases;
1469     se->databases = new;
1470 }
1471
1472 // Initialize session_database list -- this represents this session's view
1473 // of the database list -- subject to modification by the settings ws command
1474 void session_init_databases(struct session *se)
1475 {
1476     se->databases = 0;
1477     grep_databases(se, 0, session_init_databases_fun);
1478 }
1479
1480 void destroy_session(struct session *s)
1481 {
1482     yaz_log(YLOG_LOG, "Destroying session");
1483     while (s->clients)
1484         client_destroy(s->clients);
1485     nmem_destroy(s->nmem);
1486     wrbuf_destroy(s->wrbuf);
1487 }
1488
1489 struct session *new_session(NMEM nmem) 
1490 {
1491     int i;
1492     struct session *session = nmem_malloc(nmem, sizeof(*session));
1493
1494     yaz_log(YLOG_DEBUG, "New Pazpar2 session");
1495     
1496     session->total_hits = 0;
1497     session->total_records = 0;
1498     session->num_termlists = 0;
1499     session->reclist = 0;
1500     session->requestid = -1;
1501     session->clients = 0;
1502     session->expected_maxrecs = 0;
1503     session->query[0] = '\0';
1504     session->session_nmem = nmem;
1505     session->nmem = nmem_create();
1506     session->wrbuf = wrbuf_alloc();
1507     session_init_databases(session);
1508     for (i = 0; i <= SESSION_WATCH_MAX; i++)
1509     {
1510         session->watchlist[i].data = 0;
1511         session->watchlist[i].fun = 0;
1512     }
1513
1514     return session;
1515 }
1516
1517 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1518 {
1519     static struct hitsbytarget res[1000]; // FIXME MM
1520     struct client *cl;
1521
1522     *count = 0;
1523     for (cl = se->clients; cl; cl = cl->next)
1524     {
1525         char *name = session_setting_oneval(cl->database, PZ_NAME);
1526
1527         res[*count].id = cl->database->database->url;
1528         res[*count].name = *name ? name : "Unknown";
1529         res[*count].hits = cl->hits;
1530         res[*count].records = cl->records;
1531         res[*count].diagnostic = cl->diagnostic;
1532         res[*count].state = client_states[cl->state];
1533         res[*count].connected  = cl->connection ? 1 : 0;
1534         (*count)++;
1535     }
1536
1537     return res;
1538 }
1539
1540 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1541 {
1542     int i;
1543
1544     for (i = 0; i < s->num_termlists; i++)
1545         if (!strcmp((const char *) s->termlists[i].name, name))
1546             return termlist_highscore(s->termlists[i].termlist, num);
1547     return 0;
1548 }
1549
1550 #ifdef MISSING_HEADERS
1551 void report_nmem_stats(void)
1552 {
1553     size_t in_use, is_free;
1554
1555     nmem_get_memory_in_use(&in_use);
1556     nmem_get_memory_free(&is_free);
1557
1558     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1559             (long) in_use, (long) is_free);
1560 }
1561 #endif
1562
1563 struct record_cluster *show_single(struct session *s, int id)
1564 {
1565     struct record_cluster *r;
1566
1567     reclist_rewind(s->reclist);
1568     while ((r = reclist_read_record(s->reclist)))
1569         if (r->recid == id)
1570             return r;
1571     return 0;
1572 }
1573
1574 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1575         int *num, int *total, int *sumhits, NMEM nmem_show)
1576 {
1577     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
1578                                        * sizeof(struct record_cluster *));
1579     struct reclist_sortparms *spp;
1580     int i;
1581 #if USE_TIMING    
1582     yaz_timing_t t = yaz_timing_create();
1583 #endif
1584
1585     for (spp = sp; spp; spp = spp->next)
1586         if (spp->type == Metadata_sortkey_relevance)
1587         {
1588             relevance_prepare_read(s->relevance, s->reclist);
1589             break;
1590         }
1591     reclist_sort(s->reclist, sp);
1592
1593     *total = s->reclist->num_records;
1594     *sumhits = s->total_hits;
1595
1596     for (i = 0; i < start; i++)
1597         if (!reclist_read_record(s->reclist))
1598         {
1599             *num = 0;
1600             recs = 0;
1601             break;
1602         }
1603
1604     for (i = 0; i < *num; i++)
1605     {
1606         struct record_cluster *r = reclist_read_record(s->reclist);
1607         if (!r)
1608         {
1609             *num = i;
1610             break;
1611         }
1612         recs[i] = r;
1613     }
1614 #if USE_TIMING
1615     yaz_timing_stop(t);
1616     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1617             yaz_timing_get_real(t), yaz_timing_get_user(t),
1618             yaz_timing_get_sys(t));
1619     yaz_timing_destroy(&t);
1620 #endif
1621     return recs;
1622 }
1623
1624 void statistics(struct session *se, struct statistics *stat)
1625 {
1626     struct client *cl;
1627     int count = 0;
1628
1629     memset(stat, 0, sizeof(*stat));
1630     for (cl = se->clients; cl; cl = cl->next)
1631     {
1632         if (!cl->connection)
1633             stat->num_no_connection++;
1634         switch (cl->state)
1635         {
1636             case Client_Connecting: stat->num_connecting++; break;
1637             case Client_Initializing: stat->num_initializing++; break;
1638             case Client_Searching: stat->num_searching++; break;
1639             case Client_Presenting: stat->num_presenting++; break;
1640             case Client_Idle: stat->num_idle++; break;
1641             case Client_Failed: stat->num_failed++; break;
1642             case Client_Error: stat->num_error++; break;
1643             default: break;
1644         }
1645         count++;
1646     }
1647     stat->num_hits = se->total_hits;
1648     stat->num_records = se->total_records;
1649
1650     stat->num_clients = count;
1651 }
1652
1653 void start_http_listener(void)
1654 {
1655     char hp[128] = "";
1656     struct conf_server *ser = global_parameters.server;
1657
1658     if (*global_parameters.listener_override)
1659         strcpy(hp, global_parameters.listener_override);
1660     else
1661     {
1662         strcpy(hp, ser->host ? ser->host : "");
1663         if (ser->port)
1664         {
1665             if (*hp)
1666                 strcat(hp, ":");
1667             sprintf(hp + strlen(hp), "%d", ser->port);
1668         }
1669     }
1670     http_init(hp);
1671 }
1672
1673 void start_proxy(void)
1674 {
1675     char hp[128] = "";
1676     struct conf_server *ser = global_parameters.server;
1677
1678     if (*global_parameters.proxy_override)
1679         strcpy(hp, global_parameters.proxy_override);
1680     else if (ser->proxy_host || ser->proxy_port)
1681     {
1682         strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1683         if (ser->proxy_port)
1684         {
1685             if (*hp)
1686                 strcat(hp, ":");
1687             sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1688         }
1689     }
1690     else
1691         return;
1692
1693     http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1694 }
1695
1696 void start_zproxy(void)
1697 {
1698     struct conf_server *ser = global_parameters.server;
1699
1700     if (*global_parameters.zproxy_override){
1701         yaz_log(YLOG_LOG, "Z39.50 proxy  %s", 
1702                 global_parameters.zproxy_override);
1703         return;
1704     }
1705
1706     else if (ser->zproxy_host || ser->zproxy_port)
1707     {
1708         char hp[128] = "";
1709
1710         strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
1711         if (ser->zproxy_port)
1712         {
1713             if (*hp)
1714                 strcat(hp, ":");
1715             else
1716                 strcat(hp, "@:");
1717
1718             sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
1719         }
1720         strcpy(global_parameters.zproxy_override, hp);
1721         yaz_log(YLOG_LOG, "Z39.50 proxy  %s", 
1722                 global_parameters.zproxy_override);
1723
1724     }
1725     else
1726         return;
1727 }
1728
1729
1730
1731 /*
1732  * Local variables:
1733  * c-basic-offset: 4
1734  * indent-tabs-mode: nil
1735  * End:
1736  * vim: shiftwidth=4 tabstop=8 expandtab
1737  */