Pazpar2 compiles on Windows. But does not yet work
[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 #include <stdlib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #if HAVE_SYS_TIME_H
28 #include <sys/time.h>
29 #endif
30 #if HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33 #if HAVE_SYS_SOCKET_H
34 #include <sys/socket.h>
35 #endif
36 #if HAVE_NETDB_H
37 #include <netdb.h>
38 #endif
39 #include <signal.h>
40 #include <ctype.h>
41 #include <assert.h>
42
43 #include <yaz/marcdisp.h>
44 #include <yaz/comstack.h>
45 #include <yaz/tcpip.h>
46 #include <yaz/proto.h>
47 #include <yaz/readconf.h>
48 #include <yaz/pquery.h>
49 #include <yaz/otherinfo.h>
50 #include <yaz/yaz-util.h>
51 #include <yaz/nmem.h>
52 #include <yaz/query-charset.h>
53 #include <yaz/querytowrbuf.h>
54 #include <yaz/oid_db.h>
55 #include <yaz/snprintf.h>
56
57 #if HAVE_CONFIG_H
58 #include <config.h>
59 #endif
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->num_termlists = 0;
851     session->reclist = 0;
852     session->requestid = -1;
853     session->clients = 0;
854     session->expected_maxrecs = 0;
855     session->session_nmem = nmem;
856     session->nmem = nmem_create();
857     session->wrbuf = wrbuf_alloc();
858     session->databases = 0;
859     for (i = 0; i <= SESSION_WATCH_MAX; i++)
860     {
861         session->watchlist[i].data = 0;
862         session->watchlist[i].fun = 0;
863     }
864     return session;
865 }
866
867 struct hitsbytarget *hitsbytarget(struct session *se, int *count, NMEM nmem)
868 {
869     struct hitsbytarget *res = 0;
870     struct client *cl;
871     size_t sz = 0;
872
873     for (cl = se->clients; cl; cl = client_next_in_session(cl))
874         sz++;
875
876     res = nmem_malloc(nmem, sizeof(*res) * sz);
877     *count = 0;
878     for (cl = se->clients; cl; cl = client_next_in_session(cl))
879     {
880         const char *name = session_setting_oneval(client_get_database(cl),
881                                                   PZ_NAME);
882
883         res[*count].id = client_get_database(cl)->database->url;
884         res[*count].name = *name ? name : "Unknown";
885         res[*count].hits = client_get_hits(cl);
886         res[*count].records = client_get_num_records(cl);
887         res[*count].diagnostic = client_get_diagnostic(cl);
888         res[*count].state = client_get_state_str(cl);
889         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
890         (*count)++;
891     }
892     return res;
893 }
894
895 struct termlist_score **termlist(struct session *s, const char *name, int *num)
896 {
897     int i;
898
899     for (i = 0; i < s->num_termlists; i++)
900         if (!strcmp((const char *) s->termlists[i].name, name))
901             return termlist_highscore(s->termlists[i].termlist, num);
902     return 0;
903 }
904
905 #ifdef MISSING_HEADERS
906 void report_nmem_stats(void)
907 {
908     size_t in_use, is_free;
909
910     nmem_get_memory_in_use(&in_use);
911     nmem_get_memory_free(&is_free);
912
913     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
914             (long) in_use, (long) is_free);
915 }
916 #endif
917
918 struct record_cluster *show_single(struct session *s, const char *id)
919 {
920     struct record_cluster *r;
921
922     reclist_rewind(s->reclist);
923     while ((r = reclist_read_record(s->reclist)))
924         if (!strcmp(r->recid, id))
925             return r;
926     return 0;
927 }
928
929 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, 
930                              int start, int *num, int *total, int *sumhits, 
931                              NMEM nmem_show)
932 {
933     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
934                                                * sizeof(struct record_cluster *));
935     struct reclist_sortparms *spp;
936     int i;
937 #if USE_TIMING    
938     yaz_timing_t t = yaz_timing_create();
939 #endif
940
941     if (!s->relevance)
942     {
943         *num = 0;
944         *total = 0;
945         *sumhits = 0;
946         recs = 0;
947     }
948     else
949     {
950         for (spp = sp; spp; spp = spp->next)
951             if (spp->type == Metadata_sortkey_relevance)
952             {
953                 relevance_prepare_read(s->relevance, s->reclist);
954                 break;
955             }
956         reclist_sort(s->reclist, sp);
957         
958         *total = s->reclist->num_records;
959         *sumhits = s->total_hits;
960         
961         for (i = 0; i < start; i++)
962             if (!reclist_read_record(s->reclist))
963             {
964                 *num = 0;
965                 recs = 0;
966                 break;
967             }
968         
969         for (i = 0; i < *num; i++)
970         {
971             struct record_cluster *r = reclist_read_record(s->reclist);
972             if (!r)
973             {
974                 *num = i;
975                 break;
976             }
977             recs[i] = r;
978         }
979     }
980 #if USE_TIMING
981     yaz_timing_stop(t);
982     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
983             yaz_timing_get_real(t), yaz_timing_get_user(t),
984             yaz_timing_get_sys(t));
985     yaz_timing_destroy(&t);
986 #endif
987     return recs;
988 }
989
990 void statistics(struct session *se, struct statistics *stat)
991 {
992     struct client *cl;
993     int count = 0;
994
995     memset(stat, 0, sizeof(*stat));
996     for (cl = se->clients; cl; cl = client_next_in_session(cl))
997     {
998         if (!client_get_connection(cl))
999             stat->num_no_connection++;
1000         switch (client_get_state(cl))
1001         {
1002         case Client_Connecting: stat->num_connecting++; break;
1003         case Client_Initializing: stat->num_initializing++; break;
1004         case Client_Searching: stat->num_searching++; break;
1005         case Client_Presenting: stat->num_presenting++; break;
1006         case Client_Idle: stat->num_idle++; break;
1007         case Client_Failed: stat->num_failed++; break;
1008         case Client_Error: stat->num_error++; break;
1009         default: break;
1010         }
1011         count++;
1012     }
1013     stat->num_hits = se->total_hits;
1014     stat->num_records = se->total_records;
1015
1016     stat->num_clients = count;
1017 }
1018
1019 void start_http_listener(void)
1020 {
1021     char hp[128] = "";
1022     struct conf_server *ser = global_parameters.server;
1023
1024     if (*global_parameters.listener_override)
1025         strcpy(hp, global_parameters.listener_override);
1026     else
1027     {
1028         strcpy(hp, ser->host ? ser->host : "");
1029         if (ser->port)
1030         {
1031             if (*hp)
1032                 strcat(hp, ":");
1033             sprintf(hp + strlen(hp), "%d", ser->port);
1034         }
1035     }
1036     http_init(hp);
1037 }
1038
1039 void start_proxy(void)
1040 {
1041     char hp[128] = "";
1042     struct conf_server *ser = global_parameters.server;
1043
1044     if (*global_parameters.proxy_override)
1045         strcpy(hp, global_parameters.proxy_override);
1046     else if (ser->proxy_host || ser->proxy_port)
1047     {
1048         strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1049         if (ser->proxy_port)
1050         {
1051             if (*hp)
1052                 strcat(hp, ":");
1053             sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1054         }
1055     }
1056     else
1057         return;
1058
1059     http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1060 }
1061
1062
1063 // Master list of connections we're handling events to
1064 static IOCHAN channel_list = 0; 
1065 void pazpar2_add_channel(IOCHAN chan)
1066 {
1067     chan->next = channel_list;
1068     channel_list = chan;
1069 }
1070
1071 void pazpar2_event_loop()
1072 {
1073     event_loop(&channel_list);
1074 }
1075
1076 static struct record_metadata *record_metadata_init(
1077     NMEM nmem, char *value, enum conf_metadata_type type)
1078 {
1079     struct record_metadata *rec_md = record_metadata_create(nmem);
1080     if (type == Metadata_type_generic)
1081     {
1082         char * p = value;
1083         p = normalize7bit_generic(p, " ,/.:([");
1084         
1085         rec_md->data.text.disp = nmem_strdup(nmem, p);
1086         rec_md->data.text.sort = 0;
1087     }
1088     else if (type == Metadata_type_year || type == Metadata_type_date)
1089     {
1090         int first, last;
1091         int longdate = 0;
1092
1093         if (type == Metadata_type_date)
1094             longdate = 1;
1095         if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1096             return 0;
1097
1098         rec_md->data.number.min = first;
1099         rec_md->data.number.max = last;
1100     }
1101     else
1102         return 0;
1103     return rec_md;
1104 }
1105
1106 struct record *ingest_record(struct client *cl, Z_External *rec,
1107                              int record_no)
1108 {
1109     xmlDoc *xdoc = normalize_record(client_get_database(cl),
1110                                     client_get_session(cl), rec);
1111     xmlNode *root, *n;
1112     struct record *record;
1113     struct record_cluster *cluster;
1114     struct session *se = client_get_session(cl);
1115     xmlChar *mergekey, *mergekey_norm;
1116     xmlChar *type = 0;
1117     xmlChar *value = 0;
1118     struct conf_service *service = global_parameters.server->service;
1119     const char *norm_str = 0;
1120     pp2_relevance_token_t prt = 0;
1121     WRBUF norm_wr = 0;
1122
1123     if (!xdoc)
1124         return 0;
1125
1126     root = xmlDocGetRootElement(xdoc);
1127     if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
1128     {
1129         yaz_log(YLOG_WARN, "No mergekey found in record");
1130         xmlFreeDoc(xdoc);
1131         return 0;
1132     }
1133     
1134     record = record_create(se->nmem, 
1135                            service->num_metadata, service->num_sortkeys, cl,
1136                            record_no);
1137
1138     prt = pp2_relevance_tokenize(
1139         global_parameters.server->mergekey_pct, (const char *) mergekey);
1140
1141
1142     norm_wr = wrbuf_alloc();
1143     
1144     while ((norm_str = pp2_relevance_token_next(prt)))
1145     {
1146         if (*norm_str)
1147         {
1148             if (wrbuf_len(norm_wr))
1149                 wrbuf_puts(norm_wr, " ");
1150             wrbuf_puts(norm_wr, norm_str);
1151         }
1152     }
1153         
1154     mergekey_norm = (xmlChar *)nmem_strdup(se->nmem, wrbuf_cstr(norm_wr));
1155     wrbuf_destroy(norm_wr);
1156
1157     pp2_relevance_token_destroy(prt);
1158
1159     xmlFree(mergekey);
1160     
1161     cluster = reclist_insert(se->reclist, 
1162                              global_parameters.server->service, 
1163                              record, (char *) mergekey_norm, 
1164                              &se->total_merged);
1165     if (global_parameters.dump_records)
1166         yaz_log(YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1167                 client_get_database(cl)->database->url, record_no);
1168     if (!cluster)
1169     {
1170         /* no room for record */
1171         xmlFreeDoc(xdoc);
1172         return 0;
1173     }
1174     relevance_newrec(se->relevance, cluster);
1175      
1176      
1177      // now parsing XML record and adding data to cluster or record metadata
1178      for (n = root->children; n; n = n->next)
1179      {
1180          if (type)
1181              xmlFree(type);
1182          if (value)
1183              xmlFree(value);
1184          type = value = 0;
1185
1186          if (n->type != XML_ELEMENT_NODE)
1187              continue;
1188          if (!strcmp((const char *) n->name, "metadata"))
1189          {
1190              struct conf_metadata *ser_md = 0;
1191              struct conf_sortkey *ser_sk = 0;
1192              struct record_metadata **wheretoput = 0;
1193              struct record_metadata *rec_md = 0;
1194              int md_field_id = -1;
1195              int sk_field_id = -1;
1196
1197              type = xmlGetProp(n, (xmlChar *) "type");
1198              value = xmlNodeListGetString(xdoc, n->children, 1);
1199
1200              if (!type || !value || !*value)
1201                  continue;
1202
1203              md_field_id 
1204                  = conf_service_metadata_field_id(service, (const char *) type);
1205              if (md_field_id < 0)
1206              {
1207                  yaz_log(YLOG_WARN, 
1208                          "Ignoring unknown metadata element: %s", type);
1209                  continue;
1210              }
1211
1212              ser_md = &service->metadata[md_field_id];
1213
1214              if (ser_md->sortkey_offset >= 0){
1215                  sk_field_id = ser_md->sortkey_offset;
1216                  ser_sk = &service->sortkeys[sk_field_id];
1217              }
1218
1219              // non-merged metadata
1220              rec_md = record_metadata_init(se->nmem, (char *) value,
1221                                            ser_md->type);
1222              if (!rec_md)
1223              {
1224                  yaz_log(YLOG_WARN, "bad metadata data '%s' for element '%s'",
1225                          value, type);
1226                  continue;
1227              }
1228              rec_md->next = record->metadata[md_field_id];
1229              record->metadata[md_field_id] = rec_md;
1230
1231              // merged metadata
1232              rec_md = record_metadata_init(se->nmem, (char *) value,
1233                                            ser_md->type);
1234              wheretoput = &cluster->metadata[md_field_id];
1235
1236              // and polulate with data:
1237              // assign cluster or record based on merge action
1238              if (ser_md->merge == Metadata_merge_unique)
1239              {
1240                  struct record_metadata *mnode;
1241                  for (mnode = *wheretoput; mnode; mnode = mnode->next)
1242                      if (!strcmp((const char *) mnode->data.text.disp, 
1243                                  rec_md->data.text.disp))
1244                          break;
1245                  if (!mnode)
1246                  {
1247                      rec_md->next = *wheretoput;
1248                      *wheretoput = rec_md;
1249                  }
1250              }
1251              else if (ser_md->merge == Metadata_merge_longest)
1252              {
1253                  if (!*wheretoput 
1254                      || strlen(rec_md->data.text.disp) 
1255                      > strlen((*wheretoput)->data.text.disp))
1256                  {
1257                      *wheretoput = rec_md;
1258                      if (ser_sk)
1259                      {
1260                          const char *sort_str = 0;
1261                          int skip_article = 
1262                              ser_sk->type == Metadata_sortkey_skiparticle;
1263
1264                          if (!cluster->sortkeys[sk_field_id])
1265                              cluster->sortkeys[sk_field_id] = 
1266                                  nmem_malloc(se->nmem, 
1267                                              sizeof(union data_types));
1268                          
1269                          prt = pp2_relevance_tokenize(
1270                              global_parameters.server->sort_pct,
1271                              rec_md->data.text.disp);
1272
1273                          pp2_relevance_token_next(prt);
1274                          
1275                          sort_str = pp2_get_sort(prt, skip_article);
1276                          
1277                          cluster->sortkeys[sk_field_id]->text.disp = 
1278                              rec_md->data.text.disp;
1279                          if (!sort_str)
1280                          {
1281                              sort_str = rec_md->data.text.disp;
1282                              yaz_log(YLOG_WARN, 
1283                                      "Could not make sortkey. Bug #1858");
1284                          }
1285                          cluster->sortkeys[sk_field_id]->text.sort = 
1286                              nmem_strdup(se->nmem, sort_str);
1287 #if 0
1288                          yaz_log(YLOG_LOG, "text disp=%s",
1289                                  cluster->sortkeys[sk_field_id]->text.disp);
1290                          yaz_log(YLOG_LOG, "text sort=%s",
1291                                  cluster->sortkeys[sk_field_id]->text.sort);
1292 #endif
1293                          pp2_relevance_token_destroy(prt);
1294                     }
1295                 }
1296             }
1297             else if (ser_md->merge == Metadata_merge_all)
1298             {
1299                 rec_md->next = *wheretoput;
1300                 *wheretoput = rec_md;
1301             }
1302             else if (ser_md->merge == Metadata_merge_range)
1303             {
1304                 if (!*wheretoput)
1305                 {
1306                     *wheretoput = rec_md;
1307                     if (ser_sk)
1308                         cluster->sortkeys[sk_field_id] 
1309                             = &rec_md->data;
1310                 }
1311                 else
1312                 {
1313                     int this_min = rec_md->data.number.min;
1314                     int this_max = rec_md->data.number.max;
1315                     if (this_min < (*wheretoput)->data.number.min)
1316                         (*wheretoput)->data.number.min = this_min;
1317                     if (this_max > (*wheretoput)->data.number.max)
1318                         (*wheretoput)->data.number.max = this_max;
1319                 }
1320             }
1321
1322
1323             // ranking of _all_ fields enabled ... 
1324             if (ser_md->rank)
1325                 relevance_countwords(se->relevance, cluster, 
1326                                      (char *) value, ser_md->rank);
1327
1328             // construct facets ... 
1329             if (ser_md->termlist)
1330             {
1331                 if (ser_md->type == Metadata_type_year)
1332                 {
1333                     char year[64];
1334                     sprintf(year, "%d", rec_md->data.number.max);
1335                     add_facet(se, (char *) type, year);
1336                     if (rec_md->data.number.max != rec_md->data.number.min)
1337                     {
1338                         sprintf(year, "%d", rec_md->data.number.min);
1339                         add_facet(se, (char *) type, year);
1340                     }
1341                 }
1342                 else
1343                     add_facet(se, (char *) type, (char *) value);
1344             }
1345
1346             // cleaning up
1347             xmlFree(type);
1348             xmlFree(value);
1349             type = value = 0;
1350         }
1351         else
1352             yaz_log(YLOG_WARN,
1353                     "Unexpected element %s in internal record", n->name);
1354     }
1355     if (type)
1356         xmlFree(type);
1357     if (value)
1358         xmlFree(value);
1359
1360     xmlFreeDoc(xdoc);
1361
1362     relevance_donerecord(se->relevance, cluster);
1363     se->total_records++;
1364
1365     return record;
1366 }
1367
1368
1369
1370 /*
1371  * Local variables:
1372  * c-basic-offset: 4
1373  * indent-tabs-mode: nil
1374  * End:
1375  * vim: shiftwidth=4 tabstop=8 expandtab
1376  */