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