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