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