1 /******************************************************************************
3 * Copyright (C) 2012-2016 Icinga Development Team (https://www.icinga.org/) *
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 ******************************************************************************/
23 #include "config/i2-config.hpp"
24 #include "config/expression.hpp"
25 #include "config/configitembuilder.hpp"
26 #include "config/applyrule.hpp"
27 #include "config/objectrule.hpp"
28 #include "base/debuginfo.hpp"
29 #include "base/array.hpp"
30 #include "base/dictionary.hpp"
31 #include "base/function.hpp"
32 #include "base/scriptglobal.hpp"
33 #include "base/exception.hpp"
34 #include "base/convert.hpp"
35 #include "base/objectlock.hpp"
36 #include <boost/foreach.hpp>
37 #include <boost/smart_ptr/make_shared.hpp>
47 static inline Value Variable(ScriptFrame& frame, const String& name, const DebugInfo& debugInfo = DebugInfo())
50 if (frame.Locals && frame.Locals->Get(name, &value))
52 else if (frame.Self.IsObject() && frame.Locals != static_cast<Object::Ptr>(frame.Self) && HasField(frame.Self, name))
53 return GetField(frame.Self, name, frame.Sandboxed, debugInfo);
55 return ScriptGlobal::Get(name);
58 static inline Value CopyConstructorCall(const Type::Ptr& type, const Value& value, const DebugInfo& debugInfo = DebugInfo())
60 if (type->GetName() == "String")
61 return Convert::ToString(value);
62 else if (type->GetName() == "Number")
63 return Convert::ToDouble(value);
64 else if (type->GetName() == "Boolean")
65 return Convert::ToBool(value);
66 else if (!value.IsEmpty() && !type->IsAssignableFrom(value.GetReflectionType()))
67 BOOST_THROW_EXCEPTION(ScriptError("Invalid cast: Tried to cast object of type '" + value.GetReflectionType()->GetName() + "' to type '" + type->GetName() + "'", debugInfo));
72 static inline Value ConstructorCall(const Type::Ptr& type, const DebugInfo& debugInfo = DebugInfo())
74 if (type->GetName() == "String")
76 else if (type->GetName() == "Number")
78 else if (type->GetName() == "Boolean")
81 Object::Ptr object = type->Instantiate();
84 BOOST_THROW_EXCEPTION(ScriptError("Failed to instantiate object of type '" + type->GetName() + "'", debugInfo));
90 static inline Value FunctionCall(ScriptFrame& frame, const Value& self, const Function::Ptr& func, const std::vector<Value>& arguments)
94 if (!self.IsEmpty() || self.IsString())
97 return func->Invoke(arguments);
100 static inline Value NewFunction(ScriptFrame& frame, const std::vector<String>& args,
101 std::map<String, Expression *> *closedVars, const boost::shared_ptr<Expression>& expression)
103 return new Function(boost::bind(&FunctionWrapper, _1, args,
104 EvaluateClosedVars(frame, closedVars), expression));
107 static inline Value NewApply(ScriptFrame& frame, const String& type, const String& target, const String& name, const boost::shared_ptr<Expression>& filter,
108 const String& package, const String& fkvar, const String& fvvar, const boost::shared_ptr<Expression>& fterm, std::map<String, Expression *> *closedVars,
109 bool ignoreOnError, const boost::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
111 ApplyRule::AddRule(type, target, name, expression, filter, package, fkvar,
112 fvvar, fterm, ignoreOnError, debugInfo, EvaluateClosedVars(frame, closedVars));
117 static inline Value NewObject(ScriptFrame& frame, bool abstract, const String& type, const String& name, const boost::shared_ptr<Expression>& filter,
118 const String& zone, const String& package, bool ignoreOnError, std::map<String, Expression *> *closedVars, const boost::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
120 ConfigItemBuilder::Ptr item = new ConfigItemBuilder(debugInfo);
122 String checkName = name;
125 Type::Ptr ptype = Type::GetByName(type);
127 NameComposer *nc = dynamic_cast<NameComposer *>(ptype.get());
130 checkName = nc->MakeName(name, Dictionary::Ptr());
133 if (!checkName.IsEmpty()) {
134 ConfigItem::Ptr oldItem = ConfigItem::GetByTypeAndName(type, checkName);
137 std::ostringstream msgbuf;
138 msgbuf << "Object '" << name << "' of type '" << type << "' re-defined: " << debugInfo << "; previous definition: " << oldItem->GetDebugInfo();
139 BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str(), debugInfo));
146 item->AddExpression(new OwnedExpression(expression));
147 item->SetAbstract(abstract);
148 item->SetScope(EvaluateClosedVars(frame, closedVars));
150 item->SetPackage(package);
151 item->SetFilter(filter);
152 item->SetIgnoreOnError(ignoreOnError);
153 item->Compile()->Register();
158 static inline ExpressionResult For(ScriptFrame& frame, const String& fkvar, const String& fvvar, const Value& value, Expression *expression, const DebugInfo& debugInfo = DebugInfo())
160 if (value.IsObjectType<Array>()) {
161 if (!fvvar.IsEmpty())
162 BOOST_THROW_EXCEPTION(ScriptError("Cannot use dictionary iterator for array.", debugInfo));
164 Array::Ptr arr = value;
166 for (Array::SizeType i = 0; i < arr->GetLength(); i++) {
167 frame.Locals->Set(fkvar, arr->Get(i));
168 ExpressionResult res = expression->Evaluate(frame);
169 CHECK_RESULT_LOOP(res);
171 } else if (value.IsObjectType<Dictionary>()) {
173 BOOST_THROW_EXCEPTION(ScriptError("Cannot use array iterator for dictionary.", debugInfo));
175 Dictionary::Ptr dict = value;
176 std::vector<String> keys;
179 ObjectLock olock(dict);
180 BOOST_FOREACH(const Dictionary::Pair& kv, dict) {
181 keys.push_back(kv.first);
185 BOOST_FOREACH(const String& key, keys) {
186 frame.Locals->Set(fkvar, key);
187 frame.Locals->Set(fvvar, dict->Get(key));
188 ExpressionResult res = expression->Evaluate(frame);
189 CHECK_RESULT_LOOP(res);
192 BOOST_THROW_EXCEPTION(ScriptError("Invalid type in for expression: " + value.GetTypeName(), debugInfo));
197 static inline bool HasField(const Object::Ptr& context, const String& field)
199 Dictionary::Ptr dict = dynamic_pointer_cast<Dictionary>(context);
202 return dict->Contains(field);
204 Type::Ptr type = context->GetReflectionType();
209 return type->GetFieldId(field) != -1;
213 static inline Value GetPrototypeField(const Value& context, const String& field, bool not_found_error = true, const DebugInfo& debugInfo = DebugInfo())
215 Type::Ptr ctype = context.GetReflectionType();
216 Type::Ptr type = ctype;
219 Object::Ptr object = type->GetPrototype();
221 if (object && HasField(object, field))
222 return GetField(object, field, false, debugInfo);
224 type = type->GetBaseType();
228 BOOST_THROW_EXCEPTION(ScriptError("Invalid field access (for value of type '" + ctype->GetName() + "'): '" + field + "'", debugInfo));
233 static inline Value GetField(const Value& context, const String& field, bool sandboxed = false, const DebugInfo& debugInfo = DebugInfo())
235 if (context.IsEmpty() && !context.IsString())
238 if (!context.IsObject())
239 return GetPrototypeField(context, field, true, debugInfo);
241 Object::Ptr object = context;
243 Dictionary::Ptr dict = dynamic_pointer_cast<Dictionary>(object);
247 if (dict->Get(field, &value))
250 return GetPrototypeField(context, field, false, debugInfo);
253 Array::Ptr arr = dynamic_pointer_cast<Array>(object);
259 index = Convert::ToLong(field);
261 return GetPrototypeField(context, field, true, debugInfo);
264 if (index < 0 || index >= arr->GetLength())
265 BOOST_THROW_EXCEPTION(ScriptError("Array index '" + Convert::ToString(index) + "' is out of bounds.", debugInfo));
267 return arr->Get(index);
270 Type::Ptr type = object->GetReflectionType();
275 int fid = type->GetFieldId(field);
278 return GetPrototypeField(context, field, true, debugInfo);
281 Field fieldInfo = type->GetFieldInfo(fid);
283 if (fieldInfo.Attributes & FANoUserView)
284 BOOST_THROW_EXCEPTION(ScriptError("Accessing the field '" + field + "' for type '" + type->GetName() + "' is not allowed in sandbox mode."));
287 return object->GetField(fid);
290 static inline void SetField(const Object::Ptr& context, const String& field, const Value& value, const DebugInfo& debugInfo = DebugInfo())
293 BOOST_THROW_EXCEPTION(ScriptError("Cannot set field '" + field + "' on a value that is not an object.", debugInfo));
295 Dictionary::Ptr dict = dynamic_pointer_cast<Dictionary>(context);
298 dict->Set(field, value);
302 Array::Ptr arr = dynamic_pointer_cast<Array>(context);
305 int index = Convert::ToLong(field);
306 if (index >= arr->GetLength())
307 arr->Resize(index + 1);
308 arr->Set(index, value);
312 Type::Ptr type = context->GetReflectionType();
315 BOOST_THROW_EXCEPTION(ScriptError("Cannot set field on object.", debugInfo));
317 int fid = type->GetFieldId(field);
320 BOOST_THROW_EXCEPTION(ScriptError("Attribute '" + field + "' does not exist.", debugInfo));
323 context->SetField(fid, value);
324 } catch (const boost::bad_lexical_cast&) {
325 Field fieldInfo = type->GetFieldInfo(fid);
326 Type::Ptr ftype = Type::GetByName(fieldInfo.TypeName);
327 BOOST_THROW_EXCEPTION(ScriptError("Attribute '" + field + "' cannot be set to value of type '" + value.GetTypeName() + "', expected '" + ftype->GetName() + "'", debugInfo));
328 } catch (const std::bad_cast&) {
329 Field fieldInfo = type->GetFieldInfo(fid);
330 Type::Ptr ftype = Type::GetByName(fieldInfo.TypeName);
331 BOOST_THROW_EXCEPTION(ScriptError("Attribute '" + field + "' cannot be set to value of type '" + value.GetTypeName() + "', expected '" + ftype->GetName() + "'", debugInfo));
336 static inline Value FunctionWrapper(const std::vector<Value>& arguments,
337 const std::vector<String>& funcargs, const Dictionary::Ptr& closedVars, const boost::shared_ptr<Expression>& expr)
339 if (arguments.size() < funcargs.size())
340 BOOST_THROW_EXCEPTION(std::invalid_argument("Too few arguments for function"));
342 ScriptFrame *frame = ScriptFrame::GetCurrentFrame();
345 closedVars->CopyTo(frame->Locals);
347 for (std::vector<Value>::size_type i = 0; i < std::min(arguments.size(), funcargs.size()); i++)
348 frame->Locals->Set(funcargs[i], arguments[i]);
350 return expr->Evaluate(*frame);
353 static inline Dictionary::Ptr EvaluateClosedVars(ScriptFrame& frame, std::map<String, Expression *> *closedVars)
355 Dictionary::Ptr locals;
358 locals = new Dictionary();
360 typedef std::pair<String, Expression *> ClosedVar;
361 BOOST_FOREACH(const ClosedVar& cvar, *closedVars) {
362 locals->Set(cvar.first, cvar.second->Evaluate(frame));