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