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