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 "sysinfo.h"
21 #include "log.h"
22
23 ZBX_METRIC parameter_hostname =
24 /* KEY FLAG FUNCTION TEST PARAMETERS */
25 {"system.hostname", CF_HAVEPARAMS, SYSTEM_HOSTNAME, NULL};
26
SYSTEM_HOSTNAME(AGENT_REQUEST * request,AGENT_RESULT * result)27 int SYSTEM_HOSTNAME(AGENT_REQUEST *request, AGENT_RESULT *result)
28 {
29 DWORD dwSize = 256;
30 wchar_t computerName[256];
31 char *type, buffer[256];
32 int netbios;
33
34 if (1 < request->nparam)
35 {
36 SET_MSG_RESULT(result, zbx_strdup(NULL, "Too many parameters."));
37 return SYSINFO_RET_FAIL;
38 }
39
40 type = get_rparam(request, 0);
41
42 if (NULL == type || '\0' == *type || 0 == strcmp(type, "netbios"))
43 netbios = 1;
44 else if (0 == strcmp(type, "host"))
45 netbios = 0;
46 else
47 {
48 SET_MSG_RESULT(result, zbx_strdup(NULL, "Invalid first parameter."));
49 return SYSINFO_RET_FAIL;
50 }
51
52 if (1 == netbios)
53 {
54 /* Buffer size is chosen large enough to contain any DNS name, not just MAX_COMPUTERNAME_LENGTH + 1 */
55 /* characters. MAX_COMPUTERNAME_LENGTH is usually less than 32, but it varies among systems, so we */
56 /* cannot use the constant in a precompiled Windows agent, which is expected to work on any system. */
57 if (0 == GetComputerName(computerName, &dwSize))
58 {
59 zabbix_log(LOG_LEVEL_ERR, "GetComputerName() failed: %s", strerror_from_system(GetLastError()));
60 SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot obtain computer name: %s",
61 strerror_from_system(GetLastError())));
62 return SYSINFO_RET_FAIL;
63 }
64
65 SET_STR_RESULT(result, zbx_unicode_to_utf8(computerName));
66 }
67 else
68 {
69 if (SUCCEED != gethostname(buffer, sizeof(buffer)))
70 {
71 zabbix_log(LOG_LEVEL_ERR, "gethostname() failed: %s", strerror_from_system(WSAGetLastError()));
72 SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot obtain host name: %s",
73 strerror_from_system(WSAGetLastError())));
74 return SYSINFO_RET_FAIL;
75 }
76
77 SET_STR_RESULT(result, zbx_strdup(NULL, buffer));
78 }
79
80 return SYSINFO_RET_OK;
81 }
82