1 /******************************************************************************
3 * Copyright (C) 2012-2018 Icinga Development Team (https://www.icinga.com/) *
5 * This program is free software; you can redistribute it and/or *
6 * modify it under the terms of the GNU General Public License *
7 * as published by the Free Software Foundation; either version 2 *
8 * of the License, or (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the Free Software Foundation *
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
18 ******************************************************************************/
20 #include "config/configcompiler.hpp"
21 #include "config/configitem.hpp"
22 #include "base/logger.hpp"
23 #include "base/utility.hpp"
24 #include "base/loader.hpp"
25 #include "base/context.hpp"
26 #include "base/exception.hpp"
29 using namespace icinga;
31 std::vector<String> ConfigCompiler::m_IncludeSearchDirs;
32 boost::mutex ConfigCompiler::m_ZoneDirsMutex;
33 std::map<String, std::vector<ZoneFragment> > ConfigCompiler::m_ZoneDirs;
36 * Constructor for the ConfigCompiler class.
38 * @param path The path of the configuration file (or another name that
39 * identifies the source of the configuration text).
40 * @param input Input stream for the configuration file.
41 * @param zone The zone.
43 ConfigCompiler::ConfigCompiler(String path, std::istream *input,
44 String zone, String package)
45 : m_Path(std::move(path)), m_Input(input), m_Zone(std::move(zone)),
46 m_Package(std::move(package)), m_Eof(false), m_OpenBraces(0)
52 * Destructor for the ConfigCompiler class.
54 ConfigCompiler::~ConfigCompiler()
60 * Reads data from the input stream. Used internally by the lexer.
62 * @param buffer Where to store data.
63 * @param max_size The maximum number of bytes to read from the stream.
64 * @returns The actual number of bytes read.
66 size_t ConfigCompiler::ReadInput(char *buffer, size_t max_size)
68 m_Input->read(buffer, max_size);
69 return static_cast<size_t>(m_Input->gcount());
73 * Retrieves the scanner object.
75 * @returns The scanner object.
77 void *ConfigCompiler::GetScanner() const
83 * Retrieves the path for the input file.
87 const char *ConfigCompiler::GetPath() const
92 void ConfigCompiler::SetZone(const String& zone)
97 String ConfigCompiler::GetZone() const
102 void ConfigCompiler::SetPackage(const String& package)
107 String ConfigCompiler::GetPackage() const
112 void ConfigCompiler::CollectIncludes(std::vector<std::unique_ptr<Expression> >& expressions,
113 const String& file, const String& zone, const String& package)
116 expressions.emplace_back(CompileFile(file, zone, package));
117 } catch (const std::exception& ex) {
118 Log(LogWarning, "ConfigCompiler")
119 << "Cannot compile file '"
120 << file << "': " << DiagnosticInformation(ex);
125 * Handles an include directive.
127 * @param relativeBath The path this include is relative to.
128 * @param path The path from the include directive.
129 * @param search Whether to search global include dirs.
130 * @param debuginfo Debug information.
132 std::unique_ptr<Expression> ConfigCompiler::HandleInclude(const String& relativeBase, const String& path,
133 bool search, const String& zone, const String& package, const DebugInfo& debuginfo)
137 if (search || (IsAbsolutePath(path)))
140 upath = relativeBase + "/" + path;
142 String includePath = upath;
145 for (const String& dir : m_IncludeSearchDirs) {
146 String spath = dir + "/" + path;
148 if (Utility::PathExists(spath)) {
155 std::vector<std::unique_ptr<Expression> > expressions;
157 if (!Utility::Glob(includePath, std::bind(&ConfigCompiler::CollectIncludes, std::ref(expressions), _1, zone, package), GlobFile) && includePath.FindFirstOf("*?") == String::NPos) {
158 std::ostringstream msgbuf;
159 msgbuf << "Include file '" + path + "' does not exist";
160 BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str(), debuginfo));
163 std::unique_ptr<DictExpression> expr{new DictExpression(std::move(expressions))};
165 return std::move(expr);
169 * Handles recursive includes.
171 * @param relativeBase The path this include is relative to.
172 * @param path The directory path.
173 * @param pattern The file pattern.
174 * @param debuginfo Debug information.
176 std::unique_ptr<Expression> ConfigCompiler::HandleIncludeRecursive(const String& relativeBase, const String& path,
177 const String& pattern, const String& zone, const String& package, const DebugInfo&)
181 if (IsAbsolutePath(path))
184 ppath = relativeBase + "/" + path;
186 std::vector<std::unique_ptr<Expression> > expressions;
187 Utility::GlobRecursive(ppath, pattern, std::bind(&ConfigCompiler::CollectIncludes, std::ref(expressions), _1, zone, package), GlobFile);
189 std::unique_ptr<DictExpression> dict{new DictExpression(std::move(expressions))};
191 return std::move(dict);
194 void ConfigCompiler::HandleIncludeZone(const String& relativeBase, const String& tag, const String& path, const String& pattern, const String& package, std::vector<std::unique_ptr<Expression> >& expressions)
196 String zoneName = Utility::BaseName(path);
200 if (IsAbsolutePath(path))
203 ppath = relativeBase + "/" + path;
205 RegisterZoneDir(tag, ppath, zoneName);
207 Utility::GlobRecursive(ppath, pattern, std::bind(&ConfigCompiler::CollectIncludes, std::ref(expressions), _1, zoneName, package), GlobFile);
211 * Handles zone includes.
213 * @param relativeBase The path this include is relative to.
214 * @param tag The tag name.
215 * @param path The directory path.
216 * @param pattern The file pattern.
217 * @param debuginfo Debug information.
219 std::unique_ptr<Expression> ConfigCompiler::HandleIncludeZones(const String& relativeBase, const String& tag,
220 const String& path, const String& pattern, const String& package, const DebugInfo&)
223 String newRelativeBase = relativeBase;
225 if (IsAbsolutePath(path))
228 ppath = relativeBase + "/" + path;
229 newRelativeBase = ".";
232 std::vector<std::unique_ptr<Expression> > expressions;
233 Utility::Glob(ppath + "/*", std::bind(&ConfigCompiler::HandleIncludeZone, newRelativeBase, tag, _1, pattern, package, std::ref(expressions)), GlobDirectory);
234 return std::unique_ptr<Expression>(new DictExpression(std::move(expressions)));
240 * @param path A name identifying the stream.
241 * @param stream The input stream.
242 * @returns Configuration items.
244 std::unique_ptr<Expression> ConfigCompiler::CompileStream(const String& path,
245 std::istream *stream, const String& zone, const String& package)
247 CONTEXT("Compiling configuration stream with name '" + path + "'");
249 stream->exceptions(std::istream::badbit);
251 ConfigCompiler ctx(path, stream, zone, package);
254 return ctx.Compile();
255 } catch (const ScriptError& ex) {
256 return std::unique_ptr<Expression>(new ThrowExpression(MakeLiteral(ex.what()), ex.IsIncompleteExpression(), ex.GetDebugInfo()));
257 } catch (const std::exception& ex) {
258 return std::unique_ptr<Expression>(new ThrowExpression(MakeLiteral(DiagnosticInformation(ex)), false));
265 * @param path The path.
266 * @returns Configuration items.
268 std::unique_ptr<Expression> ConfigCompiler::CompileFile(const String& path, const String& zone,
269 const String& package)
271 CONTEXT("Compiling configuration file '" + path + "'");
273 std::ifstream stream(path.CStr(), std::ifstream::in);
276 BOOST_THROW_EXCEPTION(posix_error()
277 << boost::errinfo_api_function("std::ifstream::open")
278 << boost::errinfo_errno(errno)
279 << boost::errinfo_file_name(path));
281 Log(LogNotice, "ConfigCompiler")
282 << "Compiling config file: " << path;
284 return CompileStream(path, &stream, zone, package);
288 * Compiles a snippet of text.
290 * @param path A name identifying the text.
291 * @param text The text.
292 * @returns Configuration items.
294 std::unique_ptr<Expression> ConfigCompiler::CompileText(const String& path, const String& text,
295 const String& zone, const String& package)
297 std::stringstream stream(text);
298 return CompileStream(path, &stream, zone, package);
302 * Adds a directory to the list of include search dirs.
304 * @param dir The new dir.
306 void ConfigCompiler::AddIncludeSearchDir(const String& dir)
308 Log(LogInformation, "ConfigCompiler")
309 << "Adding include search dir: " << dir;
311 m_IncludeSearchDirs.push_back(dir);
314 std::vector<ZoneFragment> ConfigCompiler::GetZoneDirs(const String& zone)
316 boost::mutex::scoped_lock lock(m_ZoneDirsMutex);
317 auto it = m_ZoneDirs.find(zone);
318 if (it == m_ZoneDirs.end())
319 return std::vector<ZoneFragment>();
324 void ConfigCompiler::RegisterZoneDir(const String& tag, const String& ppath, const String& zoneName)
330 boost::mutex::scoped_lock lock(m_ZoneDirsMutex);
331 m_ZoneDirs[zoneName].push_back(zf);
334 bool ConfigCompiler::HasZoneConfigAuthority(const String& zoneName)
336 std::vector<ZoneFragment> zoneDirs = m_ZoneDirs[zoneName];
338 bool empty = zoneDirs.empty();
341 std::vector<String> paths;
342 paths.reserve(zoneDirs.size());
343 for (const ZoneFragment& zf : zoneDirs) {
344 paths.push_back(zf.Path);
347 Log(LogNotice, "ConfigCompiler")
348 << "Registered authoritative config directories for zone '" << zoneName << "': " << Utility::NaturalJoin(paths);
355 bool ConfigCompiler::IsAbsolutePath(const String& path)
358 return (path.GetLength() > 0 && path[0] == '/');
360 return !PathIsRelative(path.CStr());