Fixed bug #1395: Fixed size array in function hitsbytarget in logic.c.
[pazpar2-moved-to-github.git] / src / logic.c
1 /* $Id: logic.c,v 1.63 2007-09-05 07:24:04 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 /** \file logic.c
23     \brief high-level logic; mostly user sessions and settings
24 */
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <sys/time.h>
30 #include <unistd.h>
31 #include <sys/socket.h>
32 #include <netdb.h>
33 #include <signal.h>
34 #include <ctype.h>
35 #include <assert.h>
36
37 #include <yaz/marcdisp.h>
38 #include <yaz/comstack.h>
39 #include <yaz/tcpip.h>
40 #include <yaz/proto.h>
41 #include <yaz/readconf.h>
42 #include <yaz/pquery.h>
43 #include <yaz/otherinfo.h>
44 #include <yaz/yaz-util.h>
45 #include <yaz/nmem.h>
46 #include <yaz/query-charset.h>
47 #include <yaz/querytowrbuf.h>
48 #include <yaz/oid_db.h>
49 #include <yaz/snprintf.h>
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 "client.h"
71 #include "settings.h"
72 #include "normalize7bit.h"
73
74 #define TERMLIST_HIGH_SCORE 25
75
76 #define MAX_CHUNK 15
77
78 // Note: Some things in this structure will eventually move to configuration
79 struct parameters global_parameters = 
80 {
81     "",
82     "",
83     "", 
84     0,
85     0, /* dump_records */
86     0, /* debug_mode */
87     30,
88     "81",
89     "Index Data PazPar2",
90     VERSION,
91     600, // 10 minutes
92     60,
93     100,
94     MAX_CHUNK,
95     0,
96     0,
97     180,
98     30
99 };
100
101 // Recursively traverse query structure to extract terms.
102 void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
103 {
104     char **words;
105     int numwords;
106     int i;
107
108     switch (n->kind)
109     {
110         case CCL_RPN_AND:
111         case CCL_RPN_OR:
112         case CCL_RPN_NOT:
113         case CCL_RPN_PROX:
114             pull_terms(nmem, n->u.p[0], termlist, num);
115             pull_terms(nmem, n->u.p[1], termlist, num);
116             break;
117         case CCL_RPN_TERM:
118             nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
119             for (i = 0; i < numwords; i++)
120                 termlist[(*num)++] = words[i];
121             break;
122         default: // NOOP
123             break;
124     }
125 }
126
127
128
129 static void add_facet(struct session *s, const char *type, const char *value)
130 {
131     int i;
132
133     if (!*value)
134         return;
135     for (i = 0; i < s->num_termlists; i++)
136         if (!strcmp(s->termlists[i].name, type))
137             break;
138     if (i == s->num_termlists)
139     {
140         if (i == SESSION_MAX_TERMLISTS)
141         {
142             yaz_log(YLOG_FATAL, "Too many termlists");
143             return;
144         }
145
146         s->termlists[i].name = nmem_strdup(s->nmem, type);
147         s->termlists[i].termlist 
148             = termlist_create(s->nmem, s->expected_maxrecs,
149                               TERMLIST_HIGH_SCORE);
150         s->num_termlists = i + 1;
151     }
152     termlist_insert(s->termlists[i].termlist, value);
153 }
154
155 xmlDoc *record_to_xml(struct session_database *sdb, Z_External *rec)
156 {
157     struct database *db = sdb->database;
158     xmlDoc *rdoc = 0;
159     const Odr_oid *oid = rec->direct_reference;
160
161     /* convert response record to XML somehow */
162     if (rec->which == Z_External_octet && oid
163         && !oid_oidcmp(oid, yaz_oid_recsyn_xml))
164     {
165         /* xml already */
166         rdoc = xmlParseMemory((char*) rec->u.octet_aligned->buf,
167                               rec->u.octet_aligned->len);
168         if (!rdoc)
169         {
170             yaz_log(YLOG_FATAL, "Non-wellformed XML received from %s",
171                     db->url);
172             return 0;
173         }
174     }
175     else if (rec->which == Z_External_OPAC)
176     {
177         if (!sdb->yaz_marc)
178         {
179             yaz_log(YLOG_WARN, "MARC decoding not configured");
180             return 0;
181         }
182         else
183         {
184             /* OPAC gets converted to XML too */
185             WRBUF wrbuf_opac = wrbuf_alloc();
186             /* MARCXML inside the OPAC XML. Charset is in effect because we
187                use the yaz_marc handle */
188             yaz_marc_xml(sdb->yaz_marc, YAZ_MARC_MARCXML);
189             yaz_opac_decode_wrbuf(sdb->yaz_marc, rec->u.opac, wrbuf_opac);
190             
191             rdoc = xmlParseMemory((char*) wrbuf_buf(wrbuf_opac),
192                                   wrbuf_len(wrbuf_opac));
193             if (!rdoc)
194             {
195                 yaz_log(YLOG_WARN, "Unable to parse OPAC XML");
196                 /* Was used to debug bug #1348 */
197 #if 0
198                 FILE *f = fopen("/tmp/opac.xml.txt", "wb");
199                 if (f)
200                 {
201                     fwrite(wrbuf_buf(wrbuf_opac), 1, wrbuf_len(wrbuf_opac), f);
202                     fclose(f);
203                 }
204 #endif
205             }
206             wrbuf_destroy(wrbuf_opac);
207         }
208     }
209     else if (oid && yaz_oid_is_iso2709(oid))
210     {
211         /* ISO2709 gets converted to MARCXML */
212         if (!sdb->yaz_marc)
213         {
214             yaz_log(YLOG_WARN, "MARC decoding not configured");
215             return 0;
216         }
217         else
218         {
219             xmlNode *res;
220             char *buf;
221             int len;
222             
223             if (rec->which != Z_External_octet)
224             {
225                 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
226                         db->url);
227                 return 0;
228             }
229             buf = (char*) rec->u.octet_aligned->buf;
230             len = rec->u.octet_aligned->len;
231             if (yaz_marc_read_iso2709(sdb->yaz_marc, buf, len) < 0)
232             {
233                 yaz_log(YLOG_WARN, "Failed to decode MARC %s", db->url);
234                 return 0;
235             }
236             
237             if (yaz_marc_write_xml(sdb->yaz_marc, &res,
238                                    "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
239             {
240                 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
241                         db->url);
242                 return 0;
243             }
244             rdoc = xmlNewDoc((xmlChar *) "1.0");
245             xmlDocSetRootElement(rdoc, res);
246         }
247     }
248     else
249     {
250         char oid_name_buf[OID_STR_MAX];
251         const char *oid_name = yaz_oid_to_string_buf(oid, 0, oid_name_buf);
252         yaz_log(YLOG_FATAL, 
253                 "Unable to handle record of type %s from %s", 
254                 oid_name, db->url);
255         return 0;
256     }
257     
258     if (global_parameters.dump_records)
259     {
260         FILE *lf = yaz_log_file();
261         if (lf)
262         {
263             yaz_log(YLOG_LOG, "Un-normalized record from %s", db->url);
264 #if LIBXML_VERSION >= 20600
265             xmlDocFormatDump(lf, rdoc, 1);
266 #else
267             xmlDocDump(lf, rdoc);
268 #endif
269             fprintf(lf, "\n");
270         }
271     }
272     return rdoc;
273 }
274
275 #define MAX_XSLT_ARGS 16
276
277 // Add static values from session database settings if applicable
278 static void insert_settings_parameters(struct session_database *sdb,
279         struct session *se, char **parms)
280 {
281     struct conf_service *service = global_parameters.server->service;
282     int i;
283     int nparms = 0;
284     int offset = 0;
285
286     for (i = 0; i < service->num_metadata; i++)
287     {
288         struct conf_metadata *md = &service->metadata[i];
289         int setting;
290
291         if (md->setting == Metadata_setting_parameter &&
292                 (setting = settings_offset(md->name)) > 0)
293         {
294             const char *val = session_setting_oneval(sdb, setting);
295             if (val && nparms < MAX_XSLT_ARGS)
296             {
297                 char *buf;
298                 int len = strlen(val);
299                 buf = nmem_malloc(se->nmem, len + 3);
300                 buf[0] = '\'';
301                 strcpy(buf + 1, val);
302                 buf[len+1] = '\'';
303                 buf[len+2] = '\0';
304                 parms[offset++] = md->name;
305                 parms[offset++] = buf;
306                 nparms++;
307             }
308         }
309     }
310     parms[offset] = 0;
311 }
312
313 // Add static values from session database settings if applicable
314 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc)
315 {
316     struct conf_service *service = global_parameters.server->service;
317     int i;
318
319     for (i = 0; i < service->num_metadata; i++)
320     {
321         struct conf_metadata *md = &service->metadata[i];
322         int offset;
323
324         if (md->setting == Metadata_setting_postproc &&
325                 (offset = settings_offset(md->name)) > 0)
326         {
327             const char *val = session_setting_oneval(sdb, offset);
328             if (val)
329             {
330                 xmlNode *r = xmlDocGetRootElement(doc);
331                 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
332                         (xmlChar *) val);
333                 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
334             }
335         }
336     }
337 }
338
339 xmlDoc *normalize_record(struct session_database *sdb, struct session *se,
340         Z_External *rec)
341 {
342     struct database_retrievalmap *m;
343     xmlDoc *rdoc = record_to_xml(sdb, rec);
344     if (rdoc)
345     {
346         for (m = sdb->map; m; m = m->next)
347         {
348             xmlDoc *new = 0;
349             
350             {
351                 xmlNodePtr root = 0;
352                 char *parms[MAX_XSLT_ARGS*2+1];
353
354                 insert_settings_parameters(sdb, se, parms);
355
356                 new = xsltApplyStylesheet(m->stylesheet, rdoc, (const char **) parms);
357                 root= xmlDocGetRootElement(new);
358                 if (!new || !root || !(root->children))
359                 {
360                     yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
361                             sdb->database->url);
362                     xmlFreeDoc(new);
363                     xmlFreeDoc(rdoc);
364                     return 0;
365                 }
366             }
367             
368             xmlFreeDoc(rdoc);
369             rdoc = new;
370         }
371
372         insert_settings_values(sdb, rdoc);
373
374         if (global_parameters.dump_records)
375         {
376             FILE *lf = yaz_log_file();
377             
378             if (lf)
379             {
380                 yaz_log(YLOG_LOG, "Normalized record from %s", 
381                         sdb->database->url);
382 #if LIBXML_VERSION >= 20600
383                 xmlDocFormatDump(lf, rdoc, 1);
384 #else
385                 xmlDocDump(lf, rdoc);
386 #endif
387                 fprintf(lf, "\n");
388             }
389         }
390     }
391     return rdoc;
392 }
393
394 // Retrieve first defined value for 'name' for given database.
395 // Will be extended to take into account user associated with session
396 const char *session_setting_oneval(struct session_database *db, int offset)
397 {
398     if (!db->settings[offset])
399         return "";
400     return db->settings[offset]->value;
401 }
402
403
404
405 // Initialize YAZ Map structures for MARC-based targets
406 static int prepare_yazmarc(struct session_database *sdb)
407 {
408     const char *s;
409
410     if (!sdb->settings)
411     {
412         yaz_log(YLOG_WARN, "No settings for %s", sdb->database->url);
413         return -1;
414     }
415     if ((s = session_setting_oneval(sdb, PZ_NATIVESYNTAX)) 
416         && !strncmp(s, "iso2709", 7))
417     {
418         char *encoding = "marc-8s", *e;
419         yaz_iconv_t cm;
420
421         // See if a native encoding is specified
422         if ((e = strchr(s, ';')))
423             encoding = e + 1;
424
425         sdb->yaz_marc = yaz_marc_create();
426         yaz_marc_subfield_str(sdb->yaz_marc, "\t");
427         
428         cm = yaz_iconv_open("utf-8", encoding);
429         if (!cm)
430         {
431             yaz_log(YLOG_FATAL, 
432                     "Unable to map from %s to UTF-8 for target %s", 
433                     encoding, sdb->database->url);
434             return -1;
435         }
436         yaz_marc_iconv(sdb->yaz_marc, cm);
437     }
438     return 0;
439 }
440
441 // Prepare XSLT stylesheets for record normalization
442 // Structures are allocated on the session_wide nmem to avoid having
443 // to recompute this for every search. This would lead
444 // to leaking if a single session was to repeatedly change the PZ_XSLT
445 // setting. However, this is not a realistic use scenario.
446 static int prepare_map(struct session *se, struct session_database *sdb)
447 {
448     const char *s;
449
450     if (!sdb->settings)
451     {
452         yaz_log(YLOG_WARN, "No settings on %s", sdb->database->url);
453         return -1;
454     }
455     if ((s = session_setting_oneval(sdb, PZ_XSLT)))
456     {
457         char **stylesheets;
458         struct database_retrievalmap **m = &sdb->map;
459         int num, i;
460         char auto_stylesheet[256];
461
462         if (!strcmp(s, "auto"))
463         {
464             const char *request_syntax = session_setting_oneval(
465                 sdb, PZ_REQUESTSYNTAX);
466             if (request_syntax)
467             {
468                 char *cp;
469                 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
470                              "%s.xsl", request_syntax);
471                 for (cp = auto_stylesheet; *cp; cp++)
472                 {
473                     /* deliberately only consider ASCII */
474                     if (*cp > 32 && *cp < 127)
475                         *cp = tolower(*cp);
476                 }
477                 s = auto_stylesheet;
478             }
479             else
480             {
481                 yaz_log(YLOG_WARN, "No pz:requestsyntax for auto stylesheet");
482             }
483         }
484         nmem_strsplit(se->session_nmem, ",", s, &stylesheets, &num);
485         for (i = 0; i < num; i++)
486         {
487             (*m) = nmem_malloc(se->session_nmem, sizeof(**m));
488             (*m)->next = 0;
489             if (!((*m)->stylesheet = conf_load_stylesheet(stylesheets[i])))
490             {
491                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Unable to load stylesheet: %s",
492                         stylesheets[i]);
493                 return -1;
494             }
495             m = &(*m)->next;
496         }
497     }
498     if (!sdb->map)
499         yaz_log(YLOG_WARN, "No Normalization stylesheet for target %s",
500                 sdb->database->url);
501     return 0;
502 }
503
504 // This analyzes settings and recomputes any supporting data structures
505 // if necessary.
506 static int prepare_session_database(struct session *se, 
507                                     struct session_database *sdb)
508 {
509     if (!sdb->settings)
510     {
511         yaz_log(YLOG_WARN, 
512                 "No settings associated with %s", sdb->database->url);
513         return -1;
514     }
515     if (sdb->settings[PZ_NATIVESYNTAX] && !sdb->yaz_marc)
516     {
517         if (prepare_yazmarc(sdb) < 0)
518             return -1;
519     }
520     if (sdb->settings[PZ_XSLT] && !sdb->map)
521     {
522         if (prepare_map(se, sdb) < 0)
523             return -1;
524     }
525     return 0;
526 }
527
528 // called if watch should be removed because http_channel is to be destroyed
529 static void session_watch_cancel(void *data, struct http_channel *c)
530 {
531     struct session_watchentry *ent = data;
532
533     ent->fun = 0;
534     ent->data = 0;
535     ent->obs = 0;
536 }
537
538 // set watch. Returns 0=OK, -1 if watch is already set
539 int session_set_watch(struct session *s, int what, 
540                       session_watchfun fun, void *data,
541                       struct http_channel *chan)
542 {
543     if (s->watchlist[what].fun)
544         return -1;
545     s->watchlist[what].fun = fun;
546     s->watchlist[what].data = data;
547     s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
548                                                session_watch_cancel);
549     return 0;
550 }
551
552 void session_alert_watch(struct session *s, int what)
553 {
554     if (!s->watchlist[what].fun)
555         return;
556     http_remove_observer(s->watchlist[what].obs);
557     (*s->watchlist[what].fun)(s->watchlist[what].data);
558     s->watchlist[what].fun = 0;
559     s->watchlist[what].data = 0;
560     s->watchlist[what].obs = 0;
561 }
562
563 //callback for grep_databases
564 static void select_targets_callback(void *context, struct session_database *db)
565 {
566     struct session *se = (struct session*) context;
567     struct client *cl = client_create();
568     client_set_database(cl, db);
569     client_set_session(cl, se);
570 }
571
572 // Associates a set of clients with a session;
573 // Note: Session-databases represent databases with per-session 
574 // setting overrides
575 int select_targets(struct session *se, struct database_criterion *crit)
576 {
577     while (se->clients)
578         client_destroy(se->clients);
579
580     return session_grep_databases(se, crit, select_targets_callback);
581 }
582
583 int session_active_clients(struct session *s)
584 {
585     struct client *c;
586     int res = 0;
587
588     for (c = s->clients; c; c = client_next_in_session(c))
589         if (client_is_active(c))
590             res++;
591
592     return res;
593 }
594
595 // parses crit1=val1,crit2=val2|val3,...
596 static struct database_criterion *parse_filter(NMEM m, const char *buf)
597 {
598     struct database_criterion *res = 0;
599     char **values;
600     int num;
601     int i;
602
603     if (!buf || !*buf)
604         return 0;
605     nmem_strsplit(m, ",", buf,  &values, &num);
606     for (i = 0; i < num; i++)
607     {
608         char **subvalues;
609         int subnum;
610         int subi;
611         struct database_criterion *new = nmem_malloc(m, sizeof(*new));
612         char *eq = strchr(values[i], '=');
613         if (!eq)
614         {
615             yaz_log(YLOG_WARN, "Missing equal-sign in filter");
616             return 0;
617         }
618         *(eq++) = '\0';
619         new->name = values[i];
620         nmem_strsplit(m, "|", eq, &subvalues, &subnum);
621         new->values = 0;
622         for (subi = 0; subi < subnum; subi++)
623         {
624             struct database_criterion_value *newv
625                 = nmem_malloc(m, sizeof(*newv));
626             newv->value = subvalues[subi];
627             newv->next = new->values;
628             new->values = newv;
629         }
630         new->next = res;
631         res = new;
632     }
633     return res;
634 }
635
636 enum pazpar2_error_code search(struct session *se,
637                                char *query, char *filter,
638                                const char **addinfo)
639 {
640     int live_channels = 0;
641     int no_working = 0;
642     int no_failed = 0;
643     struct client *cl;
644     struct database_criterion *criteria;
645
646     yaz_log(YLOG_DEBUG, "Search");
647
648     *addinfo = 0;
649     nmem_reset(se->nmem);
650     se->relevance = 0;
651     se->total_records = se->total_hits = se->total_merged = 0;
652     se->reclist = 0;
653     se->num_termlists = 0;
654     criteria = parse_filter(se->nmem, filter);
655     se->requestid++;
656     live_channels = select_targets(se, criteria);
657     if (live_channels)
658     {
659         int maxrecs = live_channels * global_parameters.toget;
660         se->reclist = reclist_create(se->nmem, maxrecs);
661         se->expected_maxrecs = maxrecs;
662     }
663     else
664         return PAZPAR2_NO_TARGETS;
665
666     for (cl = se->clients; cl; cl = client_next_in_session(cl))
667     {
668         if (prepare_session_database(se, client_get_database(cl)) < 0)
669         {
670             *addinfo = client_get_database(cl)->database->url;
671             return PAZPAR2_CONFIG_TARGET;
672         }
673         // Parse query for target
674         if (client_parse_query(cl, query) < 0)
675             no_failed++;
676         else
677         {
678             no_working++;
679             client_prep_connection(cl);
680         }
681     }
682
683     // If no queries could be mapped, we signal an error
684     if (no_working == 0)
685     {
686         *addinfo = "query";
687         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
688     }
689     return PAZPAR2_NO_ERROR;
690 }
691
692 // Creates a new session_database object for a database
693 static void session_init_databases_fun(void *context, struct database *db)
694 {
695     struct session *se = (struct session *) context;
696     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
697     int num = settings_num();
698     int i;
699
700     new->database = db;
701     new->yaz_marc = 0;
702     
703 #ifdef HAVE_ICU
704     if (global_parameters.server && global_parameters.server->icu_chn)
705         new->pct = pp2_charset_create(global_parameters.server->icu_chn);
706     else
707         new->pct = pp2_charset_create(0);
708 #else // HAVE_ICU
709     new->pct = pp2_charset_create(0);
710 #endif // HAVE_ICU
711
712     new->map = 0;
713     new->settings 
714         = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
715     memset(new->settings, 0, sizeof(struct settings*) * num);
716
717     if (db->settings)
718     {
719         for (i = 0; i < num; i++)
720             new->settings[i] = db->settings[i];
721     }
722     new->next = se->databases;
723     se->databases = new;
724 }
725
726 // Doesn't free memory associated with sdb -- nmem takes care of that
727 static void session_database_destroy(struct session_database *sdb)
728 {
729     struct database_retrievalmap *m;
730
731     for (m = sdb->map; m; m = m->next)
732         xsltFreeStylesheet(m->stylesheet);
733     if (sdb->yaz_marc)
734         yaz_marc_destroy(sdb->yaz_marc);
735     if (sdb->pct)
736         pp2_charset_destroy(sdb->pct);
737 }
738
739 // Initialize session_database list -- this represents this session's view
740 // of the database list -- subject to modification by the settings ws command
741 void session_init_databases(struct session *se)
742 {
743     se->databases = 0;
744     predef_grep_databases(se, 0, session_init_databases_fun);
745 }
746
747 // Probably session_init_databases_fun should be refactored instead of
748 // called here.
749 static struct session_database *load_session_database(struct session *se, 
750                                                       char *id)
751 {
752     struct database *db = find_database(id, 0);
753
754     session_init_databases_fun((void*) se, db);
755     // New sdb is head of se->databases list
756     return se->databases;
757 }
758
759 // Find an existing session database. If not found, load it
760 static struct session_database *find_session_database(struct session *se, 
761                                                       char *id)
762 {
763     struct session_database *sdb;
764
765     for (sdb = se->databases; sdb; sdb = sdb->next)
766         if (!strcmp(sdb->database->url, id))
767             return sdb;
768     return load_session_database(se, id);
769 }
770
771 // Apply a session override to a database
772 void session_apply_setting(struct session *se, char *dbname, char *setting,
773                            char *value)
774 {
775     struct session_database *sdb = find_session_database(se, dbname);
776     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
777     int offset = settings_offset_cprefix(setting);
778
779     if (offset < 0)
780     {
781         yaz_log(YLOG_WARN, "Unknown setting %s", setting);
782         return;
783     }
784     // Jakub: This breaks the filter setting.
785     /*if (offset == PZ_ID)
786     {
787         yaz_log(YLOG_WARN, "No need to set pz:id setting. Ignoring");
788         return;
789     }*/
790     new->precedence = 0;
791     new->target = dbname;
792     new->name = setting;
793     new->value = value;
794     new->next = sdb->settings[offset];
795     sdb->settings[offset] = new;
796
797     // Force later recompute of settings-driven data structures
798     // (happens when a search starts and client connections are prepared)
799     switch (offset)
800     {
801         case PZ_NATIVESYNTAX:
802             if (sdb->yaz_marc)
803             {
804                 yaz_marc_destroy(sdb->yaz_marc);
805                 sdb->yaz_marc = 0;
806             }
807             break;
808         case PZ_XSLT:
809             if (sdb->map)
810             {
811                 struct database_retrievalmap *m;
812                 // We don't worry about the map structure -- it's in nmem
813                 for (m = sdb->map; m; m = m->next)
814                     xsltFreeStylesheet(m->stylesheet);
815                 sdb->map = 0;
816             }
817             break;
818     }
819 }
820
821 void destroy_session(struct session *s)
822 {
823     struct session_database *sdb;
824
825     while (s->clients)
826         client_destroy(s->clients);
827     for (sdb = s->databases; sdb; sdb = sdb->next)
828         session_database_destroy(sdb);
829     nmem_destroy(s->nmem);
830     wrbuf_destroy(s->wrbuf);
831 }
832
833 struct session *new_session(NMEM nmem) 
834 {
835     int i;
836     struct session *session = nmem_malloc(nmem, sizeof(*session));
837
838     yaz_log(YLOG_DEBUG, "New Pazpar2 session");
839     
840     session->relevance = 0;
841     session->total_hits = 0;
842     session->total_records = 0;
843     session->num_termlists = 0;
844     session->reclist = 0;
845     session->requestid = -1;
846     session->clients = 0;
847     session->expected_maxrecs = 0;
848     session->session_nmem = nmem;
849     session->nmem = nmem_create();
850     session->wrbuf = wrbuf_alloc();
851     session->databases = 0;
852     for (i = 0; i <= SESSION_WATCH_MAX; i++)
853     {
854         session->watchlist[i].data = 0;
855         session->watchlist[i].fun = 0;
856     }
857
858     return session;
859 }
860
861 struct hitsbytarget *hitsbytarget(struct session *se, int *count, NMEM nmem)
862 {
863     struct hitsbytarget *res = 0;
864     struct client *cl;
865     size_t sz = 0;
866
867     for (cl = se->clients; cl; cl = client_next_in_session(cl))
868         sz++;
869
870     res = nmem_malloc(nmem, sizeof(*res) * sz);
871     *count = 0;
872     for (cl = se->clients; cl; cl = client_next_in_session(cl))
873     {
874         const char *name = session_setting_oneval(client_get_database(cl),
875                                                   PZ_NAME);
876
877         res[*count].id = client_get_database(cl)->database->url;
878         res[*count].name = *name ? name : "Unknown";
879         res[*count].hits = client_get_hits(cl);
880         res[*count].records = client_get_num_records(cl);
881         res[*count].diagnostic = client_get_diagnostic(cl);
882         res[*count].state = client_get_state_str(cl);
883         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
884         (*count)++;
885     }
886     return res;
887 }
888
889 struct termlist_score **termlist(struct session *s, const char *name, int *num)
890 {
891     int i;
892
893     for (i = 0; i < s->num_termlists; i++)
894         if (!strcmp((const char *) s->termlists[i].name, name))
895             return termlist_highscore(s->termlists[i].termlist, num);
896     return 0;
897 }
898
899 #ifdef MISSING_HEADERS
900 void report_nmem_stats(void)
901 {
902     size_t in_use, is_free;
903
904     nmem_get_memory_in_use(&in_use);
905     nmem_get_memory_free(&is_free);
906
907     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
908             (long) in_use, (long) is_free);
909 }
910 #endif
911
912 struct record_cluster *show_single(struct session *s, const char *id)
913 {
914     struct record_cluster *r;
915
916     reclist_rewind(s->reclist);
917     while ((r = reclist_read_record(s->reclist)))
918         if (!strcmp(r->recid, id))
919             return r;
920     return 0;
921 }
922
923 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, 
924                              int start, int *num, int *total, int *sumhits, 
925                              NMEM nmem_show)
926 {
927     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
928                                        * sizeof(struct record_cluster *));
929     struct reclist_sortparms *spp;
930     int i;
931 #if USE_TIMING    
932     yaz_timing_t t = yaz_timing_create();
933 #endif
934
935     if (!s->relevance)
936     {
937         *num = 0;
938         *total = 0;
939         *sumhits = 0;
940         recs = 0;
941     }
942     else
943     {
944         for (spp = sp; spp; spp = spp->next)
945             if (spp->type == Metadata_sortkey_relevance)
946             {
947                 relevance_prepare_read(s->relevance, s->reclist);
948                 break;
949             }
950         reclist_sort(s->reclist, sp);
951         
952         *total = s->reclist->num_records;
953         *sumhits = s->total_hits;
954         
955         for (i = 0; i < start; i++)
956             if (!reclist_read_record(s->reclist))
957             {
958                 *num = 0;
959                 recs = 0;
960                 break;
961             }
962         
963         for (i = 0; i < *num; i++)
964         {
965             struct record_cluster *r = reclist_read_record(s->reclist);
966             if (!r)
967             {
968                 *num = i;
969                 break;
970             }
971             recs[i] = r;
972         }
973     }
974 #if USE_TIMING
975     yaz_timing_stop(t);
976     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
977             yaz_timing_get_real(t), yaz_timing_get_user(t),
978             yaz_timing_get_sys(t));
979     yaz_timing_destroy(&t);
980 #endif
981     return recs;
982 }
983
984 void statistics(struct session *se, struct statistics *stat)
985 {
986     struct client *cl;
987     int count = 0;
988
989     memset(stat, 0, sizeof(*stat));
990     for (cl = se->clients; cl; cl = client_next_in_session(cl))
991     {
992         if (!client_get_connection(cl))
993             stat->num_no_connection++;
994         switch (client_get_state(cl))
995         {
996             case Client_Connecting: stat->num_connecting++; break;
997             case Client_Initializing: stat->num_initializing++; break;
998             case Client_Searching: stat->num_searching++; break;
999             case Client_Presenting: stat->num_presenting++; break;
1000             case Client_Idle: stat->num_idle++; break;
1001             case Client_Failed: stat->num_failed++; break;
1002             case Client_Error: stat->num_error++; break;
1003             default: break;
1004         }
1005         count++;
1006     }
1007     stat->num_hits = se->total_hits;
1008     stat->num_records = se->total_records;
1009
1010     stat->num_clients = count;
1011 }
1012
1013 void start_http_listener(void)
1014 {
1015     char hp[128] = "";
1016     struct conf_server *ser = global_parameters.server;
1017
1018     if (*global_parameters.listener_override)
1019         strcpy(hp, global_parameters.listener_override);
1020     else
1021     {
1022         strcpy(hp, ser->host ? ser->host : "");
1023         if (ser->port)
1024         {
1025             if (*hp)
1026                 strcat(hp, ":");
1027             sprintf(hp + strlen(hp), "%d", ser->port);
1028         }
1029     }
1030     http_init(hp);
1031 }
1032
1033 void start_proxy(void)
1034 {
1035     char hp[128] = "";
1036     struct conf_server *ser = global_parameters.server;
1037
1038     if (*global_parameters.proxy_override)
1039         strcpy(hp, global_parameters.proxy_override);
1040     else if (ser->proxy_host || ser->proxy_port)
1041     {
1042         strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1043         if (ser->proxy_port)
1044         {
1045             if (*hp)
1046                 strcat(hp, ":");
1047             sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1048         }
1049     }
1050     else
1051         return;
1052
1053     http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1054 }
1055
1056
1057 // Master list of connections we're handling events to
1058 static IOCHAN channel_list = 0; 
1059 void pazpar2_add_channel(IOCHAN chan)
1060 {
1061     chan->next = channel_list;
1062     channel_list = chan;
1063 }
1064
1065 void pazpar2_event_loop()
1066 {
1067     event_loop(&channel_list);
1068 }
1069
1070 static struct record_metadata *record_metadata_init(
1071     NMEM nmem, char *value, enum conf_metadata_type type)
1072 {
1073     struct record_metadata *rec_md = record_metadata_create(nmem);
1074     if (type == Metadata_type_generic)
1075     {
1076         char * p = value;
1077         p = normalize7bit_generic(p, " ,/.:([");
1078         
1079         rec_md->data.text = nmem_strdup(nmem, p);
1080     }
1081     else if (type == Metadata_type_year)
1082     {
1083         int first, last;
1084         if (extract7bit_years((char *) value, &first, &last) < 0)
1085             return 0;
1086         rec_md->data.number.min = first;
1087         rec_md->data.number.max = last;
1088     }
1089     else
1090         return 0;
1091     return rec_md;
1092 }
1093
1094 struct record *ingest_record(struct client *cl, Z_External *rec,
1095                              int record_no)
1096 {
1097     xmlDoc *xdoc = normalize_record(client_get_database(cl),
1098         client_get_session(cl), rec);
1099     xmlNode *root, *n;
1100     struct record *record;
1101     struct record_cluster *cluster;
1102     struct session *se = client_get_session(cl);
1103     xmlChar *mergekey, *mergekey_norm;
1104     xmlChar *type = 0;
1105     xmlChar *value = 0;
1106     struct conf_service *service = global_parameters.server->service;
1107
1108     if (!xdoc)
1109         return 0;
1110
1111     root = xmlDocGetRootElement(xdoc);
1112     if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
1113     {
1114         yaz_log(YLOG_WARN, "No mergekey found in record");
1115         xmlFreeDoc(xdoc);
1116         return 0;
1117     }
1118
1119     record = record_create(se->nmem, 
1120                            service->num_metadata, service->num_sortkeys, cl,
1121                            record_no);
1122
1123     mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
1124     xmlFree(mergekey);
1125     normalize7bit_mergekey((char *) mergekey_norm, 0);
1126
1127     cluster = reclist_insert(se->reclist, 
1128                              global_parameters.server->service, 
1129                              record, (char *) mergekey_norm, 
1130                              &se->total_merged);
1131     if (global_parameters.dump_records)
1132         yaz_log(YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1133                 client_get_database(cl)->database->url, record_no);
1134     if (!cluster)
1135     {
1136         /* no room for record */
1137         xmlFreeDoc(xdoc);
1138         return 0;
1139     }
1140     relevance_newrec(se->relevance, cluster);
1141
1142
1143     // now parsing XML record and adding data to cluster or record metadata
1144     for (n = root->children; n; n = n->next)
1145     {
1146         if (type)
1147             xmlFree(type);
1148         if (value)
1149             xmlFree(value);
1150         type = value = 0;
1151
1152         if (n->type != XML_ELEMENT_NODE)
1153             continue;
1154         if (!strcmp((const char *) n->name, "metadata"))
1155         {
1156             struct conf_metadata *ser_md = 0;
1157             struct conf_sortkey *ser_sk = 0;
1158             struct record_metadata **wheretoput = 0;
1159             struct record_metadata *rec_md = 0;
1160             int md_field_id = -1;
1161             int sk_field_id = -1;
1162
1163             type = xmlGetProp(n, (xmlChar *) "type");
1164             value = xmlNodeListGetString(xdoc, n->children, 1);
1165
1166             if (!type || !value || !*value)
1167                 continue;
1168
1169             md_field_id 
1170                 = conf_service_metadata_field_id(service, (const char *) type);
1171             if (md_field_id < 0)
1172             {
1173                 yaz_log(YLOG_WARN, 
1174                         "Ignoring unknown metadata element: %s", type);
1175                 continue;
1176             }
1177
1178             ser_md = &service->metadata[md_field_id];
1179
1180             if (ser_md->sortkey_offset >= 0){
1181                 sk_field_id = ser_md->sortkey_offset;
1182                 ser_sk = &service->sortkeys[sk_field_id];
1183             }
1184
1185             // non-merged metadata
1186             rec_md = record_metadata_init(se->nmem, (char *) value,
1187                                           ser_md->type);
1188             if (!rec_md)
1189             {
1190                 yaz_log(YLOG_WARN, "bad metadata data '%s' for element '%s'",
1191                         value, type);
1192                 continue;
1193             }
1194             rec_md->next = record->metadata[md_field_id];
1195             record->metadata[md_field_id] = rec_md;
1196
1197             // merged metadata
1198             rec_md = record_metadata_init(se->nmem, (char *) value,
1199                                           ser_md->type);
1200             wheretoput = &cluster->metadata[md_field_id];
1201
1202             // and polulate with data:
1203             // assign cluster or record based on merge action
1204             if (ser_md->merge == Metadata_merge_unique)
1205             {
1206                 struct record_metadata *mnode;
1207                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1208                     if (!strcmp((const char *) mnode->data.text, 
1209                                 rec_md->data.text))
1210                         break;
1211                 if (!mnode)
1212                 {
1213                     rec_md->next = *wheretoput;
1214                     *wheretoput = rec_md;
1215                 }
1216             }
1217             else if (ser_md->merge == Metadata_merge_longest)
1218             {
1219                 if (!*wheretoput 
1220                     || strlen(rec_md->data.text) 
1221                        > strlen((*wheretoput)->data.text))
1222                 {
1223                     *wheretoput = rec_md;
1224                     if (ser_sk)
1225                     {
1226                         char *s = nmem_strdup(se->nmem, rec_md->data.text);
1227                         if (!cluster->sortkeys[sk_field_id])
1228                             cluster->sortkeys[sk_field_id] = 
1229                                 nmem_malloc(se->nmem, 
1230                                             sizeof(union data_types));
1231                         normalize7bit_mergekey(s,
1232                              (ser_sk->type == Metadata_sortkey_skiparticle));
1233                         cluster->sortkeys[sk_field_id]->text = s;
1234                     }
1235                 }
1236             }
1237             else if (ser_md->merge == Metadata_merge_all)
1238             {
1239                 rec_md->next = *wheretoput;
1240                 *wheretoput = rec_md;
1241             }
1242             else if (ser_md->merge == Metadata_merge_range)
1243             {
1244                 if (!*wheretoput)
1245                 {
1246                     *wheretoput = rec_md;
1247                     if (ser_sk)
1248                         cluster->sortkeys[sk_field_id] 
1249                             = &rec_md->data;
1250                 }
1251                 else
1252                 {
1253                     int this_min = rec_md->data.number.min;
1254                     int this_max = rec_md->data.number.max;
1255                     if (this_min < (*wheretoput)->data.number.min)
1256                         (*wheretoput)->data.number.min = this_min;
1257                     if (this_max > (*wheretoput)->data.number.max)
1258                         (*wheretoput)->data.number.max = this_max;
1259                 }
1260 #ifdef GAGA
1261                 if (ser_sk)
1262                 {
1263                     union data_types *sdata 
1264                         = cluster->sortkeys[sk_field_id];
1265                     yaz_log(YLOG_LOG, "SK range: %d-%d",
1266                             sdata->number.min, sdata->number.max);
1267                 }
1268 #endif
1269             }
1270
1271
1272             // ranking of _all_ fields enabled ... 
1273             if (ser_md->rank)
1274                 relevance_countwords(se->relevance, cluster, 
1275                                      (char *) value, ser_md->rank);
1276
1277             // construct facets ... 
1278             if (ser_md->termlist)
1279             {
1280                 if (ser_md->type == Metadata_type_year)
1281                 {
1282                     char year[64];
1283                     sprintf(year, "%d", rec_md->data.number.max);
1284                     add_facet(se, (char *) type, year);
1285                     if (rec_md->data.number.max != rec_md->data.number.min)
1286                     {
1287                         sprintf(year, "%d", rec_md->data.number.min);
1288                         add_facet(se, (char *) type, year);
1289                     }
1290                 }
1291                 else
1292                     add_facet(se, (char *) type, (char *) value);
1293             }
1294
1295             // cleaning up
1296             xmlFree(type);
1297             xmlFree(value);
1298             type = value = 0;
1299         }
1300         else
1301             yaz_log(YLOG_WARN,
1302                     "Unexpected element %s in internal record", n->name);
1303     }
1304     if (type)
1305         xmlFree(type);
1306     if (value)
1307         xmlFree(value);
1308
1309     xmlFreeDoc(xdoc);
1310
1311     relevance_donerecord(se->relevance, cluster);
1312     se->total_records++;
1313
1314     return record;
1315 }
1316
1317
1318
1319 /*
1320  * Local variables:
1321  * c-basic-offset: 4
1322  * indent-tabs-mode: nil
1323  * End:
1324  * vim: shiftwidth=4 tabstop=8 expandtab
1325  */