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