fixed size_t/int warnings; implemented missing constructor for Array class
[public/netxms.git] / src / server / netxmsd / netxmsd.cpp
CommitLineData
5039dede
AK
1/*
2** NetXMS - Network Management System
3** Server startup module
ed950274 4** Copyright (C) 2003-2013 NetXMS Team
5039dede
AK
5**
6** This program is free software; you can redistribute it and/or modify
7** it under the terms of the GNU General Public License as published by
8** the Free Software Foundation; either version 2 of the License, or
9** (at your option) any later version.
10**
11** This program is distributed in the hope that it will be useful,
12** but WITHOUT ANY WARRANTY; without even the implied warranty of
13** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14** GNU General Public License for more details.
15**
16** You should have received a copy of the GNU General Public License
17** along with this program; if not, write to the Free Software
18** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19**
20** File: netxmsd.cpp
21**
22**/
23
24#include "netxmsd.h"
25
26#if HAVE_GETOPT_H
27#include <getopt.h>
28#endif
29
30#ifdef _WIN32
31#include <dbghelp.h>
32#endif
33
44cdd527
VK
34#ifdef __sun
35#include <signal.h>
36#endif
37
d27e7413 38#if defined(_WITH_ENCRYPTION) && defined(_WIN32)
958a9397
VK
39#include <openssl/applink.c>
40#endif
41
f375019e
VK
42/**
43 * Global data
44 */
5039dede
AK
45BOOL g_bCheckDB = FALSE;
46
f375019e
VK
47/**
48 * Help text
49 */
e0f99bf0 50static TCHAR help_text[] = _T("NetXMS Server Version ") NETXMS_VERSION_STRING _T("\n")
f375019e 51 _T("Copyright (c) 2003-2013 NetXMS Team\n\n")
e0f99bf0
VK
52 _T("Usage: netxmsd [<options>]\n\n")
53 _T("Valid options are:\n")
54 _T(" -e : Run database check on startup\n")
55 _T(" -c <file> : Set non-default configuration file\n")
56 _T(" : Default is ") DEFAULT_CONFIG_FILE _T("\n")
57 _T(" -d : Run as daemon/service\n")
58 _T(" -D <level> : Set debug level (valid levels are 0..9)\n")
8782d780 59 _T(" -q : Disable interactive console\n")
e0f99bf0 60 _T(" -h : Display help and exit\n")
5039dede 61#ifdef _WIN32
e0f99bf0
VK
62 _T(" -I : Install Windows service\n")
63 _T(" -L <user> : Login name for service account.\n")
64 _T(" -P <passwd> : Password for service account.\n")
5039dede 65#else
e0f99bf0 66 _T(" -p <file> : Specify pid file.\n")
5039dede
AK
67#endif
68#ifdef _WIN32
e0f99bf0
VK
69 _T(" -R : Remove Windows service\n")
70 _T(" -s : Start Windows service\n")
71 _T(" -S : Stop Windows service\n")
5039dede 72#endif
e0f99bf0
VK
73 _T(" -v : Display version and exit\n")
74 _T("\n");
5039dede 75
f375019e
VK
76/**
77 * Execute command and wait
78 */
e0f99bf0 79static BOOL ExecAndWait(char *pszCommand)
5039dede
AK
80{
81 BOOL bSuccess = TRUE;
82
83#ifdef _WIN32
e0f99bf0 84 STARTUPINFOA si;
5039dede
AK
85 PROCESS_INFORMATION pi;
86
87 // Fill in process startup info structure
977e7d9d
VK
88 memset(&si, 0, sizeof(STARTUPINFOA));
89 si.cb = sizeof(STARTUPINFOA);
5039dede
AK
90 si.dwFlags = 0;
91
92 // Create new process
e0f99bf0
VK
93 if (!CreateProcessA(NULL, pszCommand, NULL, NULL, FALSE,
94 IsStandalone() ? 0 : CREATE_NO_WINDOW | DETACHED_PROCESS,
95 NULL, NULL, &si, &pi))
5039dede
AK
96 {
97 bSuccess = FALSE;
98 }
99 else
100 {
101 WaitForSingleObject(pi.hProcess, INFINITE);
102
103 // Close all handles
104 CloseHandle(pi.hThread);
105 CloseHandle(pi.hProcess);
106 }
107#else
108 bSuccess = (system(pszCommand) != -1);
109#endif
110
111 return bSuccess;
112}
113
114
41767c3d
VP
115/**
116 * Create minidump of given process
117 */
5039dede
AK
118
119#ifdef _WIN32
120
121static void CreateMiniDump(DWORD pid)
122{
123 HANDLE hFile, hProcess;
124 TCHAR error[256];
125
e0f99bf0 126 _tprintf(_T("INFO: Starting minidump for process %d\n"), pid);
5039dede
AK
127 hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
128 if (hProcess != NULL)
129 {
130 hFile = CreateFile(_T("C:\\netxmsd.mdmp"), GENERIC_WRITE, 0, NULL,
131 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
132 if (hFile != INVALID_HANDLE_VALUE)
133 {
134 MiniDumpWriteDump(hProcess, pid, hFile, MiniDumpNormal, NULL, NULL, NULL);
135 CloseHandle(hFile);
e0f99bf0 136 _tprintf(_T("INFO: Minidump created successfully\n"));
5039dede
AK
137 }
138 else
139 {
e0f99bf0 140 _tprintf(_T("ERROR: cannot create file for minidump (%s)\n"), GetSystemErrorText(GetLastError(), error, 256));
5039dede
AK
141 }
142 }
143 else
144 {
e0f99bf0 145 _tprintf(_T("ERROR: cannot open process %d (%s)\n"), pid, GetSystemErrorText(GetLastError(), error, 256));
5039dede
AK
146 }
147}
148
149#endif
150
5039dede 151#ifdef _WIN32
8782d780 152#define VALID_OPTIONS "c:CdD:qehIL:P:RsSv"
5039dede 153#else
8782d780 154#define VALID_OPTIONS "c:CdD:qehp:v"
5039dede
AK
155#endif
156
d78be64d
VK
157/**
158 * Parse command line
159 * Returns TRUE on success and FALSE on failure
160 */
5039dede
AK
161static BOOL ParseCommandLine(int argc, char *argv[])
162{
163 int ch;
e0f99bf0 164 char *eptr;
5039dede 165#ifdef _WIN32
e0f99bf0
VK
166 TCHAR login[256] = _T(""), password[256] = _T("");
167 char exePath[MAX_PATH], dllPath[MAX_PATH], *ptr;
5039dede
AK
168 BOOL useLogin = FALSE;
169#endif
170#if defined(_WIN32) || HAVE_DECL_GETOPT_LONG
171 static struct option longOptions[] =
172 {
0b8da006
AK
173 { (char *)"check-db", 0, NULL, 'e' },
174 { (char *)"config", 1, NULL, 'c' },
175 { (char *)"daemon", 0, NULL, 'd' },
176 { (char *)"debug", 1, NULL, 'D' },
177 { (char *)"help", 0, NULL, 'h' },
8782d780 178 { (char *)"quiet", 1, NULL, 'q' },
5039dede 179#ifdef _WIN32
0b8da006
AK
180 { (char *)"check-service", 0, NULL, '!' },
181 { (char *)"dump", 1, NULL, '~' },
182 { (char *)"install", 0, NULL, 'I' },
183 { (char *)"login", 1, NULL, 'L' },
184 { (char *)"password", 1, NULL, 'P' },
185 { (char *)"remove", 0, NULL, 'R' },
186 { (char *)"start", 0, NULL, 's' },
187 { (char *)"stop", 0, NULL, 'S' },
5039dede 188#else
0b8da006 189 { (char *)"pid-file", 1, NULL, 'p' },
5039dede
AK
190#endif
191 { NULL, 0, 0, 0 }
192 };
193#endif
194
195#if defined(_WIN32) || HAVE_DECL_GETOPT_LONG
196 while((ch = getopt_long(argc, argv, VALID_OPTIONS, longOptions, NULL)) != -1)
197#else
198 while((ch = getopt(argc, argv, VALID_OPTIONS)) != -1)
199#endif
200 {
201 switch(ch)
202 {
203 case 'h':
e0f99bf0 204 _tprintf(help_text);
5039dede
AK
205 return FALSE;
206 case 'v':
e0f99bf0 207 _tprintf(_T("NetXMS Server Version ") NETXMS_VERSION_STRING _T(" Build of %hs\n"), __DATE__);
5039dede
AK
208 return FALSE;
209 case 'c':
e0f99bf0
VK
210#ifdef UNICODE
211 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, g_szConfigFile, MAX_PATH);
212 g_szConfigFile[MAX_PATH - 1] = 0;
213#else
5039dede 214 nx_strncpy(g_szConfigFile, optarg, MAX_PATH);
e0f99bf0 215#endif
5039dede
AK
216 break;
217 case 'C': // Check config
218 g_dwFlags &= ~AF_DAEMON;
e0f99bf0 219 _tprintf(_T("Checking configuration file (%s):\n\n"), g_szConfigFile);
5039dede
AK
220 LoadConfig();
221 return FALSE;
222 case 'd':
223 g_dwFlags |= AF_DAEMON;
224 break;
225 case 'D': // Debug level
ed950274
VK
226 g_debugLevel = strtoul(optarg, &eptr, 0);
227 if ((*eptr != 0) || (g_debugLevel > 9))
5039dede 228 {
e0f99bf0 229 _tprintf(_T("Invalid debug level \"%hs\" - should be in range 0..9\n"), optarg);
ed950274 230 g_debugLevel = 0;
5039dede
AK
231 }
232 break;
3a82d5ae
VK
233 case 'q': // disable interactive console
234 g_dwFlags |= AF_DEBUG_CONSOLE_DISABLED;
235 break;
5039dede
AK
236 case 'e':
237 g_bCheckDB = TRUE;
238 break;
239#ifdef _WIN32
240 case 'L':
e0f99bf0
VK
241#ifdef UNICODE
242 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, login, 256);
243 login[255] = 0;
244#else
5039dede 245 nx_strncpy(login, optarg, 256);
e0f99bf0 246#endif
5039dede
AK
247 useLogin = TRUE;
248 break;
249 case 'P':
e0f99bf0
VK
250#ifdef UNICODE
251 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, password, 256);
252 password[255] = 0;
253#else
5039dede 254 nx_strncpy(password, optarg, 256);
e0f99bf0 255#endif
5039dede
AK
256 break;
257 case 'I': // Install service
258 ptr = strrchr(argv[0], '\\');
259 if (ptr != NULL)
260 ptr++;
261 else
262 ptr = argv[0];
263
264 _fullpath(exePath, ptr, 255);
265
266 if (stricmp(&exePath[strlen(exePath)-4], ".exe"))
267 strcat(exePath, ".exe");
268 strcpy(dllPath, exePath);
269 ptr = strrchr(dllPath, '\\');
270 if (ptr != NULL) // Shouldn't be NULL
271 {
272 ptr++;
273 strcpy(ptr, "libnxsrv.dll");
274 }
e0f99bf0
VK
275#ifdef UNICODE
276 WCHAR wexePath[MAX_PATH], wdllPath[MAX_PATH];
277 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, exePath, -1, wexePath, MAX_PATH);
278 wexePath[MAX_PATH - 1] = 0;
279 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, dllPath, -1, wdllPath, MAX_PATH);
280 wdllPath[MAX_PATH - 1] = 0;
281 InstallService(wexePath, wdllPath, useLogin ? login : NULL, useLogin ? password : NULL);
282#else
5039dede 283 InstallService(exePath, dllPath, useLogin ? login : NULL, useLogin ? password : NULL);
e0f99bf0 284#endif
5039dede
AK
285 return FALSE;
286 case 'R': // Remove service
287 RemoveService();
288 return FALSE;
289 case 's': // Start service
290 StartCoreService();
291 return FALSE;
292 case 'S': // Stop service
293 StopCoreService();
294 return FALSE;
295 case '!': // Check service configuration (for migration from pre-0.2.20)
296 CheckServiceConfig();
297 return FALSE;
298 case '~':
e0f99bf0 299 CreateMiniDump(strtoul(optarg, NULL, 0));
5039dede
AK
300 return FALSE;
301#endif
302 default:
303 break;
304 }
305 }
306 return TRUE;
307}
308
d78be64d
VK
309/**
310 * Startup code
311 */
06b383fe 312int main(int argc, char* argv[])
5039dede
AK
313{
314#ifdef _WIN32
315 HKEY hKey;
316 DWORD dwSize;
317#else
318 int i;
319 FILE *fp;
c601fc15 320 TCHAR *pszEnv;
5039dede
AK
321#endif
322
d40b6356 323#if defined(__sun) || defined(_AIX) || defined(__hpux)
44cdd527
VK
324 signal(SIGPIPE, SIG_IGN);
325 signal(SIGHUP, SIG_IGN);
326 signal(SIGINT, SIG_IGN);
327 signal(SIGQUIT, SIG_IGN);
328 signal(SIGUSR1, SIG_IGN);
329 signal(SIGUSR2, SIG_IGN);
330#endif
331
5039dede
AK
332 InitThreadLibrary();
333
334#ifdef NETXMS_MEMORY_DEBUG
335 InitMemoryDebugger();
336#endif
337
338 // Check for alternate config file location
339#ifdef _WIN32
42acd918 340 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\NetXMS\\Server"), 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
5039dede
AK
341 {
342 dwSize = MAX_PATH * sizeof(TCHAR);
343 RegQueryValueEx(hKey, _T("ConfigFile"), NULL, NULL, (BYTE *)g_szConfigFile, &dwSize);
344 RegCloseKey(hKey);
345 }
346#else
82d4fb3d 347 pszEnv = _tgetenv(_T("NETXMSD_CONFIG"));
5039dede
AK
348 if (pszEnv != NULL)
349 nx_strncpy(g_szConfigFile, pszEnv, MAX_PATH);
350#endif
351
1e2b0526
VP
352 if (!ParseCommandLine(argc, argv))
353 return 1;
5039dede
AK
354
355 if (!LoadConfig())
356 {
357 if (IsStandalone())
e0f99bf0 358 _tprintf(_T("Error loading configuration file\n"));
5039dede
AK
359 return 1;
360 }
361
e2e66145
VK
362 if (g_debugLevel == NXCONFIG_UNINITIALIZED_VALUE)
363 g_debugLevel = 0;
364
5039dede
AK
365 // Set exception handler
366#ifdef _WIN32
367 if (g_dwFlags & AF_CATCH_EXCEPTIONS)
4262c0dc 368 SetExceptionHandler(SEHServiceExceptionHandler, SEHServiceExceptionDataWriter,
e0f99bf0 369 g_szDumpDir, _T("netxmsd"), MSG_EXCEPTION, g_dwFlags & AF_WRITE_FULL_DUMP, IsStandalone());
5039dede
AK
370 __try {
371#endif
372
712dd47d
VK
373 // Fix path to Java VM
374#ifdef _WIN32
375 if (!_tcscmp(g_szJavaPath, _T("java")))
376 {
377 TCHAR path[MAX_PATH];
378
379 if (GetModuleFileName(NULL, path, MAX_PATH) != 0)
380 {
381 TCHAR *p = _tcsrchr(path, _T('\\'));
382 if (p != NULL)
383 {
384 p--;
385 p = _tcsrchr(p, _T('\\'));
386 if (p != NULL)
387 {
388 p++;
389 _tcscpy(p, _T("jre\\bin\\java.exe"));
390 if (_taccess(path, 4))
391 {
392 _tcscpy(g_szJavaPath, path);
393 }
394 }
395 }
396 }
397 }
398#endif
399
5039dede
AK
400 // Check database before start if requested
401 if (g_bCheckDB)
402 {
403 char szCmd[MAX_PATH + 128], *pszSep;
404
405 strncpy(szCmd, argv[0], MAX_PATH);
406 pszSep = strrchr(szCmd, FS_PATH_SEPARATOR[0]);
407 if (pszSep != NULL)
408 pszSep++;
409 else
410 pszSep = szCmd;
e0f99bf0
VK
411#ifdef UNICODE
412 snprintf(pszSep, 128, "nxdbmgr -c \"%S\" -f check", g_szConfigFile);
413#else
414 snprintf(pszSep, 128, "nxdbmgr -c \"%s\" -f check", g_szConfigFile);
415#endif
5039dede
AK
416 if (!ExecAndWait(szCmd))
417 if (IsStandalone())
e0f99bf0 418 _tprintf(_T("ERROR: Failed to execute command \"%hs\"\n"), szCmd);
5039dede
AK
419 }
420
421#ifdef _WIN32
422 if (!IsStandalone())
423 {
424 InitService();
425 }
426 else
427 {
428 if (!Initialize())
429 {
e0f99bf0 430 _tprintf(_T("NetXMS Core initialization failed\n"));
5039dede
AK
431
432 // Remove database lock
433 if (g_dwFlags & AF_DB_LOCKED)
434 {
435 UnlockDB();
436 ShutdownDB();
437 }
438 return 3;
439 }
440 Main(NULL);
441 }
442#else /* not _WIN32 */
443 if (!IsStandalone())
444 {
445 if (daemon(0, 0) == -1)
446 {
447 perror("Call to daemon() failed");
448 return 2;
449 }
450 }
451
452 // Write PID file
e0f99bf0 453 fp = _tfopen(g_szPIDFile, _T("w"));
5039dede
AK
454 if (fp != NULL)
455 {
e0f99bf0 456 _ftprintf(fp, _T("%d"), getpid());
5039dede
AK
457 fclose(fp);
458 }
459
460 // Initialize server
461 if (!Initialize())
462 {
463 // Remove database lock
464 if (g_dwFlags & AF_DB_LOCKED)
465 {
466 UnlockDB();
467 ShutdownDB();
468 }
469 return 3;
470 }
471
472 // Everything is OK, start common main loop
473 StartMainLoop(SignalHandler, Main);
474#endif /* _WIN32 */
475
476#ifdef _WIN32
477 LIBNETXMS_EXCEPTION_HANDLER
478#endif
479 return 0;
480}