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