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