]> granicus.if.org Git - icinga2/blob - lib/config/configcompiler.cpp
Fix: include_recursive should gracefully handle inaccessible files
[icinga2] / lib / config / configcompiler.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2016 Icinga Development Team (https://www.icinga.org/)  *
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 #include <boost/foreach.hpp>
29
30 using namespace icinga;
31
32 std::vector<String> ConfigCompiler::m_IncludeSearchDirs;
33 boost::mutex ConfigCompiler::m_ZoneDirsMutex;
34 std::map<String, std::vector<ZoneFragment> > ConfigCompiler::m_ZoneDirs;
35
36 /**
37  * Constructor for the ConfigCompiler class.
38  *
39  * @param path The path of the configuration file (or another name that
40  *             identifies the source of the configuration text).
41  * @param input Input stream for the configuration file.
42  * @param zone The zone.
43  */
44 ConfigCompiler::ConfigCompiler(const String& path, std::istream *input,
45     const String& zone, const String& package)
46         : m_Path(path), m_Input(input), m_Zone(zone), m_Package(package),
47           m_Eof(false), m_OpenBraces(0)
48 {
49         InitializeScanner();
50 }
51
52 /**
53  * Destructor for the ConfigCompiler class.
54  */
55 ConfigCompiler::~ConfigCompiler(void)
56 {
57         DestroyScanner();
58 }
59
60 /**
61  * Reads data from the input stream. Used internally by the lexer.
62  *
63  * @param buffer Where to store data.
64  * @param max_size The maximum number of bytes to read from the stream.
65  * @returns The actual number of bytes read.
66  */
67 size_t ConfigCompiler::ReadInput(char *buffer, size_t max_size)
68 {
69         m_Input->read(buffer, max_size);
70         return static_cast<size_t>(m_Input->gcount());
71 }
72
73 /**
74  * Retrieves the scanner object.
75  *
76  * @returns The scanner object.
77  */
78 void *ConfigCompiler::GetScanner(void) const
79 {
80         return m_Scanner;
81 }
82
83 /**
84  * Retrieves the path for the input file.
85  *
86  * @returns The path.
87  */
88 const char *ConfigCompiler::GetPath(void) const
89 {
90         return m_Path.CStr();
91 }
92
93 void ConfigCompiler::SetZone(const String& zone)
94 {
95         m_Zone = zone;
96 }
97
98 String ConfigCompiler::GetZone(void) const
99 {
100         return m_Zone;
101 }
102
103 void ConfigCompiler::SetPackage(const String& package)
104 {
105         m_Package = package;
106 }
107
108 String ConfigCompiler::GetPackage(void) const
109 {
110         return m_Package;
111 }
112
113 void ConfigCompiler::CollectIncludes(std::vector<Expression *>& expressions,
114     const String& file, const String& zone, const String& package)
115 {
116         try {
117                 Expression *expr = CompileFile(file, zone, package);
118                 expressions.push_back(expr);
119         } catch (const std::exception& ex) {
120                 Log(LogWarning, "ConfigCompiler")
121                     << "Cannot compile file '"
122                     << file << "': " << DiagnosticInformation(ex);
123         }
124 }
125
126 /**
127  * Handles an include directive.
128  *
129  * @param relativeBath The path this include is relative to.
130  * @param path The path from the include directive.
131  * @param search Whether to search global include dirs.
132  * @param debuginfo Debug information.
133  */
134 Expression *ConfigCompiler::HandleInclude(const String& relativeBase, const String& path,
135     bool search, const String& zone, const String& package, const DebugInfo& debuginfo)
136 {
137         String upath;
138
139         if (search || (path.GetLength() > 0 && path[0] == '/'))
140                 upath = path;
141         else
142                 upath = relativeBase + "/" + path;
143
144         String includePath = upath;
145
146         if (search) {
147                 BOOST_FOREACH(const String& dir, m_IncludeSearchDirs) {
148                         String spath = dir + "/" + path;
149
150                         if (Utility::PathExists(spath)) {
151                                 includePath = spath;
152                                 break;
153                         }
154                 }
155         }
156
157         std::vector<Expression *> expressions;
158
159         if (!Utility::Glob(includePath, boost::bind(&ConfigCompiler::CollectIncludes, boost::ref(expressions), _1, zone, package), GlobFile) && includePath.FindFirstOf("*?") == String::NPos) {
160                 std::ostringstream msgbuf;
161                 msgbuf << "Include file '" + path + "' does not exist";
162                 BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str(), debuginfo));
163         }
164
165         DictExpression *expr = new DictExpression(expressions);
166         expr->MakeInline();
167         return expr;
168 }
169
170 /**
171  * Handles recursive includes.
172  *
173  * @param relativeBase The path this include is relative to.
174  * @param path The directory path.
175  * @param pattern The file pattern.
176  * @param debuginfo Debug information.
177  */
178 Expression *ConfigCompiler::HandleIncludeRecursive(const String& relativeBase, const String& path,
179     const String& pattern, const String& zone, const String& package, const DebugInfo&)
180 {
181         String ppath;
182
183         if (path.GetLength() > 0 && path[0] == '/')
184                 ppath = path;
185         else
186                 ppath = relativeBase + "/" + path;
187
188         std::vector<Expression *> expressions;
189         Utility::GlobRecursive(ppath, pattern, boost::bind(&ConfigCompiler::CollectIncludes, boost::ref(expressions), _1, zone, package), GlobFile);
190
191         DictExpression *dict = new DictExpression(expressions);
192         dict->MakeInline();
193         return dict;
194 }
195
196 void ConfigCompiler::HandleIncludeZone(const String& relativeBase, const String& tag, const String& path, const String& pattern, const String& package, std::vector<Expression *>& expressions)
197 {
198         String zoneName = Utility::BaseName(path);
199
200         String ppath;
201
202         if (path.GetLength() > 0 && path[0] == '/')
203                 ppath = path;
204         else
205                 ppath = relativeBase + "/" + path;
206
207         RegisterZoneDir(tag, ppath, zoneName);
208
209         Utility::GlobRecursive(ppath, pattern, boost::bind(&ConfigCompiler::CollectIncludes, boost::ref(expressions), _1, zoneName, package), GlobFile);
210 }
211
212 /**
213  * Handles zone includes.
214  *
215  * @param relativeBase The path this include is relative to.
216  * @param tag The tag name.
217  * @param path The directory path.
218  * @param pattern The file pattern.
219  * @param debuginfo Debug information.
220  */
221 Expression *ConfigCompiler::HandleIncludeZones(const String& relativeBase, const String& tag,
222     const String& path, const String& pattern, const String& package, const DebugInfo&)
223 {
224         String ppath;
225         String newRelativeBase = relativeBase;
226
227         if (path.GetLength() > 0 && path[0] == '/')
228                 ppath = path;
229         else {
230                 ppath = relativeBase + "/" + path;
231                 newRelativeBase = ".";
232         }
233
234         std::vector<Expression *> expressions;
235         Utility::Glob(ppath + "/*", boost::bind(&ConfigCompiler::HandleIncludeZone, newRelativeBase, tag, _1, pattern, package, boost::ref(expressions)), GlobDirectory);
236         return new DictExpression(expressions);
237 }
238
239 /**
240  * Compiles a stream.
241  *
242  * @param path A name identifying the stream.
243  * @param stream The input stream.
244  * @returns Configuration items.
245  */
246 Expression *ConfigCompiler::CompileStream(const String& path,
247     std::istream *stream, const String& zone, const String& package)
248 {
249         CONTEXT("Compiling configuration stream with name '" + path + "'");
250
251         stream->exceptions(std::istream::badbit);
252
253         ConfigCompiler ctx(path, stream, zone, package);
254
255         try {
256                 return ctx.Compile();
257         } catch (const ScriptError& ex) {
258                 return new ThrowExpression(MakeLiteral(ex.what()), ex.IsIncompleteExpression(), ex.GetDebugInfo());
259         } catch (const std::exception& ex) {
260                 return new ThrowExpression(MakeLiteral(DiagnosticInformation(ex)), false);
261         }
262 }
263
264 /**
265  * Compiles a file.
266  *
267  * @param path The path.
268  * @returns Configuration items.
269  */
270 Expression *ConfigCompiler::CompileFile(const String& path, const String& zone,
271     const String& package)
272 {
273         CONTEXT("Compiling configuration file '" + path + "'");
274
275         std::ifstream stream(path.CStr(), std::ifstream::in);
276
277         if (!stream)
278                 BOOST_THROW_EXCEPTION(posix_error()
279                         << boost::errinfo_api_function("std::ifstream::open")
280                         << boost::errinfo_errno(errno)
281                         << boost::errinfo_file_name(path));
282
283         Log(LogInformation, "ConfigCompiler")
284             << "Compiling config file: " << path;
285
286         return CompileStream(path, &stream, zone, package);
287 }
288
289 /**
290  * Compiles a snippet of text.
291  *
292  * @param path A name identifying the text.
293  * @param text The text.
294  * @returns Configuration items.
295  */
296 Expression *ConfigCompiler::CompileText(const String& path, const String& text,
297     const String& zone, const String& package)
298 {
299         std::stringstream stream(text);
300         return CompileStream(path, &stream, zone, package);
301 }
302
303 /**
304  * Adds a directory to the list of include search dirs.
305  *
306  * @param dir The new dir.
307  */
308 void ConfigCompiler::AddIncludeSearchDir(const String& dir)
309 {
310         Log(LogInformation, "ConfigCompiler")
311             << "Adding include search dir: " << dir;
312
313         m_IncludeSearchDirs.push_back(dir);
314 }
315
316 std::vector<ZoneFragment> ConfigCompiler::GetZoneDirs(const String& zone)
317 {
318         boost::mutex::scoped_lock lock(m_ZoneDirsMutex);
319         std::map<String, std::vector<ZoneFragment> >::const_iterator it = m_ZoneDirs.find(zone);
320         if (it == m_ZoneDirs.end())
321                 return std::vector<ZoneFragment>();
322         else
323                 return it->second;
324 }
325
326 void ConfigCompiler::RegisterZoneDir(const String& tag, const String& ppath, const String& zoneName)
327 {
328         ZoneFragment zf;
329         zf.Tag = tag;
330         zf.Path = ppath;
331
332         boost::mutex::scoped_lock lock(m_ZoneDirsMutex);
333         m_ZoneDirs[zoneName].push_back(zf);
334 }
335
336 bool ConfigCompiler::HasZoneConfigAuthority(const String& zoneName)
337 {
338         std::vector<ZoneFragment> zoneDirs = m_ZoneDirs[zoneName];
339
340         bool empty = zoneDirs.empty();
341
342         if (!empty) {
343                 std::vector<String> paths;
344                 BOOST_FOREACH(const ZoneFragment& zf, zoneDirs) {
345                         paths.push_back(zf.Path);
346                 }
347
348                 Log(LogNotice, "ConfigCompiler")
349                     << "Registered authoritative config directories for zone '" << zoneName << "': " << Utility::NaturalJoin(paths);
350         }
351
352         return !empty;
353 }
354