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