]> granicus.if.org Git - icinga2/blob - lib/config/configcompiler.cpp
Merge pull request #5868 from Icinga/feature/expression-ptr
[icinga2] / lib / config / configcompiler.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2017 Icinga Development Team (https://www.icinga.com/)  *
4  *                                                                            *
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.                     *
9  *                                                                            *
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.                               *
14  *                                                                            *
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  ******************************************************************************/
19
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"
27 #include <fstream>
28
29 using namespace icinga;
30
31 std::vector<String> ConfigCompiler::m_IncludeSearchDirs;
32 boost::mutex ConfigCompiler::m_ZoneDirsMutex;
33 std::map<String, std::vector<ZoneFragment> > ConfigCompiler::m_ZoneDirs;
34
35 /**
36  * Constructor for the ConfigCompiler class.
37  *
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.
42  */
43 ConfigCompiler::ConfigCompiler(const String& path, std::istream *input,
44     const String& zone, const String& package)
45         : m_Path(path), m_Input(input), m_Zone(zone), m_Package(package),
46           m_Eof(false), m_OpenBraces(0)
47 {
48         InitializeScanner();
49 }
50
51 /**
52  * Destructor for the ConfigCompiler class.
53  */
54 ConfigCompiler::~ConfigCompiler(void)
55 {
56         DestroyScanner();
57 }
58
59 /**
60  * Reads data from the input stream. Used internally by the lexer.
61  *
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.
65  */
66 size_t ConfigCompiler::ReadInput(char *buffer, size_t max_size)
67 {
68         m_Input->read(buffer, max_size);
69         return static_cast<size_t>(m_Input->gcount());
70 }
71
72 /**
73  * Retrieves the scanner object.
74  *
75  * @returns The scanner object.
76  */
77 void *ConfigCompiler::GetScanner(void) const
78 {
79         return m_Scanner;
80 }
81
82 /**
83  * Retrieves the path for the input file.
84  *
85  * @returns The path.
86  */
87 const char *ConfigCompiler::GetPath(void) const
88 {
89         return m_Path.CStr();
90 }
91
92 void ConfigCompiler::SetZone(const String& zone)
93 {
94         m_Zone = zone;
95 }
96
97 String ConfigCompiler::GetZone(void) const
98 {
99         return m_Zone;
100 }
101
102 void ConfigCompiler::SetPackage(const String& package)
103 {
104         m_Package = package;
105 }
106
107 String ConfigCompiler::GetPackage(void) const
108 {
109         return m_Package;
110 }
111
112 void ConfigCompiler::CollectIncludes(std::vector<std::unique_ptr<Expression> >& expressions,
113     const String& file, const String& zone, const String& package)
114 {
115         try {
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);
121         }
122 }
123
124 /**
125  * Handles an include directive.
126  *
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.
131  */
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)
134 {
135         String upath;
136
137         if (search || (IsAbsolutePath(path)))
138                 upath = path;
139         else
140                 upath = relativeBase + "/" + path;
141
142         String includePath = upath;
143
144         if (search) {
145                 for (const String& dir : m_IncludeSearchDirs) {
146                         String spath = dir + "/" + path;
147
148                         if (Utility::PathExists(spath)) {
149                                 includePath = spath;
150                                 break;
151                         }
152                 }
153         }
154
155         std::vector<std::unique_ptr<Expression> > expressions;
156
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));
161         }
162
163         std::unique_ptr<DictExpression> expr{new DictExpression(std::move(expressions))};
164         expr->MakeInline();
165         return std::move(expr);
166 }
167
168 /**
169  * Handles recursive includes.
170  *
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.
175  */
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&)
178 {
179         String ppath;
180
181         if (IsAbsolutePath(path))
182                 ppath = path;
183         else
184                 ppath = relativeBase + "/" + path;
185
186         std::vector<std::unique_ptr<Expression> > expressions;
187         Utility::GlobRecursive(ppath, pattern, std::bind(&ConfigCompiler::CollectIncludes, std::ref(expressions), _1, zone, package), GlobFile);
188
189         std::unique_ptr<DictExpression> dict{new DictExpression(std::move(expressions))};
190         dict->MakeInline();
191         return std::move(dict);
192 }
193
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)
195 {
196         String zoneName = Utility::BaseName(path);
197
198         String ppath;
199
200         if (IsAbsolutePath(path))
201                 ppath = path;
202         else
203                 ppath = relativeBase + "/" + path;
204
205         RegisterZoneDir(tag, ppath, zoneName);
206
207         Utility::GlobRecursive(ppath, pattern, std::bind(&ConfigCompiler::CollectIncludes, std::ref(expressions), _1, zoneName, package), GlobFile);
208 }
209
210 /**
211  * Handles zone includes.
212  *
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.
218  */
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&)
221 {
222         String ppath;
223         String newRelativeBase = relativeBase;
224
225         if (IsAbsolutePath(path))
226                 ppath = path;
227         else {
228                 ppath = relativeBase + "/" + path;
229                 newRelativeBase = ".";
230         }
231
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)));
235 }
236
237 /**
238  * Compiles a stream.
239  *
240  * @param path A name identifying the stream.
241  * @param stream The input stream.
242  * @returns Configuration items.
243  */
244 std::unique_ptr<Expression> ConfigCompiler::CompileStream(const String& path,
245     std::istream *stream, const String& zone, const String& package)
246 {
247         CONTEXT("Compiling configuration stream with name '" + path + "'");
248
249         stream->exceptions(std::istream::badbit);
250
251         ConfigCompiler ctx(path, stream, zone, package);
252
253         try {
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));
259         }
260 }
261
262 /**
263  * Compiles a file.
264  *
265  * @param path The path.
266  * @returns Configuration items.
267  */
268 std::unique_ptr<Expression> ConfigCompiler::CompileFile(const String& path, const String& zone,
269     const String& package)
270 {
271         CONTEXT("Compiling configuration file '" + path + "'");
272
273         std::ifstream stream(path.CStr(), std::ifstream::in);
274
275         if (!stream)
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));
280
281         Log(LogNotice, "ConfigCompiler")
282             << "Compiling config file: " << path;
283
284         return CompileStream(path, &stream, zone, package);
285 }
286
287 /**
288  * Compiles a snippet of text.
289  *
290  * @param path A name identifying the text.
291  * @param text The text.
292  * @returns Configuration items.
293  */
294 std::unique_ptr<Expression> ConfigCompiler::CompileText(const String& path, const String& text,
295     const String& zone, const String& package)
296 {
297         std::stringstream stream(text);
298         return CompileStream(path, &stream, zone, package);
299 }
300
301 /**
302  * Adds a directory to the list of include search dirs.
303  *
304  * @param dir The new dir.
305  */
306 void ConfigCompiler::AddIncludeSearchDir(const String& dir)
307 {
308         Log(LogInformation, "ConfigCompiler")
309             << "Adding include search dir: " << dir;
310
311         m_IncludeSearchDirs.push_back(dir);
312 }
313
314 std::vector<ZoneFragment> ConfigCompiler::GetZoneDirs(const String& zone)
315 {
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>();
320         else
321                 return it->second;
322 }
323
324 void ConfigCompiler::RegisterZoneDir(const String& tag, const String& ppath, const String& zoneName)
325 {
326         ZoneFragment zf;
327         zf.Tag = tag;
328         zf.Path = ppath;
329
330         boost::mutex::scoped_lock lock(m_ZoneDirsMutex);
331         m_ZoneDirs[zoneName].push_back(zf);
332 }
333
334 bool ConfigCompiler::HasZoneConfigAuthority(const String& zoneName)
335 {
336         std::vector<ZoneFragment> zoneDirs = m_ZoneDirs[zoneName];
337
338         bool empty = zoneDirs.empty();
339
340         if (!empty) {
341                 std::vector<String> paths;
342                 for (const ZoneFragment& zf : zoneDirs) {
343                         paths.push_back(zf.Path);
344                 }
345
346                 Log(LogNotice, "ConfigCompiler")
347                     << "Registered authoritative config directories for zone '" << zoneName << "': " << Utility::NaturalJoin(paths);
348         }
349
350         return !empty;
351 }
352
353
354 bool ConfigCompiler::IsAbsolutePath(const String& path)
355 {
356 #ifndef _WIN32
357         return (path.GetLength() > 0 && path[0] == '/');
358 #else /* _WIN32 */
359         return !PathIsRelative(path.CStr());
360 #endif /* _WIN32 */
361 }
362