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