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