Add pz:memcached option
[pazpar2-moved-to-github.git] / src / settings.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 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:zproxy",
63     "pz:apdulog",
64     "pz:sru",
65     "pz:sru_version",
66     "pz:pqf_prefix",
67     "pz:sort",
68     "pz:recordfilter",
69     "pz:pqf_strftime",
70     "pz:negotiation_charset",
71     "pz:max_connections",
72     "pz:reuse_connections",
73     "pz:termlist_term_factor",
74     "pz:termlist_term_count",
75     "pz:preferred",
76     "pz:extra_args",
77     "pz:query_syntax",
78     "pz:facetmap:",
79     "pz:limitmap:",
80     "pz:url",
81     "pz:sortmap:",
82     "pz:present_chunk",
83     "pz:block_timeout",
84     "pz:extendrecs",
85     "pz:authentication_mode",
86     "pz:native_score",
87     "pz:memcached",
88     0
89 };
90
91 struct setting_dictionary
92 {
93     char **dict;
94     int size;
95     int num;
96 };
97
98 // This establishes the precedence of wildcard expressions
99 #define SETTING_WILDCARD_NO     0 // No wildcard
100 #define SETTING_WILDCARD_DB     1 // Database wildcard 'host:port/*'
101 #define SETTING_WILDCARD_YES    2 // Complete wildcard '*'
102
103 // Returns size of settings directory
104 int settings_num(struct conf_service *service)
105 {
106     return service->dictionary->num;
107 }
108
109 /* Find and possible create a new dictionary entry. Pass valid NMEM pointer if creation is allowed, otherwise null */
110 static int settings_index_lookup(struct setting_dictionary *dictionary, const char *name, NMEM nmem)
111 {
112     size_t maxlen;
113     int i;
114     const char *p;
115
116     assert(name);
117
118     if (!strncmp("pz:", name, 3) && (p = strchr(name + 3, ':')))
119         maxlen = (p - name) + 1;
120     else
121         maxlen = strlen(name) + 1;
122     for (i = 0; i < dictionary->num; i++)
123         if (!strncmp(name, dictionary->dict[i], maxlen))
124             return i;
125     if (!nmem)
126         return -1;
127     if (!strncmp("pz:", name, 3))
128         yaz_log(YLOG_WARN, "Adding pz-type setting name %s", name);
129     if (dictionary->num + 1 > dictionary->size)
130     {
131         char **tmp =
132             nmem_malloc(nmem, dictionary->size * 2 * sizeof(char*));
133         memcpy(tmp, dictionary->dict, dictionary->size * sizeof(char*));
134         dictionary->dict = tmp;
135         dictionary->size *= 2;
136     }
137     dictionary->dict[dictionary->num] = nmem_strdup(nmem, name);
138     dictionary->dict[dictionary->num][maxlen-1] = '\0';
139     return dictionary->num++;
140 }
141
142 int settings_create_offset(struct conf_service *service, const char *name)
143 {
144     return settings_index_lookup(service->dictionary, name, service->nmem);
145 }
146
147 int settings_lookup_offset(struct conf_service *service, const char *name)
148 {
149     return settings_index_lookup(service->dictionary, name, 0);
150 }
151
152 char *settings_name(struct conf_service *service, int offset)
153 {
154     assert(offset < service->dictionary->num);
155     return service->dictionary->dict[offset];
156 }
157
158
159 // Apply a session override to a database
160 void service_apply_setting(struct conf_service *service, char *setting, char *value)
161 {
162     struct setting *new = nmem_malloc(service->nmem, sizeof(*new));
163     int offset = settings_create_offset(service, setting);
164     expand_settings_array(&service->settings->settings, &service->settings->num_settings, offset, service->nmem);
165     new->precedence = 0;
166     new->target = NULL;
167     new->name = setting;
168     new->value = value;
169     new->next = service->settings->settings[offset];
170     service->settings->settings[offset] = new;
171 }
172
173
174 static int isdir(const char *path)
175 {
176     struct stat st;
177
178     if (stat(path, &st) < 0)
179     {
180         yaz_log(YLOG_FATAL|YLOG_ERRNO, "stat %s", path);
181         exit(1);
182     }
183     return st.st_mode & S_IFDIR;
184 }
185
186 // Read settings from an XML file, calling handler function for each setting
187 int settings_read_node_x(xmlNode *n,
188                          void *client_data,
189                          void (*fun)(void *client_data,
190                                      struct setting *set))
191 {
192     int ret_val = 0; /* success */
193     char *namea = (char *) xmlGetProp(n, (xmlChar *) "name");
194     char *targeta = (char *) xmlGetProp(n, (xmlChar *) "target");
195     char *valuea = (char *) xmlGetProp(n, (xmlChar *) "value");
196     char *usera = (char *) xmlGetProp(n, (xmlChar *) "user");
197     char *precedencea = (char *) xmlGetProp(n, (xmlChar *) "precedence");
198
199     for (n = n->children; n; n = n->next)
200     {
201         if (n->type != XML_ELEMENT_NODE)
202             continue;
203         if (!strcmp((const char *) n->name, "set"))
204         {
205             xmlNode *root = n->children;
206             struct setting set;
207             char *name = (char *) xmlGetProp(n, (xmlChar *) "name");
208             char *target = (char *) xmlGetProp(n, (xmlChar *) "target");
209             char *value = (char *) xmlGetProp(n, (xmlChar *) "value");
210             char *user = (char *) xmlGetProp(n, (xmlChar *) "user");
211             char *precedence = (char *) xmlGetProp(n, (xmlChar *) "precedence");
212             xmlChar *buf_out = 0;
213
214             set.next = 0;
215
216             if (precedence)
217                 set.precedence = atoi((char *) precedence);
218             else if (precedencea)
219                 set.precedence = atoi((char *) precedencea);
220             else
221                 set.precedence = 0;
222
223             set.target = target ? target : targeta;
224             set.name = name ? name : namea;
225
226             while (root && root->type != XML_ELEMENT_NODE)
227                 root = root->next;
228             if (!root)
229                 set.value = value ? value : valuea;
230             else
231             {   /* xml document content for this setting */
232                 xmlDoc *doc = xmlNewDoc(BAD_CAST "1.0");
233                 if (!doc)
234                 {
235                     if (set.name)
236                         yaz_log(YLOG_WARN, "bad XML content for setting "
237                                 "name=%s", set.name);
238                     else
239                         yaz_log(YLOG_WARN, "bad XML content for setting");
240                     ret_val = -1;
241                 }
242                 else
243                 {
244                     int len_out;
245                     xmlDocSetRootElement(doc, xmlCopyNode(root, 1));
246                     xmlDocDumpMemory(doc, &buf_out, &len_out);
247                     /* xmlDocDumpMemory 0-terminates */
248                     set.value = (char *) buf_out;
249                     xmlFreeDoc(doc);
250                 }
251             }
252
253             if (set.name && set.value && set.target)
254                 (*fun)(client_data, &set);
255             else
256             {
257                 if (set.name)
258                     yaz_log(YLOG_WARN, "missing value and/or target for "
259                             "setting name=%s", set.name);
260                 else
261                     yaz_log(YLOG_WARN, "missing name/value/target for setting");
262                 ret_val = -1;
263             }
264             xmlFree(buf_out);
265             xmlFree(name);
266             xmlFree(precedence);
267             xmlFree(value);
268             xmlFree(user);
269             xmlFree(target);
270         }
271         else
272         {
273             yaz_log(YLOG_WARN, "Unknown element %s in settings file",
274                     (char*) n->name);
275             ret_val = -1;
276         }
277     }
278     xmlFree(namea);
279     xmlFree(precedencea);
280     xmlFree(valuea);
281     xmlFree(usera);
282     xmlFree(targeta);
283     return ret_val;
284 }
285
286 static int read_settings_file(const char *path,
287                               void *client_data,
288                               void (*fun)(void *client_data,
289                                           struct setting *set))
290 {
291     xmlDoc *doc = xmlParseFile(path);
292     xmlNode *n;
293     int ret;
294
295     if (!doc)
296     {
297         yaz_log(YLOG_FATAL, "Failed to parse %s", path);
298         return -1;
299     }
300     n = xmlDocGetRootElement(doc);
301     ret = settings_read_node_x(n, client_data, fun);
302
303     xmlFreeDoc(doc);
304     return ret;
305 }
306
307
308 // Recursively read files or directories, invoking a
309 // callback for each one
310 static int read_settings(const char *path,
311                           void *client_data,
312                           void (*fun)(void *client_data,
313                                       struct setting *set))
314 {
315     int ret = 0;
316     DIR *d;
317     struct dirent *de;
318     char *dot;
319
320     if (isdir(path))
321     {
322         if (!(d = opendir(path)))
323         {
324             yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", path);
325             return -1;
326         }
327         while ((de = readdir(d)))
328         {
329             char tmp[1024];
330             if (*de->d_name == '.' || !strcmp(de->d_name, "CVS"))
331                 continue;
332             sprintf(tmp, "%s/%s", path, de->d_name);
333             if (read_settings(tmp, client_data, fun))
334                 ret = -1;
335         }
336         closedir(d);
337     }
338     else if ((dot = strrchr(path, '.')) && !strcmp(dot + 1, "xml"))
339         ret = read_settings_file(path, client_data, fun);
340     return ret;
341 }
342
343 // Determines if a ZURL is a wildcard, and what kind
344 static int zurl_wildcard(const char *zurl)
345 {
346     if (!zurl)
347         return SETTING_WILDCARD_NO;
348     if (*zurl == '*')
349         return SETTING_WILDCARD_YES;
350     else if (*(zurl + strlen(zurl) - 1) == '*')
351         return SETTING_WILDCARD_DB;
352     else
353         return SETTING_WILDCARD_NO;
354 }
355
356 struct update_database_context {
357     struct setting *set;
358     struct conf_service *service;
359 };
360
361 void expand_settings_array(struct setting ***set_ar, int *num, int offset,
362                            NMEM nmem)
363 {
364     assert(offset >= 0);
365     assert(*set_ar);
366     if (offset >= *num)
367     {
368         int i, n_num = offset + 10;
369         struct setting **n_ar = nmem_malloc(nmem, n_num * sizeof(*n_ar));
370         for (i = 0; i < *num; i++)
371             n_ar[i] = (*set_ar)[i];
372         for (; i < n_num; i++)
373             n_ar[i] = 0;
374         *num = n_num;
375         *set_ar = n_ar;
376     }
377 }
378
379 void expand_settings_array2(struct settings_array *settings, int offset, NMEM nmem)
380 {
381     assert(offset >= 0);
382     assert(settings);
383     if (offset >= settings->num_settings)
384     {
385         int i, n_num = offset + 10;
386         struct setting **n_ar = nmem_malloc(nmem, n_num * sizeof(*n_ar));
387         for (i = 0; i < settings->num_settings; i++)
388             n_ar[i] = settings->settings[i];
389         for (; i < n_num; i++)
390             n_ar[i] = 0;
391         settings->num_settings = n_num;
392         settings->settings = n_ar;
393     }
394 }
395
396 static void update_settings(struct setting *set, struct settings_array *settings, int offset, NMEM nmem)
397 {
398     struct setting **sp;
399     yaz_log(YLOG_DEBUG, "update service settings offset %d with %s=%s", offset, set->name, set->value);
400     expand_settings_array2(settings, offset, nmem);
401
402     // First we determine if this setting is overriding any existing settings
403     // with the same name.
404     assert(offset < settings->num_settings);
405     for (sp = &settings->settings[offset]; *sp; )
406         if (!strcmp((*sp)->name, set->name))
407         {
408             if ((*sp)->precedence < set->precedence)
409             {
410                 // We discard the value (nmem keeps track of the space)
411                 *sp = (*sp)->next; // unlink value from existing setting
412             }
413             else if ((*sp)->precedence > set->precedence)
414             {
415                 // Db contains a higher-priority setting. Abort search
416                 break;
417             }
418             else if (zurl_wildcard((*sp)->target) > zurl_wildcard(set->target))
419             {
420                 // target-specific value trumps wildcard. Delete.
421                 *sp = (*sp)->next; // unlink.....
422             }
423             else if (zurl_wildcard((*sp)->target) < zurl_wildcard(set->target))
424                 // Db already contains higher-priority setting. Abort search
425                 break;
426             else
427                 sp = &(*sp)->next;
428         }
429         else
430             sp = &(*sp)->next;
431     if (!*sp) // is null when there are no higher-priority settings, so we add one
432     {
433         struct setting *new = nmem_malloc(nmem, sizeof(*new));
434         memset(new, 0, sizeof(*new));
435         new->precedence = set->precedence;
436         new->target = nmem_strdup_null(nmem, set->target);
437         new->name = nmem_strdup_null(nmem, set->name);
438         new->value = nmem_strdup_null(nmem, set->value);
439         new->next = settings->settings[offset];
440         settings->settings[offset] = new;
441     }
442 }
443
444
445 // This is called from grep_databases -- adds/overrides setting for a target
446 // This is also where the rules for precedence of settings are implemented
447 static void update_database_fun(void *context, struct database *db)
448 {
449     struct setting *set = ((struct update_database_context *)
450                            context)->set;
451     struct conf_service *service = ((struct update_database_context *)
452                                     context)->service;
453     struct setting **sp;
454     int offset;
455
456     // Is this the right database?
457     if (!match_zurl(db->id, set->target))
458         return;
459
460     offset = settings_create_offset(service, set->name);
461     expand_settings_array(&db->settings, &db->num_settings, offset, service->nmem);
462
463     // First we determine if this setting is overriding  any existing settings
464     // with the same name.
465     assert(offset < db->num_settings);
466     for (sp = &db->settings[offset]; *sp; )
467         if (!strcmp((*sp)->name, set->name))
468         {
469             if ((*sp)->precedence < set->precedence)
470             {
471                 // We discard the value (nmem keeps track of the space)
472                 *sp = (*sp)->next; // unlink value from existing setting
473             }
474             else if ((*sp)->precedence > set->precedence)
475             {
476                 // Db contains a higher-priority setting. Abort search
477                 break;
478             }
479             else if (zurl_wildcard((*sp)->target) > zurl_wildcard(set->target))
480             {
481                 // target-specific value trumps wildcard. Delete.
482                 *sp = (*sp)->next; // unlink.....
483             }
484             else if (zurl_wildcard((*sp)->target) < zurl_wildcard(set->target))
485                 // Db already contains higher-priority setting. Abort search
486                 break;
487             else
488                 sp = &(*sp)->next;
489         }
490         else
491             sp = &(*sp)->next;
492     if (!*sp) // is null when there are no higher-priority settings, so we add one
493     {
494         struct setting *new = nmem_malloc(service->nmem, sizeof(*new));
495
496         memset(new, 0, sizeof(*new));
497         new->precedence = set->precedence;
498         new->target = nmem_strdup(service->nmem, set->target);
499         new->name = nmem_strdup(service->nmem, set->name);
500         new->value = nmem_strdup(service->nmem, set->value);
501         new->next = db->settings[offset];
502         db->settings[offset] = new;
503     }
504 }
505
506 // Callback -- updates database records with dictionary entries as appropriate
507 // This is used in pass 2 to assign name/value pairs to databases
508 static void update_databases(void *client_data, struct setting *set)
509 {
510     struct conf_service *service = (struct conf_service *) client_data;
511     struct update_database_context context;
512     context.set = set;
513     context.service = service;
514     predef_grep_databases(&context, service, update_database_fun);
515 }
516
517 // This simply copies the 'hard' (application-specific) settings
518 // to the settings dictionary.
519 static void initialize_hard_settings(struct conf_service *service)
520 {
521     struct setting_dictionary *dict = service->dictionary;
522     dict->dict = nmem_malloc(service->nmem, sizeof(hard_settings) - sizeof(char*));
523     dict->size = (sizeof(hard_settings) - sizeof(char*)) / sizeof(char*);
524     memcpy(dict->dict, hard_settings, dict->size * sizeof(char*));
525     dict->num = dict->size;
526 }
527
528 // Read any settings names introduced in service definition (config) and add to dictionary
529 // This is done now to avoid errors if user settings are declared in session overrides
530 void initialize_soft_settings(struct conf_service *service)
531 {
532     int i;
533     for (i = 0; i < service->num_metadata; i++)
534     {
535         struct conf_metadata *md = &service->metadata[i];
536
537         if (md->setting != Metadata_setting_no)
538             settings_create_offset(service, md->name);
539
540         // Also create setting for some metadata attributes.
541         if (md->limitmap) {
542             int index;
543             WRBUF wrbuf = wrbuf_alloc();
544             yaz_log(YLOG_DEBUG, "Metadata %s has limitmap: %s ",md->name,  md->limitmap);
545             wrbuf_printf(wrbuf, "pz:limitmap:%s", md->name);
546             index = settings_create_offset(service, wrbuf_cstr(wrbuf));
547             if (index >= 0) {
548                 struct setting new;
549                 int offset;
550                 yaz_log(YLOG_DEBUG, "Service %s default %s=%s",
551                         (service->id ? service->id: "unknown"), wrbuf_cstr(wrbuf), md->limitmap);
552                 new.name = (char *) wrbuf_cstr(wrbuf);
553                 new.value = md->limitmap;
554                 new.next = 0;
555                 new.target = 0;
556                 new.precedence = 0;
557                 offset = settings_create_offset(service, new.name);
558                 update_settings(&new, service->settings, offset, service->nmem);
559             }
560             wrbuf_destroy(wrbuf);
561         // TODO same for facetmap
562         }
563     }
564 }
565
566 static void prepare_target_dictionary(void *client_data, struct setting *set)
567 {
568     struct conf_service *service = (struct conf_service *) client_data;
569
570     // If target address is not wildcard, add the database
571     if (*set->target && !zurl_wildcard(set->target))
572         create_database_for_service(set->target, service);
573 }
574
575 void init_settings(struct conf_service *service)
576 {
577     struct setting_dictionary *new;
578
579     assert(service->nmem);
580
581     new = nmem_malloc(service->nmem, sizeof(*new));
582     memset(new, 0, sizeof(*new));
583     service->dictionary = new;
584     initialize_hard_settings(service);
585     initialize_soft_settings(service);
586 }
587
588 int settings_read_file(struct conf_service *service, const char *path,
589                        int pass)
590 {
591     if (pass == 1)
592         return read_settings(path, service, prepare_target_dictionary);
593     else
594         return read_settings(path, service, update_databases);
595 }
596
597 int settings_read_node(struct conf_service *service, xmlNode *n,
598                         int pass)
599 {
600     if (pass == 1)
601         return settings_read_node_x(n, service, prepare_target_dictionary);
602     else
603         return settings_read_node_x(n, service, update_databases);
604 }
605
606 /*
607  * Local variables:
608  * c-basic-offset: 4
609  * c-file-style: "Stroustrup"
610  * indent-tabs-mode: nil
611  * End:
612  * vim: shiftwidth=4 tabstop=8 expandtab
613  */
614