1 /******************************************************************************
3 * Copyright (C) 2012-2017 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 ******************************************************************************/
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"
45 static inline bool FindVarImportRef(ScriptFrame& frame, const String& name, Value *result, const DebugInfo& debugInfo = DebugInfo())
47 Array::Ptr imports = ScriptFrame::GetImports();
49 ObjectLock olock(imports);
50 for (const Value& import : imports) {
51 Object::Ptr obj = import;
52 if (obj->HasOwnField(name)) {
61 static inline bool FindVarImport(ScriptFrame& frame, const String& name, Value *result, const DebugInfo& debugInfo = DebugInfo())
65 if (FindVarImportRef(frame, name, &parent, debugInfo)) {
66 *result = GetField(parent, name, frame.Sandboxed, debugInfo);
73 static inline Value ConstructorCall(const Type::Ptr& type, const std::vector<Value>& args, const DebugInfo& debugInfo = DebugInfo())
75 if (type->GetName() == "String") {
78 else if (args.size() == 1)
79 return Convert::ToString(args[0]);
81 BOOST_THROW_EXCEPTION(ScriptError("Too many arguments for constructor."));
82 } else if (type->GetName() == "Number") {
85 else if (args.size() == 1)
86 return Convert::ToDouble(args[0]);
88 BOOST_THROW_EXCEPTION(ScriptError("Too many arguments for constructor."));
89 } else if (type->GetName() == "Boolean") {
92 else if (args.size() == 1)
93 return Convert::ToBool(args[0]);
95 BOOST_THROW_EXCEPTION(ScriptError("Too many arguments for constructor."));
96 } else if (args.size() == 1 && type->IsAssignableFrom(args[0].GetReflectionType()))
99 return type->Instantiate(args);
102 static inline Value FunctionCall(ScriptFrame& frame, const Value& self, const Function::Ptr& func, const std::vector<Value>& arguments)
104 if (!self.IsEmpty() || self.IsString())
105 return func->InvokeThis(self, arguments);
107 return func->Invoke(arguments);
111 static inline Value NewFunction(ScriptFrame& frame, const String& name, const std::vector<String>& argNames,
112 std::map<String, Expression *> *closedVars, const std::shared_ptr<Expression>& expression)
114 auto evaluatedClosedVars = EvaluateClosedVars(frame, closedVars);
116 auto wrapper = [argNames, evaluatedClosedVars, expression](const std::vector<Value>& arguments) {
117 if (arguments.size() < argNames.size())
118 BOOST_THROW_EXCEPTION(std::invalid_argument("Too few arguments for function"));
120 ScriptFrame *frame = ScriptFrame::GetCurrentFrame();
122 if (evaluatedClosedVars)
123 evaluatedClosedVars->CopyTo(frame->Locals);
125 for (std::vector<Value>::size_type i = 0; i < std::min(arguments.size(), argNames.size()); i++)
126 frame->Locals->Set(argNames[i], arguments[i]);
128 return expression->Evaluate(*frame);
131 return new Function(name, wrapper, argNames);
134 static inline Value NewApply(ScriptFrame& frame, const String& type, const String& target, const String& name, const std::shared_ptr<Expression>& filter,
135 const String& package, const String& fkvar, const String& fvvar, const std::shared_ptr<Expression>& fterm, std::map<String, Expression *> *closedVars,
136 bool ignoreOnError, const std::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
138 ApplyRule::AddRule(type, target, name, expression, filter, package, fkvar,
139 fvvar, fterm, ignoreOnError, debugInfo, EvaluateClosedVars(frame, closedVars));
144 static inline Value NewObject(ScriptFrame& frame, bool abstract, const Type::Ptr& type, const String& name, const std::shared_ptr<Expression>& filter,
145 const String& zone, const String& package, bool defaultTmpl, bool ignoreOnError, std::map<String, Expression *> *closedVars, const std::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
147 ConfigItemBuilder::Ptr item = new ConfigItemBuilder(debugInfo);
149 String checkName = name;
152 NameComposer *nc = dynamic_cast<NameComposer *>(type.get());
155 checkName = nc->MakeName(name, nullptr);
158 if (!checkName.IsEmpty()) {
159 ConfigItem::Ptr oldItem = ConfigItem::GetByTypeAndName(type, checkName);
162 std::ostringstream msgbuf;
163 msgbuf << "Object '" << name << "' of type '" << type->GetName() << "' re-defined: " << debugInfo << "; previous definition: " << oldItem->GetDebugInfo();
164 BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str(), debugInfo));
168 if (filter && !ObjectRule::IsValidSourceType(type->GetName())) {
169 std::ostringstream msgbuf;
170 msgbuf << "Object '" << name << "' of type '" << type->GetName() << "' must not have 'assign where' and 'ignore where' rules: " << debugInfo;
171 BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str(), debugInfo));
178 item->AddExpression(new ImportDefaultTemplatesExpression());
180 item->AddExpression(new OwnedExpression(expression));
181 item->SetAbstract(abstract);
182 item->SetScope(EvaluateClosedVars(frame, closedVars));
184 item->SetPackage(package);
185 item->SetFilter(filter);
186 item->SetDefaultTemplate(defaultTmpl);
187 item->SetIgnoreOnError(ignoreOnError);
188 item->Compile()->Register();
193 static inline ExpressionResult For(ScriptFrame& frame, const String& fkvar, const String& fvvar, const Value& value, Expression *expression, const DebugInfo& debugInfo = DebugInfo())
195 if (value.IsObjectType<Array>()) {
196 if (!fvvar.IsEmpty())
197 BOOST_THROW_EXCEPTION(ScriptError("Cannot use dictionary iterator for array.", debugInfo));
199 Array::Ptr arr = value;
201 for (Array::SizeType i = 0; i < arr->GetLength(); i++) {
202 frame.Locals->Set(fkvar, arr->Get(i));
203 ExpressionResult res = expression->Evaluate(frame);
204 CHECK_RESULT_LOOP(res);
206 } else if (value.IsObjectType<Dictionary>()) {
208 BOOST_THROW_EXCEPTION(ScriptError("Cannot use array iterator for dictionary.", debugInfo));
210 Dictionary::Ptr dict = value;
211 std::vector<String> keys;
214 ObjectLock olock(dict);
215 for (const Dictionary::Pair& kv : dict) {
216 keys.push_back(kv.first);
220 for (const String& key : keys) {
221 frame.Locals->Set(fkvar, key);
222 frame.Locals->Set(fvvar, dict->Get(key));
223 ExpressionResult res = expression->Evaluate(frame);
224 CHECK_RESULT_LOOP(res);
227 BOOST_THROW_EXCEPTION(ScriptError("Invalid type in for expression: " + value.GetTypeName(), debugInfo));
232 static inline Value GetField(const Value& context, const String& field, bool sandboxed = false, const DebugInfo& debugInfo = DebugInfo())
234 if (unlikely(context.IsEmpty() && !context.IsString()))
237 if (unlikely(!context.IsObject()))
238 return GetPrototypeField(context, field, true, debugInfo);
240 Object::Ptr object = context;
242 return object->GetFieldByName(field, sandboxed, debugInfo);
245 static inline void SetField(const Object::Ptr& context, const String& field, const Value& value, const DebugInfo& debugInfo = DebugInfo())
248 BOOST_THROW_EXCEPTION(ScriptError("Cannot set field '" + field + "' on a value that is not an object.", debugInfo));
250 return context->SetFieldByName(field, value, debugInfo);
254 static inline Dictionary::Ptr EvaluateClosedVars(ScriptFrame& frame, std::map<String, Expression *> *closedVars)
256 Dictionary::Ptr locals;
259 locals = new Dictionary();
261 typedef std::pair<String, Expression *> ClosedVar;
262 for (const ClosedVar& cvar : *closedVars) {
263 locals->Set(cvar.first, cvar.second->Evaluate(frame));