summaryrefslogtreecommitdiff
path: root/src/config/File.cxx
blob: 8c3ab111bd9e2eedddd84a79aad46b027c52d0be (plain)
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
/*
 * Copyright 2003-2020 The Music Player Daemon Project
 * http://www.musicpd.org
 *
 * This program 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 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "File.hxx"
#include "Data.hxx"
#include "Param.hxx"
#include "Block.hxx"
#include "Templates.hxx"
#include "system/Error.hxx"
#include "util/Tokenizer.hxx"
#include "util/StringStrip.hxx"
#include "util/StringAPI.hxx"
#include "util/Domain.hxx"
#include "util/RuntimeError.hxx"
#include "fs/FileSystem.hxx"
#include "fs/List.hxx"
#include "fs/Path.hxx"
#include "fs/io/FileReader.hxx"
#include "fs/io/BufferedReader.hxx"
#include "Log.hxx"

#include <assert.h>

static constexpr char CONF_COMMENT = '#';

static constexpr Domain config_file_domain("config_file");

/**
 * Read a string value as the last token of a line.  Throws on error.
 */
static auto
ExpectValueAndEnd(Tokenizer &tokenizer)
{
	auto value = tokenizer.NextString();
	if (!value)
		throw std::runtime_error("Value missing");

	if (!tokenizer.IsEnd() && tokenizer.CurrentChar() != CONF_COMMENT)
		throw std::runtime_error("Unknown tokens after value");

	return value;
}

static void
config_read_name_value(ConfigBlock &block, char *input, unsigned line)
{
	Tokenizer tokenizer(input);

	const char *name = tokenizer.NextWord();
	assert(name != nullptr);

	auto value = ExpectValueAndEnd(tokenizer);

	const BlockParam *bp = block.GetBlockParam(name);
	if (bp != nullptr)
		throw FormatRuntimeError("\"%s\" is duplicate, first defined on line %i",
					 name, bp->line);

	block.AddBlockParam(name, value, line);
}

static ConfigBlock
config_read_block(BufferedReader &reader)
{
	ConfigBlock block(reader.GetLineNumber());

	while (true) {
		char *line = reader.ReadLine();
		if (line == nullptr)
			throw std::runtime_error("Expected '}' before end-of-file");

		line = StripLeft(line);
		if (*line == 0 || *line == CONF_COMMENT)
			continue;

		if (*line == '}') {
			/* end of this block; return from the function
			   (and from this "while" loop) */

			line = StripLeft(line + 1);
			if (*line != 0 && *line != CONF_COMMENT)
				throw std::runtime_error("Unknown tokens after '}'");

			return block;
		}

		/* parse name and value */

		config_read_name_value(block, line,
				       reader.GetLineNumber());
	}
}

static void
ReadConfigBlock(ConfigData &config_data, BufferedReader &reader,
		const char *name, ConfigBlockOption o,
		Tokenizer &tokenizer)
{
	const auto i = unsigned(o);
	const ConfigTemplate &option = config_block_templates[i];

	if (option.deprecated)
		FormatWarning(config_file_domain,
			      "config parameter \"%s\" on line %u is deprecated",
			      name, reader.GetLineNumber());

	if (!option.repeatable)
		if (const auto *block = config_data.GetBlock(o))
			throw FormatRuntimeError("config parameter \"%s\" is first defined "
						 "on line %d and redefined on line %u\n",
						 name, block->line,
						 reader.GetLineNumber());

	/* now parse the block or the value */

	if (tokenizer.CurrentChar() != '{')
		throw std::runtime_error("'{' expected");

	char *line = StripLeft(tokenizer.Rest() + 1);
	if (*line != 0 && *line != CONF_COMMENT)
		throw std::runtime_error("Unknown tokens after '{'");

	config_data.AddBlock(o, config_read_block(reader));
}

static void
ReadConfigParam(ConfigData &config_data, BufferedReader &reader,
		const char *name, ConfigOption o,
		Tokenizer &tokenizer)
{
	const auto i = unsigned(o);
	const ConfigTemplate &option = config_param_templates[i];

	if (option.deprecated)
		FormatWarning(config_file_domain,
			      "config parameter \"%s\" on line %u is deprecated",
			      name, reader.GetLineNumber());

	if (!option.repeatable)
		/* if the option is not repeatable, override the old
		   value by removing it first */
		config_data.GetParamList(o).clear();

	/* now parse the block or the value */

	config_data.AddParam(o, ConfigParam(ExpectValueAndEnd(tokenizer),
					    reader.GetLineNumber()));
}

/**
 * @param directory the directory used to resolve relative paths
 */
static void
ReadConfigFile(ConfigData &config_data, BufferedReader &reader, Path directory)
{
	while (true) {
		char *line = reader.ReadLine();
		if (line == nullptr)
			return;

		line = StripLeft(line);
		if (*line == 0 || *line == CONF_COMMENT)
			continue;

		/* the first token in each line is the name, followed
		   by either the value or '{' */

		Tokenizer tokenizer(line);
		const char *name = tokenizer.NextWord();
		assert(name != nullptr);

		if (StringIsEqual(name, "include")) {
			// TODO: detect recursion
			// TODO: Config{Block,Param} have only line number but no file name
			const auto pattern = AllocatedPath::Apply(directory,
								  AllocatedPath::FromUTF8Throw(ExpectValueAndEnd(tokenizer)));
			for (const auto &path : ListWildcard(pattern))
				ReadConfigFile(config_data, path);
			continue;
		}

		if (StringIsEqual(name, "include_optional")) {
			const auto pattern = AllocatedPath::Apply(directory,
								  AllocatedPath::FromUTF8Throw(ExpectValueAndEnd(tokenizer)));

			std::forward_list<AllocatedPath> l;
			try {
				l = ListWildcard(pattern);
			} catch (const std::system_error &e) {
				/* ignore "file not found */
				if (!IsFileNotFound(e) && !IsPathNotFound(e))
					throw;
			}

			for (const auto &path : l)
				if (PathExists(path))
					ReadConfigFile(config_data, path);
			continue;
		}

		/* get the definition of that option, and check the
		   "repeatable" flag */

		const ConfigOption o = ParseConfigOptionName(name);
		ConfigBlockOption bo;
		if (o != ConfigOption::MAX) {
			ReadConfigParam(config_data, reader, name, o,
					tokenizer);
		} else if ((bo = ParseConfigBlockOptionName(name)) != ConfigBlockOption::MAX) {
			ReadConfigBlock(config_data, reader, name, bo,
					tokenizer);
		} else {
			throw FormatRuntimeError("unrecognized parameter: %s\n",
						 name);
		}
	}
}

void
ReadConfigFile(ConfigData &config_data, Path path)
{
	assert(!path.IsNull());
	const std::string path_utf8 = path.ToUTF8();

	FormatDebug(config_file_domain, "loading file %s", path_utf8.c_str());

	FileReader file(path);

	BufferedReader reader(file);

	try {
		ReadConfigFile(config_data, reader, path.GetDirectoryName());
	} catch (...) {
		std::throw_with_nested(FormatRuntimeError("Error in %s line %u",
							  path_utf8.c_str(),
							  reader.GetLineNumber()));
	}
}