File.cxx 6.92 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 The Music Player Daemon Project
3
 * http://www.musicpd.org
Warren Dukes's avatar
Warren Dukes committed
4 5 6 7 8 9 10 11 12 13
 *
 * 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.
14 15 16 17
 *
 * 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.
Warren Dukes's avatar
Warren Dukes committed
18 19
 */

20
#include "File.hxx"
21
#include "Data.hxx"
22
#include "Param.hxx"
23
#include "Block.hxx"
24
#include "Templates.hxx"
25
#include "system/Error.hxx"
26
#include "util/Tokenizer.hxx"
27
#include "util/StringStrip.hxx"
28
#include "util/StringAPI.hxx"
29
#include "util/Domain.hxx"
30
#include "util/RuntimeError.hxx"
31
#include "fs/FileSystem.hxx"
32
#include "fs/List.hxx"
33
#include "fs/Path.hxx"
34 35
#include "fs/io/FileReader.hxx"
#include "fs/io/BufferedReader.hxx"
36
#include "Log.hxx"
37

38
#include <assert.h>
Warren Dukes's avatar
Warren Dukes committed
39

40
static constexpr char CONF_COMMENT = '#';
41

42 43
static constexpr Domain config_file_domain("config_file");

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
/**
 * 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;
}

60 61
static void
config_read_name_value(ConfigBlock &block, char *input, unsigned line)
62
{
63 64
	Tokenizer tokenizer(input);

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

68
	auto value = ExpectValueAndEnd(tokenizer);
69

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

75
	block.AddBlockParam(name, std::move(value), line);
76 77
}

78
static ConfigBlock
79
config_read_block(BufferedReader &reader)
80
{
81
	ConfigBlock block(reader.GetLineNumber());
82

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

88
		line = StripLeft(line);
89 90
		if (*line == 0 || *line == CONF_COMMENT)
			continue;
91

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

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

100
			return block;
101
		}
102

103
		/* parse name and value */
104

105
		config_read_name_value(block, line,
106
				       reader.GetLineNumber());
107
	}
108 109
}

110
static void
111
ReadConfigBlock(ConfigData &config_data, BufferedReader &reader,
112
		const char *name, ConfigBlockOption o,
113
		Tokenizer &tokenizer)
114 115 116
{
	const unsigned i = unsigned(o);
	const ConfigTemplate &option = config_block_templates[i];
117

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

123 124 125 126 127 128
	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());
129 130 131

	/* now parse the block or the value */

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

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

139
	config_data.AddBlock(o, config_read_block(reader));
140 141
}

142
static void
143 144
ReadConfigParam(ConfigData &config_data, BufferedReader &reader,
		const char *name, ConfigOption o,
145
		Tokenizer &tokenizer)
Avuton Olrich's avatar
Avuton Olrich committed
146
{
147
	const unsigned i = unsigned(o);
148
	const ConfigTemplate &option = config_param_templates[i];
149

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

155 156 157 158 159 160
	if (!option.repeatable)
		if (const auto *param = config_data.GetParam(o))
			throw FormatRuntimeError("config parameter \"%s\" is first defined "
						 "on line %d and redefined on line %u\n",
						 name, param->line,
						 reader.GetLineNumber());
161 162 163

	/* now parse the block or the value */

164 165
	config_data.AddParam(o, ConfigParam(ExpectValueAndEnd(tokenizer),
					    reader.GetLineNumber()));
166 167
}

168 169 170
/**
 * @param directory the directory used to resolve relative paths
 */
171
static void
172
ReadConfigFile(ConfigData &config_data, BufferedReader &reader, Path directory)
173
{
174 175 176
	while (true) {
		char *line = reader.ReadLine();
		if (line == nullptr)
177
			return;
178 179

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

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

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

190
		if (StringIsEqual(name, "include")) {
191
			// TODO: detect recursion
192
			// TODO: Config{Block,Param} have only line number but no file name
193 194 195 196
			const auto pattern = AllocatedPath::Apply(directory,
								  AllocatedPath::FromUTF8Throw(ExpectValueAndEnd(tokenizer)));
			for (const auto &path : ListWildcard(pattern))
				ReadConfigFile(config_data, path);
197 198 199 200
			continue;
		}

		if (StringIsEqual(name, "include_optional")) {
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
			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);
216 217 218
			continue;
		}

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

222
		const ConfigOption o = ParseConfigOptionName(name);
223
		ConfigBlockOption bo;
224
		if (o != ConfigOption::MAX) {
225 226
			ReadConfigParam(config_data, reader, name, o,
					tokenizer);
227
		} else if ((bo = ParseConfigBlockOptionName(name)) != ConfigBlockOption::MAX) {
228 229
			ReadConfigBlock(config_data, reader, name, bo,
					tokenizer);
230
		} else {
231 232
			throw FormatRuntimeError("unrecognized parameter: %s\n",
						 name);
233
		}
Warren Dukes's avatar
Warren Dukes committed
234
	}
235
}
236

237 238
void
ReadConfigFile(ConfigData &config_data, Path path)
239 240 241 242
{
	assert(!path.IsNull());
	const std::string path_utf8 = path.ToUTF8();

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

245
	FileReader file(path);
246

247
	BufferedReader reader(file);
248 249

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