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