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