summaryrefslogtreecommitdiffstats
path: root/lib/remote/consolehandler.cpp
blob: f5a470a9aca096a57985269097a975544488ae2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#include "remote/configobjectslock.hpp"
#include "remote/consolehandler.hpp"
#include "remote/httputility.hpp"
#include "remote/filterutility.hpp"
#include "config/configcompiler.hpp"
#include "base/configtype.hpp"
#include "base/configwriter.hpp"
#include "base/scriptglobal.hpp"
#include "base/logger.hpp"
#include "base/serializer.hpp"
#include "base/timer.hpp"
#include "base/namespace.hpp"
#include "base/initialize.hpp"
#include "base/utility.hpp"
#include <boost/thread/once.hpp>
#include <set>

using namespace icinga;

REGISTER_URLHANDLER("/v1/console", ConsoleHandler);

static std::mutex l_QueryMutex;
static std::map<String, ApiScriptFrame> l_ApiScriptFrames;
static Timer::Ptr l_FrameCleanupTimer;
static std::mutex l_ApiScriptMutex;

static void ScriptFrameCleanupHandler()
{
	std::unique_lock<std::mutex> lock(l_ApiScriptMutex);

	std::vector<String> cleanup_keys;

	typedef std::pair<String, ApiScriptFrame> KVPair;

	for (const KVPair& kv : l_ApiScriptFrames) {
		if (kv.second.Seen < Utility::GetTime() - 1800)
			cleanup_keys.push_back(kv.first);
	}

	for (const String& key : cleanup_keys)
		l_ApiScriptFrames.erase(key);
}

static void EnsureFrameCleanupTimer()
{
	static boost::once_flag once = BOOST_ONCE_INIT;

	boost::call_once(once, []() {
		l_FrameCleanupTimer = Timer::Create();
		l_FrameCleanupTimer->OnTimerExpired.connect([](const Timer * const&) { ScriptFrameCleanupHandler(); });
		l_FrameCleanupTimer->SetInterval(30);
		l_FrameCleanupTimer->Start();
	});
}

bool ConsoleHandler::HandleRequest(
	AsioTlsStream& stream,
	const ApiUser::Ptr& user,
	boost::beast::http::request<boost::beast::http::string_body>& request,
	const Url::Ptr& url,
	boost::beast::http::response<boost::beast::http::string_body>& response,
	const Dictionary::Ptr& params,
	boost::asio::yield_context& yc,
	HttpServerConnection& server
)
{
	namespace http = boost::beast::http;

	if (url->GetPath().size() != 3)
		return false;

	if (request.method() != http::verb::post)
		return false;

	QueryDescription qd;

	String methodName = url->GetPath()[2];

	FilterUtility::CheckPermission(user, "console");

	String session = HttpUtility::GetLastParameter(params, "session");

	if (session.IsEmpty())
		session = Utility::NewUniqueID();

	String command = HttpUtility::GetLastParameter(params, "command");

	bool sandboxed = HttpUtility::GetLastParameter(params, "sandboxed");

	ConfigObjectsSharedLock lock (std::try_to_lock);

	if (!lock) {
		HttpUtility::SendJsonError(response, params, 503, "Icinga is reloading.");
		return true;
	}

	if (methodName == "execute-script")
		return ExecuteScriptHelper(request, response, params, command, session, sandboxed);
	else if (methodName == "auto-complete-script")
		return AutocompleteScriptHelper(request, response, params, command, session, sandboxed);

	HttpUtility::SendJsonError(response, params, 400, "Invalid method specified: " + methodName);
	return true;
}

bool ConsoleHandler::ExecuteScriptHelper(boost::beast::http::request<boost::beast::http::string_body>& request,
	boost::beast::http::response<boost::beast::http::string_body>& response,
	const Dictionary::Ptr& params, const String& command, const String& session, bool sandboxed)
{
	namespace http = boost::beast::http;

	Log(LogNotice, "Console")
		<< "Executing expression: " << command;

	EnsureFrameCleanupTimer();

	ApiScriptFrame& lsf = l_ApiScriptFrames[session];
	lsf.Seen = Utility::GetTime();

	if (!lsf.Locals)
		lsf.Locals = new Dictionary();

	String fileName = "<" + Convert::ToString(lsf.NextLine) + ">";
	lsf.NextLine++;

	lsf.Lines[fileName] = command;

	Dictionary::Ptr resultInfo;
	std::unique_ptr<Expression> expr;
	Value exprResult;

	try {
		expr = ConfigCompiler::CompileText(fileName, command);

		ScriptFrame frame(true);
		frame.Locals = lsf.Locals;
		frame.Self = lsf.Locals;
		frame.Sandboxed = sandboxed;

		exprResult = expr->Evaluate(frame);

		resultInfo = new Dictionary({
			{ "code", 200 },
			{ "status", "Executed successfully." },
			{ "result", Serialize(exprResult, 0) }
		});
	} catch (const ScriptError& ex) {
		DebugInfo di = ex.GetDebugInfo();

		std::ostringstream msgbuf;

		msgbuf << di.Path << ": " << lsf.Lines[di.Path] << "\n"
			<< String(di.Path.GetLength() + 2, ' ')
			<< String(di.FirstColumn, ' ') << String(di.LastColumn - di.FirstColumn + 1, '^') << "\n"
			<< ex.what() << "\n";

		resultInfo = new Dictionary({
			{ "code", 500 },
			{ "status", String(msgbuf.str()) },
			{ "incomplete_expression", ex.IsIncompleteExpression() },
			{ "debug_info", new Dictionary({
				{ "path", di.Path },
				{ "first_line", di.FirstLine },
				{ "first_column", di.FirstColumn },
				{ "last_line", di.LastLine },
				{ "last_column", di.LastColumn }
			}) }
		});
	}

	Dictionary::Ptr result = new Dictionary({
		{ "results", new Array({ resultInfo }) }
	});

	response.result(http::status::ok);
	HttpUtility::SendJsonBody(response, params, result);

	return true;
}

