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