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