]> granicus.if.org Git - icinga2/blob - lib/config/configcompiler.cpp
Merge pull request #5042 from mbrgm/upgrade-docs-link
[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<Expression *>& expressions,
113     const String& file, const String& zone, const String& package)
114 {
115         try {
116                 Expression *expr = CompileFile(file, zone, package);
117                 expressions.push_back(expr);
118         } catch (const std::exception& ex) {
119                 Log(LogWarning, "ConfigCompiler")
120                     << "Cannot compile file '"
121                     << file << "': " << DiagnosticInformation(ex);
122         }
123 }
124
125 /**
126  * Handles an include directive.
127  *
128  * @param relativeBath The path this include is relative to.
129  * @param path The path from the include directive.
130  * @param search Whether to search global include dirs.
131  * @param debuginfo Debug information.
132  */
133 Expression *ConfigCompiler::HandleInclude(const String& relativeBase, const String& path,
134     bool search, const String& zone, const String& package, const DebugInfo& debuginfo)
135 {
136         String upath;
137
138         if (search || (IsAbsolutePath(path)))
139                 upath = path;
140         else
141                 upath = relativeBase + "/" + path;
142
143         String includePath = upath;
144
145         if (search) {
146                 for (const String& dir : m_IncludeSearchDirs) {
147                         String spath = dir + "/" + path;
148
149                         if (Utility::PathExists(spath)) {
150                                 includePath = spath;
151                                 break;
152                         }
153                 }
154         }
155
156         std::vector<Expression *> expressions;
157
158         if (!Utility::Glob(includePath, boost::bind(&ConfigCompiler::CollectIncludes, boost::ref(expressions), _1, zone, package), GlobFile) && includePath.FindFirstOf("*?") == String::NPos) {
159                 std::ostringstream msgbuf;
160                 msgbuf << "Include file '" + path + "' does not exist";
161                 BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str(), debuginfo));
162         }
163
164         DictExpression *expr = new DictExpression(expressions);
165         expr->MakeInline();
166         return expr;
167 }
168
169 /**
170  * Handles recursive includes.
171  *
172  * @param relativeBase The path this include is relative to.
173  * @param path The directory path.
174  * @param pattern The file pattern.
175  * @param debuginfo Debug information.
176  */
177 Expression *ConfigCompiler::HandleIncludeRecursive(const String& relativeBase, const String& path,
178     const String& pattern, const String& zone, const String& package, const DebugInfo&)
179 {
180         String ppath;
181
182         if (IsAbsolutePath(path))
183                 ppath = path;
184         else
185                 ppath = relativeBase + "/" + path;
186
187         std::vector<Expression *> expressions;
188         Utility::GlobRecursive(ppath, pattern, boost::bind(&ConfigCompiler::CollectIncludes, boost::ref(expressions), _1, zone, package), GlobFile);
189
190         DictExpression *dict = new DictExpression(expressions);
191         dict->MakeInline();
192         return dict;
193 }
194
195 void ConfigCompiler::HandleIncludeZone(const String& relativeBase, const String& tag, const String& path, const String& pattern, const String& package, std::vector<Expression *>& expressions)
196 {
197         String zoneName = Utility::BaseName(path);
198
199         String ppath;
200
201         if (IsAbsolutePath(path))
202                 ppath = path;
203         else
204                 ppath = relativeBase + "/" + path;
205
206         RegisterZoneDir(tag, ppath, zoneName);
207
208         Utility::GlobRecursive(ppath, pattern, boost::bind(&ConfigCompiler::CollectIncludes, boost::ref(expressions), _1, zoneName, package), GlobFile);
209 }
210
211 /**
212  * Handles zone includes.
213  *
214  * @param relativeBase The path this include is relative to.
215  * @param tag The tag name.
216  * @param path The directory path.
217  * @param pattern The file pattern.
218  * @param debuginfo Debug information.
219  */
220 Expression *ConfigCompiler::HandleIncludeZones(const String& relativeBase, const String& tag,
221     const String& path, const String& pattern, const String& package, const DebugInfo&)
222 {
223         String ppath;
224         String newRelativeBase = relativeBase;
225
226         if (IsAbsolutePath(path))
227                 ppath = path;
228         else {
229                 ppath = relativeBase + "/" + path;
230                 newRelativeBase = ".";
231         }
232
233         std::vector<Expression *> expressions;
234         Utility::Glob(ppath + "/*", boost::bind(&ConfigCompiler::HandleIncludeZone, newRelativeBase, tag, _1, pattern, package, boost::ref(expressions)), GlobDirectory);
235         return new DictExpression(expressions);
236 }
237
238 /**
239  * Compiles a stream.
240  *
241  * @param path A name identifying the stream.
242  * @param stream The input stream.
243  * @returns Configuration items.
244  */
245 Expression *ConfigCompiler::CompileStream(const String& path,
246     std::istream *stream, const String& zone, const String& package)
247 {
248         CONTEXT("Compiling configuration stream with name '" + path + "'");
249
250         stream->exceptions(std::istream::badbit);
251
252         ConfigCompiler ctx(path, stream, zone, package);
253
254         try {
255                 return ctx.Compile();
256         } catch (const ScriptError& ex) {
257                 return new ThrowExpression(MakeLiteral(ex.what()), ex.IsIncompleteExpression(), ex.GetDebugInfo());
258         } catch (const std::exception& ex) {
259                 return new ThrowExpression(MakeLiteral(DiagnosticInformation(ex)), false);
260         }
261 }
262
263 /**
264  * Compiles a file.
265  *
266  * @param path The path.
267  * @returns Configuration items.
268  */
269 Expression *ConfigCompiler::CompileFile(const String& path, const String& zone,
270     const String& package)
271 {
272         CONTEXT("Compiling configuration file '" + path + "'");
273
274         std::ifstream stream(path.CStr(), std::ifstream::in);
275
276         if (!stream)
277                 BOOST_THROW_EXCEPTION(posix_error()
278                         << boost::errinfo_api_function("std::ifstream::open")
279                         << boost::errinfo_errno(errno)
280                         << boost::errinfo_file_name(path));
281
282         Log(LogNotice, "ConfigCompiler")
283             << "Compiling config file: " << path;
284
285         return CompileStream(path, &stream, zone, package);
286 }
287
288 /**
289  * Compiles a snippet of text.
290  *
291  * @param path A name identifying the text.
292  * @param text The text.
293  * @returns Configuration items.
294  */
295 Expression *ConfigCompiler::CompileText(const String& path, const String& text,
296     const String& zone, const String& package)
297 {
298         std::stringstream stream(text);
299         return CompileStream(path, &stream, zone, package);
300 }
301
302 /**
303  * Adds a directory to the list of include search dirs.
304  *
305  * @param dir The new dir.
306  */
307 void ConfigCompiler::AddIncludeSearchDir(const String& dir)
308 {
309         Log(LogInformation, "ConfigCompiler")
310             << "Adding include search dir: " << dir;
311
312         m_IncludeSearchDirs.push_back(dir);
313 }
314
315 std::vector<ZoneFragment> ConfigCompiler::GetZoneDirs(const String& zone)
316 {
317         boost::mutex::scoped_lock lock(m_ZoneDirsMutex);
318         auto it = m_ZoneDirs.find(zone);
319         if (it == m_ZoneDirs.end())
320                 return std::vector<ZoneFragment>();
321         else
322                 return it->second;
323 }
324
325 void ConfigCompiler::RegisterZoneDir(const String& tag, const String& ppath, const String& zoneName)
326 {
327         ZoneFragment zf;
328         zf.Tag = tag;
329         zf.Path = ppath;
330
331         boost::mutex::scoped_lock lock(m_ZoneDirsMutex);
332         m_ZoneDirs[zoneName].push_back(zf);
333 }
334
335 bool ConfigCompiler::HasZoneConfigAuthority(const String& zoneName)
336 {
337         std::vector<ZoneFragment> zoneDirs = m_ZoneDirs[zoneName];
338
339         bool empty = zoneDirs.empty();
340
341         if (!empty) {
342                 std::vector<String> paths;
343                 for (const ZoneFragment& zf : zoneDirs) {
344                         paths.push_back(zf.Path);
345                 }
346
347                 Log(LogNotice, "ConfigCompiler")
348                     << "Registered authoritative config directories for zone '" << zoneName << "': " << Utility::NaturalJoin(paths);
349         }
350
351         return !empty;
352 }
353
354
355 bool ConfigCompiler::IsAbsolutePath(const String& path)
356 {
357 #ifndef _WIN32
358         return (path.GetLength() > 0 && path[0] == '/');
359 #else /* _WIN32 */
360         return !PathIsRelative(path.CStr());
361 #endif /* _WIN32 */
362 }
363