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