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