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