New setting embed_xslt
[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:termlist_term_count",
75     "pz:preferred",
76     "pz:extra_args",
77     "pz:query_syntax",
78     "pz:facetmap:",
79     "pz:limitmap:",
80     "pz:url",
81     "pz:sortmap:",
82     "pz:present_chunk",
83     "pz:block_timeout",
84     "pz:embed_xslt",
85     0
86 };
87
88 struct setting_dictionary
89 {
90     char **dict;
91     int size;
92     int num;
93 };
94
95 // This establishes the precedence of wildcard expressions
96 #define SETTING_WILDCARD_NO     0 // No wildcard
97 #define SETTING_WILDCARD_DB     1 // Database wildcard 'host:port/*'
98 #define SETTING_WILDCARD_YES    2 // Complete wildcard '*'
99
100 // Returns size of settings directory
101 int settings_num(struct conf_service *service)
102 {
103     return service->dictionary->num;
104 }
105
106 /* Find and possible create a new dictionary entry. Pass valid NMEM pointer if creation is allowed, otherwise null */
107 static int settings_index_lookup(struct setting_dictionary *dictionary, const char *name, NMEM nmem)
108 {
109     size_t maxlen;
110     int i;
111     const char *p;
112     
113     assert(name);
114
115     if (!strncmp("pz:", name, 3) && (p = strchr(name + 3, ':')))
116         maxlen = (p - name) + 1;
117     else
118         maxlen = strlen(name) + 1;
119     for (i = 0; i < dictionary->num; i++)
120         if (!strncmp(name, dictionary->dict[i], maxlen))
121             return i;
122     if (!nmem)
123         return -1;
124     if (!strncmp("pz:", name, 3))
125         yaz_log(YLOG_WARN, "Adding pz-type setting name %s", name);
126     if (dictionary->num + 1 > dictionary->size)
127     {
128         char **tmp =
129             nmem_malloc(nmem, dictionary->size * 2 * sizeof(char*));
130         memcpy(tmp, dictionary->dict, dictionary->size * sizeof(char*));
131         dictionary->dict = tmp;
132         dictionary->size *= 2;
133     }
134     dictionary->dict[dictionary->num] = nmem_strdup(nmem, name);
135     dictionary->dict[dictionary->num][maxlen-1] = '\0';
136     return dictionary->num++;
137 }
138
139 int settings_create_offset(struct conf_service *service, const char *name)
140 {
141     return settings_index_lookup(service->dictionary, name, service->nmem);
142 }
143
144 int settings_lookup_offset(struct conf_service *service, const char *name)
145 {
146     return settings_index_lookup(service->dictionary, name, 0);
147 }
148
149 char *settings_name(struct conf_service *service, int offset)
150 {
151     assert(offset < service->dictionary->num);
152     return service->dictionary->dict[offset];
153 }
154
155
156 // Apply a session override to a database
157 void service_apply_setting(struct conf_service *service, char *setting, char *value)
158 {
159     struct setting *new = nmem_malloc(service->nmem, sizeof(*new));
160     int offset = settings_create_offset(service, setting);
161     expand_settings_array(&service->settings->settings, &service->settings->num_settings, offset, service->nmem);
162     new->precedence = 0;
163     new->target = NULL;
164     new->name = setting;
165     new->value = value;
166     new->next = service->settings->settings[offset];
167     service->settings->settings[offset] = new;
168 }
169
170
171 static int isdir(const char *path)
172 {
173     struct stat st;
174
175     if (stat(path, &st) < 0)
176     {
177         yaz_log(YLOG_FATAL|YLOG_ERRNO, "stat %s", path);
178         exit(1);
179     }
180     return st.st_mode & S_IFDIR;
181 }
182
183 // Read settings from an XML file, calling handler function for each setting
184 int settings_read_node_x(xmlNode *n,
185                          void *client_data,
186                          void (*fun)(void *client_data,
187                                      struct setting *set))
188 {
189     int ret_val = 0; /* success */
190     char *namea = (char *) xmlGetProp(n, (xmlChar *) "name");
191     char *targeta = (char *) xmlGetProp(n, (xmlChar *) "target");
192     char *valuea = (char *) xmlGetProp(n, (xmlChar *) "value");
193     char *usera = (char *) xmlGetProp(n, (xmlChar *) "user");
194     char *precedencea = (char *) xmlGetProp(n, (xmlChar *) "precedence");
195
196     for (n = n->children; n; n = n->next)
197     {
198         if (n->type != XML_ELEMENT_NODE)
199             continue;
200         if (!strcmp((const char *) n->name, "set"))
201         {
202             struct setting set;
203             char *name = (char *) xmlGetProp(n, (xmlChar *) "name");
204             char *target = (char *) xmlGetProp(n, (xmlChar *) "target");
205             char *value = (char *) xmlGetProp(n, (xmlChar *) "value");
206             char *user = (char *) xmlGetProp(n, (xmlChar *) "user");
207             char *precedence = (char *) xmlGetProp(n, (xmlChar *) "precedence");
208
209             if (precedence)
210                 set.precedence = atoi((char *) precedence);
211             else if (precedencea)
212                 set.precedence = atoi((char *) precedencea);
213             else
214                 set.precedence = 0;
215
216             set.target = target ? target : targeta;
217             set.name = name ? name : namea;
218             set.value = value ? value : valuea;
219             set.next = 0;
220
221             if (set.name && set.value && set.target)
222                 (*fun)(client_data, &set);
223             else
224             {
225                 if (set.name)
226                     yaz_log(YLOG_WARN, "missing value and/or target for "
227                             "setting name=%s", set.name);
228                 else
229                     yaz_log(YLOG_WARN, "missing name/value/target for setting");
230                 ret_val = -1;
231             }
232             xmlFree(name);
233             xmlFree(precedence);
234             xmlFree(value);
235             xmlFree(user);
236             xmlFree(target);
237         }
238         else
239         {
240             yaz_log(YLOG_WARN, "Unknown element %s in settings file", 
241                     (char*) n->name);
242             ret_val = -1;
243         }
244     }
245     xmlFree(namea);
246     xmlFree(precedencea);
247     xmlFree(valuea);
248     xmlFree(usera);
249     xmlFree(targeta);
250     return ret_val;
251 }
252  
253 static int read_settings_file(const char *path,
254                               void *client_data,
255                               void (*fun)(void *client_data,
256                                           struct setting *set))
257 {
258     xmlDoc *doc = xmlParseFile(path);
259     xmlNode *n;
260     int ret;
261
262     if (!doc)
263     {
264         yaz_log(YLOG_FATAL, "Failed to parse %s", path);
265         return -1;
266     }
267     n = xmlDocGetRootElement(doc);
268     ret = settings_read_node_x(n, client_data, fun);
269
270     xmlFreeDoc(doc);
271     return ret;
272 }
273
274
275 // Recursively read files or directories, invoking a 
276 // callback for each one
277 static int read_settings(const char *path,
278                           void *client_data,
279                           void (*fun)(void *client_data,
280                                       struct setting *set))
281 {
282     int ret = 0;
283     DIR *d;
284     struct dirent *de;
285     char *dot;
286
287     if (isdir(path))
288     {
289         if (!(d = opendir(path)))
290         {
291             yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", path);
292             return -1;
293         }
294         while ((de = readdir(d)))
295         {
296             char tmp[1024];
297             if (*de->d_name == '.' || !strcmp(de->d_name, "CVS"))
298                 continue;
299             sprintf(tmp, "%s/%s", path, de->d_name);
300             if (read_settings(tmp, client_data, fun))
301                 ret = -1;
302         }
303         closedir(d);
304     }
305     else if ((dot = strrchr(path, '.')) && !strcmp(dot + 1, "xml"))
306         ret = read_settings_file(path, client_data, fun);
307     return ret;
308 }
309
310 // Determines if a ZURL is a wildcard, and what kind
311 static int zurl_wildcard(const char *zurl)
312 {
313     if (!zurl)
314         return SETTING_WILDCARD_NO;
315     if (*zurl == '*')
316         return SETTING_WILDCARD_YES;
317     else if (*(zurl + strlen(zurl) - 1) == '*')
318         return SETTING_WILDCARD_DB;
319     else
320         return SETTING_WILDCARD_NO;
321 }
322
323 struct update_database_context {
324     struct setting *set;
325     struct conf_service *service;
326 };
327
328 void expand_settings_array(struct setting ***set_ar, int *num, int offset,
329                            NMEM nmem)
330 {
331     assert(offset >= 0);
332     assert(*set_ar);
333     if (offset >= *num)
334     {
335         int i, n_num = offset + 10;
336         struct setting **n_ar = nmem_malloc(nmem, n_num * sizeof(*n_ar));
337         for (i = 0; i < *num; i++)
338             n_ar[i] = (*set_ar)[i];
339         for (; i < n_num; i++)
340             n_ar[i] = 0;
341         *num = n_num;
342         *set_ar = n_ar;
343     }
344 }
345
346 void expand_settings_array2(struct settings *settings, int offset, NMEM nmem)
347 {
348     assert(offset >= 0);
349     assert(settings);
350     if (offset >= settings->num_settings)
351     {
352         int i, n_num = offset + 10;
353         struct setting **n_ar = nmem_malloc(nmem, n_num * sizeof(*n_ar));
354         for (i = 0; i < settings->num_settings; i++)
355             n_ar[i] = settings->settings[i];
356         for (; i < n_num; i++)
357             n_ar[i] = 0;
358         settings->num_settings = n_num;
359         settings->settings = n_ar;
360     }
361 }
362
363 static void update_settings(struct setting *set, struct settings *settings, int offset, NMEM nmem)
364 {
365     struct setting **sp;
366     yaz_log(YLOG_LOG, "update service settings offset %d with %s=%s", offset, set->name, set->value);
367     expand_settings_array2(settings, offset, nmem);
368
369     // First we determine if this setting is overriding any existing settings
370     // with the same name.
371     assert(offset < settings->num_settings);
372     for (sp = &settings->settings[offset]; *sp; )
373         if (!strcmp((*sp)->name, set->name))
374         {
375             if ((*sp)->precedence < set->precedence)
376             {
377                 // We discard the value (nmem keeps track of the space)
378                 *sp = (*sp)->next; // unlink value from existing setting
379             }
380             else if ((*sp)->precedence > set->precedence)
381             {
382                 // Db contains a higher-priority setting. Abort search
383                 break;
384             }
385             else if (zurl_wildcard((*sp)->target) > zurl_wildcard(set->target))
386             {
387                 // target-specific value trumps wildcard. Delete.
388                 *sp = (*sp)->next; // unlink.....
389             }
390             else if (zurl_wildcard((*sp)->target) < zurl_wildcard(set->target))
391                 // Db already contains higher-priority setting. Abort search
392                 break;
393             else
394                 sp = &(*sp)->next;
395         }
396         else
397             sp = &(*sp)->next;
398     if (!*sp) // is null when there are no higher-priority settings, so we add one
399     {
400         struct setting *new = nmem_malloc(nmem, sizeof(*new));
401         memset(new, 0, sizeof(*new));
402         new->precedence = set->precedence;
403         new->target = nmem_strdup_null(nmem, set->target);
404         new->name = nmem_strdup_null(nmem, set->name);
405         new->value = nmem_strdup_null(nmem, set->value);
406         new->next = settings->settings[offset];
407         settings->settings[offset] = new;
408     }
409 }
410
411
412 // This is called from grep_databases -- adds/overrides setting for a target
413 // This is also where the rules for precedence of settings are implemented
414 static void update_database_fun(void *context, struct database *db)
415 {
416     struct setting *set = ((struct update_database_context *)
417                            context)->set;
418     struct conf_service *service = ((struct update_database_context *) 
419                                     context)->service;
420     struct setting **sp;
421     int offset;
422
423     // Is this the right database?
424     if (!match_zurl(db->id, set->target))
425         return;
426
427     offset = settings_create_offset(service, set->name);
428     expand_settings_array(&db->settings, &db->num_settings, offset, service->nmem);
429
430     // First we determine if this setting is overriding  any existing settings
431     // with the same name.
432     assert(offset < db->num_settings);
433     for (sp = &db->settings[offset]; *sp; )
434         if (!strcmp((*sp)->name, set->name))
435         {
436             if ((*sp)->precedence < set->precedence)
437             {
438                 // We discard the value (nmem keeps track of the space)
439                 *sp = (*sp)->next; // unlink value from existing setting
440             }
441             else if ((*sp)->precedence > set->precedence)
442             {
443                 // Db contains a higher-priority setting. Abort search
444                 break;
445             }
446             else if (zurl_wildcard((*sp)->target) > zurl_wildcard(set->target))
447             {
448                 // target-specific value trumps wildcard. Delete.
449                 *sp = (*sp)->next; // unlink.....
450             }
451             else if (zurl_wildcard((*sp)->target) < zurl_wildcard(set->target))
452                 // Db already contains higher-priority setting. Abort search
453                 break;
454             else
455                 sp = &(*sp)->next;
456         }
457         else
458             sp = &(*sp)->next;
459     if (!*sp) // is null when there are no higher-priority settings, so we add one
460     {
461         struct setting *new = nmem_malloc(service->nmem, sizeof(*new));
462
463         memset(new, 0, sizeof(*new));
464         new->precedence = set->precedence;
465         new->target = nmem_strdup(service->nmem, set->target);
466         new->name = nmem_strdup(service->nmem, set->name);
467         new->value = nmem_strdup(service->nmem, set->value);
468         new->next = db->settings[offset];
469         db->settings[offset] = new;
470     }
471 }
472
473 // Callback -- updates database records with dictionary entries as appropriate
474 // This is used in pass 2 to assign name/value pairs to databases
475 static void update_databases(void *client_data, struct setting *set)
476 {
477     struct conf_service *service = (struct conf_service *) client_data;
478     struct update_database_context context;
479     context.set = set;
480     context.service = service;
481     predef_grep_databases(&context, service, update_database_fun);
482 }
483
484 // This simply copies the 'hard' (application-specific) settings
485 // to the settings dictionary.
486 static void initialize_hard_settings(struct conf_service *service)
487 {
488     struct setting_dictionary *dict = service->dictionary;
489     dict->dict = nmem_malloc(service->nmem, sizeof(hard_settings) - sizeof(char*));
490     dict->size = (sizeof(hard_settings) - sizeof(char*)) / sizeof(char*);
491     memcpy(dict->dict, hard_settings, dict->size * sizeof(char*));
492     dict->num = dict->size;
493 }
494
495 // Read any settings names introduced in service definition (config) and add to dictionary
496 // This is done now to avoid errors if user settings are declared in session overrides
497 void initialize_soft_settings(struct conf_service *service)
498 {
499     int i;
500     for (i = 0; i < service->num_metadata; i++)
501     {
502         struct conf_metadata *md = &service->metadata[i];
503
504         if (md->setting != Metadata_setting_no)
505             settings_create_offset(service, md->name);
506
507         // Also create setting for some metadata attributes.
508         if (md->limitmap) {
509             int index; 
510             WRBUF wrbuf = wrbuf_alloc();
511             yaz_log(YLOG_DEBUG, "Metadata %s has limitmap: %s ",md->name,  md->limitmap);
512             wrbuf_printf(wrbuf, "pz:limitmap:%s", md->name);
513             index = settings_create_offset(service, wrbuf_cstr(wrbuf));
514             if (index >= 0) {
515                 struct setting new;
516                 int offset;
517                 yaz_log(YLOG_DEBUG, "Service %s default %s=%s",
518                         (service->id ? service->id: "unknown"), wrbuf_cstr(wrbuf), md->limitmap);
519                 new.name = (char *) wrbuf_cstr(wrbuf);
520                 new.value = md->limitmap;
521                 new.next = 0;
522                 new.target = 0;
523                 new.precedence = 0;
524                 offset = settings_create_offset(service, new.name);
525                 update_settings(&new, service->settings, offset, service->nmem);
526             }
527             wrbuf_destroy(wrbuf);
528         // TODO same for facetmap
529         }
530     }
531 }
532
533 static void prepare_target_dictionary(void *client_data, struct setting *set)
534 {
535     struct conf_service *service = (struct conf_service *) client_data;
536
537     // If target address is not wildcard, add the database
538     if (*set->target && !zurl_wildcard(set->target))
539         create_database_for_service(set->target, service);
540 }
541
542 void init_settings(struct conf_service *service)
543 {
544     struct setting_dictionary *new;
545     
546     assert(service->nmem);
547     
548     new = nmem_malloc(service->nmem, sizeof(*new));
549     memset(new, 0, sizeof(*new));
550     service->dictionary = new;
551     initialize_hard_settings(service);
552     initialize_soft_settings(service);
553 }
554
555 int settings_read_file(struct conf_service *service, const char *path,
556                        int pass)
557 {
558     if (pass == 1)
559         return read_settings(path, service, prepare_target_dictionary);
560     else
561         return read_settings(path, service, update_databases);
562 }
563
564 int settings_read_node(struct conf_service *service, xmlNode *n,
565                         int pass)
566 {
567     if (pass == 1)
568         return settings_read_node_x(n, service, prepare_target_dictionary);
569     else
570         return settings_read_node_x(n, service, update_databases);
571 }
572
573 /*
574  * Local variables:
575  * c-basic-offset: 4
576  * c-file-style: "Stroustrup"
577  * indent-tabs-mode: nil
578  * End:
579  * vim: shiftwidth=4 tabstop=8 expandtab
580  */
581