Merge branch 'master' into fis
[public/netxms.git] / src / server / core / main.cpp
CommitLineData
5039dede
AK
1/*
2** NetXMS - Network Management System
fdbee7f8 3** Copyright (C) 2003-2013 NetXMS Team
5039dede
AK
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., 675 Mass Ave, Cambridge, MA 02139, USA.
18**
19** File: main.cpp
20**
21**/
22
23#include "nxcore.h"
24#include <netxmsdb.h>
fdbee7f8 25#include <netxms_mt.h>
5039dede 26
b847803c 27#if !defined(_WIN32) && HAVE_READLINE_READLINE_H && HAVE_READLINE && !defined(UNICODE)
0322eed7
VK
28#include <readline/readline.h>
29#include <readline/history.h>
30#define USE_READLINE 1
5039dede
AK
31#endif
32
33#ifdef _WIN32
a23d8e0d
VK
34#include <errno.h>
35#include <psapi.h>
7bdb43c3 36#include <conio.h>
d717b69c
VK
37#define open _open
38#define write _write
39#define close _close
5039dede 40#else
a23d8e0d
VK
41#include <signal.h>
42#include <sys/wait.h>
5039dede
AK
43#endif
44
3a82d5ae
VK
45/**
46 * Messages generated by mc.pl (for UNIX version only)
47 */
5039dede
AK
48#ifndef _WIN32
49extern unsigned int g_dwNumMessages;
50extern const TCHAR *g_szMessages[];
51#endif
52
8f99849c
VK
53/**
54 * Shutdown reasons
55 */
030a0779
VK
56#define SHUTDOWN_DEFAULT 0
57#define SHUTDOWN_FROM_CONSOLE 1
58#define SHUTDOWN_BY_SIGNAL 2
5039dede 59
8f99849c
VK
60/**
61 * Externals
62 */
5039dede
AK
63extern Queue g_statusPollQueue;
64extern Queue g_configPollQueue;
040c45fa 65extern Queue g_topologyPollQueue;
5039dede
AK
66extern Queue g_routePollQueue;
67extern Queue g_discoveryPollQueue;
68extern Queue g_nodePollerQueue;
69extern Queue g_conditionPollerQueue;
70extern Queue *g_pItemQueue;
71
36e44abe 72void InitClientListeners();
534e1b83 73void InitMobileDeviceListeners();
36e44abe 74void InitCertificates();
ab185583
VK
75void InitUsers();
76void CleanupUsers();
058bf6fc
VK
77
78#if XMPP_SUPPORTED
244c65ef 79void StopXMPPConnector();
058bf6fc 80#endif
5039dede 81
534e1b83
VK
82/**
83 * Thread functions
84 */
85THREAD_RESULT THREAD_CALL HouseKeeper(void *);
86THREAD_RESULT THREAD_CALL Syncer(void *);
87THREAD_RESULT THREAD_CALL NodePoller(void *);
88THREAD_RESULT THREAD_CALL PollManager(void *);
89THREAD_RESULT THREAD_CALL EventProcessor(void *);
90THREAD_RESULT THREAD_CALL WatchdogThread(void *);
91THREAD_RESULT THREAD_CALL ClientListener(void *);
92THREAD_RESULT THREAD_CALL ClientListenerIPv6(void *);
93THREAD_RESULT THREAD_CALL MobileDeviceListener(void *);
94THREAD_RESULT THREAD_CALL MobileDeviceListenerIPv6(void *);
95THREAD_RESULT THREAD_CALL ISCListener(void *);
96THREAD_RESULT THREAD_CALL LocalAdminListener(void *);
97THREAD_RESULT THREAD_CALL SNMPTrapReceiver(void *);
98THREAD_RESULT THREAD_CALL SyslogDaemon(void *);
99THREAD_RESULT THREAD_CALL BeaconPoller(void *);
100THREAD_RESULT THREAD_CALL JobManagerThread(void *);
101THREAD_RESULT THREAD_CALL UptimeCalculator(void *);
d75003e1 102THREAD_RESULT THREAD_CALL ReportingServerConnector(void *);
058bf6fc
VK
103
104#if XMPP_SUPPORTED
244c65ef 105THREAD_RESULT THREAD_CALL XMPPConnectionManager(void *);
058bf6fc 106#endif
5039dede 107
534e1b83
VK
108/**
109 * Global variables
110 */
5039dede
AK
111TCHAR NXCORE_EXPORTABLE g_szConfigFile[MAX_PATH] = DEFAULT_CONFIG_FILE;
112TCHAR NXCORE_EXPORTABLE g_szLogFile[MAX_PATH] = DEFAULT_LOG_FILE;
967893bb
VK
113UINT32 g_dwLogRotationMode = NXLOG_ROTATION_BY_SIZE;
114UINT32 g_dwMaxLogSize = 16384 * 1024;
115UINT32 g_dwLogHistorySize = 4;
4f8998ca 116TCHAR g_szDailyLogFileSuffix[64] = _T("");
5039dede 117TCHAR NXCORE_EXPORTABLE g_szDumpDir[MAX_PATH] = DEFAULT_DUMP_DIR;
29dc8792 118char g_szCodePage[256] = ICONV_DEFAULT_CODEPAGE;
5039dede
AK
119TCHAR NXCORE_EXPORTABLE g_szListenAddress[MAX_PATH] = _T("0.0.0.0");
120#ifndef _WIN32
b07c50cc 121TCHAR NXCORE_EXPORTABLE g_szPIDFile[MAX_PATH] = _T("/var/run/netxmsd.pid");
5039dede
AK
122#endif
123DB_HANDLE g_hCoreDB = 0;
967893bb
VK
124UINT32 g_dwDiscoveryPollingInterval;
125UINT32 g_dwStatusPollingInterval;
126UINT32 g_dwConfigurationPollingInterval;
127UINT32 g_dwRoutingTableUpdateInterval;
128UINT32 g_dwTopologyPollingInterval;
129UINT32 g_dwConditionPollingInterval;
c59466d2
VK
130UINT32 g_icmpPingSize;
131UINT32 g_icmpPingTimeout = 1500; // ICMP ping timeout (milliseconds)
132UINT32 g_auditFlags;
133UINT32 g_slmPollingInterval;
d96bd4c7 134TCHAR g_szDataDir[MAX_PATH] = _T("");
9796ce45 135TCHAR g_szLibDir[MAX_PATH] = DEFAULT_LIBDIR;
712dd47d
VK
136TCHAR g_szJavaLibDir[MAX_PATH] = DEFAULT_JAVA_LIBDIR;
137TCHAR NXCORE_EXPORTABLE g_szJavaPath[MAX_DB_NAME] = _T("java");
28f5b9a4 138int g_nDBSyntax = DB_SYNTAX_UNKNOWN;
967893bb 139UINT32 NXCORE_EXPORTABLE g_processAffinityMask = DEFAULT_AFFINITY_MASK;
5039dede
AK
140QWORD g_qwServerId;
141RSA *g_pServerKey = NULL;
c59466d2
VK
142time_t g_serverStartTime = 0;
143UINT32 g_lockTimeout = 60000; // Default timeout for acquiring mutex
144UINT32 g_agentCommandTimeout = 4000; // Default timeout for requests to agent
145UINT32 g_thresholdRepeatInterval = 0; // Disabled by default
146int g_requiredPolls = 1;
b8c1ec69 147DB_DRIVER g_dbDriver = NULL;
5039dede 148
f375019e
VK
149/**
150 * Static data
151 */
5039dede
AK
152static CONDITION m_condShutdown = INVALID_CONDITION_HANDLE;
153static THREAD m_thPollManager = INVALID_THREAD_HANDLE;
154static THREAD m_thHouseKeeper = INVALID_THREAD_HANDLE;
155static THREAD m_thSyncer = INVALID_THREAD_HANDLE;
156static THREAD m_thSyslogDaemon = INVALID_THREAD_HANDLE;
058bf6fc 157#if XMPP_SUPPORTED
244c65ef 158static THREAD m_thXMPPConnector = INVALID_THREAD_HANDLE;
058bf6fc 159#endif
5039dede
AK
160static int m_nShutdownReason = SHUTDOWN_DEFAULT;
161
162#ifndef _WIN32
163static pthread_t m_signalHandlerThread;
164#endif
165
496390c2
VK
166/**
167 * Sleep for specified number of seconds or until system shutdown arrives
168 * Function will return TRUE if shutdown event occurs
169 *
170 * @param seconds seconds to sleep
171 * @return true if server is shutting down
172 */
173BOOL NXCORE_EXPORTABLE SleepAndCheckForShutdown(int seconds)
5039dede 174{
496390c2 175 return ConditionWait(m_condShutdown, seconds * 1000);
5039dede
AK
176}
177
496390c2
VK
178/**
179 * Disconnect from database (exportable function for startup module)
180 */
73869331 181void NXCORE_EXPORTABLE ShutdownDB()
5039dede
AK
182{
183 if (g_hCoreDB != NULL)
184 DBDisconnect(g_hCoreDB);
b8c1ec69 185 DBUnloadDriver(g_dbDriver);
5039dede
AK
186}
187
496390c2
VK
188/**
189 * Check data directory for existence
190 */
35f836fe 191static BOOL CheckDataDir()
5039dede 192{
35f836fe 193 TCHAR szBuffer[MAX_PATH];
5039dede 194
35f836fe 195 if (_tchdir(g_szDataDir) == -1)
5039dede
AK
196 {
197 nxlog_write(MSG_INVALID_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", g_szDataDir);
198 return FALSE;
199 }
200
201#ifdef _WIN32
35f836fe 202#define MKDIR(name) _tmkdir(name)
5039dede 203#else
35f836fe 204#define MKDIR(name) _tmkdir(name, 0700)
5039dede
AK
205#endif
206
207 // Create directory for mib files if it doesn't exist
35f836fe
VK
208 _tcscpy(szBuffer, g_szDataDir);
209 _tcscat(szBuffer, DDIR_MIBS);
5039dede
AK
210 if (MKDIR(szBuffer) == -1)
211 if (errno != EEXIST)
212 {
213 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
214 return FALSE;
215 }
216
5039dede 217 // Create directory for package files if it doesn't exist
35f836fe
VK
218 _tcscpy(szBuffer, g_szDataDir);
219 _tcscat(szBuffer, DDIR_PACKAGES);
5039dede
AK
220 if (MKDIR(szBuffer) == -1)
221 if (errno != EEXIST)
222 {
223 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
224 return FALSE;
225 }
226
4d0c32f3 227 // Create directory for map background images if it doesn't exist
35f836fe
VK
228 _tcscpy(szBuffer, g_szDataDir);
229 _tcscat(szBuffer, DDIR_BACKGROUNDS);
4d0c32f3
VK
230 if (MKDIR(szBuffer) == -1)
231 if (errno != EEXIST)
232 {
233 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
234 return FALSE;
235 }
236
e6b9439a
AK
237 // Create directory for image library is if does't exists
238 _tcscpy(szBuffer, g_szDataDir);
239 _tcscat(szBuffer, DDIR_IMAGES);
240 if (MKDIR(szBuffer) == -1)
241 {
242 if (errno != EEXIST)
243 {
244 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
245 return FALSE;
246 }
247 }
248
6f16f12d
VK
249 // Create directory for shared file store if does't exists
250 _tcscpy(szBuffer, g_szDataDir);
251 _tcscat(szBuffer, DDIR_SHARED_FILES);
252 if (MKDIR(szBuffer) == -1)
253 {
254 if (errno != EEXIST)
255 {
256 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
257 return FALSE;
258 }
259 }
260
619e5c9b
VK
261 // Create directory for file store if does't exists
262 _tcscpy(szBuffer, g_szDataDir);
263 _tcscat(szBuffer, DDIR_FILES);
264 if (MKDIR(szBuffer) == -1)
265 {
266 if (errno != EEXIST)
267 {
268 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
57fef75c
VK
269 return FALSE;
270 }
271 }
272
273 // Create directory for reports if does't exists
274 _tcscpy(szBuffer, g_szDataDir);
275 _tcscat(szBuffer, DDIR_REPORTS);
276 if (MKDIR(szBuffer) == -1)
277 {
278 if (errno != EEXIST)
279 {
280 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
619e5c9b
VK
281 return FALSE;
282 }
283 }
284
5039dede
AK
285#undef MKDIR
286
287 return TRUE;
288}
289
496390c2
VK
290/**
291 * Load global configuration parameters
292 */
5039dede
AK
293static void LoadGlobalConfig()
294{
35f836fe
VK
295 g_dwDiscoveryPollingInterval = ConfigReadInt(_T("DiscoveryPollingInterval"), 900);
296 g_dwStatusPollingInterval = ConfigReadInt(_T("StatusPollingInterval"), 60);
297 g_dwConfigurationPollingInterval = ConfigReadInt(_T("ConfigurationPollingInterval"), 3600);
298 g_dwRoutingTableUpdateInterval = ConfigReadInt(_T("RoutingTableUpdateInterval"), 300);
040c45fa 299 g_dwTopologyPollingInterval = ConfigReadInt(_T("TopologyPollingInterval"), 1800);
35f836fe 300 g_dwConditionPollingInterval = ConfigReadInt(_T("ConditionPollingInterval"), 60);
c59466d2 301 g_slmPollingInterval = ConfigReadInt(_T("SlmPollingInterval"), 60);
35f836fe 302 if (ConfigReadInt(_T("DeleteEmptySubnets"), 1))
5039dede 303 g_dwFlags |= AF_DELETE_EMPTY_SUBNETS;
35f836fe 304 if (ConfigReadInt(_T("EnableSNMPTraps"), 1))
5039dede 305 g_dwFlags |= AF_ENABLE_SNMP_TRAPD;
35f836fe 306 if (ConfigReadInt(_T("EnableZoning"), 0))
5039dede 307 g_dwFlags |= AF_ENABLE_ZONING;
549f48b3
VK
308 if (ConfigReadInt(_T("EnableObjectTransactions"), 0))
309 g_dwFlags |= AF_ENABLE_OBJECT_TRANSACTIONS;
35f836fe 310 if (ConfigReadInt(_T("EnableMultipleDBConnections"), 1))
2a8e6a7b
VK
311 {
312 // SQLite has troubles with multiple connections to the same database
313 // from different threads, and it does not speed up database access
314 // anyway, so we will not enable multiple connections for SQLite
315 if (g_nDBSyntax != DB_SYNTAX_SQLITE)
316 {
317 g_dwFlags |= AF_ENABLE_MULTIPLE_DB_CONN;
318 }
319 else
320 {
321 DbgPrintf(1, _T("Configuration parameter EnableMultipleDBConnections ignored because database engine is SQLite"));
322 }
323 }
35f836fe 324 if (ConfigReadInt(_T("RunNetworkDiscovery"), 0))
5039dede 325 g_dwFlags |= AF_ENABLE_NETWORK_DISCOVERY;
35f836fe 326 if (ConfigReadInt(_T("ActiveNetworkDiscovery"), 0))
5039dede 327 g_dwFlags |= AF_ACTIVE_NETWORK_DISCOVERY;
e02953a4
VK
328 if (ConfigReadInt(_T("UseSNMPTrapsForDiscovery"), 0))
329 g_dwFlags |= AF_SNMP_TRAP_DISCOVERY;
35f836fe 330 if (ConfigReadInt(_T("ResolveNodeNames"), 1))
5039dede 331 g_dwFlags |= AF_RESOLVE_NODE_NAMES;
35f836fe 332 if (ConfigReadInt(_T("SyncNodeNamesWithDNS"), 0))
5039dede 333 g_dwFlags |= AF_SYNC_NODE_NAMES_WITH_DNS;
35f836fe 334 if (ConfigReadInt(_T("CheckTrustedNodes"), 1))
5039dede 335 g_dwFlags |= AF_CHECK_TRUSTED_NODES;
3bbc7435
AK
336 if (ConfigReadInt(_T("EnableNXSLContainerFunctions"), 1))
337 g_dwFlags |= AF_ENABLE_NXSL_CONTAINER_FUNCS;
a203ea53
AK
338 if (ConfigReadInt(_T("UseFQDNForNodeNames"), 1))
339 g_dwFlags |= AF_USE_FQDN_FOR_NODE_NAMES;
dc4a1aec
AK
340 if (ConfigReadInt(_T("ApplyDCIFromTemplateToDisabledDCI"), 0))
341 g_dwFlags |= AF_APPLY_TO_DISABLED_DCI_FROM_TEMPLATE;
fc958888 342
d96bd4c7
VK
343 if (g_szDataDir[0] == 0)
344 {
35f836fe 345 ConfigReadStr(_T("DataDirectory"), g_szDataDir, MAX_PATH, DEFAULT_DATA_DIR);
d96bd4c7
VK
346 DbgPrintf(1, _T("Data directory set to %s from server configuration variable"), g_szDataDir);
347 }
348 else
349 {
350 DbgPrintf(1, _T("Using data directory %s"), g_szDataDir);
351 }
352
c59466d2
VK
353 g_icmpPingTimeout = ConfigReadInt(_T("IcmpPingTimeout"), 1500);
354 g_icmpPingSize = ConfigReadInt(_T("IcmpPingSize"), 46);
355 g_lockTimeout = ConfigReadInt(_T("LockTimeout"), 60000);
35f836fe 356 g_dwSNMPTimeout = ConfigReadInt(_T("SNMPRequestTimeout"), 2000);
c59466d2
VK
357 g_agentCommandTimeout = ConfigReadInt(_T("AgentCommandTimeout"), 4000);
358 g_thresholdRepeatInterval = ConfigReadInt(_T("ThresholdRepeatInterval"), 0);
359 g_requiredPolls = ConfigReadInt(_T("PollCountForStatusChange"), 1);
5039dede
AK
360}
361
fdbee7f8
VK
362/**
363 * Initialize cryptografic functions
364 */
73869331 365static BOOL InitCryptografy()
5039dede
AK
366{
367#ifdef _WITH_ENCRYPTION
35f836fe 368 TCHAR szKeyFile[MAX_PATH];
5039dede
AK
369 BOOL bResult = FALSE;
370 int fd, iPolicy;
967893bb 371 UINT32 dwLen;
5039dede
AK
372 BYTE *pBufPos, *pKeyBuffer, hash[SHA1_DIGEST_SIZE];
373
6468147c 374 if (!InitCryptoLib(ConfigReadULong(_T("AllowedCiphers"), 0x7F), DbgPrintf2))
5039dede
AK
375 return FALSE;
376
958a9397 377 SSL_library_init();
0fd5c0a1 378 SSL_load_error_strings();
958a9397 379
35f836fe
VK
380 _tcscpy(szKeyFile, g_szDataDir);
381 _tcscat(szKeyFile, DFILE_KEYS);
382 fd = _topen(szKeyFile, O_RDONLY | O_BINARY);
5039dede
AK
383 g_pServerKey = LoadRSAKeys(szKeyFile);
384 if (g_pServerKey == NULL)
385 {
35f836fe 386 DbgPrintf(1, _T("Generating RSA key pair..."));
5039dede
AK
387 g_pServerKey = RSA_generate_key(NETXMS_RSA_KEYLEN, 17, NULL, 0);
388 if (g_pServerKey != NULL)
389 {
35f836fe 390 fd = _topen(szKeyFile, O_WRONLY | O_BINARY | O_CREAT | O_TRUNC, 0600);
5039dede
AK
391 if (fd != -1)
392 {
393 dwLen = i2d_RSAPublicKey(g_pServerKey, NULL);
394 dwLen += i2d_RSAPrivateKey(g_pServerKey, NULL);
395 pKeyBuffer = (BYTE *)malloc(dwLen);
396
397 pBufPos = pKeyBuffer;
398 i2d_RSAPublicKey(g_pServerKey, &pBufPos);
399 i2d_RSAPrivateKey(g_pServerKey, &pBufPos);
967893bb 400 write(fd, &dwLen, sizeof(UINT32));
5039dede
AK
401 write(fd, pKeyBuffer, dwLen);
402
403 CalculateSHA1Hash(pKeyBuffer, dwLen, hash);
404 write(fd, hash, SHA1_DIGEST_SIZE);
405
406 close(fd);
407 free(pKeyBuffer);
408 bResult = TRUE;
409 }
c578be51
AK
410 else
411 {
412 DbgPrintf(0, _T("Failed to open %s for writing"), szKeyFile);
413 }
5039dede 414 }
c578be51
AK
415 else
416 {
417 DbgPrintf(0, _T("Failed to generate RSA key"));
418 }
5039dede
AK
419 }
420 else
421 {
422 bResult = TRUE;
423 }
424
35f836fe 425 iPolicy = ConfigReadInt(_T("DefaultEncryptionPolicy"), 1);
5039dede
AK
426 if ((iPolicy < 0) || (iPolicy > 3))
427 iPolicy = 1;
428 SetAgentDEP(iPolicy);
429
430 return bResult;
431#else
432 return TRUE;
433#endif
434}
435
496390c2
VK
436/**
437 * Check if process with given PID exists and is a NetXMS server process
438 */
967893bb 439static BOOL IsNetxmsdProcess(UINT32 dwPID)
5039dede
AK
440{
441#ifdef _WIN32
442 HANDLE hProcess;
443 TCHAR szExtModule[MAX_PATH], szIntModule[MAX_PATH];
444 BOOL bRet = FALSE;
445
446 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwPID);
447 if (hProcess != NULL)
448 {
449 if ((GetModuleBaseName(hProcess, NULL, szExtModule, MAX_PATH) > 0) &&
450 (GetModuleBaseName(GetCurrentProcess(), NULL, szIntModule, MAX_PATH) > 0))
451 {
452 bRet = !_tcsicmp(szExtModule, szIntModule);
453 }
454 else
455 {
456 // Cannot read process name, for safety assume that it's a server process
457 bRet = TRUE;
458 }
459 CloseHandle(hProcess);
460 }
461 return bRet;
462#else
463 return (kill((pid_t)dwPID, 0) != -1);
464#endif
465}
466
496390c2
VK
467/**
468 * Database event handler
469 */
35f836fe 470static void DBEventHandler(DWORD dwEvent, const WCHAR *pszArg1, const WCHAR *pszArg2, void *userArg)
5039dede
AK
471{
472 if (!(g_dwFlags & AF_SERVER_INITIALIZED))
473 return; // Don't try to do anything if server is not ready yet
474
475 switch(dwEvent)
476 {
477 case DBEVENT_CONNECTION_LOST:
478 PostEvent(EVENT_DB_CONNECTION_LOST, g_dwMgmtNode, NULL);
479 g_dwFlags |= AF_DB_CONNECTION_LOST;
480 NotifyClientSessions(NX_NOTIFY_DBCONN_STATUS, FALSE);
481 break;
482 case DBEVENT_CONNECTION_RESTORED:
483 PostEvent(EVENT_DB_CONNECTION_RESTORED, g_dwMgmtNode, NULL);
484 g_dwFlags &= ~AF_DB_CONNECTION_LOST;
485 NotifyClientSessions(NX_NOTIFY_DBCONN_STATUS, TRUE);
486 break;
4d0c32f3 487 case DBEVENT_QUERY_FAILED:
5049e942 488 PostEvent(EVENT_DB_QUERY_FAILED, g_dwMgmtNode, "uu", pszArg1, pszArg2);
4d0c32f3 489 break;
5039dede
AK
490 default:
491 break;
492 }
493}
494
496390c2
VK
495/**
496 * Send console message to session with open console
497 */
f669df41
VK
498static void SendConsoleMessage(ClientSession *session, void *arg)
499{
500 if (session->isConsoleOpen())
501 {
502 CSCPMessage msg;
503
504 msg.SetCode(CMD_ADM_MESSAGE);
505 msg.SetVariable(VID_MESSAGE, (TCHAR *)arg);
d3a7cf4c 506 session->postMessage(&msg);
f669df41
VK
507 }
508}
509
d6217efa
VK
510/**
511 * Console writer
512 */
f669df41
VK
513static void LogConsoleWriter(const TCHAR *format, ...)
514{
515 TCHAR buffer[8192];
516 va_list args;
517
518 va_start(args, format);
519 _vsntprintf(buffer, 8192, format, args);
520 buffer[8191] = 0;
521 va_end(args);
522
523 WriteToTerminal(buffer);
524
525 EnumerateClientSessions(SendConsoleMessage, buffer);
526}
527
fdbee7f8
VK
528/**
529 * Server initialization
530 */
bc980b27 531BOOL NXCORE_EXPORTABLE Initialize()
5039dede
AK
532{
533 int i, iDBVersion;
967893bb 534 UINT32 dwAddr;
35f836fe 535 TCHAR szInfo[256];
5039dede 536
c59466d2
VK
537 g_serverStartTime = time(NULL);
538 srand((unsigned int)g_serverStartTime);
4f8998ca
VK
539
540 if (!(g_dwFlags & AF_USE_SYSLOG))
541 {
542 if (!nxlog_set_rotation_policy((int)g_dwLogRotationMode, (int)g_dwMaxLogSize, (int)g_dwLogHistorySize, g_szDailyLogFileSuffix))
543 if (!(g_dwFlags & AF_DAEMON))
544 _tprintf(_T("WARNING: cannot set log rotation policy; using default values\n"));
545 }
9d381279
VK
546 if (!nxlog_open((g_dwFlags & AF_USE_SYSLOG) ? NETXMSD_SYSLOG_NAME : g_szLogFile,
547 ((g_dwFlags & AF_USE_SYSLOG) ? NXLOG_USE_SYSLOG : 0) | ((g_dwFlags & AF_DAEMON) ? 0 : NXLOG_PRINT_TO_STDOUT),
548 _T("LIBNXSRV.DLL"),
5039dede 549#ifdef _WIN32
9d381279 550 0, NULL))
5039dede 551#else
9d381279 552 g_dwNumMessages, g_szMessages))
5039dede 553#endif
9d381279
VK
554 {
555 _ftprintf(stderr, _T("FATAL ERROR: Cannot open log file\n"));
556 return FALSE;
557 }
f669df41 558 nxlog_set_console_writer(LogConsoleWriter);
5039dede
AK
559
560 // Set code page
561#ifndef _WIN32
562 if (SetDefaultCodepage(g_szCodePage))
563 {
f5797a09 564 DbgPrintf(1, _T("Code page set to %hs"), g_szCodePage);
5039dede
AK
565 }
566 else
567 {
f375019e 568 nxlog_write(MSG_CODEPAGE_ERROR, EVENTLOG_WARNING_TYPE, "m", g_szCodePage);
5039dede
AK
569 }
570#endif
571
73869331
VK
572 // Set process affinity mask
573 if (g_processAffinityMask != DEFAULT_AFFINITY_MASK)
574 {
575#ifdef _WIN32
576 if (SetProcessAffinityMask(GetCurrentProcess(), g_processAffinityMask))
577 DbgPrintf(1, _T("Process affinity mask set to 0x%08X"), g_processAffinityMask);
578#else
579 nxlog_write(MSG_SET_PROCESS_AFFINITY_NOT_SUPPORTED, EVENTLOG_WARNING_TYPE, NULL);
580#endif
581 }
582
5039dede
AK
583#ifdef _WIN32
584 WSADATA wsaData;
1ddf3f0c
VK
585 int wrc = WSAStartup(MAKEWORD(2, 2), &wsaData);
586 if (wrc != 0)
587 {
588 nxlog_write(MSG_WSASTARTUP_FAILED, EVENTLOG_ERROR_TYPE, "e", wrc);
589 return FALSE;
590 }
5039dede
AK
591#endif
592
593 InitLocalNetInfo();
594
595 // Create queue for delayed SQL queries
73869331 596 g_pLazyRequestQueue = new Queue(256, 64);
c9a9601c 597 g_pIDataInsertQueue = new Queue(1024, 1024);
5039dede
AK
598
599 // Initialize database driver and connect to database
9d88cdc9 600 DBSetDebugPrintCallback(DbgPrintf2);
b8c1ec69
VK
601 if (!DBInit(MSG_OTHER, (g_dwFlags & AF_LOG_SQL_ERRORS) ? MSG_SQL_ERROR : 0))
602 return FALSE;
ed950274 603 g_dbDriver = DBLoadDriver(g_szDbDriver, g_szDbDrvParams, (g_debugLevel >= 9), DBEventHandler, NULL);
b8c1ec69 604 if (g_dbDriver == NULL)
5039dede
AK
605 return FALSE;
606
607 // Connect to database
465b3f2d 608 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
5039dede
AK
609 for(i = 0; ; i++)
610 {
f3c30cf5 611 g_hCoreDB = DBConnect(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, errorText);
5039dede
AK
612 if ((g_hCoreDB != NULL) || (i == 5))
613 break;
614 ThreadSleep(5);
615 }
616 if (g_hCoreDB == NULL)
617 {
465b3f2d 618 nxlog_write(MSG_DB_CONNFAIL, EVENTLOG_ERROR_TYPE, "s", errorText);
5039dede
AK
619 return FALSE;
620 }
35f836fe 621 DbgPrintf(1, _T("Successfully connected to database %s@%s"), g_szDbName, g_szDbServer);
5039dede
AK
622
623 // Check database version
28f5b9a4 624 iDBVersion = DBGetSchemaVersion(g_hCoreDB);
5039dede
AK
625 if (iDBVersion != DB_FORMAT_VERSION)
626 {
627 nxlog_write(MSG_WRONG_DB_VERSION, EVENTLOG_ERROR_TYPE, "dd", iDBVersion, DB_FORMAT_VERSION);
628 return FALSE;
629 }
630
35f836fe
VK
631 int baseSize = ConfigReadInt(_T("ConnectionPoolBaseSize"), 5);
632 int maxSize = ConfigReadInt(_T("ConnectionPoolMaxSize"), 20);
633 int cooldownTime = ConfigReadInt(_T("ConnectionPoolCooldownTime"), 300);
30d9c43c 634 DBConnectionPoolStartup(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, baseSize, maxSize, cooldownTime, 0, g_hCoreDB);
e94b29f6 635 g_dwFlags |= AF_DB_CONNECTION_POOL_READY;
f727d089 636
5039dede 637 // Read database syntax
28f5b9a4 638 g_nDBSyntax = DBGetSyntax(g_hCoreDB);
5039dede
AK
639
640 // Read server ID
35f836fe 641 ConfigReadStr(_T("ServerID"), szInfo, 256, _T(""));
5039dede
AK
642 StrStrip(szInfo);
643 if (szInfo[0] != 0)
644 {
645 StrToBin(szInfo, (BYTE *)&g_qwServerId, sizeof(QWORD));
646 }
647 else
648 {
649 // Generate new ID
650 g_qwServerId = (((QWORD)time(NULL)) << 32) | rand();
651 BinToStr((BYTE *)&g_qwServerId, sizeof(QWORD), szInfo);
35f836fe 652 ConfigWriteStr(_T("ServerID"), szInfo, TRUE);
5039dede
AK
653 }
654
655 // Initialize locks
656retry_db_lock:
657 if (!InitLocks(&dwAddr, szInfo))
658 {
659 if (dwAddr == UNLOCKED) // Some SQL problems
660 {
661 nxlog_write(MSG_INIT_LOCKS_FAILED, EVENTLOG_ERROR_TYPE, NULL);
662 }
663 else // Database already locked by another server instance
664 {
665 // Check for lock from crashed/terminated local process
666 if (dwAddr == GetLocalIpAddr())
667 {
967893bb 668 UINT32 dwPID;
5039dede 669
35f836fe 670 dwPID = ConfigReadULong(_T("DBLockPID"), 0);
5039dede
AK
671 if (!IsNetxmsdProcess(dwPID) || (dwPID == GetCurrentProcessId()))
672 {
673 UnlockDB();
674 nxlog_write(MSG_DB_LOCK_REMOVED, EVENTLOG_INFORMATION_TYPE, NULL);
675 goto retry_db_lock;
676 }
677 }
678 nxlog_write(MSG_DB_LOCKED, EVENTLOG_ERROR_TYPE, "as", dwAddr, szInfo);
679 }
680 return FALSE;
681 }
682 g_dwFlags |= AF_DB_LOCKED;
683
684 // Load global configuration parameters
685 LoadGlobalConfig();
958a9397 686 CASReadSettings();
35f836fe 687 DbgPrintf(1, _T("Global configuration loaded"));
5039dede
AK
688
689 // Check data directory
690 if (!CheckDataDir())
691 return FALSE;
692
693 // Initialize cryptografy
694 if (!InitCryptografy())
695 {
696 nxlog_write(MSG_INIT_CRYPTO_FAILED, EVENTLOG_ERROR_TYPE, NULL);
697 return FALSE;
698 }
699
700 // Initialize certificate store and CA
701 InitCertificates();
702
5039dede
AK
703 // Create synchronization stuff
704 m_condShutdown = ConditionCreate(TRUE);
705
706 // Setup unique identifiers table
707 if (!InitIdTable())
708 return FALSE;
35f836fe 709 DbgPrintf(2, _T("ID table created"));
5039dede 710
24dc5346
VK
711 // Update status for unfinished jobs in job history
712 DBQuery(g_hCoreDB, _T("UPDATE job_history SET status=4,failure_message='Aborted due to server shutdown or crash' WHERE status NOT IN (3,4,5)"));
713
5039dede
AK
714 // Load and compile scripts
715 LoadScripts();
716
f7e4c50e
VK
717 // Initialize watchdog
718 WatchdogInit();
719
53d2de79 720 // Load modules
890478d8
VK
721 if (!LoadNetXMSModules())
722 return FALSE; // Mandatory module not loaded
53d2de79 723
5039dede
AK
724 // Initialize mailer and SMS sender
725 InitMailer();
726 InitSMSSender();
727
728 // Load users from database
ab185583 729 InitUsers();
5039dede
AK
730 if (!LoadUsers())
731 {
732 nxlog_write(MSG_ERROR_LOADING_USERS, EVENTLOG_ERROR_TYPE, NULL);
733 return FALSE;
734 }
35f836fe 735 DbgPrintf(2, _T("User accounts loaded"));
5039dede
AK
736
737 // Initialize audit
738 InitAuditLog();
739
740 // Initialize objects infrastructure and load objects from database
9796ce45 741 LoadNetworkDeviceDrivers();
5039dede
AK
742 ObjectsInit();
743 if (!LoadObjects())
744 return FALSE;
35f836fe 745 DbgPrintf(1, _T("Objects loaded and initialized"));
5039dede
AK
746
747 // Initialize situations
748 if (!SituationsInit())
749 return FALSE;
35f836fe 750 DbgPrintf(1, _T("Situations loaded and initialized"));
5039dede
AK
751
752 // Initialize and load event actions
753 if (!InitActions())
754 {
755 nxlog_write(MSG_ACTION_INIT_ERROR, EVENTLOG_ERROR_TYPE, NULL);
756 return FALSE;
757 }
758
759 // Initialize event handling subsystem
760 if (!InitEventSubsystem())
761 return FALSE;
762
763 // Initialize alarms
1b94acbf 764 if (!g_alarmMgr.init())
5039dede
AK
765 return FALSE;
766
767 // Initialize data collection subsystem
768 if (!InitDataCollector())
769 return FALSE;
770
e05b1945 771 InitLogAccess();
d77baddd 772 FileUploadJob::init();
fdbee7f8 773 InitMappingTables();
e05b1945 774
5039dede
AK
775 // Check if management node object presented in database
776 CheckForMgmtNode();
777 if (g_dwMgmtNode == 0)
778 {
779 nxlog_write(MSG_CANNOT_FIND_SELF, EVENTLOG_ERROR_TYPE, NULL);
780 return FALSE;
781 }
782
783 // Start threads
784 ThreadCreate(WatchdogThread, 0, NULL);
785 ThreadCreate(NodePoller, 0, NULL);
3929b1ca 786 ThreadCreate(JobManagerThread, 0, NULL);
5039dede
AK
787 m_thSyncer = ThreadCreateEx(Syncer, 0, NULL);
788 m_thHouseKeeper = ThreadCreateEx(HouseKeeper, 0, NULL);
789 m_thPollManager = ThreadCreateEx(PollManager, 0, NULL);
790
791 // Start event processor
792 ThreadCreate(EventProcessor, 0, NULL);
793
794 // Start SNMP trapper
795 InitTraps();
35f836fe 796 if (ConfigReadInt(_T("EnableSNMPTraps"), 1))
5039dede
AK
797 ThreadCreate(SNMPTrapReceiver, 0, NULL);
798
799 // Start built-in syslog daemon
35f836fe 800 if (ConfigReadInt(_T("EnableSyslogDaemon"), 0))
5039dede
AK
801 m_thSyslogDaemon = ThreadCreateEx(SyslogDaemon, 0, NULL);
802
35f836fe 803 // Start database _T("lazy") write thread
5039dede
AK
804 StartDBWriter();
805
806 // Start local administartive interface listener if required
35f836fe 807 if (ConfigReadInt(_T("EnableAdminInterface"), 1))
5039dede
AK
808 ThreadCreate(LocalAdminListener, 0, NULL);
809
5039dede
AK
810 // Start beacon host poller
811 ThreadCreate(BeaconPoller, 0, NULL);
812
813 // Start inter-server communication listener
35f836fe 814 if (ConfigReadInt(_T("EnableISCListener"), 0))
5039dede
AK
815 ThreadCreate(ISCListener, 0, NULL);
816
d75003e1
AK
817 // Start reporting server connector
818 if (ConfigReadInt(_T("EnableReportingServer"), 0))
819 ThreadCreate(ReportingServerConnector, 0, NULL);
820
5039dede 821 // Allow clients to connect
36e44abe 822 InitClientListeners();
5039dede 823 ThreadCreate(ClientListener, 0, NULL);
36e44abe
VK
824#ifdef WITH_IPV6
825 ThreadCreate(ClientListenerIPv6, 0, NULL);
826#endif
5039dede 827
534e1b83
VK
828 // Allow mobile devices to connect
829 InitMobileDeviceListeners();
830 ThreadCreate(MobileDeviceListener, 0, NULL);
831#ifdef WITH_IPV6
832 ThreadCreate(MobileDeviceListenerIPv6, 0, NULL);
833#endif
834
86457857
AK
835 // Start uptime calculator for SLM
836 ThreadCreate(UptimeCalculator, 0, NULL);
837
712dd47d
VK
838 DbgPrintf(2, _T("Java VM: %s"), g_szJavaPath);
839 DbgPrintf(2, _T("Java LIBDIR: %s"), g_szJavaLibDir);
840 DbgPrintf(2, _T("LIBDIR: %s"), g_szLibDir);
841
1b42a673 842 // Call startup functions for the modules
967893bb 843 for(UINT32 i = 0; i < g_dwNumModules; i++)
53d2de79
VK
844 {
845 if (g_pModuleList[i].pfServerStarted != NULL)
846 g_pModuleList[i].pfServerStarted();
847 }
848
058bf6fc 849#if XMPP_SUPPORTED
244c65ef
VK
850 if (ConfigReadInt(_T("EnableXMPPConnector"), 1))
851 {
852 m_thXMPPConnector = ThreadCreateEx(XMPPConnectionManager, 0, NULL);
853 }
058bf6fc 854#endif
244c65ef 855
5039dede 856 g_dwFlags |= AF_SERVER_INITIALIZED;
35f836fe 857 DbgPrintf(1, _T("Server initialization completed"));
5039dede
AK
858 return TRUE;
859}
860
371d9c60
VK
861/**
862 * Server shutdown
863 */
035a4d73 864void NXCORE_EXPORTABLE Shutdown()
5039dede 865{
5039dede
AK
866 // Notify clients
867 NotifyClientSessions(NX_NOTIFY_SHUTDOWN, 0);
868
869 nxlog_write(MSG_SERVER_STOPPED, EVENTLOG_INFORMATION_TYPE, NULL);
870 g_dwFlags |= AF_SHUTDOWN; // Set shutdown flag
871 ConditionSet(m_condShutdown);
872
058bf6fc 873#if XMPP_SUPPORTED
244c65ef 874 StopXMPPConnector();
058bf6fc 875#endif
244c65ef 876
5039dede
AK
877#ifndef _WIN32
878 if (IsStandalone() && (m_nShutdownReason != SHUTDOWN_BY_SIGNAL))
879 {
880 pthread_kill(m_signalHandlerThread, SIGUSR1); // Terminate signal handler
881 }
882#endif
883
496390c2 884 // Call shutdown functions for the modules
967893bb 885 for(UINT32 i = 0; i < g_dwNumModules; i++)
496390c2
VK
886 {
887 if (g_pModuleList[i].pfShutdown != NULL)
888 g_pModuleList[i].pfShutdown();
889 }
890
4f50e45c 891 // Stop event processor
5039dede 892 g_pEventQueue->Clear();
4f50e45c 893 g_pEventQueue->Put(INVALID_POINTER_VALUE);
5039dede
AK
894
895 ShutdownMailer();
896 ShutdownSMSSender();
897
898 ThreadSleep(1); // Give other threads a chance to terminate in a safe way
35f836fe 899 DbgPrintf(2, _T("All threads was notified, continue with shutdown"));
5039dede
AK
900
901 // Wait for critical threads
902 ThreadJoin(m_thHouseKeeper);
903 ThreadJoin(m_thPollManager);
904 ThreadJoin(m_thSyncer);
905 ThreadJoin(m_thSyslogDaemon);
058bf6fc 906#if XMPP_SUPPORTED
244c65ef 907 ThreadJoin(m_thXMPPConnector);
058bf6fc 908#endif
5039dede
AK
909
910 SaveObjects(g_hCoreDB);
35f836fe 911 DbgPrintf(2, _T("All objects saved to database"));
5039dede 912 SaveUsers(g_hCoreDB);
35f836fe 913 DbgPrintf(2, _T("All users saved to database"));
5039dede 914 StopDBWriter();
35f836fe 915 DbgPrintf(1, _T("Database writer stopped"));
5039dede 916
ab185583
VK
917 CleanupUsers();
918
5039dede
AK
919 // Remove database lock
920 UnlockDB();
921
922 // Disconnect from database and unload driver
923 if (g_hCoreDB != NULL)
924 DBDisconnect(g_hCoreDB);
c20b2798
AK
925
926 DBConnectionPoolShutdown();
927
b8c1ec69 928 DBUnloadDriver(g_dbDriver);
35f836fe 929 DbgPrintf(1, _T("Database driver unloaded"));
5039dede
AK
930
931 CleanupActions();
932 ShutdownEventSubsystem();
35f836fe 933 DbgPrintf(1, _T("Event processing stopped"));
5039dede
AK
934
935 // Delete all objects
936 //for(i = 0; i < g_dwIdIndexSize; i++)
937 // delete g_pIndexById[i].pObject;
938
939 delete g_pScriptLibrary;
940
941 nxlog_close();
942
943 // Remove PID file
944#ifndef _WIN32
dda7c270 945 _tremove(g_szPIDFile);
5039dede
AK
946#endif
947
948 // Terminate process
949#ifdef _WIN32
950 if (!(g_dwFlags & AF_DAEMON))
951 ExitProcess(0);
952#else
953 exit(0);
954#endif
955}
956
371d9c60
VK
957/**
958 * Fast server shutdown - normally called only by Windows service on system shutdown
959 */
f669df41 960void NXCORE_EXPORTABLE FastShutdown()
5039dede
AK
961{
962 g_dwFlags |= AF_SHUTDOWN; // Set shutdown flag
963 ConditionSet(m_condShutdown);
964
965 SaveObjects(g_hCoreDB);
35f836fe 966 DbgPrintf(2, _T("All objects saved to database"));
5039dede 967 SaveUsers(g_hCoreDB);
35f836fe 968 DbgPrintf(2, _T("All users saved to database"));
5039dede
AK
969
970 // Remove database lock first, because we have a chance to loose DB connection
971 UnlockDB();
972
973 // Stop database writers
974 StopDBWriter();
35f836fe 975 DbgPrintf(1, _T("Database writer stopped"));
5039dede
AK
976
977 nxlog_close();
978}
979
fdbee7f8
VK
980/**
981 * Compare given string to command template with abbreviation possibility
982 */
983static bool IsCommand(const TCHAR *pszTemplate, TCHAR *pszString, int iMinChars)
5039dede
AK
984{
985 int i;
986
987 // Convert given string to uppercase
35f836fe 988 _tcsupr(pszString);
5039dede
AK
989
990 for(i = 0; pszString[i] != 0; i++)
991 if (pszString[i] != pszTemplate[i])
fdbee7f8 992 return false;
5039dede 993 if (i < iMinChars)
fdbee7f8
VK
994 return false;
995 return true;
5039dede
AK
996}
997
fdbee7f8
VK
998/**
999 * Dump index
1000 */
d5e19c61 1001struct __dump_index_data
5039dede 1002{
d5e19c61
VK
1003 CONSOLE_CTX console;
1004 bool indexByIP;
1005};
5039dede 1006
d5e19c61
VK
1007static void DumpIndexCallback(NetObj *object, void *data)
1008{
1009 struct __dump_index_data *d = (struct __dump_index_data *)data;
1010 if (d->indexByIP)
5039dede 1011 {
d5e19c61
VK
1012 TCHAR buffer[16];
1013 ConsolePrintf(d->console, _T("%08X [%-15s] %p %s\n"), object->IpAddr(),
1014 IpToStr(object->IpAddr(), buffer),
1015 object, object->Name());
5039dede 1016 }
d5e19c61
VK
1017 else
1018 {
1019 ConsolePrintf(d->console, _T("%08X %p %s\n"), object->Id(), object, object->Name());
1020 }
1021}
5039dede 1022
d5e19c61
VK
1023static void DumpIndex(CONSOLE_CTX pCtx, ObjectIndex *index, bool indexByIp)
1024{
1025 struct __dump_index_data data;
1026 data.console = pCtx;
1027 data.indexByIP = indexByIp;
1028 index->forEach(DumpIndexCallback, &data);
5039dede
AK
1029}
1030
e323047c
VK
1031/**
1032 * Process command entered from command line in standalone mode
1033 * Return TRUE if command was _T("down")
1034 */
35f836fe 1035int ProcessConsoleCommand(const TCHAR *pszCmdLine, CONSOLE_CTX pCtx)
5039dede 1036{
35f836fe 1037 const TCHAR *pArg;
48c0079d 1038 TCHAR szBuffer[256], *eptr;
5039dede
AK
1039 int nExitCode = CMD_EXIT_CONTINUE;
1040
1041 // Get command
1042 pArg = ExtractWord(pszCmdLine, szBuffer);
1043
35f836fe 1044 if (IsCommand(_T("DEBUG"), szBuffer, 2))
5039dede
AK
1045 {
1046 // Get argument
1047 pArg = ExtractWord(pArg, szBuffer);
48c0079d
VK
1048 int level = (int)_tcstol(szBuffer, &eptr, 0);
1049 if ((*eptr == 0) && (level >= 0) && (level <= 9))
5039dede 1050 {
967893bb 1051 g_debugLevel = (UINT32)level;
48c0079d 1052 ConsolePrintf(pCtx, (level == 0) ? _T("Debug mode turned off\n") : _T("Debug level set to %d\n"), level);
5039dede 1053 }
35f836fe 1054 else if (IsCommand(_T("OFF"), szBuffer, 2))
5039dede 1055 {
ed950274 1056 g_debugLevel = 0;
35f836fe 1057 ConsolePrintf(pCtx, _T("Debug mode turned off\n"));
5039dede
AK
1058 }
1059 else
1060 {
1061 if (szBuffer[0] == 0)
35f836fe 1062 ConsolePrintf(pCtx, _T("ERROR: Missing argument\n\n"));
5039dede 1063 else
48c0079d 1064 ConsolePrintf(pCtx, _T("ERROR: Invalid debug level\n\n"));
5039dede
AK
1065 }
1066 }
35f836fe 1067 else if (IsCommand(_T("DOWN"), szBuffer, 4))
5039dede 1068 {
35f836fe 1069 ConsolePrintf(pCtx, _T("Proceeding with server shutdown...\n"));
5039dede
AK
1070 nExitCode = CMD_EXIT_SHUTDOWN;
1071 }
35f836fe 1072 else if (IsCommand(_T("DUMP"), szBuffer, 4))
5039dede
AK
1073 {
1074 DumpProcess(pCtx);
1075 }
206e268e
VK
1076 else if (IsCommand(_T("GET"), szBuffer, 3))
1077 {
1078 pArg = ExtractWord(pArg, szBuffer);
1079 if (szBuffer[0] != 0)
1080 {
1081 TCHAR value[256];
1082 ConfigReadStr(szBuffer, value, 256, _T(""));
1083 ConsolePrintf(pCtx, _T("%s = %s\n"), szBuffer, value);
1084 }
1085 else
1086 {
1087 ConsolePrintf(pCtx, _T("Variable name missing\n"));
1088 }
1089 }
35f836fe 1090 else if (IsCommand(_T("RAISE"), szBuffer, 5))
5039dede
AK
1091 {
1092 // Get argument
1093 pArg = ExtractWord(pArg, szBuffer);
1094
35f836fe 1095 if (IsCommand(_T("ACCESS"), szBuffer, 6))
5039dede 1096 {
35f836fe 1097 ConsolePrintf(pCtx, _T("Raising exception...\n"));
5039dede
AK
1098 char *p = NULL;
1099 *p = 0;
1100 }
35f836fe 1101 else if (IsCommand(_T("BREAKPOINT"), szBuffer, 5))
5039dede
AK
1102 {
1103#ifdef _WIN32
35f836fe 1104 ConsolePrintf(pCtx, _T("Raising exception...\n"));
5039dede
AK
1105 RaiseException(EXCEPTION_BREAKPOINT, 0, 0, NULL);
1106#else
35f836fe 1107 ConsolePrintf(pCtx, _T("ERROR: Not supported on current platform\n"));
5039dede
AK
1108#endif
1109 }
1110 else
1111 {
35f836fe 1112 ConsolePrintf(pCtx, _T("Invalid exception name; possible names are:\nACCESS BREAKPOINT\n"));
5039dede
AK
1113 }
1114 }
35f836fe 1115 else if (IsCommand(_T("EXIT"), szBuffer, 4))
5039dede 1116 {
f669df41 1117 if ((pCtx->hSocket != -1) || (pCtx->session != NULL))
5039dede 1118 {
35f836fe 1119 ConsolePrintf(pCtx, _T("Closing session...\n"));
5039dede
AK
1120 nExitCode = CMD_EXIT_CLOSE_SESSION;
1121 }
1122 else
1123 {
35f836fe 1124 ConsolePrintf(pCtx, _T("Cannot exit from local server console\n"));
5039dede
AK
1125 }
1126 }
206e268e
VK
1127 else if (IsCommand(_T("SET"), szBuffer, 3))
1128 {
1129 pArg = ExtractWord(pArg, szBuffer);
1130 if (szBuffer[0] != 0)
1131 {
1132 TCHAR value[256];
1133 pArg = ExtractWord(pArg, value);
1134 if (ConfigWriteStr(szBuffer, value, TRUE, TRUE, TRUE))
1135 {
1136 ConsolePrintf(pCtx, _T("Configuration variable %s updated\n"), szBuffer);
1137 }
1138 else
1139 {
1140 ConsolePrintf(pCtx, _T("ERROR: cannot update configuration variable %s\n"), szBuffer);
1141 }
1142 }
1143 else
1144 {
1145 ConsolePrintf(pCtx, _T("Variable name missing\n"));
1146 }
1147 }
35f836fe 1148 else if (IsCommand(_T("SHOW"), szBuffer, 2))
5039dede
AK
1149 {
1150 // Get argument
1151 pArg = ExtractWord(pArg, szBuffer);
1152
50d0de67
VK
1153 if (IsCommand(_T("COMPONENTS"), szBuffer, 1))
1154 {
1155 // Get argument
1156 pArg = ExtractWord(pArg, szBuffer);
967893bb 1157 UINT32 dwNode = _tcstoul(szBuffer, NULL, 0);
50d0de67
VK
1158 if (dwNode != 0)
1159 {
1160 NetObj *pObject = FindObjectById(dwNode);
1161 if (pObject != NULL)
1162 {
1163 if (pObject->Type() == OBJECT_NODE)
1164 {
8836184f
VK
1165 ComponentTree *components = ((Node *)pObject)->getComponents();
1166 if (components != NULL)
50d0de67 1167 {
8836184f
VK
1168 components->print(pCtx);
1169 components->decRefCount();
50d0de67
VK
1170 }
1171 else
1172 {
1173 ConsolePrintf(pCtx, _T("ERROR: Node does not have physical component information\n\n"));
1174 }
1175 }
1176 else
1177 {
1178 ConsolePrintf(pCtx, _T("ERROR: Object is not a node\n\n"));
1179 }
1180 }
1181 else
1182 {
1183 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode);
1184 }
1185 }
1186 else
1187 {
1188 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node ID\n\n"));
1189 }
1190 }
9c133761
VK
1191 else if (IsCommand(_T("DBCP"), szBuffer, 4))
1192 {
1193 ObjectArray<PoolConnectionInfo> *list = DBConnectionPoolGetConnectionList();
1194 for(int i = 0; i < list->size(); i++)
1195 {
1196 PoolConnectionInfo *c = list->get(i);
1197 TCHAR accessTime[64];
1198 struct tm *ltm = localtime(&c->lastAccessTime);
1199 _tcsftime(accessTime, 64, _T("%d.%b.%Y %H:%M:%S"), ltm);
1200 ConsolePrintf(pCtx, _T("%p %s %hs:%d\n"), c->handle, accessTime, c->srcFile, c->srcLine);
1201 }
1202 ConsolePrintf(pCtx, _T("%d database connections in use\n\n"), list->size());
1203 delete list;
1204 }
4321449e
VK
1205 else if (IsCommand(_T("FDB"), szBuffer, 3))
1206 {
1207 // Get argument
1208 pArg = ExtractWord(pArg, szBuffer);
1209 UINT32 dwNode = _tcstoul(szBuffer, NULL, 0);
1210 if (dwNode != 0)
1211 {
1212 NetObj *pObject = FindObjectById(dwNode);
1213 if (pObject != NULL)
1214 {
1215 if (pObject->Type() == OBJECT_NODE)
1216 {
1217 ForwardingDatabase *fdb = ((Node *)pObject)->getSwitchForwardingDatabase();
1218 if (fdb != NULL)
1219 {
1220 fdb->print(pCtx, (Node *)pObject);
1221 fdb->decRefCount();
1222 }
1223 else
1224 {
1225 ConsolePrintf(pCtx, _T("ERROR: Node does not have forwarding database information\n\n"));
1226 }
1227 }
1228 else
1229 {
1230 ConsolePrintf(pCtx, _T("ERROR: Object is not a node\n\n"));
1231 }
1232 }
1233 else
1234 {
1235 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode);
1236 }
1237 }
1238 else
1239 {
1240 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node ID\n\n"));
1241 }
1242 }
50d0de67 1243 else if (IsCommand(_T("FLAGS"), szBuffer, 1))
5039dede 1244 {
35f836fe 1245 ConsolePrintf(pCtx, _T("Flags: 0x%08X\n"), g_dwFlags);
5039dede
AK
1246 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DAEMON));
1247 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_USE_SYSLOG));
1248 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_NETWORK_DISCOVERY));
1249 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ACTIVE_NETWORK_DISCOVERY));
1250 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_LOG_SQL_ERRORS));
1251 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DELETE_EMPTY_SUBNETS));
1252 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_SNMP_TRAPD));
1253 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_ZONING));
5039dede 1254 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SYNC_NODE_NAMES_WITH_DNS));
cbc777ee 1255 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_CHECK_TRUSTED_NODES));
549f48b3
VK
1256 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_NXSL_CONTAINER_FUNCS));
1257 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_USE_FQDN_FOR_NODE_NAMES));
1258 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_APPLY_TO_DISABLED_DCI_FROM_TEMPLATE));
1259 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DEBUG_CONSOLE_DISABLED));
1260 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_OBJECT_TRANSACTIONS));
cbc777ee
VK
1261 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_WRITE_FULL_DUMP));
1262 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_RESOLVE_NODE_NAMES));
5039dede 1263 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_CATCH_EXCEPTIONS));
5039dede
AK
1264 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_INTERNAL_CA));
1265 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DB_LOCKED));
cbc777ee 1266 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_MULTIPLE_DB_CONN));
5039dede 1267 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DB_CONNECTION_LOST));
cbc777ee 1268 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_NO_NETWORK_CONNECTIVITY));
5039dede 1269 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_EVENT_STORM_DETECTED));
e02953a4 1270 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SNMP_TRAP_DISCOVERY));
5039dede
AK
1271 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SERVER_INITIALIZED));
1272 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SHUTDOWN));
35f836fe 1273 ConsolePrintf(pCtx, _T("\n"));
5039dede 1274 }
35f836fe 1275 else if (IsCommand(_T("INDEX"), szBuffer, 1))
5039dede
AK
1276 {
1277 // Get argument
1278 pArg = ExtractWord(pArg, szBuffer);
1279
35f836fe 1280 if (IsCommand(_T("CONDITION"), szBuffer, 1))
5039dede 1281 {
d5e19c61 1282 DumpIndex(pCtx, &g_idxConditionById, false);
5039dede 1283 }
35f836fe 1284 else if (IsCommand(_T("ID"), szBuffer, 2))
5039dede 1285 {
d5e19c61 1286 DumpIndex(pCtx, &g_idxObjectById, false);
5039dede 1287 }
35f836fe 1288 else if (IsCommand(_T("INTERFACE"), szBuffer, 2))
5039dede 1289 {
d5e19c61 1290 DumpIndex(pCtx, &g_idxInterfaceByAddr, true);
6aba3998 1291 }
16d6f798
VK
1292 else if (IsCommand(_T("NODEADDR"), szBuffer, 5))
1293 {
1294 DumpIndex(pCtx, &g_idxNodeByAddr, true);
1295 }
1296 else if (IsCommand(_T("NODEID"), szBuffer, 5))
6aba3998 1297 {
d5e19c61 1298 DumpIndex(pCtx, &g_idxNodeById, false);
5039dede 1299 }
35f836fe 1300 else if (IsCommand(_T("SUBNET"), szBuffer, 1))
5039dede 1301 {
d5e19c61 1302 DumpIndex(pCtx, &g_idxSubnetByAddr, true);
5039dede 1303 }
16d6f798
VK
1304 else if (IsCommand(_T("ZONE"), szBuffer, 1))
1305 {
1306 DumpIndex(pCtx, &g_idxZoneByGUID, true);
1307 }
5039dede
AK
1308 else
1309 {
1310 if (szBuffer[0] == 0)
35f836fe 1311 ConsolePrintf(pCtx, _T("ERROR: Missing index name\n")
16d6f798 1312 _T("Valid names are: CONDITION, ID, INTERFACE, NODEADDR, NODEID, SUBNET, ZONE\n\n"));
5039dede 1313 else
35f836fe 1314 ConsolePrintf(pCtx, _T("ERROR: Invalid index name\n\n"));
5039dede
AK
1315 }
1316 }
35f836fe 1317 else if (IsCommand(_T("MEMORY"), szBuffer, 2))
5039dede
AK
1318 {
1319#ifdef NETXMS_MEMORY_DEBUG
1320 PrintMemoryBlocks();
1321#else
35f836fe 1322 ConsolePrintf(pCtx, _T("ERROR: Server was compiled without memory debugger\n\n"));
5039dede
AK
1323#endif
1324 }
35f836fe 1325 else if (IsCommand(_T("OBJECTS"), szBuffer, 1))
5039dede
AK
1326 {
1327 DumpObjects(pCtx);
1328 }
35f836fe 1329 else if (IsCommand(_T("POLLERS"), szBuffer, 1))
5039dede
AK
1330 {
1331 ShowPollerState(pCtx);
1332 }
35f836fe 1333 else if (IsCommand(_T("QUEUES"), szBuffer, 1))
5039dede 1334 {
35f836fe
VK
1335 ShowQueueStats(pCtx, &g_conditionPollerQueue, _T("Condition poller"));
1336 ShowQueueStats(pCtx, &g_configPollQueue, _T("Configuration poller"));
040c45fa 1337 ShowQueueStats(pCtx, &g_topologyPollQueue, _T("Topology poller"));
35f836fe
VK
1338 ShowQueueStats(pCtx, g_pItemQueue, _T("Data collector"));
1339 ShowQueueStats(pCtx, g_pLazyRequestQueue, _T("Database writer"));
c9a9601c 1340 ShowQueueStats(pCtx, g_pIDataInsertQueue, _T("Database writer (IData)"));
35f836fe
VK
1341 ShowQueueStats(pCtx, g_pEventQueue, _T("Event processor"));
1342 ShowQueueStats(pCtx, &g_discoveryPollQueue, _T("Network discovery poller"));
1343 ShowQueueStats(pCtx, &g_nodePollerQueue, _T("Node poller"));
1344 ShowQueueStats(pCtx, &g_routePollQueue, _T("Routing table poller"));
1345 ShowQueueStats(pCtx, &g_statusPollQueue, _T("Status poller"));
1346 ConsolePrintf(pCtx, _T("\n"));
5039dede 1347 }
35f836fe 1348 else if (IsCommand(_T("ROUTING-TABLE"), szBuffer, 1))
5039dede 1349 {
967893bb 1350 UINT32 dwNode;
5039dede
AK
1351 NetObj *pObject;
1352
1353 pArg = ExtractWord(pArg, szBuffer);
35f836fe 1354 dwNode = _tcstoul(szBuffer, NULL, 0);
5039dede
AK
1355 if (dwNode != 0)
1356 {
1357 pObject = FindObjectById(dwNode);
1358 if (pObject != NULL)
1359 {
1360 if (pObject->Type() == OBJECT_NODE)
1361 {
1362 ROUTING_TABLE *pRT;
35f836fe 1363 TCHAR szIpAddr[16];
5039dede
AK
1364 int i;
1365
35f836fe 1366 ConsolePrintf(pCtx, _T("Routing table for node %s:\n\n"), pObject->Name());
58b3e451 1367 pRT = ((Node *)pObject)->getCachedRoutingTable();
5039dede
AK
1368 if (pRT != NULL)
1369 {
1370 for(i = 0; i < pRT->iNumEntries; i++)
1371 {
35f836fe
VK
1372 _sntprintf(szBuffer, 256, _T("%s/%d"), IpToStr(pRT->pRoutes[i].dwDestAddr, szIpAddr),
1373 BitsInMask(pRT->pRoutes[i].dwDestMask));
1374 ConsolePrintf(pCtx, _T("%-18s %-15s %-6d %d\n"), szBuffer,
1375 IpToStr(pRT->pRoutes[i].dwNextHop, szIpAddr),
1376 pRT->pRoutes[i].dwIfIndex, pRT->pRoutes[i].dwRouteType);
5039dede 1377 }
35f836fe 1378 ConsolePrintf(pCtx, _T("\n"));
5039dede
AK
1379 }
1380 else
1381 {
35f836fe 1382 ConsolePrintf(pCtx, _T("Node doesn't have cached routing table\n\n"));
5039dede
AK
1383 }
1384 }
1385 else
1386 {
35f836fe 1387 ConsolePrintf(pCtx, _T("ERROR: Object is not a node\n\n"));
5039dede
AK
1388 }
1389 }
1390 else
1391 {
35f836fe 1392 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode);
5039dede
AK
1393 }
1394 }
1395 else
1396 {
35f836fe 1397 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node ID\n\n"));
5039dede
AK
1398 }
1399 }
35f836fe 1400 else if (IsCommand(_T("SESSIONS"), szBuffer, 2))
5039dede 1401 {
534e1b83
VK
1402 ConsolePrintf(pCtx, _T("\x1b[1mCLIENT SESSIONS\x1b[0m\n============================================================\n"));
1403 DumpClientSessions(pCtx);
1404 ConsolePrintf(pCtx, _T("\n\x1b[1mMOBILE DEVICE SESSIONS\x1b[0m\n============================================================\n"));
1405 DumpMobileDeviceSessions(pCtx);
5039dede 1406 }
35f836fe 1407 else if (IsCommand(_T("STATS"), szBuffer, 2))
5039dede
AK
1408 {
1409 ShowServerStats(pCtx);
1410 }
35f836fe 1411 else if (IsCommand(_T("USERS"), szBuffer, 1))
5039dede
AK
1412 {
1413 DumpUsers(pCtx);
1414 }
b0ff1179
VK
1415 else if (IsCommand(_T("VLANS"), szBuffer, 1))
1416 {
967893bb 1417 UINT32 dwNode;
b0ff1179
VK
1418 NetObj *pObject;
1419
1420 pArg = ExtractWord(pArg, szBuffer);
1421 dwNode = _tcstoul(szBuffer, NULL, 0);
1422 if (dwNode != 0)
1423 {
1424 pObject = FindObjectById(dwNode);
1425 if (pObject != NULL)
1426 {
1427 if (pObject->Type() == OBJECT_NODE)
1428 {
1429 VlanList *vlans = ((Node *)pObject)->getVlans();
1430 if (vlans != NULL)
1431 {
1432 ConsolePrintf(pCtx, _T("\x1b[1mVLAN\x1b[0m | \x1b[1mName\x1b[0m | \x1b[1mPorts\x1b[0m\n")
1433 _T("-----+------------------+-----------------------------------------------------------------\n"));
1434 for(int i = 0; i < vlans->getSize(); i++)
1435 {
1436 VlanInfo *vlan = vlans->get(i);
1437 ConsolePrintf(pCtx, _T("%4d | %-16s |"), vlan->getVlanId(), vlan->getName());
1438 for(int j = 0; j < vlan->getNumPorts(); j++)
1439 ConsolePrintf(pCtx, _T(" %d.%d"), (int)(vlan->getPorts()[j] >> 16), (int)(vlan->getPorts()[j] & 0xFFFF));
1440 ConsolePrintf(pCtx, _T("\n"));
1441 }
1442 ConsolePrintf(pCtx, _T("\n"));
1443 vlans->decRefCount();
1444 }
1445 else
1446 {
1447 ConsolePrintf(pCtx, _T("\x1b[31mNode doesn't have VLAN information\x1b[0m\n\n"));
1448 }
1449 }
1450 else
1451 {
1452 ConsolePrintf(pCtx, _T("\x1b[31mERROR: Object is not a node\x1b[0m\n\n"));
1453 }
1454 }
1455 else
1456 {
1457 ConsolePrintf(pCtx, _T("\x1b[31mERROR: Object with ID %d does not exist\x1b[0m\n\n"), dwNode);
1458 }
1459 }
1460 else
1461 {
1462 ConsolePrintf(pCtx, _T("\x1b[31mERROR: Invalid or missing node ID\x1b[0m\n\n"));
1463 }
1464 }
35f836fe 1465 else if (IsCommand(_T("WATCHDOG"), szBuffer, 1))
5039dede
AK
1466 {
1467 WatchdogPrintStatus(pCtx);
35f836fe 1468 ConsolePrintf(pCtx, _T("\n"));
5039dede
AK
1469 }
1470 else
1471 {
1472 if (szBuffer[0] == 0)
35f836fe 1473 ConsolePrintf(pCtx, _T("ERROR: Missing subcommand\n\n"));
5039dede 1474 else
35f836fe 1475 ConsolePrintf(pCtx, _T("ERROR: Invalid SHOW subcommand\n\n"));
5039dede
AK
1476 }
1477 }
06a8857b
AK
1478 else if (IsCommand(_T("EXEC"), szBuffer, 3))
1479 {
1480 pArg = ExtractWord(pArg, szBuffer);
35104062 1481
e323047c
VK
1482 bool libraryLocked = true;
1483 g_pScriptLibrary->lock();
1484
35104062
VK
1485 NXSL_Program *compiledScript = g_pScriptLibrary->findScript(szBuffer);
1486 if (compiledScript == NULL)
06a8857b 1487 {
e323047c
VK
1488 g_pScriptLibrary->unlock();
1489 libraryLocked = false;
35104062 1490 char *script;
967893bb 1491 UINT32 fileSize;
35104062 1492 if ((script = (char *)LoadFile(szBuffer, &fileSize)) != NULL)
06a8857b 1493 {
35104062
VK
1494 const int errorMsgLen = 512;
1495 TCHAR errorMsg[errorMsgLen];
1496#ifdef UNICODE
1497 WCHAR *wscript = WideStringFromMBString(script);
1498 compiledScript = NXSLCompile(wscript, errorMsg, errorMsgLen);
1499 free(wscript);
1500#else
1501 compiledScript = NXSLCompile(script, errorMsg, errorMsgLen);
1502#endif
1503 free(script);
1504 if (compiledScript == NULL)
06a8857b 1505 {
35104062 1506 ConsolePrintf(pCtx, _T("ERROR: Script compilation error: %s\n\n"), errorMsg);
06a8857b
AK
1507 }
1508 }
1509 else
1510 {
35104062 1511 ConsolePrintf(pCtx, _T("ERROR: Script \"%s\" not found\n\n"), szBuffer);
06a8857b
AK
1512 }
1513 }
35104062
VK
1514
1515 if (compiledScript != NULL)
06a8857b 1516 {
35104062 1517 NXSL_ServerEnv *pEnv = new NXSL_ServerEnv;
2773ef30 1518 pEnv->setConsole(pCtx);
35104062
VK
1519
1520 NXSL_Value *argv[32];
1521 int argc = 0;
1522 while(argc < 32)
1523 {
1524 pArg = ExtractWord(pArg, szBuffer);
1525 if (szBuffer[0] == 0)
1526 break;
1527 argv[argc++] = new NXSL_Value(szBuffer);
1528 }
1529
1530 if (compiledScript->run(pEnv, argc, argv) == 0)
1531 {
1532 NXSL_Value *pValue = compiledScript->getResult();
1533 int retCode = pValue->getValueAsInt32();
1534 ConsolePrintf(pCtx, _T("INFO: Script finished with rc=%d\n\n"), retCode);
1535 }
1536 else
1537 {
1538 ConsolePrintf(pCtx, _T("ERROR: Script finished with error: %s\n\n"), compiledScript->getErrorText());
1539 }
06a8857b 1540 }
e323047c
VK
1541 if (libraryLocked)
1542 g_pScriptLibrary->unlock();
06a8857b 1543 }
35f836fe 1544 else if (IsCommand(_T("TRACE"), szBuffer, 1))
5039dede 1545 {
967893bb 1546 UINT32 dwNode1, dwNode2;
5039dede 1547 NetObj *pObject1, *pObject2;
6d069676 1548 NetworkPath *pTrace;
35f836fe 1549 TCHAR szNextHop[16];
5039dede
AK
1550 int i;
1551
1552 // Get arguments
1553 pArg = ExtractWord(pArg, szBuffer);
35f836fe 1554 dwNode1 = _tcstoul(szBuffer, NULL, 0);
5039dede
AK
1555
1556 pArg = ExtractWord(pArg, szBuffer);
35f836fe 1557 dwNode2 = _tcstoul(szBuffer, NULL, 0);
5039dede
AK
1558
1559 if ((dwNode1 != 0) && (dwNode2 != 0))
1560 {
1561 pObject1 = FindObjectById(dwNode1);
1562 if (pObject1 == NULL)
1563 {
35f836fe 1564 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode1);
5039dede
AK
1565 }
1566 else
1567 {
1568 pObject2 = FindObjectById(dwNode2);
1569 if (pObject2 == NULL)
1570 {
35f836fe 1571 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode2);
5039dede
AK
1572 }
1573 else
1574 {
6d069676 1575 if ((pObject1->Type() == OBJECT_NODE) && (pObject2->Type() == OBJECT_NODE))
5039dede
AK
1576 {
1577 pTrace = TraceRoute((Node *)pObject1, (Node *)pObject2);
1578 if (pTrace != NULL)
1579 {
6d069676
VK
1580 ConsolePrintf(pCtx, _T("Trace from %s to %s (%d hops, %s):\n"),
1581 pObject1->Name(), pObject2->Name(), pTrace->getHopCount(),
1582 pTrace->isComplete() ? _T("complete") : _T("incomplete"));
1583 for(i = 0; i < pTrace->getHopCount(); i++)
1584 {
1585 HOP_INFO *hop = pTrace->getHopInfo(i);
35f836fe 1586 ConsolePrintf(pCtx, _T("[%d] %s %s %s %d\n"),
6d069676
VK
1587 hop->object->Id(),
1588 hop->object->Name(),
1589 IpToStr(hop->nextHop, szNextHop),
1590 hop->isVpn ? _T("VPN Connector ID:") : _T("Interface Index: "),
1591 hop->ifIndex);
1592 }
1593 delete pTrace;
35f836fe 1594 ConsolePrintf(pCtx, _T("\n"));
5039dede
AK
1595 }
1596 else
1597 {
35f836fe 1598 ConsolePrintf(pCtx, _T("ERROR: Call to TraceRoute() failed\n\n"));
5039dede
AK
1599 }
1600 }
1601 else
1602 {
35f836fe 1603 ConsolePrintf(pCtx, _T("ERROR: Object is not a node\n\n"));
5039dede
AK
1604 }
1605 }
1606 }
1607 }
1608 else
1609 {
35f836fe 1610 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node id(s)\n\n"));
5039dede
AK
1611 }
1612 }
35f836fe 1613 else if (IsCommand(_T("HELP"), szBuffer, 2) || IsCommand(_T("?"), szBuffer, 1))
5039dede 1614 {
35f836fe 1615 ConsolePrintf(pCtx, _T("Valid commands are:\n")
48c0079d 1616 _T(" debug [<level>|off] - Set debug level (valid range is 0..9)\n")
48a3497b
VK
1617 _T(" down - Shutdown NetXMS server\n")
1618 _T(" exec <script> [<params>] - Executes NXSL script from script library\n")
35f836fe 1619 _T(" exit - Exit from remote session\n")
206e268e 1620 _T(" get <variable> - Get value of server configuration variable\n")
35f836fe
VK
1621 _T(" help - Display this help\n")
1622 _T(" raise <exception> - Raise exception\n")
206e268e 1623 _T(" set <variable> <value> - Set value of server configuration variable\n")
50d0de67 1624 _T(" show components <node> - Show physical components of given node\n")
9c133761 1625 _T(" show dbcp - Show active sessions in database connection pool\n")
48a3497b 1626 _T(" show fdb <node> - Show forwarding database for node\n")
35f836fe
VK
1627 _T(" show flags - Show internal server flags\n")
1628 _T(" show index <index> - Show internal index\n")
35f836fe
VK
1629 _T(" show objects - Dump network objects to screen\n")
1630 _T(" show pollers - Show poller threads state information\n")
1631 _T(" show queues - Show internal queues statistics\n")
1632 _T(" show routing-table <node> - Show cached routing table for node\n")
1633 _T(" show sessions - Show active client sessions\n")
1634 _T(" show stats - Show server statistics\n")
1635 _T(" show users - Show users\n")
b0ff1179 1636 _T(" show vlans <node> - Show cached VLAN information for node\n")
35f836fe
VK
1637 _T(" show watchdog - Display watchdog information\n")
1638 _T(" trace <node1> <node2> - Show network path trace between two nodes\n")
1639 _T("\nAlmost all commands can be abbreviated to 2 or 3 characters\n")
1640 _T("\n"));
5039dede
AK
1641 }
1642 else
1643 {
35f836fe 1644 ConsolePrintf(pCtx, _T("UNKNOWN COMMAND\n\n"));
5039dede
AK
1645 }
1646
1647 return nExitCode;
1648}
1649
fdbee7f8
VK
1650/**
1651 * Signal handler for UNIX platforms
1652 */
5039dede
AK
1653#ifndef _WIN32
1654
1655void SignalHandlerStub(int nSignal)
1656{
1657 // should be unused, but JIC...
1658 if (nSignal == SIGCHLD)
1659 {
1660 while (waitpid(-1, NULL, WNOHANG) > 0)
1661 ;
1662 }
1663}
1664
1665THREAD_RESULT NXCORE_EXPORTABLE THREAD_CALL SignalHandler(void *pArg)
1666{
1667 sigset_t signals;
1668 int nSignal;
1669 BOOL bCallShutdown = FALSE;
1670
1671 m_signalHandlerThread = pthread_self();
1672
1673 // default for SIGCHLD: ignore
1674 signal(SIGCHLD, &SignalHandlerStub);
1675
1676 sigemptyset(&signals);
1677 sigaddset(&signals, SIGTERM);
1678 sigaddset(&signals, SIGINT);
5039dede
AK
1679 sigaddset(&signals, SIGSEGV);
1680 sigaddset(&signals, SIGCHLD);
1681 sigaddset(&signals, SIGHUP);
1682 sigaddset(&signals, SIGUSR1);
1683 sigaddset(&signals, SIGUSR2);
95e2329a
VK
1684#if !defined(__sun) && !defined(_AIX) && !defined(__hpux)
1685 sigaddset(&signals, SIGPIPE);
1686#endif
5039dede
AK
1687
1688 sigprocmask(SIG_BLOCK, &signals, NULL);
1689
1690 while(1)
1691 {
1692 if (sigwait(&signals, &nSignal) == 0)
1693 {
1694 switch(nSignal)
1695 {
1696 case SIGTERM:
1697 case SIGINT:
1698 m_nShutdownReason = SHUTDOWN_BY_SIGNAL;
1699 if (IsStandalone())
1700 bCallShutdown = TRUE;
1701 ConditionSet(m_condShutdown);
1702 goto stop_handler;
1703 case SIGSEGV:
1704 abort();
1705 break;
1706 case SIGCHLD:
1707 while (waitpid(-1, NULL, WNOHANG) > 0)
1708 ;
1709 break;
1710 case SIGUSR1:
1711 if (g_dwFlags & AF_SHUTDOWN)
1712 goto stop_handler;
1713 break;
1714 default:
1715 break;
1716 }
1717 }
1718 else
1719 {
1720 ThreadSleepMs(100);
1721 }
1722 }
1723
1724stop_handler:
1725 sigprocmask(SIG_UNBLOCK, &signals, NULL);
1726 if (bCallShutdown)
1727 Shutdown();
1728 return THREAD_OK;
1729}
1730
1731#endif
1732
fdbee7f8
VK
1733/**
1734 * Common main()
1735 */
5039dede
AK
1736THREAD_RESULT NXCORE_EXPORTABLE THREAD_CALL Main(void *pArg)
1737{
1738 nxlog_write(MSG_SERVER_STARTED, EVENTLOG_INFORMATION_TYPE, NULL);
1739
7bdb43c3
VK
1740 if (IsStandalone())
1741 {
1742 if (!(g_dwFlags & AF_DEBUG_CONSOLE_DISABLED))
1743 {
1744 char *ptr, szCommand[256];
1745 struct __console_ctx ctx;
35f836fe 1746#ifdef UNICODE
7bdb43c3 1747 WCHAR wcCommand[256];
35f836fe 1748#endif
5039dede 1749
7bdb43c3
VK
1750 ctx.hSocket = -1;
1751 ctx.socketMutex = INVALID_MUTEX_HANDLE;
1752 ctx.pMsg = NULL;
1753 ctx.session = NULL;
1754 ctx.output = NULL;
1755 WriteToTerminal(_T("\nNetXMS Server V") NETXMS_VERSION_STRING _T(" Build ") NETXMS_VERSION_BUILD_STRING _T(" Ready\n")
1756 _T("Enter \"\x1b[1mhelp\x1b[0m\" for command list or \"\x1b[1mdown\x1b[0m\" for server shutdown\n")
1757 _T("System Console\n\n"));
5039dede
AK
1758
1759#if USE_READLINE
7bdb43c3
VK
1760 // Initialize readline library if we use it
1761 rl_bind_key('\t', RL_INSERT_CAST rl_insert);
5039dede
AK
1762#endif
1763
7bdb43c3
VK
1764 while(1)
1765 {
5039dede 1766#if USE_READLINE
7bdb43c3 1767 ptr = readline("\x1b[33mnetxmsd:\x1b[0m ");
5039dede 1768#else
7bdb43c3
VK
1769 WriteToTerminal(_T("\x1b[33mnetxmsd:\x1b[0m "));
1770 fflush(stdout);
1771 if (fgets(szCommand, 255, stdin) == NULL)
1772 break; // Error reading stdin
1773 ptr = strchr(szCommand, '\n');
1774 if (ptr != NULL)
1775 *ptr = 0;
1776 ptr = szCommand;
5039dede
AK
1777#endif
1778
7bdb43c3
VK
1779 if (ptr != NULL)
1780 {
35f836fe 1781#ifdef UNICODE
7bdb43c3
VK
1782 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, ptr, -1, wcCommand, 256);
1783 wcCommand[255] = 0;
1784 StrStrip(wcCommand);
1785 if (wcCommand[0] != 0)
1786 {
1787 if (ProcessConsoleCommand(wcCommand, &ctx) == CMD_EXIT_SHUTDOWN)
35f836fe 1788#else
7bdb43c3
VK
1789 StrStrip(ptr);
1790 if (*ptr != 0)
1791 {
1792 if (ProcessConsoleCommand(ptr, &ctx) == CMD_EXIT_SHUTDOWN)
35f836fe 1793#endif
7bdb43c3 1794 break;
5039dede 1795#if USE_READLINE
7bdb43c3 1796 add_history(ptr);
5039dede 1797#endif
7bdb43c3 1798 }
5039dede 1799#if USE_READLINE
7bdb43c3 1800 free(ptr);
5039dede 1801#endif
7bdb43c3
VK
1802 }
1803 else
1804 {
1805 _tprintf(_T("\n"));
1806 }
1807 }
5039dede
AK
1808
1809#if USE_READLINE
7bdb43c3 1810 free(ptr);
5039dede 1811#endif
7bdb43c3
VK
1812 m_nShutdownReason = SHUTDOWN_FROM_CONSOLE;
1813 Shutdown();
1814 }
1815 else
1816 {
1817 // standalone with debug console disabled
1818#ifdef _WIN32
1819 _tprintf(_T("Server running. Press ESC to shutdown.\n"));
1820 while(1)
1821 {
1822 if (_getch() == 27)
1823 break;
1824 }
1825 _tprintf(_T("Server shutting down...\n"));
1826 Shutdown();
1827#else
1828 _tprintf(_T("Server running. Press Ctrl+C to shutdown.\n"));
1829 // Shutdown will be called from signal handler
1830 ConditionWait(m_condShutdown, INFINITE);
1831#endif
1832 }
5039dede
AK
1833 }
1834 else
1835 {
1836 ConditionWait(m_condShutdown, INFINITE);
1837 // On Win32, Shutdown() will be called by service control handler
1838#ifndef _WIN32
1839 Shutdown();
1840#endif
1841 }
1842 return THREAD_OK;
1843}
1844
fdbee7f8
VK
1845/**
1846 * Initiate server shutdown
1847 */
035a4d73 1848void InitiateShutdown()
5039dede
AK
1849{
1850#ifdef _WIN32
1851 Shutdown();
1852#else
1853 if (IsStandalone())
1854 {
1855 Shutdown();
1856 }
1857 else
1858 {
1859 pthread_kill(m_signalHandlerThread, SIGTERM);
1860 }
1861#endif
1862}
1863
fdbee7f8
VK
1864/**
1865 *DLL Entry point
1866 */
5039dede
AK
1867#ifdef _WIN32
1868
1869BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
1870{
1871 if (dwReason == DLL_PROCESS_ATTACH)
1872 DisableThreadLibraryCalls(hInstance);
1873 return TRUE;
1874}
1875
1876#endif