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