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