Fix nasty bug of overrides not working
[pazpar2-moved-to-github.git] / src / settings.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2009 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 "direntz.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 "pazpar2.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:ip",
63     "pz:zproxy",
64     "pz:apdulog",
65     "pz:sru",
66     "pz:sru_version",
67     "pz:pqf_prefix",
68     "pz:sort",
69     "pz:recordfilter",
70     0
71 };
72
73 struct setting_dictionary
74 {
75     char **dict;
76     int size;
77     int num;
78 };
79
80 // This establishes the precedence of wildcard expressions
81 #define SETTING_WILDCARD_NO     0 // No wildcard
82 #define SETTING_WILDCARD_DB     1 // Database wildcard 'host:port/*'
83 #define SETTING_WILDCARD_YES    2 // Complete wildcard '*'
84
85 // Returns size of settings directory
86 int settings_num(struct conf_service *service)
87 {
88     return service->dictionary->num;
89 }
90
91 int settings_offset(struct conf_service *service, const char *name)
92 {
93     int i;
94
95     if (!name)
96         name = "";
97     for (i = 0; i < service->dictionary->num; i++)
98         if (!strcmp(name, service->dictionary->dict[i]))
99             return i;
100     return -1;
101 }
102
103 // Ignores everything after second colon, if present
104 // A bit of a hack to support the pz:cclmap: scheme (and more to come?)
105 int settings_offset_cprefix(struct conf_service *service, const char *name)
106 {
107     const char *p;
108     int maxlen = 100;
109     int i;
110
111     if (!strncmp("pz:", name, 3) && (p = strchr(name + 3, ':')))
112         maxlen = (p - name) + 1;
113     for (i = 0; i < service->dictionary->num; i++)
114         if (!strncmp(name, service->dictionary->dict[i], maxlen))
115             return i;
116     return -1;
117 }
118
119 char *settings_name(struct conf_service *service, int offset)
120 {
121     return service->dictionary->dict[offset];
122 }
123
124 static int isdir(const char *path)
125 {
126     struct stat st;
127
128     if (stat(path, &st) < 0)
129     {
130         yaz_log(YLOG_FATAL|YLOG_ERRNO, "stat %s", path);
131         exit(1);
132     }
133     return st.st_mode & S_IFDIR;
134 }
135
136 // Read settings from an XML file, calling handler function for each setting
137 void settings_read_node_x(xmlNode *n,
138                           void *client_data,
139                           void (*fun)(void *client_data,
140                                       struct setting *set))
141 {
142     xmlChar *namea, *targeta, *valuea, *usera, *precedencea;
143
144     namea = xmlGetProp(n, (xmlChar *) "name");
145     targeta = xmlGetProp(n, (xmlChar *) "target");
146     valuea = xmlGetProp(n, (xmlChar *) "value");
147     usera = xmlGetProp(n, (xmlChar *) "user");
148     precedencea = xmlGetProp(n, (xmlChar *) "precedence");
149     for (n = n->children; n; n = n->next)
150     {
151         if (n->type != XML_ELEMENT_NODE)
152             continue;
153         if (!strcmp((const char *) n->name, "set"))
154         {
155             char *name, *target, *value, *user, *precedence;
156
157             name = (char *) xmlGetProp(n, (xmlChar *) "name");
158             target = (char *) xmlGetProp(n, (xmlChar *) "target");
159             value = (char *) xmlGetProp(n, (xmlChar *) "value");
160             user = (char *) xmlGetProp(n, (xmlChar *) "user");
161             precedence = (char *) xmlGetProp(n, (xmlChar *) "precedence");
162
163             if ((!name && !namea) || (!value && !valuea) || (!target && !targeta))
164             {
165                 yaz_log(YLOG_FATAL, "set must specify name, value, and target");
166                 exit(1);
167             }
168             else
169             {
170                 struct setting set;
171                 char nameb[1024];
172                 char targetb[1024];
173                 char valueb[1024];
174
175                 // Copy everything into a temporary buffer -- we decide
176                 // later if we are keeping it.
177                 if (precedence)
178                     set.precedence = atoi((char *) precedence);
179                 else if (precedencea)
180                     set.precedence = atoi((char *) precedencea);
181                 else
182                     set.precedence = 0;
183                 if (target)
184                     strcpy(targetb, target);
185                 else
186                     strcpy(targetb, (const char *) targeta);
187                 set.target = targetb;
188                 if (name)
189                     strcpy(nameb, name);
190                 else
191                     strcpy(nameb, (const char *) namea);
192                 set.name = nameb;
193                 if (value)
194                     strcpy(valueb, value);
195                 else
196                     strcpy(valueb, (const char *) valuea);
197                 set.value = valueb;
198                 set.next = 0;
199                 (*fun)(client_data, &set);
200             }
201             xmlFree(name);
202             xmlFree(precedence);
203             xmlFree(value);
204             xmlFree(user);
205             xmlFree(target);
206         }
207         else
208         {
209             yaz_log(YLOG_FATAL, "Unknown element %s in settings file", (char*) n->name);
210             exit(1);
211         }
212     }
213     xmlFree(namea);
214     xmlFree(precedencea);
215     xmlFree(valuea);
216     xmlFree(usera);
217     xmlFree(targeta);
218 }
219  
220 static void read_settings_file(const char *path,
221                                void *client_data,
222                                void (*fun)(void *client_data,
223                                            struct setting *set))
224 {
225     xmlDoc *doc = xmlParseFile(path);
226     xmlNode *n;
227
228     if (!doc)
229     {
230         yaz_log(YLOG_FATAL, "Failed to parse %s", path);
231         exit(1);
232     }
233     n = xmlDocGetRootElement(doc);
234     settings_read_node_x(n, client_data, fun);
235
236     xmlFreeDoc(doc);
237 }
238
239
240 // Recursively read files or directories, invoking a 
241 // callback for each one
242 static void read_settings(const char *path,
243                           void *client_data,
244                           void (*fun)(void *client_data,
245                                       struct setting *set))
246 {
247     DIR *d;
248     struct dirent *de;
249     char *dot;
250
251     if (isdir(path))
252     {
253         if (!(d = opendir(path)))
254         {
255             yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", path);
256             exit(1);
257         }
258         while ((de = readdir(d)))
259         {
260             char tmp[1024];
261             if (*de->d_name == '.' || !strcmp(de->d_name, "CVS"))
262                 continue;
263             sprintf(tmp, "%s/%s", path, de->d_name);
264             read_settings(tmp, client_data, fun);
265         }
266         closedir(d);
267     }
268     else if ((dot = strrchr(path, '.')) && !strcmp(dot + 1, "xml"))
269         read_settings_file(path, client_data, fun);
270 }
271
272 // Determines if a ZURL is a wildcard, and what kind
273 static int zurl_wildcard(const char *zurl)
274 {
275     if (!zurl)
276         return SETTING_WILDCARD_NO;
277     if (*zurl == '*')
278         return SETTING_WILDCARD_YES;
279     else if (*(zurl + strlen(zurl) - 1) == '*')
280         return SETTING_WILDCARD_DB;
281     else
282         return SETTING_WILDCARD_NO;
283 }
284
285 // Callback. Adds a new entry to the dictionary if necessary
286 // This is used in pass 1 to determine layout of dictionary
287 // and to load any databases mentioned
288 static void prepare_dictionary(struct conf_service *service,
289                                struct setting *set)
290 {
291     struct setting_dictionary *dictionary = service->dictionary;
292
293     int i;
294     char *p;
295
296     // Determine if we already have a dictionary entry
297     if (!strncmp(set->name, "pz:", 3) && (p = strchr(set->name + 3, ':')))
298         *(p + 1) = '\0';
299     for (i = 0; i < dictionary->num; i++)
300         if (!strcmp(dictionary->dict[i], set->name))
301             return;
302
303     if (!strncmp(set->name, "pz:", 3)) // Probably a typo in config file
304         {
305             yaz_log(YLOG_FATAL, "Unknown pz: setting '%s'", set->name);
306             exit(1);
307         }
308
309     // Create a new dictionary entry
310     // Grow dictionary if necessary
311     if (!dictionary->size)
312         dictionary->dict =
313             nmem_malloc(service->nmem, (dictionary->size = 50) * sizeof(char*));
314     else if (dictionary->num + 1 > dictionary->size)
315     {
316         char **tmp =
317             nmem_malloc(service->nmem, dictionary->size * 2 * sizeof(char*));
318         memcpy(tmp, dictionary->dict, dictionary->size * sizeof(char*));
319         dictionary->dict = tmp;
320         dictionary->size *= 2;
321     }
322     dictionary->dict[dictionary->num++] = nmem_strdup(service->nmem, set->name);
323 }
324
325
326 struct update_database_context {
327     struct setting *set;
328     struct conf_service *service;
329 };
330
331 // This is called from grep_databases -- adds/overrides setting for a target
332 // This is also where the rules for precedence of settings are implemented
333 static void update_database(void *context, struct database *db)
334 {
335     struct setting *set = ((struct update_database_context *)
336                            context)->set;
337     struct conf_service *service = ((struct update_database_context *) 
338                                     context)->service;
339     struct setting **sp;
340     int offset;
341
342     // Is this the right database?
343     if (!match_zurl(db->url, set->target))
344         return;
345
346     if ((offset = settings_offset_cprefix(service, set->name)) < 0)
347         return ;
348
349     // First we determine if this setting is overriding  any existing settings
350     // with the same name.
351     assert(offset < db->num_settings);
352     for (sp = &db->settings[offset]; *sp; )
353         if (!strcmp((*sp)->name, set->name))
354         {
355             if ((*sp)->precedence < set->precedence)
356             {
357                 // We discard the value (nmem keeps track of the space)
358                 *sp = (*sp)->next; // unlink value from existing setting
359             }
360             else if ((*sp)->precedence > set->precedence)
361             {
362                 // Db contains a higher-priority setting. Abort search
363                 break;
364             }
365             else if (zurl_wildcard((*sp)->target) > zurl_wildcard(set->target))
366             {
367                 // target-specific value trumps wildcard. Delete.
368                 *sp = (*sp)->next; // unlink.....
369             }
370             else if (!zurl_wildcard((*sp)->target))
371                 // Db already contains higher-priority setting. Abort search
372                 break;
373             else
374                 sp = &(*sp)->next;
375         }
376         else
377             sp = &(*sp)->next;
378     if (!*sp) // is null when there are no higher-priority settings, so we add one
379     {
380         struct setting *new = nmem_malloc(service->nmem, sizeof(*new));
381
382         memset(new, 0, sizeof(*new));
383         new->precedence = set->precedence;
384         new->target = nmem_strdup(service->nmem, set->target);
385         new->name = nmem_strdup(service->nmem, set->name);
386         new->value = nmem_strdup(service->nmem, set->value);
387         new->next = db->settings[offset];
388         db->settings[offset] = new;
389     }
390 }
391
392 // Callback -- updates database records with dictionary entries as appropriate
393 // This is used in pass 2 to assign name/value pairs to databases
394 static void update_databases(void *client_data, struct setting *set)
395 {
396     struct conf_service *service = (struct conf_service *) client_data;
397     struct update_database_context context;
398     context.set = set;
399     context.service = service;
400     predef_grep_databases(&context, service, 0, update_database);
401 }
402
403 // This simply copies the 'hard' (application-specific) settings
404 // to the settings dictionary.
405 static void initialize_hard_settings(struct conf_service *service)
406 {
407     struct setting_dictionary *dict = service->dictionary;
408     dict->dict = nmem_malloc(service->nmem, sizeof(hard_settings) - sizeof(char*));
409     dict->size = (sizeof(hard_settings) - sizeof(char*)) / sizeof(char*);
410     memcpy(dict->dict, hard_settings, dict->size * sizeof(char*));
411     dict->num = dict->size;
412 }
413
414 // Read any settings names introduced in service definition (config) and add to dictionary
415 // This is done now to avoid errors if user settings are declared in session overrides
416 static void initialize_soft_settings(struct conf_service *service)
417 {
418     int i;
419
420     for (i = 0; i < service->num_metadata; i++)
421     {
422         struct setting set;
423         struct conf_metadata *md = &service->metadata[i];
424
425         if (md->setting == Metadata_setting_no)
426             continue;
427
428         set.precedence = 0;
429         set.target = "";
430         set.name = md->name;
431         set.value = "";
432         set.next = 0;
433         prepare_dictionary(service, &set);
434     }
435 }
436
437 static void prepare_target_dictionary(void *client_data, struct setting *set)
438 {
439     struct conf_service *service = (struct conf_service *) client_data;
440     struct setting_dictionary *dictionary = service->dictionary;
441
442     int i;
443     char *p;
444
445     // If target address is not wildcard, add the database
446     if (*set->target && !zurl_wildcard(set->target))
447         find_database(set->target, 0, service);
448
449     // Determine if we already have a dictionary entry
450     if (!strncmp(set->name, "pz:", 3) && (p = strchr(set->name + 3, ':')))
451         *(p + 1) = '\0';
452     for (i = 0; i < dictionary->num; i++)
453         if (!strcmp(dictionary->dict[i], set->name))
454             return;
455     yaz_log(YLOG_WARN, "Setting '%s' not configured as metadata", set->name);
456 }
457
458 void init_settings(struct conf_service *service)
459 {
460     struct setting_dictionary *new;
461     
462     assert(service->nmem);
463     
464     new = nmem_malloc(service->nmem, sizeof(*new));
465     memset(new, 0, sizeof(*new));
466     service->dictionary = new;
467     initialize_hard_settings(service);
468     initialize_soft_settings(service);
469 }
470
471 void settings_read_file(struct conf_service *service, const char *path,
472                         int pass)
473 {
474     if (pass == 1)
475         read_settings(path, service, prepare_target_dictionary);
476     else
477         read_settings(path, service, update_databases);
478 }
479
480 void settings_read_node(struct conf_service *service, xmlNode *n,
481                         int pass)
482 {
483     if (pass == 1)
484         settings_read_node_x(n, service, prepare_target_dictionary);
485     else
486         settings_read_node_x(n, service, update_databases);
487 }
488
489 /*
490  * Local variables:
491  * c-basic-offset: 4
492  * c-file-style: "Stroustrup"
493  * indent-tabs-mode: nil
494  * End:
495  * vim: shiftwidth=4 tabstop=8 expandtab
496  */
497