Towards normalized rankings (PAZ-909)
[pazpar2-moved-to-github.git] / src / settings.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2013 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 // This module implements a generic system of settings
21 // (attribute-value) that can be associated with search targets. The
22 // system supports both default values, per-target overrides, and
23 // per-user settings.
24
25 #if HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29
30 #include <string.h>
31 #include <assert.h>
32 #include <stdio.h>
33 #include <sys/types.h>
34 #include <yaz/dirent.h>
35 #include <stdlib.h>
36 #include <sys/stat.h>
37
38 #include <libxml/parser.h>
39 #include <libxml/tree.h>
40
41 #include <yaz/nmem.h>
42 #include <yaz/log.h>
43
44 #include "session.h"
45 #include "database.h"
46 #include "settings.h"
47
48 // Used for initializing setting_dictionary with pazpar2-specific settings
49 static char *hard_settings[] = {
50     "pz:piggyback",
51     "pz:elements",
52     "pz:requestsyntax",
53     "pz:cclmap:",
54     "pz:xslt",
55     "pz:nativesyntax",
56     "pz:authentication",
57     "pz:allow",
58     "pz:maxrecs",
59     "pz:id",
60     "pz:name",
61     "pz:queryencoding",
62     "pz:zproxy",
63     "pz:apdulog",
64     "pz:sru",
65     "pz:sru_version",
66     "pz:pqf_prefix",
67     "pz:sort",
68     "pz:recordfilter",
69     "pz:pqf_strftime",
70     "pz:negotiation_charset",
71     "pz:max_connections",
72     "pz:reuse_connections",
73     "pz:termlist_term_factor",
74     "pz:termlist_term_count",
75     "pz:preferred",
76     "pz:extra_args",
77     "pz:query_syntax",
78     "pz:facetmap:",
79     "pz:limitmap:",
80     "pz:url",
81     "pz:sortmap:",
82     "pz:present_chunk",
83     "pz:block_timeout",
84     "pz:extendrecs",
85     "pz:authentication_mode",
86     "pz:native_score",
87     0
88 };
89
90 struct setting_dictionary
91 {
92     char **dict;
93     int size;
94     int num;
95 };
96
97 // This establishes the precedence of wildcard expressions
98 #define SETTING_WILDCARD_NO     0 // No wildcard
99 #define SETTING_WILDCARD_DB     1 // Database wildcard 'host:port/*'
100 #define SETTING_WILDCARD_YES    2 // Complete wildcard '*'
101
102 // Returns size of settings directory
103 int settings_num(struct conf_service *service)
104 {
105     return service->dictionary->num;
106 }
107
108 /* Find and possible create a new dictionary entry. Pass valid NMEM pointer if creation is allowed, otherwise null */
109 static int settings_index_lookup(struct setting_dictionary *dictionary, const char *name, NMEM nmem)
110 {
111     size_t maxlen;
112     int i;
113     const char *p;
114
115     assert(name);
116
117     if (!strncmp("pz:", name, 3) && (p = strchr(name + 3, ':')))
118         maxlen = (p - name) + 1;
119     else
120         maxlen = strlen(name) + 1;
121     for (i = 0; i < dictionary->num; i++)
122         if (!strncmp(name, dictionary->dict[i], maxlen))
123             return i;
124     if (!nmem)
125         return -1;
126     if (!strncmp("pz:", name, 3))
127         yaz_log(YLOG_WARN, "Adding pz-type setting name %s", name);
128     if (dictionary->num + 1 > dictionary->size)
129     {
130         char **tmp =
131             nmem_malloc(nmem, dictionary->size * 2 * sizeof(char*));
132         memcpy(tmp, dictionary->dict, dictionary->size * sizeof(char*));
133         dictionary->dict = tmp;
134         dictionary->size *= 2;
135     }
136     dictionary->dict[dictionary->num] = nmem_strdup(nmem, name);
137     dictionary->dict[dictionary->num][maxlen-1] = '\0';
138     return dictionary->num++;
139 }
140
141 int settings_create_offset(struct conf_service *service, const char *name)
142 {
143     return settings_index_lookup(service->dictionary, name, service->nmem);
144 }
145
146 int settings_lookup_offset(struct conf_service *service, const char *name)
147 {
148     return settings_index_lookup(service->dictionary, name, 0);
149 }
150
151 char *settings_name(struct conf_service *service, int offset)
152 {
153     assert(offset < service->dictionary->num);
154     return service->dictionary->dict[offset];
155 }
156
157
158 // Apply a session override to a database
159 void service_apply_setting(struct conf_service *service, char *setting, char *value)
160 {
161     struct setting *new = nmem_malloc(service->nmem, sizeof(*new));
162     int offset = settings_create_offset(service, setting);
163     expand_settings_array(&service->settings->settings, &service->settings->num_settings, offset, service->nmem);
164     new->precedence = 0;
165     new->target = NULL;
166     new->name = setting;
167     new->value = value;
168     new->next = service->settings->settings[offset];
169     service->settings->settings[offset] = new;
170 }
171
172
173 static int isdir(const char *path)
174 {
175     struct stat st;
176
177     if (stat(path, &st) < 0)
178     {
179         yaz_log(YLOG_FATAL|YLOG_ERRNO, "stat %s", path);
180         exit(1);
181     }
182     return st.st_mode & S_IFDIR;
183 }
184
185 // Read settings from an XML file, calling handler function for each setting
186 int settings_read_node_x(xmlNode *n,
187                          void *client_data,
188                          void (*fun)(void *client_data,
189                                      struct setting *set))
190 {
191     int ret_val = 0; /* success */
192     char *namea = (char *) xmlGetProp(n, (xmlChar *) "name");
193     char *targeta = (char *) xmlGetProp(n, (xmlChar *) "target");
194     char *valuea = (char *) xmlGetProp(n, (xmlChar *) "value");
195     char *usera = (char *) xmlGetProp(n, (xmlChar *) "user");
196     char *precedencea = (char *) xmlGetProp(n, (xmlChar *) "precedence");
197
198     for (n = n->children; n; n = n->next)
199     {
200         if (n->type != XML_ELEMENT_NODE)
201             continue;
202         if (!strcmp((const char *) n->name, "set"))
203         {
204             xmlNode *root = n->children;
205             struct setting set;
206             char *name = (char *) xmlGetProp(n, (xmlChar *) "name");
207             char *target = (char *) xmlGetProp(n, (xmlChar *) "target");
208             char *value = (char *) xmlGetProp(n, (xmlChar *) "value");
209             char *user = (char *) xmlGetProp(n, (xmlChar *) "user");
210             char *precedence = (char *) xmlGetProp(n, (xmlChar *) "precedence");
211             xmlChar *buf_out = 0;
212
213             set.next = 0;
214
215             if (precedence)
216                 set.precedence = atoi((char *) precedence);
217             else if (precedencea)
218                 set.precedence = atoi((char *) precedencea);
219             else
220                 set.precedence = 0;
221
222             set.target = target ? target : targeta;
223             set.name = name ? name : namea;
224
225             while (root && root->type != XML_ELEMENT_NODE)
226                 root = root->next;
227             if (!root)
228                 set.value = value ? value : valuea;
229             else
230             {   /* xml document content for this setting */
231                 xmlDoc *doc = xmlNewDoc(BAD_CAST "1.0");
232                 if (!doc)
233                 {
234                     if (set.name)
235                         yaz_log(YLOG_WARN, "bad XML content for setting "
236                                 "name=%s", set.name);
237                     else
238                         yaz_log(YLOG_WARN, "bad XML content for setting");
239                     ret_val = -1;
240                 }
241                 else
242                 {
243                     int len_out;
244                     xmlDocSetRootElement(doc, xmlCopyNode(root, 1));
245                     xmlDocDumpMemory(doc, &buf_out, &len_out);
246                     /* xmlDocDumpMemory 0-terminates */
247                     set.value = (char *) buf_out;
248                     xmlFreeDoc(doc);
249                 }
250             }
251
252             if (set.name && set.value && set.target)
253                 (*fun)(client_data, &set);
254             else
255             {
256                 if (set.name)
257                     yaz_log(YLOG_WARN, "missing value and/or target for "
258                             "setting name=%s", set.name);
259                 else
260                     yaz_log(YLOG_WARN, "missing name/value/target for setting");
261                 ret_val = -1;
262             }
263             xmlFree(buf_out);
264             xmlFree(name);
265             xmlFree(precedence);
266             xmlFree(value);
267             xmlFree(user);
268             xmlFree(target);
269         }
270         else
271         {
272             yaz_log(YLOG_WARN, "Unknown element %s in settings file",
273                     (char*) n->name);
274             ret_val = -1;
275         }
276     }
277     xmlFree(namea);
278     xmlFree(precedencea);
279     xmlFree(valuea);
280     xmlFree(usera);
281     xmlFree(targeta);
282     return ret_val;
283 }
284
285 static int read_settings_file(const char *path,
286                               void *client_data,
287                               void (*fun)(void *client_data,
288                                           struct setting *set))
289 {
290     xmlDoc *doc = xmlParseFile(path);
291     xmlNode *n;
292     int ret;
293
294     if (!doc)
295     {
296         yaz_log(YLOG_FATAL, "Failed to parse %s", path);
297         return -1;
298     }
299     n = xmlDocGetRootElement(doc);
300     ret = settings_read_node_x(n, client_data, fun);
301
302     xmlFreeDoc(doc);
303     return ret;
304 }
305
306
307 // Recursively read files or directories, invoking a
308 // callback for each one
309 static int read_settings(const char *path,
310                           void *client_data,
311                           void (*fun)(void *client_data,
312                                       struct setting *set))
313 {
314     int ret = 0;
315     DIR *d;
316     struct dirent *de;
317     char *dot;
318
319     if (isdir(path))
320     {
321         if (!(d = opendir(path)))
322         {
323             yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", path);
324             return -1;
325         }
326         while ((de = readdir(d)))
327         {
328             char tmp[1024];
329             if (*de->d_name == '.' || !strcmp(de->d_name, "CVS"))
330                 continue;
331             sprintf(tmp, "%s/%s", path, de->d_name);
332             if (read_settings(tmp, client_data, fun))
333                 ret = -1;
334         }
335         closedir(d);
336     }
337     else if ((dot = strrchr(path, '.')) && !strcmp(dot + 1, "xml"))
338         ret = read_settings_file(path, client_data, fun);
339     return ret;
340 }
341
342 // Determines if a ZURL is a wildcard, and what kind
343 static int zurl_wildcard(const char *zurl)
344 {
345     if (!zurl)
346         return SETTING_WILDCARD_NO;
347     if (*zurl == '*')
348         return SETTING_WILDCARD_YES;
349     else if (*(zurl + strlen(zurl) - 1) == '*')
350         return SETTING_WILDCARD_DB;
351     else
352         return SETTING_WILDCARD_NO;
353 }
354
355 struct update_database_context {
356     struct setting *set;
357     struct conf_service *service;
358 };
359
360 void expand_settings_array(struct setting ***set_ar, int *num, int offset,
361                            NMEM nmem)
362 {
363     assert(offset >= 0);
364     assert(*set_ar);
365     if (offset >= *num)
366     {
367         int i, n_num = offset + 10;
368         struct setting **n_ar = nmem_malloc(nmem, n_num * sizeof(*n_ar));
369         for (i = 0; i < *num; i++)
370             n_ar[i] = (*set_ar)[i];
371         for (; i < n_num; i++)
372             n_ar[i] = 0;
373         *num = n_num;
374         *set_ar = n_ar;
375     }
376 }
377
378 void expand_settings_array2(struct settings_array *settings, int offset, NMEM nmem)
379 {
380     assert(offset >= 0);
381     assert(settings);
382     if (offset >= settings->num_settings)
383     {
384         int i, n_num = offset + 10;
385         struct setting **n_ar = nmem_malloc(nmem, n_num * sizeof(*n_ar));
386         for (i = 0; i < settings->num_settings; i++)
387             n_ar[i] = settings->settings[i];
388         for (; i < n_num; i++)
389             n_ar[i] = 0;
390         settings->num_settings = n_num;
391         settings->settings = n_ar;
392     }
393 }
394
395 static void update_settings(struct setting *set, struct settings_array *settings, int offset, NMEM nmem)
396 {
397     struct setting **sp;
398     yaz_log(YLOG_DEBUG, "update service settings offset %d with %s=%s", offset, set->name, set->value);
399     expand_settings_array2(settings, offset, nmem);
400
401     // First we determine if this setting is overriding any existing settings
402     // with the same name.
403     assert(offset < settings->num_settings);
404     for (sp = &settings->settings[offset]; *sp; )
405         if (!strcmp((*sp)->name, set->name))
406         {
407             if ((*sp)->precedence < set->precedence)
408             {
409                 // We discard the value (nmem keeps track of the space)
410                 *sp = (*sp)->next; // unlink value from existing setting
411             }
412             else if ((*sp)->precedence > set->precedence)
413             {
414                 // Db contains a higher-priority setting. Abort search
415                 break;
416             }
417             else if (zurl_wildcard((*sp)->target) > zurl_wildcard(set->target))
418             {
419                 // target-specific value trumps wildcard. Delete.
420                 *sp = (*sp)->next; // unlink.....
421             }
422             else if (zurl_wildcard((*sp)->target) < zurl_wildcard(set->target))
423                 // Db already contains higher-priority setting. Abort search
424                 break;
425             else
426                 sp = &(*sp)->next;
427         }
428         else
429             sp = &(*sp)->next;
430     if (!*sp) // is null when there are no higher-priority settings, so we add one
431     {
432         struct setting *new = nmem_malloc(nmem, sizeof(*new));
433         memset(new, 0, sizeof(*new));
434         new->precedence = set->precedence;
435         new->target = nmem_strdup_null(nmem, set->target);
436         new->name = nmem_strdup_null(nmem, set->name);
437         new->value = nmem_strdup_null(nmem, set->value);
438         new->next = settings->settings[offset];
439         settings->settings[offset] = new;
440     }
441 }
442
443
444 // This is called from grep_databases -- adds/overrides setting for a target
445 // This is also where the rules for precedence of settings are implemented
446 static void update_database_fun(void *context, struct database *db)
447 {
448     struct setting *set = ((struct update_database_context *)
449                            context)->set;
450     struct conf_service *service = ((struct update_database_context *)
451                                     context)->service;
452     struct setting **sp;
453     int offset;
454
455     // Is this the right database?
456     if (!match_zurl(db->id, set->target))
457         return;
458
459     offset = settings_create_offset(service, set->name);
460     expand_settings_array(&db->settings, &db->num_settings, offset, service->nmem);
461
462     // First we determine if this setting is overriding  any existing settings
463     // with the same name.
464     assert(offset < db->num_settings);
465     for (sp = &db->settings[offset]; *sp; )
466         if (!strcmp((*sp)->name, set->name))
467         {
468             if ((*sp)->precedence < set->precedence)
469             {
470                 // We discard the value (nmem keeps track of the space)
471                 *sp = (*sp)->next; // unlink value from existing setting
472             }
473             else if ((*sp)->precedence > set->precedence)
474             {
475                 // Db contains a higher-priority setting. Abort search
476                 break;
477             }
478             else if (zurl_wildcard((*sp)->target) > zurl_wildcard(set->target))
479             {
480                 // target-specific value trumps wildcard. Delete.
481                 *sp = (*sp)->next; // unlink.....
482             }
483             else if (zurl_wildcard((*sp)->target) < zurl_wildcard(set->target))
484                 // Db already contains higher-priority setting. Abort search
485                 break;
486             else
487                 sp = &(*sp)->next;
488         }
489         else
490             sp = &(*sp)->next;
491     if (!*sp) // is null when there are no higher-priority settings, so we add one
492     {
493         struct setting *new = nmem_malloc(service->nmem, sizeof(*new));
494
495         memset(new, 0, sizeof(*new));
496         new->precedence = set->precedence;
497         new->target = nmem_strdup(service->nmem, set->target);
498         new->name = nmem_strdup(service->nmem, set->name);
499         new->value = nmem_strdup(service->nmem, set->value);
500         new->next = db->settings[offset];
501         db->settings[offset] = new;
502     }
503 }
504
505 // Callback -- updates database records with dictionary entries as appropriate
506 // This is used in pass 2 to assign name/value pairs to databases
507 static void update_databases(void *client_data, struct setting *set)
508 {
509     struct conf_service *service = (struct conf_service *) client_data;
510     struct update_database_context context;
511     context.set = set;
512     context.service = service;
513     predef_grep_databases(&context, service, update_database_fun);
514 }
515
516 // This simply copies the 'hard' (application-specific) settings
517 // to the settings dictionary.
518 static void initialize_hard_settings(struct conf_service *service)
519 {
520     struct setting_dictionary *dict = service->dictionary;
521     dict->dict = nmem_malloc(service->nmem, sizeof(hard_settings) - sizeof(char*));
522     dict->size = (sizeof(hard_settings) - sizeof(char*)) / sizeof(char*);
523     memcpy(dict->dict, hard_settings, dict->size * sizeof(char*));
524     dict->num = dict->size;
525 }
526
527 // Read any settings names introduced in service definition (config) and add to dictionary
528 // This is done now to avoid errors if user settings are declared in session overrides
529 void initialize_soft_settings(struct conf_service *service)
530 {
531     int i;
532     for (i = 0; i < service->num_metadata; i++)
533     {
534         struct conf_metadata *md = &service->metadata[i];
535
536         if (md->setting != Metadata_setting_no)
537             settings_create_offset(service, md->name);
538
539         // Also create setting for some metadata attributes.
540         if (md->limitmap) {
541             int index;
542             WRBUF wrbuf = wrbuf_alloc();
543             yaz_log(YLOG_DEBUG, "Metadata %s has limitmap: %s ",md->name,  md->limitmap);
544             wrbuf_printf(wrbuf, "pz:limitmap:%s", md->name);
545             index = settings_create_offset(service, wrbuf_cstr(wrbuf));
546             if (index >= 0) {
547                 struct setting new;
548                 int offset;
549                 yaz_log(YLOG_DEBUG, "Service %s default %s=%s",
550                         (service->id ? service->id: "unknown"), wrbuf_cstr(wrbuf), md->limitmap);
551                 new.name = (char *) wrbuf_cstr(wrbuf);
552                 new.value = md->limitmap;
553                 new.next = 0;
554                 new.target = 0;
555                 new.precedence = 0;
556                 offset = settings_create_offset(service, new.name);
557                 update_settings(&new, service->settings, offset, service->nmem);
558             }
559             wrbuf_destroy(wrbuf);
560         // TODO same for facetmap
561         }
562     }
563 }
564
565 static void prepare_target_dictionary(void *client_data, struct setting *set)
566 {
567     struct conf_service *service = (struct conf_service *) client_data;
568
569     // If target address is not wildcard, add the database
570     if (*set->target && !zurl_wildcard(set->target))
571         create_database_for_service(set->target, service);
572 }
573
574 void init_settings(struct conf_service *service)
575 {
576     struct setting_dictionary *new;
577
578     assert(service->nmem);
579
580     new = nmem_malloc(service->nmem, sizeof(*new));
581     memset(new, 0, sizeof(*new));
582     service->dictionary = new;
583     initialize_hard_settings(service);
584     initialize_soft_settings(service);
585 }
586
587 int settings_read_file(struct conf_service *service, const char *path,
588                        int pass)
589 {
590     if (pass == 1)
591         return read_settings(path, service, prepare_target_dictionary);
592     else
593         return read_settings(path, service, update_databases);
594 }
595
596 int settings_read_node(struct conf_service *service, xmlNode *n,
597                         int pass)
598 {
599     if (pass == 1)
600         return settings_read_node_x(n, service, prepare_target_dictionary);
601     else
602         return settings_read_node_x(n, service, update_databases);
603 }
604
605 /*
606  * Local variables:
607  * c-basic-offset: 4
608  * c-file-style: "Stroustrup"
609  * indent-tabs-mode: nil
610  * End:
611  * vim: shiftwidth=4 tabstop=8 expandtab
612  */
613