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