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