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