fixed memory leaks
[public/netxms.git] / src / server / include / nms_core.h
1 /*
2 ** NetXMS - Network Management System
3 ** Copyright (C) 2003-2012 Victor Kirhenshtein
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: nms_core.h
20 **
21 **/
22
23 #ifndef _nms_core_h_
24 #define _nms_core_h_
25
26 #ifdef _WIN32
27 #ifdef NXCORE_EXPORTS
28 #define NXCORE_EXPORTABLE __declspec(dllexport)
29 #else
30 #define NXCORE_EXPORTABLE __declspec(dllimport)
31 #endif
32 #else /* _WIN32 */
33 #define NXCORE_EXPORTABLE
34 #endif
35
36 #define LIBNXCL_NO_DECLARATIONS 1
37
38 #include <nms_common.h>
39
40 #ifndef _WIN32
41
42 #if HAVE_SYS_TYPES_H
43 # include <sys/types.h>
44 #endif
45
46 #if HAVE_DLFCN_H
47 #include <dlfcn.h>
48 #endif
49
50 #define WSAGetLastError() (errno)
51
52 #endif /* _WIN32 */
53
54 #include <time.h>
55 #include <stdio.h>
56 #include <string.h>
57 #include <stdarg.h>
58
59 #ifdef _WITH_ENCRYPTION
60 #include <openssl/ssl.h>
61 #endif
62
63 #define SHOW_FLAG_VALUE(x) _T(" %-32s = %d\n"), _T(#x), (g_dwFlags & x) ? 1 : 0
64
65
66 //
67 // Common includes
68 //
69
70 #include <nms_util.h>
71 #include <dbdrv.h>
72 #include <nms_cscp.h>
73 #include <uuid.h>
74 #include <nxsrvapi.h>
75 #include <nxqueue.h>
76 #include <nxsnmp.h>
77 #include <nxmodule.h>
78 #include <nxsl.h>
79 #include <nxdbapi.h>
80 #include <nddrv.h>
81 #include <nxcore_smclp.h>
82
83 /**
84 * Console context
85 */
86 struct __console_ctx
87 {
88 SOCKET hSocket;
89 MUTEX socketMutex;
90 CSCPMessage *pMsg;
91 ClientSession *session;
92 String *output;
93 };
94
95 typedef __console_ctx * CONSOLE_CTX;
96
97 /**
98 * Server includes
99 */
100 #include "nms_dcoll.h"
101 #include "nms_users.h"
102 #include "nxcore_winperf.h"
103 #include "nms_objects.h"
104 #include "nms_locks.h"
105 #include "nms_pkg.h"
106 #include "nms_topo.h"
107 #include "nms_script.h"
108 #include "nxcore_situations.h"
109 #include "nxcore_jobs.h"
110 #include "nxcore_logs.h"
111
112 /**
113 * Common constants and macros
114 */
115 #define MAX_LINE_SIZE 4096
116 #define GROUP_FLAG_BIT ((UINT32)0x80000000)
117 #define CHECKPOINT_SNMP_PORT 260
118 #define DEFAULT_AFFINITY_MASK 0xFFFFFFFF
119
120 typedef void * HSNMPSESSION;
121
122 /**
123 * Prefixes for poller messages
124 */
125 #define POLLER_ERROR _T("\x7F") _T("e")
126 #define POLLER_WARNING _T("\x7Fw")
127 #define POLLER_INFO _T("\x7Fi")
128
129 /**
130 * Unique identifier group codes
131 */
132 #define IDG_NETWORK_OBJECT 0
133 #define IDG_CONTAINER_CAT 1
134 #define IDG_EVENT 2
135 #define IDG_ITEM 3
136 #define IDG_SNMP_TRAP 4
137 #define IDG_JOB 5
138 #define IDG_ACTION 6
139 #define IDG_EVENT_GROUP 7
140 #define IDG_THRESHOLD 8
141 #define IDG_USER 9
142 #define IDG_USER_GROUP 10
143 #define IDG_ALARM 11
144 #define IDG_ALARM_NOTE 12
145 #define IDG_PACKAGE 13
146 #define IDG_SLM_TICKET 14
147 #define IDG_OBJECT_TOOL 15
148 #define IDG_SCRIPT 16
149 #define IDG_AGENT_CONFIG 17
150 #define IDG_GRAPH 18
151 #define IDG_CERTIFICATE 19
152 #define IDG_SITUATION 20
153 #define IDG_DCT_COLUMN 21
154 #define IDG_MAPPING_TABLE 22
155 #define IDG_DCI_SUMMARY_TABLE 23
156
157 /**
158 * Exit codes for console commands
159 */
160 #define CMD_EXIT_CONTINUE 0
161 #define CMD_EXIT_CLOSE_SESSION 1
162 #define CMD_EXIT_SHUTDOWN 2
163
164 /**
165 * Network discovery mode
166 */
167 #define DISCOVERY_DISABLED 0
168 #define DISCOVERY_PASSIVE_ONLY 1
169 #define DISCOVERY_ACTIVE 2
170
171 /**
172 * Client session flags
173 */
174 #define CSF_EPP_LOCKED ((UINT32)0x0002)
175 #define CSF_PACKAGE_DB_LOCKED ((UINT32)0x0004)
176 #define CSF_USER_DB_LOCKED ((UINT32)0x0008)
177 #define CSF_EPP_UPLOAD ((UINT32)0x0010)
178 #define CSF_CONSOLE_OPEN ((UINT32)0x0020)
179 #define CSF_AUTHENTICATED ((UINT32)0x0080)
180 #define CSF_RECEIVING_MAP_DATA ((UINT32)0x0200)
181 #define CSF_SYNC_OBJECT_COMMENTS ((UINT32)0x0400)
182
183 /**
184 * Client session states
185 */
186 #define SESSION_STATE_INIT 0
187 #define SESSION_STATE_IDLE 1
188 #define SESSION_STATE_PROCESSING 2
189
190 /**
191 * Information categories for UPDATE_INFO structure
192 */
193 #define INFO_CAT_EVENT 1
194 #define INFO_CAT_OBJECT_CHANGE 2
195 #define INFO_CAT_ALARM 3
196 #define INFO_CAT_ACTION 4
197 #define INFO_CAT_SYSLOG_MSG 5
198 #define INFO_CAT_SNMP_TRAP 6
199 #define INFO_CAT_AUDIT_RECORD 7
200 #define INFO_CAT_SITUATION 8
201 #define INFO_CAT_LIBRARY_IMAGE 9
202
203 /**
204 * Certificate types
205 */
206 #define CERT_TYPE_TRUSTED_CA 0
207 #define CERT_TYPE_USER 1
208
209 /**
210 * Audit subsystems
211 */
212 #define AUDIT_SECURITY _T("SECURITY")
213 #define AUDIT_OBJECTS _T("OBJECTS")
214 #define AUDIT_SYSCFG _T("SYSCFG")
215 #define AUDIT_CONSOLE _T("CONSOLE")
216
217 /**
218 * Event handling subsystem definitions
219 */
220 #include "nms_events.h"
221 #include "nms_actions.h"
222 #include "nms_alarm.h"
223
224 /**
225 * New node information
226 */
227 typedef struct
228 {
229 UINT32 dwIpAddr;
230 UINT32 dwNetMask;
231 UINT32 zoneId;
232 BOOL ignoreFilter;
233 BYTE bMacAddr[MAC_ADDR_LENGTH];
234 } NEW_NODE;
235
236 /**
237 * New node flags
238 */
239 #define NNF_IS_SNMP 0x0001
240 #define NNF_IS_AGENT 0x0002
241 #define NNF_IS_ROUTER 0x0004
242 #define NNF_IS_BRIDGE 0x0008
243 #define NNF_IS_PRINTER 0x0010
244 #define NNF_IS_CDP 0x0020
245 #define NNF_IS_SONMP 0x0040
246 #define NNF_IS_LLDP 0x0080
247
248 /**
249 * Node information for autodiscovery filter
250 */
251 typedef struct
252 {
253 UINT32 dwIpAddr;
254 UINT32 dwNetMask;
255 UINT32 dwSubnetAddr;
256 UINT32 dwFlags;
257 int nSNMPVersion;
258 TCHAR szObjectId[MAX_OID_LEN * 4]; // SNMP OID
259 TCHAR szAgentVersion[MAX_AGENT_VERSION_LEN];
260 TCHAR szPlatform[MAX_PLATFORM_NAME_LEN];
261 } DISCOVERY_FILTER_DATA;
262
263 /**
264 * Data update structure for client sessions
265 */
266 typedef struct
267 {
268 UINT32 dwCategory; // Data category - event, network object, etc.
269 UINT32 dwCode; // Data-specific update code
270 void *pData; // Pointer to data block
271 } UPDATE_INFO;
272
273
274 /**
275 * Extended agent connection
276 */
277 class AgentConnectionEx : public AgentConnection
278 {
279 protected:
280 UINT32 m_nodeId;
281
282 virtual void printMsg(const TCHAR *format, ...);
283 virtual void onTrap(CSCPMessage *msg);
284 virtual void onDataPush(CSCPMessage *msg);
285 virtual void onFileMonitoringData(CSCPMessage *msg);
286
287 public:
288 AgentConnectionEx(UINT32 nodeId, UINT32 ipAddr, WORD port = AGENT_LISTEN_PORT, int authMethod = AUTH_NONE, const TCHAR *secret = NULL) :
289 AgentConnection(ipAddr, port, authMethod, secret) { m_nodeId = nodeId; }
290 virtual ~AgentConnectionEx();
291
292 UINT32 deployPolicy(AgentPolicy *policy);
293 UINT32 uninstallPolicy(AgentPolicy *policy);
294 };
295
296 /**
297 * Mobile device session
298 */
299 class NXCORE_EXPORTABLE MobileDeviceSession
300 {
301 private:
302 SOCKET m_hSocket;
303 Queue *m_pSendQueue;
304 Queue *m_pMessageQueue;
305 UINT32 m_dwIndex;
306 int m_iState;
307 WORD m_wCurrentCmd;
308 UINT32 m_dwUserId;
309 UINT32 m_deviceObjectId;
310 CSCP_BUFFER *m_pMsgBuffer;
311 NXCPEncryptionContext *m_pCtx;
312 BYTE m_challenge[CLIENT_CHALLENGE_SIZE];
313 THREAD m_hWriteThread;
314 THREAD m_hProcessingThread;
315 MUTEX m_mutexSocketWrite;
316 struct sockaddr *m_clientAddr;
317 TCHAR m_szHostName[256]; // IP address of name of conneced host in textual form
318 TCHAR m_szUserName[MAX_SESSION_NAME]; // String in form login_name@host
319 TCHAR m_szClientInfo[96]; // Client app info string
320 UINT32 m_dwEncryptionRqId;
321 UINT32 m_dwEncryptionResult;
322 CONDITION m_condEncryptionSetup;
323 UINT32 m_dwRefCount;
324 bool m_isAuthenticated;
325
326 static THREAD_RESULT THREAD_CALL readThreadStarter(void *);
327 static THREAD_RESULT THREAD_CALL writeThreadStarter(void *);
328 static THREAD_RESULT THREAD_CALL processingThreadStarter(void *);
329
330 void readThread();
331 void writeThread();
332 void processingThread();
333
334 void setupEncryption(CSCPMessage *request);
335 void respondToKeepalive(UINT32 dwRqId);
336 void debugPrintf(int level, const TCHAR *format, ...);
337 void sendServerInfo(UINT32 dwRqId);
338 void login(CSCPMessage *pRequest);
339 void updateDeviceInfo(CSCPMessage *pRequest);
340 void updateDeviceStatus(CSCPMessage *pRequest);
341
342 public:
343 MobileDeviceSession(SOCKET hSocket, struct sockaddr *addr);
344 ~MobileDeviceSession();
345
346 void incRefCount() { m_dwRefCount++; }
347 void decRefCount() { if (m_dwRefCount > 0) m_dwRefCount--; }
348
349 void run();
350
351 void postMessage(CSCPMessage *pMsg) { m_pSendQueue->Put(pMsg->CreateMessage()); }
352 void sendMessage(CSCPMessage *pMsg);
353
354 UINT32 getIndex() { return m_dwIndex; }
355 void setIndex(UINT32 dwIndex) { if (m_dwIndex == INVALID_INDEX) m_dwIndex = dwIndex; }
356 int getState() { return m_iState; }
357 const TCHAR *getUserName() { return m_szUserName; }
358 const TCHAR *getClientInfo() { return m_szClientInfo; }
359 const TCHAR *getHostName() { return m_szHostName; }
360 UINT32 getUserId() { return m_dwUserId; }
361 bool isAuthenticated() { return m_isAuthenticated; }
362 WORD getCurrentCmd() { return m_wCurrentCmd; }
363 int getCipher() { return (m_pCtx == NULL) ? -1 : m_pCtx->getCipher(); }
364 };
365
366 /**
367 * Client (user) session
368 */
369 #define DECLARE_THREAD_STARTER(func) static THREAD_RESULT THREAD_CALL ThreadStarter_##func(void *);
370
371 class NXCORE_EXPORTABLE ClientSession
372 {
373 private:
374 SOCKET m_hSocket;
375 Queue *m_pSendQueue;
376 Queue *m_pMessageQueue;
377 Queue *m_pUpdateQueue;
378 UINT32 m_dwIndex;
379 int m_iState;
380 WORD m_wCurrentCmd;
381 UINT32 m_dwUserId;
382 UINT32 m_dwSystemAccess; // User's system access rights
383 UINT32 m_dwFlags; // Session flags
384 int m_clientType; // Client system type - desktop, web, mobile, etc.
385 CSCP_BUFFER *m_pMsgBuffer;
386 NXCPEncryptionContext *m_pCtx;
387 BYTE m_challenge[CLIENT_CHALLENGE_SIZE];
388 THREAD m_hWriteThread;
389 THREAD m_hProcessingThread;
390 THREAD m_hUpdateThread;
391 MUTEX m_mutexSocketWrite;
392 MUTEX m_mutexSendEvents;
393 MUTEX m_mutexSendSyslog;
394 MUTEX m_mutexSendTrapLog;
395 MUTEX m_mutexSendObjects;
396 MUTEX m_mutexSendAlarms;
397 MUTEX m_mutexSendActions;
398 MUTEX m_mutexSendAuditLog;
399 MUTEX m_mutexSendSituations;
400 MUTEX m_mutexPollerInit;
401 struct sockaddr *m_clientAddr;
402 TCHAR m_workstation[256]; // IP address or name of connected host in textual form
403 TCHAR m_webServerAddress[256]; // IP address or name of web server for web sessions
404 TCHAR m_szUserName[MAX_SESSION_NAME]; // String in form login_name@host
405 TCHAR m_szClientInfo[96]; // Client app info string
406 time_t m_loginTime;
407 UINT32 m_dwOpenDCIListSize; // Number of open DCI lists
408 UINT32 *m_pOpenDCIList; // List of nodes with DCI lists open
409 UINT32 m_dwNumRecordsToUpload; // Number of records to be uploaded
410 UINT32 m_dwRecordsUploaded;
411 EPRule **m_ppEPPRuleList; // List of loaded EPP rules
412 int m_hCurrFile;
413 UINT32 m_dwFileRqId;
414 UINT32 m_dwUploadCommand;
415 UINT32 m_dwUploadData;
416 uuid_t m_uploadImageGuid;
417 TCHAR m_szCurrFileName[MAX_PATH];
418 UINT32 m_dwRefCount;
419 UINT32 m_dwEncryptionRqId;
420 UINT32 m_dwEncryptionResult;
421 CONDITION m_condEncryptionSetup;
422 UINT32 m_dwActiveChannels; // Active data channels
423 CONSOLE_CTX m_console; // Server console context
424
425 static THREAD_RESULT THREAD_CALL readThreadStarter(void *);
426 static THREAD_RESULT THREAD_CALL writeThreadStarter(void *);
427 static THREAD_RESULT THREAD_CALL processingThreadStarter(void *);
428 static THREAD_RESULT THREAD_CALL updateThreadStarter(void *);
429 static THREAD_RESULT THREAD_CALL pollerThreadStarter(void *);
430
431 DECLARE_THREAD_STARTER(getCollectedData)
432 DECLARE_THREAD_STARTER(getTableCollectedData)
433 DECLARE_THREAD_STARTER(clearDCIData)
434 DECLARE_THREAD_STARTER(queryParameter)
435 DECLARE_THREAD_STARTER(queryAgentTable)
436 DECLARE_THREAD_STARTER(queryL2Topology)
437 DECLARE_THREAD_STARTER(sendEventLog)
438 DECLARE_THREAD_STARTER(sendSyslog)
439 DECLARE_THREAD_STARTER(createObject)
440 DECLARE_THREAD_STARTER(getServerFile)
441 DECLARE_THREAD_STARTER(getAgentFile)
442 DECLARE_THREAD_STARTER(cancelFileMonitoring)
443 DECLARE_THREAD_STARTER(queryServerLog)
444 DECLARE_THREAD_STARTER(getServerLogQueryData)
445 DECLARE_THREAD_STARTER(executeAction)
446 DECLARE_THREAD_STARTER(findNodeConnection)
447 DECLARE_THREAD_STARTER(findMacAddress)
448 DECLARE_THREAD_STARTER(findIpAddress)
449 DECLARE_THREAD_STARTER(processConsoleCommand)
450 DECLARE_THREAD_STARTER(sendMib)
451 DECLARE_THREAD_STARTER(getReportResults)
452 DECLARE_THREAD_STARTER(deleteReportResults)
453 DECLARE_THREAD_STARTER(renderReport)
454 DECLARE_THREAD_STARTER(getNetworkPath)
455 DECLARE_THREAD_STARTER(getAlarmEvents)
456 DECLARE_THREAD_STARTER(forwardToReportingServer)
457
458 void readThread();
459 void writeThread();
460 void processingThread();
461 void updateThread();
462 void pollerThread(Node *pNode, int iPollType, UINT32 dwRqId);
463
464 void setupEncryption(CSCPMessage *request);
465 void respondToKeepalive(UINT32 dwRqId);
466 void onFileUpload(BOOL bSuccess);
467 void debugPrintf(int level, const TCHAR *format, ...);
468 void sendServerInfo(UINT32 dwRqId);
469 void login(CSCPMessage *pRequest);
470 void sendAllObjects(CSCPMessage *pRequest);
471 void sendSelectedObjects(CSCPMessage *pRequest);
472 void sendEventLog(CSCPMessage *pRequest);
473 void sendAllConfigVars(UINT32 dwRqId);
474 void setConfigVariable(CSCPMessage *pRequest);
475 void deleteConfigVariable(CSCPMessage *pRequest);
476 void sendUserDB(UINT32 dwRqId);
477 void sendAllAlarms(UINT32 dwRqId);
478 void createUser(CSCPMessage *pRequest);
479 void updateUser(CSCPMessage *pRequest);
480 void deleteUser(CSCPMessage *pRequest);
481 void setPassword(CSCPMessage *pRequest);
482 void lockUserDB(UINT32 dwRqId, BOOL bLock);
483 void sendEventDB(UINT32 dwRqId);
484 void modifyEventTemplate(CSCPMessage *pRequest);
485 void deleteEventTemplate(CSCPMessage *pRequest);
486 void generateEventCode(UINT32 dwRqId);
487 void modifyObject(CSCPMessage *pRequest);
488 void changeObjectMgmtStatus(CSCPMessage *pRequest);
489 void openNodeDCIList(CSCPMessage *pRequest);
490 void closeNodeDCIList(CSCPMessage *pRequest);
491 void modifyNodeDCI(CSCPMessage *pRequest);
492 void copyDCI(CSCPMessage *pRequest);
493 void applyTemplate(CSCPMessage *pRequest);
494 void getCollectedData(CSCPMessage *pRequest);
495 void getTableCollectedData(CSCPMessage *pRequest);
496 bool getCollectedDataFromDB(CSCPMessage *request, CSCPMessage *response, DataCollectionTarget *object, int dciType);
497 void clearDCIData(CSCPMessage *pRequest);
498 void changeDCIStatus(CSCPMessage *pRequest);
499 void getLastValues(CSCPMessage *pRequest);
500 void getTableLastValues(CSCPMessage *pRequest);
501 void getThresholdSummary(CSCPMessage *request);
502 void openEPP(CSCPMessage *request);
503 void closeEPP(UINT32 dwRqId);
504 void saveEPP(CSCPMessage *pRequest);
505 void processEPPRecord(CSCPMessage *pRequest);
506 void sendMIBTimestamp(UINT32 dwRqId);
507 void sendMib(CSCPMessage *request);
508 void createObject(CSCPMessage *request);
509 void changeObjectBinding(CSCPMessage *request, BOOL bBind);
510 void deleteObject(CSCPMessage *request);
511 void getAlarm(CSCPMessage *request);
512 void getAlarmEvents(CSCPMessage *request);
513 void acknowledgeAlarm(CSCPMessage *request);
514 void resolveAlarm(CSCPMessage *request, bool terminate);
515 void deleteAlarm(CSCPMessage *request);
516 void getAlarmNotes(CSCPMessage *pRequest);
517 void updateAlarmNote(CSCPMessage *pRequest);
518 void createAction(CSCPMessage *pRequest);
519 void updateAction(CSCPMessage *pRequest);
520 void deleteAction(CSCPMessage *pRequest);
521 void sendAllActions(UINT32 dwRqId);
522 void SendContainerCategories(UINT32 dwRqId);
523 void forcedNodePoll(CSCPMessage *pRequest);
524 void onTrap(CSCPMessage *pRequest);
525 void onWakeUpNode(CSCPMessage *pRequest);
526 void queryParameter(CSCPMessage *pRequest);
527 void queryAgentTable(CSCPMessage *pRequest);
528 void editTrap(int iOperation, CSCPMessage *pRequest);
529 void LockTrapCfg(UINT32 dwRqId, BOOL bLock);
530 void sendAllTraps(UINT32 dwRqId);
531 void sendAllTraps2(UINT32 dwRqId);
532 void LockPackageDB(UINT32 dwRqId, BOOL bLock);
533 void SendAllPackages(UINT32 dwRqId);
534 void InstallPackage(CSCPMessage *pRequest);
535 void RemovePackage(CSCPMessage *pRequest);
536 void DeployPackage(CSCPMessage *pRequest);
537 void getParametersList(CSCPMessage *pRequest);
538 void getUserVariable(CSCPMessage *pRequest);
539 void setUserVariable(CSCPMessage *pRequest);
540 void copyUserVariable(CSCPMessage *pRequest);
541 void enumUserVariables(CSCPMessage *pRequest);
542 void deleteUserVariable(CSCPMessage *pRequest);
543 void changeObjectZone(CSCPMessage *pRequest);
544 void getAgentConfig(CSCPMessage *pRequest);
545 void updateAgentConfig(CSCPMessage *pRequest);
546 void executeAction(CSCPMessage *pRequest);
547 void sendObjectTools(UINT32 dwRqId);
548 void sendObjectToolDetails(CSCPMessage *pRequest);
549 void updateObjectTool(CSCPMessage *pRequest);
550 void deleteObjectTool(CSCPMessage *pRequest);
551 void changeObjecToolDisableStatuss(CSCPMessage *pRequest);
552 void generateObjectToolId(UINT32 dwRqId);
553 void execTableTool(CSCPMessage *pRequest);
554 void changeSubscription(CSCPMessage *pRequest);
555 void sendSyslog(CSCPMessage *pRequest);
556 void sendServerStats(UINT32 dwRqId);
557 void sendScriptList(UINT32 dwRqId);
558 void sendScript(CSCPMessage *pRequest);
559 void updateScript(CSCPMessage *pRequest);
560 void renameScript(CSCPMessage *pRequest);
561 void deleteScript(CSCPMessage *pRequest);
562 void SendSessionList(UINT32 dwRqId);
563 void KillSession(CSCPMessage *pRequest);
564 void SendTrapLog(CSCPMessage *pRequest);
565 void StartSnmpWalk(CSCPMessage *pRequest);
566 void resolveDCINames(CSCPMessage *pRequest);
567 UINT32 resolveDCIName(UINT32 dwNode, UINT32 dwItem, TCHAR **ppszName);
568 void SendConfigForAgent(CSCPMessage *pRequest);
569 void sendAgentCfgList(UINT32 dwRqId);
570 void OpenAgentConfig(CSCPMessage *pRequest);
571 void SaveAgentConfig(CSCPMessage *pRequest);
572 void DeleteAgentConfig(CSCPMessage *pRequest);
573 void SwapAgentConfigs(CSCPMessage *pRequest);
574 void SendObjectComments(CSCPMessage *pRequest);
575 void updateObjectComments(CSCPMessage *pRequest);
576 void pushDCIData(CSCPMessage *pRequest);
577 void getAddrList(CSCPMessage *pRequest);
578 void setAddrList(CSCPMessage *pRequest);
579 void resetComponent(CSCPMessage *pRequest);
580 void sendDCIEventList(CSCPMessage *request);
581 void SendDCIInfo(CSCPMessage *pRequest);
582 void sendPerfTabDCIList(CSCPMessage *pRequest);
583 void exportConfiguration(CSCPMessage *pRequest);
584 void importConfiguration(CSCPMessage *pRequest);
585 void SendGraphList(UINT32 dwRqId);
586 void SaveGraph(CSCPMessage *pRequest);
587 void DeleteGraph(CSCPMessage *pRequest);
588 void AddCACertificate(CSCPMessage *pRequest);
589 void DeleteCertificate(CSCPMessage *pRequest);
590 void UpdateCertificateComments(CSCPMessage *pRequest);
591 void getCertificateList(UINT32 dwRqId);
592 void queryL2Topology(CSCPMessage *pRequest);
593 void sendSMS(CSCPMessage *pRequest);
594 void SendCommunityList(UINT32 dwRqId);
595 void UpdateCommunityList(CSCPMessage *pRequest);
596 void getSituationList(UINT32 dwRqId);
597 void createSituation(CSCPMessage *pRequest);
598 void updateSituation(CSCPMessage *pRequest);
599 void deleteSituation(CSCPMessage *pRequest);
600 void deleteSituationInstance(CSCPMessage *pRequest);
601 void setConfigCLOB(CSCPMessage *pRequest);
602 void getConfigCLOB(CSCPMessage *pRequest);
603 void registerAgent(CSCPMessage *pRequest);
604 void getServerFile(CSCPMessage *pRequest);
605 void cancelFileMonitoring(CSCPMessage *request);
606 void getAgentFile(CSCPMessage *pRequest);
607 void testDCITransformation(CSCPMessage *pRequest);
608 void sendJobList(UINT32 dwRqId);
609 void cancelJob(CSCPMessage *pRequest);
610 void holdJob(CSCPMessage *pRequest);
611 void unholdJob(CSCPMessage *pRequest);
612 void deployAgentPolicy(CSCPMessage *pRequest, bool uninstallFlag);
613 void getUserCustomAttribute(CSCPMessage *request);
614 void setUserCustomAttribute(CSCPMessage *request);
615 void openServerLog(CSCPMessage *request);
616 void closeServerLog(CSCPMessage *request);
617 void queryServerLog(CSCPMessage *request);
618 void getServerLogQueryData(CSCPMessage *request);
619 void sendUsmCredentials(UINT32 dwRqId);
620 void updateUsmCredentials(CSCPMessage *pRequest);
621 void sendDCIThresholds(CSCPMessage *request);
622 void addClusterNode(CSCPMessage *request);
623 void findNodeConnection(CSCPMessage *request);
624 void findMacAddress(CSCPMessage *request);
625 void findIpAddress(CSCPMessage *request);
626 void sendLibraryImage(CSCPMessage *request);
627 void updateLibraryImage(CSCPMessage *request);
628 void listLibraryImages(CSCPMessage *request);
629 void deleteLibraryImage(CSCPMessage *request);
630 void executeServerCommand(CSCPMessage *request);
631 void uploadFileToAgent(CSCPMessage *request);
632 void listServerFileStore(CSCPMessage *request);
633 void processConsoleCommand(CSCPMessage *msg);
634 void openConsole(UINT32 rqId);
635 void closeConsole(UINT32 rqId);
636 void getVlans(CSCPMessage *msg);
637 void receiveFile(CSCPMessage *request);
638 void deleteFile(CSCPMessage *request);
639 void executeReport(CSCPMessage *msg);
640 void getReportResults(CSCPMessage *msg);
641 void deleteReportResults(CSCPMessage *msg);
642 void renderReport(CSCPMessage *request);
643 void getNetworkPath(CSCPMessage *request);
644 void getNodeComponents(CSCPMessage *request);
645 void getNodeSoftware(CSCPMessage *request);
646 void getWinPerfObjects(CSCPMessage *request);
647 void listMappingTables(CSCPMessage *request);
648 void getMappingTable(CSCPMessage *request);
649 void updateMappingTable(CSCPMessage *request);
650 void deleteMappingTable(CSCPMessage *request);
651 void getWirelessStations(CSCPMessage *request);
652 void getSummaryTables(UINT32 rqId);
653 void getSummaryTableDetails(CSCPMessage *request);
654 void modifySummaryTable(CSCPMessage *request);
655 void deleteSummaryTable(CSCPMessage *request);
656 void querySummaryTable(CSCPMessage *request);
657 void forwardToReportingServer(CSCPMessage *request);
658 void getSubnetAddressMap(CSCPMessage *request);
659
660 public:
661 ClientSession(SOCKET hSocket, struct sockaddr *addr);
662 ~ClientSession();
663
664 void incRefCount() { m_dwRefCount++; }
665 void decRefCount() { if (m_dwRefCount > 0) m_dwRefCount--; }
666
667 void run();
668
669 void postMessage(CSCPMessage *pMsg) { m_pSendQueue->Put(pMsg->CreateMessage()); }
670 void sendMessage(CSCPMessage *pMsg);
671 void sendRawMessage(CSCP_MESSAGE *pMsg);
672 void sendPollerMsg(UINT32 dwRqId, const TCHAR *pszMsg);
673 BOOL sendFile(const TCHAR *file, UINT32 dwRqId, long sizeLimit);
674
675 UINT32 getIndex() { return m_dwIndex; }
676 void setIndex(UINT32 dwIndex) { if (m_dwIndex == INVALID_INDEX) m_dwIndex = dwIndex; }
677 int getState() { return m_iState; }
678 const TCHAR *getUserName() { return m_szUserName; }
679 const TCHAR *getClientInfo() { return m_szClientInfo; }
680 const TCHAR *getWorkstation() { return m_workstation; }
681 const TCHAR *getWebServerAddress() { return m_webServerAddress; }
682 UINT32 getUserId() { return m_dwUserId; }
683 UINT32 getSystemRights() { return m_dwSystemAccess; }
684 bool isAuthenticated() { return (m_dwFlags & CSF_AUTHENTICATED) ? true : false; }
685 bool isConsoleOpen() { return (m_dwFlags & CSF_CONSOLE_OPEN) ? true : false; }
686 bool isSubscribed(UINT32 dwChannel) { return (m_dwActiveChannels & dwChannel) ? true : false; }
687 WORD getCurrentCmd() { return m_wCurrentCmd; }
688 int getCipher() { return (m_pCtx == NULL) ? -1 : m_pCtx->getCipher(); }
689 int getClientType() { return m_clientType; }
690 time_t getLoginTime() { return m_loginTime; }
691
692 bool checkSysAccessRights(UINT32 requiredAccess)
693 {
694 return (m_dwUserId == 0) ? true :
695 ((requiredAccess & m_dwSystemAccess) == requiredAccess);
696 }
697
698 void kill();
699 void notify(UINT32 dwCode, UINT32 dwData = 0);
700
701 void queueUpdate(UPDATE_INFO *pUpdate) { m_pUpdateQueue->Put(pUpdate); }
702 void onNewEvent(Event *pEvent);
703 void onSyslogMessage(NX_SYSLOG_RECORD *pRec);
704 void onNewSNMPTrap(CSCPMessage *pMsg);
705 void onObjectChange(NetObj *pObject);
706 void onUserDBUpdate(int code, UINT32 id, UserDatabaseObject *user);
707 void onAlarmUpdate(UINT32 dwCode, NXC_ALARM *pAlarm);
708 void onActionDBUpdate(UINT32 dwCode, NXC_ACTION *pAction);
709 void onSituationChange(CSCPMessage *msg);
710 void onLibraryImageChange(uuid_t *guid, bool removed = false);
711 };
712
713 /**
714 * Delayed SQL request
715 */
716 typedef struct
717 {
718 TCHAR *query;
719 int bindCount;
720 BYTE *sqlTypes;
721 TCHAR *bindings[1]; /* actual size determined by bindCount field */
722 } DELAYED_SQL_REQUEST;
723
724 /**
725 * Delayed request for idata_ INSERT
726 */
727 typedef struct
728 {
729 time_t timestamp;
730 UINT32 nodeId;
731 UINT32 dciId;
732 TCHAR value[MAX_RESULT_LENGTH];
733 } DELAYED_IDATA_INSERT;
734
735 /**
736 * Graph ACL entry
737 */
738 struct GRAPH_ACL_ENTRY
739 {
740 UINT32 dwGraphId;
741 UINT32 dwUserId;
742 UINT32 dwAccess;
743 };
744
745 /**
746 * Information about graph with name existence and it's ID.
747 */
748 struct GRAPH_ACL_AND_ID
749 {
750 UINT32 graphId;
751 UINT32 status;
752 };
753
754 /**
755 * Functions
756 */
757 BOOL NXCORE_EXPORTABLE ConfigReadStr(const TCHAR *szVar, TCHAR *szBuffer, int iBufSize, const TCHAR *szDefault);
758 #ifdef UNICODE
759 BOOL NXCORE_EXPORTABLE ConfigReadStrA(const WCHAR *szVar, char *szBuffer, int iBufSize, const char *szDefault);
760 #else
761 #define ConfigReadStrA ConfigReadStr
762 #endif
763 int NXCORE_EXPORTABLE ConfigReadInt(const TCHAR *szVar, int iDefault);
764 UINT32 NXCORE_EXPORTABLE ConfigReadULong(const TCHAR *szVar, UINT32 dwDefault);
765 BOOL NXCORE_EXPORTABLE ConfigReadByteArray(const TCHAR *pszVar, int *pnArray,
766 int nSize, int nDefault);
767 BOOL NXCORE_EXPORTABLE ConfigWriteStr(const TCHAR *szVar, const TCHAR *szValue, BOOL bCreate,
768 BOOL isVisible = TRUE, BOOL needRestart = FALSE);
769 BOOL NXCORE_EXPORTABLE ConfigWriteInt(const TCHAR *szVar, int iValue, BOOL bCreate,
770 BOOL isVisible = TRUE, BOOL needRestart = FALSE);
771 BOOL NXCORE_EXPORTABLE ConfigWriteULong(const TCHAR *szVar, UINT32 dwValue, BOOL bCreate,
772 BOOL isVisible = TRUE, BOOL needRestart = FALSE);
773 BOOL NXCORE_EXPORTABLE ConfigWriteByteArray(const TCHAR *pszVar, int *pnArray,
774 int nSize, BOOL bCreate,
775 BOOL isVisible = TRUE, BOOL needRestart = FALSE);
776 TCHAR NXCORE_EXPORTABLE *ConfigReadCLOB(const TCHAR *var, const TCHAR *defValue);
777 BOOL NXCORE_EXPORTABLE ConfigWriteCLOB(const TCHAR *var, const TCHAR *value, BOOL bCreate);
778
779 BOOL NXCORE_EXPORTABLE MetaDataReadStr(const TCHAR *szVar, TCHAR *szBuffer, int iBufSize, const TCHAR *szDefault);
780
781 BOOL NXCORE_EXPORTABLE LoadConfig();
782
783 void NXCORE_EXPORTABLE Shutdown();
784 void NXCORE_EXPORTABLE FastShutdown();
785 BOOL NXCORE_EXPORTABLE Initialize();
786 THREAD_RESULT NXCORE_EXPORTABLE THREAD_CALL Main(void *);
787 void NXCORE_EXPORTABLE ShutdownDB();
788 void InitiateShutdown();
789
790 BOOL NXCORE_EXPORTABLE SleepAndCheckForShutdown(int iSeconds);
791
792 void ConsolePrintf(CONSOLE_CTX pCtx, const TCHAR *pszFormat, ...)
793 #if !defined(UNICODE) && (defined(__GNUC__) || defined(__clang__))
794 __attribute__ ((format(printf, 2, 3)))
795 #endif
796 ;
797 int ProcessConsoleCommand(const TCHAR *pszCmdLine, CONSOLE_CTX pCtx);
798
799 void SaveObjects(DB_HANDLE hdb);
800 void NXCORE_EXPORTABLE ObjectTransactionStart();
801 void NXCORE_EXPORTABLE ObjectTransactionEnd();
802
803 void NXCORE_EXPORTABLE QueueSQLRequest(const TCHAR *query);
804 void NXCORE_EXPORTABLE QueueSQLRequest(const TCHAR *query, int bindCount, int *sqlTypes, const TCHAR **values);
805 void QueueIDataInsert(time_t timestamp, UINT32 nodeId, UINT32 dciId, const TCHAR *value);
806 void StartDBWriter();
807 void StopDBWriter();
808
809 bool NXCORE_EXPORTABLE IsDatabaseRecordExist(DB_HANDLE hdb, const TCHAR *table, const TCHAR *idColumn, UINT32 id);
810
811 void DecodeSQLStringAndSetVariable(CSCPMessage *pMsg, UINT32 dwVarId, TCHAR *pszStr);
812
813 SNMP_SecurityContext *SnmpCheckCommSettings(SNMP_Transport *pTransport, int *version, SNMP_SecurityContext *originalContext, StringList *customTestOids);
814 void StrToMac(const TCHAR *pszStr, BYTE *pBuffer);
815
816 void InitLocalNetInfo();
817
818 ARP_CACHE *GetLocalArpCache();
819 ARP_CACHE *SnmpGetArpCache(UINT32 dwVersion, SNMP_Transport *pTransport);
820
821 InterfaceList *GetLocalInterfaceList();
822 void SnmpGetInterfaceStatus(UINT32 dwVersion, SNMP_Transport *pTransport, UINT32 dwIfIndex, int *adminState, int *operState);
823
824 ROUTING_TABLE *SnmpGetRoutingTable(UINT32 dwVersion, SNMP_Transport *pTransport);
825
826 void LoadNetworkDeviceDrivers();
827 NetworkDeviceDriver *FindDriverForNode(Node *node, SNMP_Transport *pTransport);
828 NetworkDeviceDriver *FindDriverByName(const TCHAR *name);
829 void AddDriverSpecificOids(StringList *list);
830
831 void WatchdogInit();
832 UINT32 WatchdogAddThread(const TCHAR *szName, time_t tNotifyInterval);
833 void WatchdogNotify(UINT32 dwId);
834 void WatchdogPrintStatus(CONSOLE_CTX pCtx);
835
836 void CheckForMgmtNode();
837 Node *PollNewNode(UINT32 dwIpAddr, UINT32 dwNetMask, UINT32 dwCreationFlags, WORD agentPort,
838 WORD snmpPort, const TCHAR *pszName, UINT32 dwProxyNode, UINT32 dwSNMPProxy, Cluster *pCluster,
839 UINT32 zoneId, bool doConfPoll, bool discoveredNode);
840
841 void NXCORE_EXPORTABLE EnumerateClientSessions(void (*pHandler)(ClientSession *, void *), void *pArg);
842 void NXCORE_EXPORTABLE NotifyClientSessions(UINT32 dwCode, UINT32 dwData);
843 int GetSessionCount(bool withRoot = true);
844 bool IsLoggedIn(UINT32 dwUserId);
845
846 void GetSysInfoStr(TCHAR *pszBuffer, int nMaxSize);
847 UINT32 GetLocalIpAddr();
848 TCHAR *GetLocalHostName(TCHAR *buffer, size_t bufSize);
849
850 BOOL ExecCommand(TCHAR *pszCommand);
851 BOOL SendMagicPacket(UINT32 dwIpAddr, BYTE *pbMacAddr, int iNumPackets);
852
853 BOOL InitIdTable();
854 UINT32 CreateUniqueId(int iGroup);
855 QWORD CreateUniqueEventId();
856 void SaveCurrentFreeId();
857
858 void InitMailer();
859 void ShutdownMailer();
860 void NXCORE_EXPORTABLE PostMail(const TCHAR *pszRcpt, const TCHAR *pszSubject, const TCHAR *pszText);
861
862 void InitSMSSender();
863 void ShutdownSMSSender();
864 void NXCORE_EXPORTABLE PostSMS(const TCHAR *pszRcpt, const TCHAR *pszText);
865
866 void InitTraps();
867 void SendTrapsToClient(ClientSession *pSession, UINT32 dwRqId);
868 void CreateTrapCfgMessage(CSCPMessage &msg);
869 UINT32 CreateNewTrap(UINT32 *pdwTrapId);
870 UINT32 CreateNewTrap(NXC_TRAP_CFG_ENTRY *pTrap);
871 UINT32 UpdateTrapFromMsg(CSCPMessage *pMsg);
872 UINT32 DeleteTrap(UINT32 dwId);
873 void CreateNXMPTrapRecord(String &str, UINT32 dwId);
874
875 BOOL IsTableTool(UINT32 dwToolId);
876 BOOL CheckObjectToolAccess(UINT32 dwToolId, UINT32 dwUserId);
877 UINT32 ExecuteTableTool(UINT32 dwToolId, Node *pNode, UINT32 dwRqId, ClientSession *pSession);
878 UINT32 DeleteObjectToolFromDB(UINT32 dwToolId);
879 UINT32 ChangeObjectToolDisableStatuss(UINT32 toolID);
880 UINT32 UpdateObjectToolFromMessage(CSCPMessage *pMsg);
881
882 UINT32 ModifySummaryTable(CSCPMessage *msg, LONG *newId);
883 UINT32 DeleteSummaryTable(LONG tableId);
884 Table *QuerySummaryTable(LONG tableId, UINT32 baseObjectId, UINT32 userId, UINT32 *rcc);
885
886 void CreateMessageFromSyslogMsg(CSCPMessage *pMsg, NX_SYSLOG_RECORD *pRec);
887 void ReinitializeSyslogParser();
888
889 void EscapeString(String &str);
890
891 void InitAuditLog();
892 void NXCORE_EXPORTABLE WriteAuditLog(const TCHAR *subsys, BOOL isSuccess, UINT32 userId,
893 const TCHAR *workstation, UINT32 objectId,
894 const TCHAR *format, ...);
895
896 bool ValidateConfig(Config *config, UINT32 flags, TCHAR *errorText, int errorTextLen);
897 UINT32 ImportConfig(Config *config, UINT32 flags);
898
899 #ifdef _WITH_ENCRYPTION
900 X509 *CertificateFromLoginMessage(CSCPMessage *pMsg);
901 BOOL ValidateUserCertificate(X509 *pCert, const TCHAR *pszLogin, BYTE *pChallenge,
902 BYTE *pSignature, UINT32 dwSigLen, int nMappingMethod,
903 const TCHAR *pszMappingData);
904 void ReloadCertificates();
905 #endif
906
907 #ifndef _WIN32
908 THREAD_RESULT NXCORE_EXPORTABLE THREAD_CALL SignalHandler(void *);
909 #endif /* not _WIN32 */
910
911 void DbgTestRWLock(RWLOCK hLock, const TCHAR *szName, CONSOLE_CTX pCtx);
912 void DumpClientSessions(CONSOLE_CTX pCtx);
913 void DumpMobileDeviceSessions(CONSOLE_CTX pCtx);
914 void ShowPollerState(CONSOLE_CTX pCtx);
915 void SetPollerInfo(int nIdx, const TCHAR *pszMsg);
916 void ShowServerStats(CONSOLE_CTX pCtx);
917 void ShowQueueStats(CONSOLE_CTX pCtx, Queue *pQueue, const TCHAR *pszName);
918 void DumpProcess(CONSOLE_CTX pCtx);
919
920 GRAPH_ACL_ENTRY *LoadGraphACL(UINT32 graphId, int *pnACLSize);
921 BOOL CheckGraphAccess(GRAPH_ACL_ENTRY *pACL, int nACLSize, UINT32 graphId, UINT32 graphUserId, UINT32 graphDesiredAccess);
922 UINT32 GetGraphAccessCheckResult(UINT32 graphId, UINT32 graphUserId);
923 GRAPH_ACL_AND_ID IsGraphNameExists(const TCHAR *graphName);
924
925 #if XMPP_SUPPORTED
926 bool SendXMPPMessage(const TCHAR *rcpt, const TCHAR *message);
927 #endif
928
929 /**
930 * File monitoring
931 */
932 struct MONITORED_FILE
933 {
934 TCHAR fileName[MAX_PATH];
935 ClientSession *session;
936 UINT32 nodeID;
937 };
938
939 class FileMonitoringList
940 {
941 private:
942 MUTEX m_mutex;
943 ObjectArray<MONITORED_FILE> m_monitoredFiles;
944 MONITORED_FILE* m_monitoredFile;
945
946 public:
947 FileMonitoringList();
948 ~FileMonitoringList();
949 void addMonitoringFile(MONITORED_FILE *fileForAdd);
950 bool checkDuplicate(MONITORED_FILE *fileForAdd);
951 ObjectArray<ClientSession>* findClientByFNameAndNodeID(const TCHAR *fileName, UINT32 nodeID);
952 bool removeMonitoringFile(MONITORED_FILE *fileForRemove);
953 void removeDisconectedNode(UINT32 nodeId);
954
955 private:
956 void lock();
957 void unlock();
958 };
959
960 /**
961 * Global variables
962 */
963 extern TCHAR NXCORE_EXPORTABLE g_szConfigFile[];
964 extern TCHAR NXCORE_EXPORTABLE g_szLogFile[];
965 extern UINT32 g_dwLogRotationMode;
966 extern UINT32 g_dwMaxLogSize;
967 extern UINT32 g_dwLogHistorySize;
968 extern TCHAR g_szDailyLogFileSuffix[64];
969 extern TCHAR NXCORE_EXPORTABLE g_szDumpDir[];
970 extern TCHAR NXCORE_EXPORTABLE g_szListenAddress[];
971 #ifndef _WIN32
972 extern TCHAR NXCORE_EXPORTABLE g_szPIDFile[];
973 #endif
974 extern TCHAR g_szDataDir[];
975 extern TCHAR g_szLibDir[];
976 extern TCHAR g_szJavaLibDir[];
977 extern UINT32 NXCORE_EXPORTABLE g_processAffinityMask;
978 extern QWORD g_qwServerId;
979 extern RSA *g_pServerKey;
980 extern UINT32 g_icmpPingSize;
981 extern UINT32 g_icmpPingTimeout;
982 extern UINT32 g_auditFlags;
983 extern time_t g_serverStartTime;
984 extern UINT32 g_lockTimeout;
985 extern UINT32 g_agentCommandTimeout;
986 extern UINT32 g_thresholdRepeatInterval;
987 extern int g_requiredPolls;
988 extern UINT32 g_slmPollingInterval;
989
990 extern TCHAR g_szDbDriver[];
991 extern TCHAR g_szDbDrvParams[];
992 extern TCHAR g_szDbServer[];
993 extern TCHAR g_szDbLogin[];
994 extern TCHAR g_szDbPassword[];
995 extern TCHAR g_szDbName[];
996 extern TCHAR g_szDbSchema[];
997 extern TCHAR NXCORE_EXPORTABLE g_szJavaPath[];
998 extern DB_DRIVER g_dbDriver;
999 extern DB_HANDLE NXCORE_EXPORTABLE g_hCoreDB;
1000 extern Queue *g_pLazyRequestQueue;
1001 extern Queue *g_pIDataInsertQueue;
1002
1003 extern int NXCORE_EXPORTABLE g_nDBSyntax;
1004 extern FileMonitoringList g_monitoringList;
1005
1006 #endif /* _nms_core_h_ */