aboutsummaryrefslogtreecommitdiff
path: root/src/org/gnunet/util/Configuration.java
blob: 001477a1c56e99b7e8266ac548b34c4c0acc5b40 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
     This file is part of GNUnet.
     (C) 2009 Christian Grothoff (and other contributing authors)

     GNUnet is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published
     by the Free Software Foundation; either version 2, or (at your
     option) any later version.

     GNUnet is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with GNUnet; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
     Boston, MA 02111-1307, USA.
 */

package org.gnunet.util;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.common.io.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Configuration management.
 *
 * @author Florian Dold
 */
public class Configuration {
    public static class ParsingError extends RuntimeException {
        ParsingError(String msg) {
            super(msg);
        }

        ParsingError(String msg, final Throwable t) {
            super(msg, t);
        }
    }

    private static final Logger logger = LoggerFactory
            .getLogger(Configuration.class);

    private static Pattern section = Pattern.compile("\\[(.*?)\\]");
    private static Pattern tag = Pattern.compile("(\\S+?)\\s*=(.*?)");
    private static Pattern whitspace = Pattern.compile("\\s*");

    // rows are sections, colums are options
    private final Table<String, String, String> sections = HashBasedTable.create();

    private final Map<String, Set<String>> sectionSources = new HashMap<String, Set<String>>(20);

    /**
     * Start with an empty configuration.
     */
    public Configuration() {
    }


    /**
     * Expand an expression of the form "$FOO/BAR" to "DIRECTORY/BAR" where
     * either in the "PATHS" section or the environment "FOO" is set to
     * "DIRECTORY".
     *
     * @param orig string to $-expand
     * @return $-expanded string
     */
    public String expandDollar(String orig) {
        Map<String, String> env = System.getenv();
        for (final Map.Entry<String, String> e : env.entrySet()) {
            orig = orig.replace("$" + e.getKey(), e.getValue());
        }

        for (final Map.Entry<String, String> e : sections.row("PATHS").entrySet()) {
            orig = orig.replace("$" + e.getKey(), e.getValue());
        }
        return orig;
    }

    /**
     * Returns all configuration options in a section.
     *
     * @param s the section of interest
     * @return an unmodifiable view of the section.
     */
    public Map<String, String> getSection(String s) {
        Map<String, String> m = sections.row(s);
        return Collections.unmodifiableMap(m);
    }

    /**
     * Returns the names of all non-empty sections
     *
     * @return set of non-empty section names
     */
    public Set<String> getSections() {
        return sections.rowKeySet();
    }

    /**
     * Get a configuration value that should be in a set of predefined strings
     *
     * @param section section of interest
     * @param option  option of interest
     * @param choices list of legal values
     * @return matching value from choices
     */
    public String getValueChoice(String section, String option,
                                 Iterable<String> choices) {
        String value = getValueString(section, option);
        if (value == null) {
            throw new ParsingError(String.format(
                    "Failure in configuration section %s: value not found",
                    section));
        }
        for (String c : choices) {
            if (c.equals(value)) {
                return value;
            }
        }
        throw new ParsingError(String.format(
                "Failure in configuration section %s: invalid value", section));
    }


    /**
     * Get a configuration value that should be a number
     *
     * @param section section of interest
     * @param option  option of interest
     * @return null if value not in configuration, the option's value otherwise
     */
    public long getValueNumer(String section, String option) {
        String num_str = getValueString(section, option);
        if (num_str == null) {
            logSectionSources(section);
            throw new ParsingError("Failure in configuration section "
                    + section + " option " + option + ": value empty");
        }
        try {
            return Long.parseLong(num_str);
        } catch (NumberFormatException e) {
            throw new ParsingError("Failure in configuration section "
                    + section + " option " + option + ": " + e.getMessage(), e);
        }
    }

    private void logSectionSources(String section) {
        Set<String> sources = sectionSources.get(section);
        if (sources == null) {
            logger.info("No sources for section '{}'", section);
        } else {
            logger.info("Sources for section '{}': {}", section, sources);
        }
    }

    /**
     * Set an option to a string value in a section.
     *
     * @param section section of interest
     * @param option  option of interest
     * @return value
     */
    public String getValueString(String section, String option) {
        ensureSectionExists(section);
        return sections.get(section, option);
    }

