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