bool ConsoleHandler::AutocompleteScriptHelper(boost::beast::http::request<boost::beast::http::string_body>& request,
	boost::beast::http::response<boost::beast::http::string_body>& response,
	const Dictionary::Ptr& params, const String& command, const String& session, bool sandboxed)
{
	namespace http = boost::beast::http;

	Log(LogInformation, "Console")
		<< "Auto-completing expression: " << command;

	EnsureFrameCleanupTimer();

	ApiScriptFrame& lsf = l_ApiScriptFrames[session];
	lsf.Seen = Utility::GetTime();

	if (!lsf.Locals)
		lsf.Locals = new Dictionary();


	ScriptFrame frame(true);
	frame.Locals = lsf.Locals;
	frame.Self = lsf.Locals;
	frame.Sandboxed = sandboxed;

	Dictionary::Ptr result1 = new Dictionary({
		{ "code", 200 },
		{ "status", "Auto-completed successfully." },
		{ "suggestions", Array::FromVector(GetAutocompletionSuggestions(command, frame)) }
	});

	Dictionary::Ptr result = new Dictionary({
		{ "results", new Array({ result1 }) }
	});

	response.result(http::status::ok);
	HttpUtility::SendJsonBody(response, params, result);

	return true;
}

static void AddSuggestion(std::vector<String>& matches, const String& word, const String& suggestion)
{
	if (suggestion.Find(word) != 0)
		return;

	matches.push_back(suggestion);
}

static void AddSuggestions(std::vector<String>& matches, const String& word, const String& pword, bool withFields, const Value& value)
{
	String prefix;

	if (!pword.IsEmpty())
		prefix = pword + ".";

	if (value.IsObjectType<Dictionary>()) {
		Dictionary::Ptr dict = value;

		ObjectLock olock(dict);
		for (const Dictionary::Pair& kv : dict) {
			AddSuggestion(matches, word, prefix + kv.first);
		}
	}

	if (value.IsObjectType<Namespace>()) {
		Namespace::Ptr ns = value;

		ObjectLock olock(ns);
		for (const Namespace::Pair& kv : ns) {
			AddSuggestion(matches, word, prefix + kv.first);
		}
	}

	if (withFields) {
		Type::Ptr type = value.GetReflectionType();

		for (int i = 0; i < type->GetFieldCount(); i++) {
			Field field = type->GetFieldInfo(i);

			AddSuggestion(matches, word, prefix + field.Name);
		}

		while (type) {
			Object::Ptr prototype = type->GetPrototype();
			Dictionary::Ptr dict = dynamic_pointer_cast<Dictionary>(prototype);

			if (dict) {
				ObjectLock olock(dict);
				for (const Dictionary::Pair& kv : dict) {
					AddSuggestion(matches, word, prefix + kv.first);
				}
			}

			type = type->GetBaseType();
		}
	}
}

std::vector<String> ConsoleHandler::GetAutocompletionSuggestions(const String& word, ScriptFrame& frame)
{
	std::vector<String> matches;

	for (const String& keyword : ConfigWriter::GetKeywords()) {
		AddSuggestion(matches, word, keyword);
	}

	{
		ObjectLock olock(frame.Locals);
		for (const Dictionary::Pair& kv : frame.Locals) {
			AddSuggestion(matches, word, kv.first);
		}
	}

	{
		ObjectLock olock(ScriptGlobal::GetGlobals());
		for (const Namespace::Pair& kv : ScriptGlobal::GetGlobals()) {
			AddSuggestion(matches, word, kv.first);
		}
	}

	Namespace::Ptr systemNS = ScriptGlobal::Get("System");

	AddSuggestions(matches, word, "", false, systemNS);
	AddSuggestions(matches, word, "", true, systemNS->Get("Configuration"));
	AddSuggestions(matches, word, "", false, ScriptGlobal::Get("Types"));
	AddSuggestions(matches, word, "", false, ScriptGlobal::Get("Icinga"));

	String::SizeType cperiod = word.RFind(".");

	if (cperiod != String::NPos) {
		String pword = word.SubStr(0, cperiod);

		Value value;

		try {
			std::unique_ptr<Expression> expr = ConfigCompiler::CompileText("temp", pword);

			if (expr)
				value = expr->Evaluate(frame);

			AddSuggestions(matches, word, pword, true, value);
		} catch (...) { /* Ignore the exception */ }
	}

	return matches;
}