Fixed non unicode build
[public/netxms.git] / src / server / netxmsd / netxmsd.cpp
CommitLineData
5039dede
AK
1/*
2** NetXMS - Network Management System
3** Server startup module
3adc64ec 4** Copyright (C) 2003-2017 Raden Solutions
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
d27e7413 34#if defined(_WITH_ENCRYPTION) && defined(_WIN32)
958a9397
VK
35#include <openssl/applink.c>
36#endif
37
f375019e
VK
38/**
39 * Global data
40 */
5039dede
AK
41BOOL g_bCheckDB = FALSE;
42
f375019e 43/**
2df047f4
VK
44 * Debug level
45 */
46static int s_debugLevel = NXCONFIG_UNINITIALIZED_VALUE;
b41dff2a 47static TCHAR *s_debugTags = NULL;
2df047f4
VK
48
49/**
f375019e
VK
50 * Help text
51 */
f62b7eab 52static TCHAR help_text[] = _T("NetXMS Server Version ") NETXMS_VERSION_STRING _T(" Build ") NETXMS_VERSION_BUILD_STRING _T(" (") NETXMS_BUILD_TAG _T(")") IS_UNICODE_BUILD_STRING _T("\n")
43a6f3ca 53 _T("Copyright (c) 2003-2015 Raden Solutions\n\n")
e0f99bf0
VK
54 _T("Usage: netxmsd [<options>]\n\n")
55 _T("Valid options are:\n")
56 _T(" -e : Run database check on startup\n")
57 _T(" -c <file> : Set non-default configuration file\n")
e0f99bf0
VK
58 _T(" -d : Run as daemon/service\n")
59 _T(" -D <level> : Set debug level (valid levels are 0..9)\n")
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 67#endif
7bdb43c3 68 _T(" -q : Disable interactive console\n")
5039dede 69#ifdef _WIN32
e0f99bf0
VK
70 _T(" -R : Remove Windows service\n")
71 _T(" -s : Start Windows service\n")
72 _T(" -S : Stop Windows service\n")
5039dede 73#endif
e0f99bf0
VK
74 _T(" -v : Display version and exit\n")
75 _T("\n");
5039dede 76
f375019e
VK
77/**
78 * Execute command and wait
79 */
e0f99bf0 80static BOOL ExecAndWait(char *pszCommand)
5039dede
AK
81{
82 BOOL bSuccess = TRUE;
83
84#ifdef _WIN32
e0f99bf0 85 STARTUPINFOA si;
5039dede
AK
86 PROCESS_INFORMATION pi;
87
88 // Fill in process startup info structure
977e7d9d
VK
89 memset(&si, 0, sizeof(STARTUPINFOA));
90 si.cb = sizeof(STARTUPINFOA);
5039dede
AK
91 si.dwFlags = 0;
92
93 // Create new process
e0f99bf0
VK
94 if (!CreateProcessA(NULL, pszCommand, NULL, NULL, FALSE,
95 IsStandalone() ? 0 : CREATE_NO_WINDOW | DETACHED_PROCESS,
96 NULL, NULL, &si, &pi))
5039dede
AK
97 {
98 bSuccess = FALSE;
99 }
100 else
101 {
102 WaitForSingleObject(pi.hProcess, INFINITE);
103
104 // Close all handles
105 CloseHandle(pi.hThread);
106 CloseHandle(pi.hProcess);
107 }
108#else
109 bSuccess = (system(pszCommand) != -1);
110#endif
111
112 return bSuccess;
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 {
1b9f9924 134 MiniDumpWriteDump(hProcess, pid, hFile, MiniDumpWithDataSegs, NULL, NULL, NULL);
5039dede 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
7bdb43c3 152#define VALID_OPTIONS "c:CdD:ehIL:P:qRsSv"
5039dede 153#else
7bdb43c3 154#define VALID_OPTIONS "c:CdD:ehp:qv"
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':
e5390fb5 207 {
f62b7eab 208 _tprintf(_T("NetXMS Server Version ") NETXMS_VERSION_STRING _T(" Build ") NETXMS_VERSION_BUILD_STRING _T(" (") NETXMS_BUILD_TAG _T(")") IS_UNICODE_BUILD_STRING _T("\n"));
e5390fb5
VK
209 String ciphers = NXCPGetSupportedCiphersAsText();
210 _tprintf(_T("NXCP: %d.%d.%d.%d (%s)\n"),
211 NXCP_VERSION, CLIENT_PROTOCOL_VERSION_BASE, CLIENT_PROTOCOL_VERSION_MOBILE, CLIENT_PROTOCOL_VERSION_FULL,
212 ciphers.isEmpty() ? _T("NO ENCRYPTION") : ciphers.getBuffer());
ef6a61aa 213 _tprintf(_T("Built with: %hs\n"), CPP_COMPILER_VERSION);
e5390fb5 214 }
5039dede
AK
215 return FALSE;
216 case 'c':
e0f99bf0
VK
217#ifdef UNICODE
218 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, g_szConfigFile, MAX_PATH);
219 g_szConfigFile[MAX_PATH - 1] = 0;
220#else
5039dede 221 nx_strncpy(g_szConfigFile, optarg, MAX_PATH);
e0f99bf0 222#endif
5039dede
AK
223 break;
224 case 'C': // Check config
c8076b19 225 g_flags &= ~AF_DAEMON;
e0f99bf0 226 _tprintf(_T("Checking configuration file (%s):\n\n"), g_szConfigFile);
2df047f4 227 LoadConfig(&s_debugLevel);
5039dede
AK
228 return FALSE;
229 case 'd':
c8076b19 230 g_flags |= AF_DAEMON;
5039dede
AK
231 break;
232 case 'D': // Debug level
2df047f4
VK
233 s_debugLevel = strtoul(optarg, &eptr, 0);
234 if ((*eptr != 0) || (s_debugLevel > 9))
5039dede 235 {
e0f99bf0 236 _tprintf(_T("Invalid debug level \"%hs\" - should be in range 0..9\n"), optarg);
2df047f4 237 s_debugLevel = 0;
5039dede
AK
238 }
239 break;
3a82d5ae 240 case 'q': // disable interactive console
c8076b19 241 g_flags |= AF_DEBUG_CONSOLE_DISABLED;
3a82d5ae 242 break;
5039dede
AK
243 case 'e':
244 g_bCheckDB = TRUE;
245 break;
246#ifdef _WIN32
247 case 'L':
e0f99bf0
VK
248#ifdef UNICODE
249 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, login, 256);
250 login[255] = 0;
251#else
5039dede 252 nx_strncpy(login, optarg, 256);
e0f99bf0 253#endif
5039dede
AK
254 useLogin = TRUE;
255 break;
0df29c69
VK
256#ifndef _WIN32
257 case 'p': // PID file
258#ifdef UNICODE
259 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, g_szPIDFile, MAX_PATH);
260 g_szPIDFile[MAX_PATH - 1] = 0;
261#else
262 nx_strncpy(g_szPIDFile, optarg, MAX_PATH);
263#endif
264 break;
265#endif
5039dede 266 case 'P':
e0f99bf0
VK
267#ifdef UNICODE
268 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, password, 256);
269 password[255] = 0;
270#else
5039dede 271 nx_strncpy(password, optarg, 256);
e0f99bf0 272#endif
5039dede
AK
273 break;
274 case 'I': // Install service
275 ptr = strrchr(argv[0], '\\');
276 if (ptr != NULL)
277 ptr++;
278 else
279 ptr = argv[0];
280
281 _fullpath(exePath, ptr, 255);
282
283 if (stricmp(&exePath[strlen(exePath)-4], ".exe"))
284 strcat(exePath, ".exe");
285 strcpy(dllPath, exePath);
286 ptr = strrchr(dllPath, '\\');
287 if (ptr != NULL) // Shouldn't be NULL
288 {
289 ptr++;
290 strcpy(ptr, "libnxsrv.dll");
291 }
e0f99bf0
VK
292#ifdef UNICODE
293 WCHAR wexePath[MAX_PATH], wdllPath[MAX_PATH];
294 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, exePath, -1, wexePath, MAX_PATH);
295 wexePath[MAX_PATH - 1] = 0;
296 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, dllPath, -1, wdllPath, MAX_PATH);
297 wdllPath[MAX_PATH - 1] = 0;
298 InstallService(wexePath, wdllPath, useLogin ? login : NULL, useLogin ? password : NULL);
299#else
5039dede 300 InstallService(exePath, dllPath, useLogin ? login : NULL, useLogin ? password : NULL);
e0f99bf0 301#endif
5039dede
AK
302 return FALSE;
303 case 'R': // Remove service
304 RemoveService();
305 return FALSE;
306 case 's': // Start service
307 StartCoreService();
308 return FALSE;
309 case 'S': // Stop service
310 StopCoreService();
311 return FALSE;
312 case '!': // Check service configuration (for migration from pre-0.2.20)
313 CheckServiceConfig();
314 return FALSE;
315 case '~':
e0f99bf0 316 CreateMiniDump(strtoul(optarg, NULL, 0));
5039dede
AK
317 return FALSE;
318#endif
319 default:
320 break;
321 }
322 }
323 return TRUE;
324}
325
d78be64d
VK
326/**
327 * Startup code
328 */
06b383fe 329int main(int argc, char* argv[])
5039dede 330{
d37e7f10 331 InitNetXMSProcess(false);
5039dede 332
5039dede
AK
333 // Check for alternate config file location
334#ifdef _WIN32
fe8ea784 335 HKEY hKey;
42acd918 336 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\NetXMS\\Server"), 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
5039dede 337 {
fe8ea784 338 DWORD dwSize = MAX_PATH * sizeof(TCHAR);
5039dede
AK
339 RegQueryValueEx(hKey, _T("ConfigFile"), NULL, NULL, (BYTE *)g_szConfigFile, &dwSize);
340 RegCloseKey(hKey);
341 }
342#else
38ffd4b0
VK
343 const TCHAR *configEnv = _tgetenv(_T("NETXMSD_CONFIG"));
344 if ((configEnv != NULL) && (*configEnv != 0))
345 {
a2ef43f7 346 nx_strncpy(g_szConfigFile, configEnv, MAX_PATH);
38ffd4b0 347 }
5039dede
AK
348#endif
349
1e2b0526
VP
350 if (!ParseCommandLine(argc, argv))
351 return 1;
5039dede 352
2df047f4 353 if (!LoadConfig(&s_debugLevel))
5039dede
AK
354 {
355 if (IsStandalone())
e0f99bf0 356 _tprintf(_T("Error loading configuration file\n"));
5039dede
AK
357 return 1;
358 }
359
2df047f4
VK
360 if (s_debugLevel == NXCONFIG_UNINITIALIZED_VALUE)
361 s_debugLevel = 0;
362 nxlog_set_debug_level(s_debugLevel);
b41dff2a 363 free(s_debugTags);
e2e66145 364
5039dede
AK
365 // Set exception handler
366#ifdef _WIN32
c8076b19 367 if (g_flags & AF_CATCH_EXCEPTIONS)
4262c0dc 368 SetExceptionHandler(SEHServiceExceptionHandler, SEHServiceExceptionDataWriter,
c8076b19 369 g_szDumpDir, _T("netxmsd"), MSG_EXCEPTION, (g_flags & AF_WRITE_FULL_DUMP) ? true : false, IsStandalone());
5039dede
AK
370 __try {
371#endif
372
373 // Check database before start if requested
374 if (g_bCheckDB)
375 {
376 char szCmd[MAX_PATH + 128], *pszSep;
377
378 strncpy(szCmd, argv[0], MAX_PATH);
379 pszSep = strrchr(szCmd, FS_PATH_SEPARATOR[0]);
380 if (pszSep != NULL)
381 pszSep++;
382 else
383 pszSep = szCmd;
e0f99bf0
VK
384#ifdef UNICODE
385 snprintf(pszSep, 128, "nxdbmgr -c \"%S\" -f check", g_szConfigFile);
386#else
387 snprintf(pszSep, 128, "nxdbmgr -c \"%s\" -f check", g_szConfigFile);
388#endif
5039dede
AK
389 if (!ExecAndWait(szCmd))
390 if (IsStandalone())
e0f99bf0 391 _tprintf(_T("ERROR: Failed to execute command \"%hs\"\n"), szCmd);
5039dede
AK
392 }
393
394#ifdef _WIN32
395 if (!IsStandalone())
396 {
397 InitService();
398 }
399 else
400 {
401 if (!Initialize())
402 {
e0f99bf0 403 _tprintf(_T("NetXMS Core initialization failed\n"));
5039dede
AK
404
405 // Remove database lock
c8076b19 406 if (g_flags & AF_DB_LOCKED)
5039dede
AK
407 {
408 UnlockDB();
409 ShutdownDB();
410 }
c370cbf9 411 nxlog_close();
5039dede
AK
412 return 3;
413 }
414 Main(NULL);
415 }
416#else /* not _WIN32 */
417 if (!IsStandalone())
418 {
419 if (daemon(0, 0) == -1)
420 {
421 perror("Call to daemon() failed");
422 return 2;
423 }
424 }
425
426 // Write PID file
fe8ea784 427 FILE *fp = _tfopen(g_szPIDFile, _T("w"));
5039dede
AK
428 if (fp != NULL)
429 {
e0f99bf0 430 _ftprintf(fp, _T("%d"), getpid());
5039dede
AK
431 fclose(fp);
432 }
433
434 // Initialize server
435 if (!Initialize())
436 {
437 // Remove database lock
c8076b19 438 if (g_flags & AF_DB_LOCKED)
5039dede
AK
439 {
440 UnlockDB();
441 ShutdownDB();
442 }
c370cbf9 443 nxlog_close();
5039dede
AK
444 return 3;
445 }
446
447 // Everything is OK, start common main loop
448 StartMainLoop(SignalHandler, Main);
449#endif /* _WIN32 */
450
451#ifdef _WIN32
452 LIBNETXMS_EXCEPTION_HANDLER
453#endif
454 return 0;
455}