    /**
     * Gets a configuration value that should be in a set of {"YES","NO"}.
     *
     * @param section section of interest
     * @param option  option of interest
     * @return true, false, null
     */
    public boolean getValueYesNo(String section, String option) {
        final String v = getValueChoice(section, option,
                Arrays.asList("YES", "NO"));
        if (v == null) {
            Set<String> sources = sectionSources.get(section);
            if (sources == null) {
                logger.info("No sources for section '{}'", section);
            } else {
                logger.info("Sources for section '{}': {}", section, sources);
            }
            throw new ParsingError(String.format(
                    "Failure in configuration section '%s': option '%s' not found",
                    section, option));
        }
        if (v.equals("YES")) {
            return true;
        }
        if (v.equals("NO")) {
            return false;
        }
        throw new ParsingError(
                "Configuration error: value not recognized as YES or NO");
    }

    /**
     * Tests if we have a value for a particular option.
     *
     * @param section section of interest
     * @param option  option of interest
     * @return true if so, false of not
     */
    public boolean haveValue(String section, String option) {
        return sections.contains(section, option);
    }

    /**
     * Parse a configuration file, add all of the options in the file to the
     * configuration environment.
     *
     * @param filename name of the configuration file
     */
    public void parse(String filename) {
        filename = replaceHome(filename);

        String current_section = "";

        Iterator<String> it;

        try {
            List<String> lines = Files.readLines(new File(filename), Charset.defaultCharset());
            it = lines.iterator();
        } catch (IOException e) {
            throw new ParsingError("Cannot read configuration file '" + filename + "'");
        }

        int lineNumer = 1;

        while (it.hasNext()) {
            String line = it.next();
            // strip comment
            line = line.split("#")[0];
            Matcher m;

            if ((m = tag.matcher(line)).matches()) {
                String option = m.group(1).trim();
                String value = m.group(2).trim();

                if (value.length() != 0 && value.charAt(0) == '"') {
                    int pos = value.indexOf('"', 1);
                    if (pos == -1) {
                        logger.warn("incorrecly quoted config value");
                        continue;
                    }
                    value = value.substring(1, pos);
                }
                setValueString(current_section, option, value);
            } else if ((m = section.matcher(line)).matches()) {
                current_section = m.group(1).trim();
                if (sectionSources.containsKey(current_section)) {
                    sectionSources.get(current_section).add(filename);
                } else {
                    sectionSources.put(current_section, new HashSet<String>(Collections.singleton(filename)));
                }
            } else if (whitspace.matcher(line).matches()) {
                // whitespace is ok
            } else {
                logger.warn(String.format("skipped unreadable line %s in configuration file '%s': '%s'", lineNumer,
                        filename, line));
            }

            lineNumer++;
        }
    }

    private String replaceHome(String filename) {
        String home = System.getenv("HOME");
        return home != null ? filename.replace("~", home) : filename;
    }

    /**
     * Remove the given section and all options in it.
     */
    public void removeSection(String section) {
        sections.row(section).clear();
    }

    /**
     * Set an option to a string value in a section.
     *
     * @param section section of interest
     * @param option  option of interest
     * @param value   value to set
     */
    public void setValueNumber(String section, String option,
                               long value) {
        setValueString(section, option, "" + value);
    }

    /**
     * Set an option to a string value in a section.
     *
     * @param section section of interest
     * @param option  option of interest
     * @param value   value to set
     */
    public void setValueString(String section, String option,
                               String value) {
        sections.put(section, option, value);
    }

    /**
     * Write configuration file.
     *
     * @param filename where to write the configuration
     */
    public void write(String filename) throws IOException {
        BufferedWriter w = new BufferedWriter(new FileWriter(new File(
                filename)));
        for (String section : sections.rowKeySet()) {
            w.write("["+section+"]");
            w.newLine();
            for (Map.Entry<String,String> e : sections.row(section).entrySet()) {
                w.write(e.getKey() + " = " + e.getValue());
                w.newLine();
            }
        }
        w.close();
    }


    public void loadDefaults() {
        Collection<File> dirs = new ArrayList<File>(5);
        dirs.add(new File("/usr/share/gnunet/config.d/"));
        dirs.add(new File("/usr/local/share/gnunet/config.d/"));
        String pfx = System.getenv("GNUNET_PREFIX");
        if (pfx != null) {
            dirs.add(new File(pfx, "share/gnunet/config.d/"));
            dirs.add(new File(pfx, "config.d/"));
            dirs.add(new File(pfx, "gnunet/config.d/"));
        }
        for (File dir : dirs) {
            if (dir.exists() && dir.isDirectory()) {
                File[] files = dir.listFiles();
                if (files == null) {
                    continue;
                }
                for (File f : files) {
                    parse(f.getAbsolutePath());
                }
            }
        }
    }

    private void ensureSectionExists(String section) {
        if (!sections.containsRow(section)) {
            throw new ConfigurationException("Required section '" + section + "' not in configuration");
        }
    }

    public static class ConfigurationException extends RuntimeException {
        public ConfigurationException(String string) {
            super(string);
        }
    }
}