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