Fix for bug 3948.
[pazpar2-moved-to-github.git] / src / settings.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2011 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 <yaz/dirent.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 "session.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     "pz:sort",
69     "pz:recordfilter",
70     "pz:pqf_strftime",
71     "pz:negotiation_charset",
72     "pz:max_connections",
73     "pz:reuse_connections",     /* PZ_REUSE_CONNECTION    */
74     "pz:termlist_term_sort",    /* PZ_TERMLIST_TERM_SORT  */
75     "pz:termlist_term_count",   /* PZ_TERMLIST_TERM_COUNT */
76     "pz:termlist_term_factor",  /* PZ_TERMLIST_TERM_FACTOR*/
77     "pz:preferred",             /* PZ_PREFERRED           */
78     0
79 };
80
81 struct setting_dictionary
82 {
83     char **dict;
84     int size;
85     int num;
86 };
87
88 // This establishes the precedence of wildcard expressions
89 #define SETTING_WILDCARD_NO     0 // No wildcard
90 #define SETTING_WILDCARD_DB     1 // Database wildcard 'host:port/*'
91 #define SETTING_WILDCARD_YES    2 // Complete wildcard '*'
92
93 // Returns size of settings directory
94 int settings_num(struct conf_service *service)
95 {
96     return service->dictionary->num;
97 }
98
99 static int settings_lookup(struct conf_service *service, const char *name,
100                            int allow_create)
101 {
102     size_t maxlen;
103     int i;
104     const char *p;
105     struct setting_dictionary *dictionary = service->dictionary;
106     
107     assert(name);
108
109     if (!strncmp("pz:", name, 3) && (p = strchr(name + 3, ':')))
110         maxlen = (p - name) + 1;
111     else
112         maxlen = strlen(name) + 1;
113     for (i = 0; i < dictionary->num; i++)
114         if (!strncmp(name, dictionary->dict[i], maxlen))
115             return i;
116     if (!allow_create)
117         return -1;
118     if (!strncmp("pz:", name, 3))
119         yaz_log(YLOG_WARN, "Adding pz-type setting name %s", name);
120     if (dictionary->num + 1 > dictionary->size)
121     {
122         char **tmp =
123             nmem_malloc(service->nmem, dictionary->size * 2 * sizeof(char*));
124         memcpy(tmp, dictionary->dict, dictionary->size * sizeof(char*));
125         dictionary->dict = tmp;
126         dictionary->size *= 2;
127     }
128     dictionary->dict[dictionary->num] = nmem_strdup(service->nmem, name);
129     dictionary->dict[dictionary->num][maxlen-1] = '\0';
130     return dictionary->num++;
131 }
132
133 int settings_create_offset(struct conf_service *service, const char *name)
134 {
135     return settings_lookup(service, name, 1);
136 }
137
138 int settings_lookup_offset(struct conf_service *service, const char *name)
139 {
140     return settings_lookup(service, name, 0);
141 }
142
143 char *settings_name(struct conf_service *service, int offset)
144 {
145     assert(offset < service->dictionary->num);
146     return service->dictionary->dict[offset];
147 }
148
149 static int isdir(const char *path)
150 {
151     struct stat st;
152
153     if (stat(path, &st) < 0)
154     {
155         yaz_log(YLOG_FATAL|YLOG_ERRNO, "stat %s", path);
156         exit(1);
157     }
158     return st.st_mode & S_IFDIR;
159 }
160
161 // Read settings from an XML file, calling handler function for each setting
162 void settings_read_node_x(xmlNode *n,
163                           void *client_data,
164                           void (*fun)(void *client_data,
165                                       struct setting *set))
166 {
167     xmlChar *namea, *targeta, *valuea, *usera, *precedencea;
168
169     namea = xmlGetProp(n, (xmlChar *) "name");
170     targeta = xmlGetProp(n, (xmlChar *) "target");
171     valuea = xmlGetProp(n, (xmlChar *) "value");
172     usera = xmlGetProp(n, (xmlChar *) "user");
173     precedencea = xmlGetProp(n, (xmlChar *) "precedence");
174     for (n = n->children; n; n = n->next)
175     {
176         if (n->type != XML_ELEMENT_NODE)
177             continue;
178         if (!strcmp((const char *) n->name, "set"))
179         {
180             char *name, *target, *value, *user, *precedence;
181
182             name = (char *) xmlGetProp(n, (xmlChar *) "name");
183             target = (char *) xmlGetProp(n, (xmlChar *) "target");
184             value = (char *) xmlGetProp(n, (xmlChar *) "value");
185             user = (char *) xmlGetProp(n, (xmlChar *) "user");
186             precedence = (char *) xmlGetProp(n, (xmlChar *) "precedence");
187
188             if ((!name && !namea) || (!value && !valuea) || (!target && !targeta))
189             {
190                 yaz_log(YLOG_FATAL, "set must specify name, value, and target");
191                 exit(1);
192             }
193             else
194             {
195                 struct setting set;
196                 char nameb[1024];
197                 char targetb[1024];
198                 char valueb[1024];
199
200                 // Copy everything into a temporary buffer -- we decide
201                 // later if we are keeping it.
202                 if (precedence)
203                     set.precedence = atoi((char *) precedence);
204                 else if (precedencea)
205                     set.precedence = atoi((char *) precedencea);
206                 else
207                     set.precedence = 0;
208                 if (target)
209                     strcpy(targetb, target);
210                 else
211                     strcpy(targetb, (const char *) targeta);
212                 set.target = targetb;
213                 if (name)
214                     strcpy(nameb, name);
215                 else
216                     strcpy(nameb, (const char *) namea);
217                 set.name = nameb;
218                 if (value)
219                     strcpy(valueb, value);
220                 else
221                     strcpy(valueb, (const char *) valuea);
222                 set.value = valueb;
223                 set.next = 0;
224                 (*fun)(client_data, &set);
225             }
226             xmlFree(name);
227             xmlFree(precedence);
228             xmlFree(value);
229             xmlFree(user);
230             xmlFree(target);
231         }
232         else
233         {
234             yaz_log(YLOG_FATAL, "Unknown element %s in settings file", (char*) n->name);
235             exit(1);
236         }
237     }
238     xmlFree(namea);
239     xmlFree(precedencea);
240     xmlFree(valuea);
241     xmlFree(usera);
242     xmlFree(targeta);
243 }
244  
245 static void read_settings_file(const char *path,
246                                void *client_data,
247                                void (*fun)(void *client_data,
248                                            struct setting *set))
249 {
250     xmlDoc *doc = xmlParseFile(path);
251     xmlNode *n;
252
253     if (!doc)
254     {
255         yaz_log(YLOG_FATAL, "Failed to parse %s", path);
256         exit(1);
257     }
258     n = xmlDocGetRootElement(doc);
259     settings_read_node_x(n, client_data, fun);
260
261     xmlFreeDoc(doc);
262 }
263
264
265 // Recursively read files or directories, invoking a 
266 // callback for each one
267 static void read_settings(const char *path,
268                           void *client_data,
269                           void (*fun)(void *client_data,
270                                       struct setting *set))
271 {
272     DIR *d;
273     struct dirent *de;
274     char *dot;
275
276     if (isdir(path))
277     {
278         if (!(d = opendir(path)))
279         {
280             yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", path);
281             exit(1);
282         }
283         while ((de = readdir(d)))
284         {
285             char tmp[1024];
286             if (*de->d_name == '.' || !strcmp(de->d_name, "CVS"))
287                 continue;
288             sprintf(tmp, "%s/%s", path, de->d_name);
289             read_settings(tmp, client_data, fun);
290         }
291         closedir(d);
292     }
293     else if ((dot = strrchr(path, '.')) && !strcmp(dot + 1, "xml"))
294         read_settings_file(path, client_data, fun);
295 }
296
297 // Determines if a ZURL is a wildcard, and what kind
298 static int zurl_wildcard(const char *zurl)
299 {
300     if (!zurl)
301         return SETTING_WILDCARD_NO;
302     if (*zurl == '*')
303         return SETTING_WILDCARD_YES;
304     else if (*(zurl + strlen(zurl) - 1) == '*')
305         return SETTING_WILDCARD_DB;
306     else
307         return SETTING_WILDCARD_NO;
308 }
309
310 struct update_database_context {
311     struct setting *set;
312     struct conf_service *service;
313 };
314
315 void expand_settings_array(struct setting ***set_ar, int *num, int offset,
316                            NMEM nmem)
317 {
318     assert(offset >= 0);
319     assert(*set_ar);
320     if (offset >= *num)
321     {
322         int i, n_num = offset + 10;
323         struct setting **n_ar = nmem_malloc(nmem, n_num * sizeof(*n_ar));
324         for (i = 0; i < *num; i++)
325             n_ar[i] = (*set_ar)[i];
326         for (; i < n_num; i++)
327             n_ar[i] = 0;
328         *num = n_num;
329         *set_ar = n_ar;
330     }
331 }
332
333 // This is called from grep_databases -- adds/overrides setting for a target
334 // This is also where the rules for precedence of settings are implemented
335 static void update_database(void *context, struct database *db)
336 {
337     struct setting *set = ((struct update_database_context *)
338                            context)->set;
339     struct conf_service *service = ((struct update_database_context *) 
340                                     context)->service;
341     struct setting **sp;
342     int offset;
343
344     // Is this the right database?
345     if (!match_zurl(db->url, set->target))
346         return;
347
348     offset = settings_create_offset(service, set->name);
349     expand_settings_array(&db->settings, &db->num_settings, offset,
350                           service->nmem);
351
352     // First we determine if this setting is overriding  any existing settings
353     // with the same name.
354     assert(offset < db->num_settings);
355     for (sp = &db->settings[offset]; *sp; )
356         if (!strcmp((*sp)->name, set->name))
357         {
358             if ((*sp)->precedence < set->precedence)
359             {
360                 // We discard the value (nmem keeps track of the space)
361                 *sp = (*sp)->next; // unlink value from existing setting
362             }
363             else if ((*sp)->precedence > set->precedence)
364             {
365                 // Db contains a higher-priority setting. Abort search
366                 break;
367             }
368             else if (zurl_wildcard((*sp)->target) > zurl_wildcard(set->target))
369             {
370                 // target-specific value trumps wildcard. Delete.
371                 *sp = (*sp)->next; // unlink.....
372             }
373             else if (zurl_wildcard((*sp)->target) < zurl_wildcard(set->target))
374                 // Db already contains higher-priority setting. Abort search
375                 break;
376             else
377                 sp = &(*sp)->next;
378         }
379         else
380             sp = &(*sp)->next;
381     if (!*sp) // is null when there are no higher-priority settings, so we add one
382     {
383         struct setting *new = nmem_malloc(service->nmem, sizeof(*new));
384
385         memset(new, 0, sizeof(*new));
386         new->precedence = set->precedence;
387         new->target = nmem_strdup(service->nmem, set->target);
388         new->name = nmem_strdup(service->nmem, set->name);
389         new->value = nmem_strdup(service->nmem, set->value);
390         new->next = db->settings[offset];
391         db->settings[offset] = new;
392     }
393 }
394
395 // Callback -- updates database records with dictionary entries as appropriate
396 // This is used in pass 2 to assign name/value pairs to databases
397 static void update_databases(void *client_data, struct setting *set)
398 {
399     struct conf_service *service = (struct conf_service *) client_data;
400     struct update_database_context context;
401     context.set = set;
402     context.service = service;
403     predef_grep_databases(&context, service, update_database);
404 }
405
406 // This simply copies the 'hard' (application-specific) settings
407 // to the settings dictionary.
408 static void initialize_hard_settings(struct conf_service *service)
409 {
410     struct setting_dictionary *dict = service->dictionary;
411     dict->dict = nmem_malloc(service->nmem, sizeof(hard_settings) - sizeof(char*));
412     dict->size = (sizeof(hard_settings) - sizeof(char*)) / sizeof(char*);
413     memcpy(dict->dict, hard_settings, dict->size * sizeof(char*));
414     dict->num = dict->size;
415 }
416
417 // Read any settings names introduced in service definition (config) and add to dictionary
418 // This is done now to avoid errors if user settings are declared in session overrides
419 static void initialize_soft_settings(struct conf_service *service)
420 {
421     int i;
422
423     for (i = 0; i < service->num_metadata; i++)
424     {
425         struct conf_metadata *md = &service->metadata[i];
426
427         if (md->setting == Metadata_setting_no)
428             continue;
429
430         settings_create_offset(service, md->name);
431     }
432 }
433
434 static void prepare_target_dictionary(void *client_data, struct setting *set)
435 {
436     struct conf_service *service = (struct conf_service *) client_data;
437     struct setting_dictionary *dictionary = service->dictionary;
438
439     int i;
440     char *p;
441
442     // If target address is not wildcard, add the database
443     if (*set->target && !zurl_wildcard(set->target))
444         find_database(set->target, service);
445
446     // Determine if we already have a dictionary entry
447     if (!strncmp(set->name, "pz:", 3) && (p = strchr(set->name + 3, ':')))
448         *(p + 1) = '\0';
449     for (i = 0; i < dictionary->num; i++)
450         if (!strcmp(dictionary->dict[i], set->name))
451             return;
452     yaz_log(YLOG_WARN, "Setting '%s' not configured as metadata", set->name);
453 }
454
455 void init_settings(struct conf_service *service)
456 {
457     struct setting_dictionary *new;
458     
459     assert(service->nmem);
460     
461     new = nmem_malloc(service->nmem, sizeof(*new));
462     memset(new, 0, sizeof(*new));
463     service->dictionary = new;
464     initialize_hard_settings(service);
465     initialize_soft_settings(service);
466 }
467
468 void settings_read_file(struct conf_service *service, const char *path,
469                         int pass)
470 {
471     if (pass == 1)
472         read_settings(path, service, prepare_target_dictionary);
473     else
474         read_settings(path, service, update_databases);
475 }
476
477 void settings_read_node(struct conf_service *service, xmlNode *n,
478                         int pass)
479 {
480     if (pass == 1)
481         settings_read_node_x(n, service, prepare_target_dictionary);
482     else
483         settings_read_node_x(n, service, update_databases);
484 }
485
486 /*
487  * Local variables:
488  * c-basic-offset: 4
489  * c-file-style: "Stroustrup"
490  * indent-tabs-mode: nil
491  * End:
492  * vim: shiftwidth=4 tabstop=8 expandtab
493  */
494