1 /*
2 ** Zabbix
3 ** Copyright (C) 2001-2021 Zabbix SIA
4 **
5 ** This program is free software; you can redistribute it and/or modify
6 ** it under the terms of the GNU General Public License as published by
7 ** the Free Software Foundation; either version 2 of the License, or
8 ** (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
17 ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 **/
19 
20 #include "checks_script.h"
21 #include "zbxembed.h"
22 #include "log.h"
23 
24 static zbx_es_t	es_engine;
25 
scriptitem_es_engine_init(void)26 void	scriptitem_es_engine_init(void)
27 {
28 	zbx_es_init(&es_engine);
29 }
30 
scriptitem_es_engine_destroy(void)31 void	scriptitem_es_engine_destroy(void)
32 {
33 	if (SUCCEED == zbx_es_is_env_initialized(&es_engine))
34 		zbx_es_destroy(&es_engine);
35 }
36 
get_value_script(DC_ITEM * item,AGENT_RESULT * result)37 int	get_value_script(DC_ITEM *item, AGENT_RESULT *result)
38 {
39 	char		*error = NULL, *script_bin = NULL, *output = NULL;
40 	int		script_bin_sz, timeout_seconds, ret = NOTSUPPORTED;
41 
42 	if (FAIL == is_time_suffix(item->timeout, &timeout_seconds, strlen(item->timeout)))
43 	{
44 		SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Invalid timeout: %s", item->timeout));
45 		return ret;
46 	}
47 
48 	if (SUCCEED != zbx_es_is_env_initialized(&es_engine) && SUCCEED != zbx_es_init_env(&es_engine, &error))
49 	{
50 		SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot initialize scripting environment: %s", error));
51 		return ret;
52 	}
53 
54 	if (SUCCEED != zbx_es_compile(&es_engine, item->params, &script_bin, &script_bin_sz, &error))
55 	{
56 		SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot compile script: %s", error));
57 		goto err;
58 	}
59 
60 	zbx_es_set_timeout(&es_engine, timeout_seconds);
61 
62 	if (SUCCEED != zbx_es_execute(&es_engine, NULL, script_bin, script_bin_sz, item->script_params, &output,
63 			&error))
64 	{
65 		SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot execute script: %s", error));
66 		goto err;
67 	}
68 
69 	ret = SUCCEED;
70 	SET_TEXT_RESULT(result, NULL != output ? output : zbx_strdup(NULL, ""));
71 err:
72 	if (SUCCEED == zbx_es_fatal_error(&es_engine))
73 	{
74 		char	*errlog = NULL;
75 
76 		if (SUCCEED != zbx_es_destroy_env(&es_engine, &errlog))
77 		{
78 			zabbix_log(LOG_LEVEL_WARNING,
79 					"Cannot destroy embedded scripting engine environment: %s", errlog);
80 			zbx_free(errlog);
81 		}
82 	}
83 
84 	zbx_free(script_bin);
85 	zbx_free(error);
86 
87 	return ret;
88 }
89