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