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