5eeb8da5feb9ddd6a42a947b598e235aa24311ba
[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
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 void pushData(CSCPMessage *request);
342
343 public:
344 MobileDeviceSession(SOCKET hSocket, struct sockaddr *addr);
345 ~MobileDeviceSession();
346
347 void incRefCount() { m_dwRefCount++; }
348 void decRefCount() { if (m_dwRefCount > 0) m_dwRefCount--; }
349
350 void run();
351
352 void postMessage(CSCPMessage *pMsg) { m_pSendQueue->Put(pMsg->createMessage()); }
353 void sendMessage(CSCPMessage *pMsg);
354
355 UINT32 getIndex() { return m_dwIndex; }
356 void setIndex(UINT32 dwIndex) { if (m_dwIndex == INVALID_INDEX) m_dwIndex = dwIndex; }
357 int getState() { return m_iState; }
358 const TCHAR *getUserName() { return m_szUserName; }
359 const TCHAR *getClientInfo() { return m_szClientInfo; }
360 const TCHAR *getHostName() { return m_szHostName; }
361 UINT32 getUserId() { return m_dwUserId; }
362 bool isAuthenticated() { return m_isAuthenticated; }
363 WORD getCurrentCmd() { return m_wCurrentCmd; }
364 int getCipher() { return (m_pCtx == NULL) ? -1 : m_pCtx->getCipher(); }
365 };
366
367 /**
368 * Client (user) session
369 */
370 #define DECLARE_THREAD_STARTER(func) static THREAD_RESULT THREAD_CALL ThreadStarter_##func(void *);
371
372 class NXCORE_EXPORTABLE ClientSession
373 {
374 private:
375 SOCKET m_hSocket;
376 Queue *m_pSendQueue;
377 Queue *m_pMessageQueue;
378 Queue *m_pUpdateQueue;
379 UINT32 m_dwIndex;
380 int m_iState;
381 WORD m_wCurrentCmd;
382 UINT32 m_dwUserId;
383 UINT32 m_dwSystemAccess; // User's system access rights
384 UINT32 m_dwFlags; // Session flags
385 int m_clientType; // Client system type - desktop, web, mobile, etc.
386 CSCP_BUFFER *m_pMsgBuffer;
387 NXCPEncryptionContext *m_pCtx;
388 BYTE m_challenge[CLIENT_CHALLENGE_SIZE];
389 THREAD m_hWriteThread;
390 THREAD m_hProcessingThread;
391 THREAD m_hUpdateThread;
392 MUTEX m_mutexSocketWrite;
393 MUTEX m_mutexSendEvents;
394 MUTEX m_mutexSendSyslog;
395 MUTEX m_mutexSendTrapLog;
396 MUTEX m_mutexSendObjects;
397 MUTEX m_mutexSendAlarms;
398 MUTEX m_mutexSendActions;
399 MUTEX m_mutexSendAuditLog;
400 MUTEX m_mutexSendSituations;
401 MUTEX m_mutexPollerInit;
402 struct sockaddr *m_clientAddr;
403 TCHAR m_workstation[256]; // IP address or name of connected host in textual form
404 TCHAR m_webServerAddress[256]; // IP address or name of web server for web sessions
405 TCHAR m_szUserName[MAX_SESSION_NAME]; // String in form login_name@host
406 TCHAR m_szClientInfo[96]; // Client app info string
407 time_t m_loginTime;
408 UINT32 m_dwOpenDCIListSize; // Number of open DCI lists
409 UINT32 *m_pOpenDCIList; // List of nodes with DCI lists open
410 UINT32 m_dwNumRecordsToUpload; // Number of records to be uploaded
411 UINT32 m_dwRecordsUploaded;
412 EPRule **m_ppEPPRuleList; // List of loaded EPP rules
413 int m_hCurrFile;
414 UINT32 m_dwFileRqId;
415 UINT32 m_dwUploadCommand;
416 UINT32 m_dwUploadData;
417 uuid_t m_uploadImageGuid;
418 TCHAR m_szCurrFileName[MAX_PATH];
419 UINT32 m_dwRefCount;
420 UINT32 m_dwEncryptionRqId;
421 UINT32 m_dwEncryptionResult;
422 CONDITION m_condEncryptionSetup;
423 UINT32 m_dwActiveChannels; // Active data channels
424 CONSOLE_CTX m_console; // Server console context
425 StringList m_musicTypeList;
426
427 static THREAD_RESULT THREAD_CALL readThreadStarter(void *);
428 static THREAD_RESULT THREAD_CALL writeThreadStarter(void *);
429 static THREAD_RESULT THREAD_CALL processingThreadStarter(void *);
430 static THREAD_RESULT THREAD_CALL updateThreadStarter(void *);
431 static THREAD_RESULT THREAD_CALL pollerThreadStarter(void *);
432
433 DECLARE_THREAD_STARTER(getCollectedData)
434 DECLARE_THREAD_STARTER(getTableCollectedData)
435 DECLARE_THREAD_STARTER(clearDCIData)
436 DECLARE_THREAD_STARTER(queryParameter)
437 DECLARE_THREAD_STARTER(queryAgentTable)
438 DECLARE_THREAD_STARTER(queryL2Topology)
439 DECLARE_THREAD_STARTER(sendEventLog)
440 DECLARE_THREAD_STARTER(sendSyslog)
441 DECLARE_THREAD_STARTER(createObject)
442 DECLARE_THREAD_STARTER(getServerFile)
443 DECLARE_THREAD_STARTER(getAgentFile)
444 DECLARE_THREAD_STARTER(cancelFileMonitoring)
445 DECLARE_THREAD_STARTER(queryServerLog)
446 DECLARE_THREAD_STARTER(getServerLogQueryData)
447 DECLARE_THREAD_STARTER(executeAction)
448 DECLARE_THREAD_STARTER(findNodeConnection)
449 DECLARE_THREAD_STARTER(findMacAddress)
450 DECLARE_THREAD_STARTER(findIpAddress)
451 DECLARE_THREAD_STARTER(processConsoleCommand)
452 DECLARE_THREAD_STARTER(sendMib)
453 DECLARE_THREAD_STARTER(getNetworkPath)
454 DECLARE_THREAD_STARTER(getAlarmEvents)
455 DECLARE_THREAD_STARTER(openHelpdeskIssue)
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 getLastValuesByDciId(CSCPMessage *pRequest);
501 void getTableLastValues(CSCPMessage *pRequest);
502 void getThresholdSummary(CSCPMessage *request);
503 void openEPP(CSCPMessage *request);
504 void closeEPP(UINT32 dwRqId);
505 void saveEPP(CSCPMessage *pRequest);
506 void processEPPRecord(CSCPMessage *pRequest);
507 void sendMIBTimestamp(UINT32 dwRqId);
508 void sendMib(CSCPMessage *request);
509 void createObject(CSCPMessage *request);
510 void changeObjectBinding(CSCPMessage *request, BOOL bBind);
511 void deleteObject(CSCPMessage *request);
512 void getAlarm(CSCPMessage *request);
513 void getAlarmEvents(CSCPMessage *request);
514 void acknowledgeAlarm(CSCPMessage *request);
515 void resolveAlarm(CSCPMessage *request, bool terminate);
516 void deleteAlarm(CSCPMessage *request);
517 void openHelpdeskIssue(CSCPMessage *request);
518 void getHelpdeskUrl(CSCPMessage *request);
519 void unlinkHelpdeskIssue(CSCPMessage *request);
520 void getAlarmComments(CSCPMessage *pRequest);
521 void updateAlarmComment(CSCPMessage *pRequest);
522 void deleteAlarmComment(CSCPMessage *request);
523 void updateAlarmStatusFlow(CSCPMessage *request);
524 void createAction(CSCPMessage *pRequest);
525 void updateAction(CSCPMessage *pRequest);
526 void deleteAction(CSCPMessage *pRequest);
527 void sendAllActions(UINT32 dwRqId);
528 void SendContainerCategories(UINT32 dwRqId);
529 void forcedNodePoll(CSCPMessage *pRequest);
530 void onTrap(CSCPMessage *pRequest);
531 void onWakeUpNode(CSCPMessage *pRequest);
532 void queryParameter(CSCPMessage *pRequest);
533 void queryAgentTable(CSCPMessage *pRequest);
534 void editTrap(int iOperation, CSCPMessage *pRequest);
535 void LockTrapCfg(UINT32 dwRqId, BOOL bLock);
536 void sendAllTraps(UINT32 dwRqId);
537 void sendAllTraps2(UINT32 dwRqId);
538 void LockPackageDB(UINT32 dwRqId, BOOL bLock);
539 void SendAllPackages(UINT32 dwRqId);
540 void InstallPackage(CSCPMessage *pRequest);
541 void RemovePackage(CSCPMessage *pRequest);
542 void DeployPackage(CSCPMessage *pRequest);
543 void getParametersList(CSCPMessage *pRequest);
544 void getUserVariable(CSCPMessage *pRequest);
545 void setUserVariable(CSCPMessage *pRequest);
546 void copyUserVariable(CSCPMessage *pRequest);
547 void enumUserVariables(CSCPMessage *pRequest);
548 void deleteUserVariable(CSCPMessage *pRequest);
549 void changeObjectZone(CSCPMessage *pRequest);
550 void getAgentConfig(CSCPMessage *pRequest);
551 void updateAgentConfig(CSCPMessage *pRequest);
552 void executeAction(CSCPMessage *pRequest);
553 void sendObjectTools(UINT32 dwRqId);
554 void sendObjectToolDetails(CSCPMessage *pRequest);
555 void updateObjectTool(CSCPMessage *pRequest);
556 void deleteObjectTool(CSCPMessage *pRequest);
557 void changeObjectToolStatus(CSCPMessage *pRequest);
558 void generateObjectToolId(UINT32 dwRqId);
559 void execTableTool(CSCPMessage *pRequest);
560 void changeSubscription(CSCPMessage *pRequest);
561 void sendSyslog(CSCPMessage *pRequest);
562 void sendServerStats(UINT32 dwRqId);
563 void sendScriptList(UINT32 dwRqId);
564 void sendScript(CSCPMessage *pRequest);
565 void updateScript(CSCPMessage *pRequest);
566 void renameScript(CSCPMessage *pRequest);
567 void deleteScript(CSCPMessage *pRequest);
568 void SendSessionList(UINT32 dwRqId);
569 void KillSession(CSCPMessage *pRequest);
570 void SendTrapLog(CSCPMessage *pRequest);
571 void StartSnmpWalk(CSCPMessage *pRequest);
572 void resolveDCINames(CSCPMessage *pRequest);
573 UINT32 resolveDCIName(UINT32 dwNode, UINT32 dwItem, TCHAR **ppszName);
574 void sendConfigForAgent(CSCPMessage *pRequest);
575 void sendAgentCfgList(UINT32 dwRqId);
576 void OpenAgentConfig(CSCPMessage *pRequest);
577 void SaveAgentConfig(CSCPMessage *pRequest);
578 void DeleteAgentConfig(CSCPMessage *pRequest);
579 void SwapAgentConfigs(CSCPMessage *pRequest);
580 void SendObjectComments(CSCPMessage *pRequest);
581 void updateObjectComments(CSCPMessage *pRequest);
582 void pushDCIData(CSCPMessage *pRequest);
583 void getAddrList(CSCPMessage *pRequest);
584 void setAddrList(CSCPMessage *pRequest);
585 void resetComponent(CSCPMessage *pRequest);
586 void sendDCIEventList(CSCPMessage *request);
587 void SendDCIInfo(CSCPMessage *pRequest);
588 void sendPerfTabDCIList(CSCPMessage *pRequest);
589 void exportConfiguration(CSCPMessage *pRequest);
590 void importConfiguration(CSCPMessage *pRequest);
591 void sendGraphList(UINT32 dwRqId);
592 void saveGraph(CSCPMessage *pRequest);
593 void deleteGraph(CSCPMessage *pRequest);
594 void AddCACertificate(CSCPMessage *pRequest);
595 void DeleteCertificate(CSCPMessage *pRequest);
596 void UpdateCertificateComments(CSCPMessage *pRequest);
597 void getCertificateList(UINT32 dwRqId);
598 void queryL2Topology(CSCPMessage *pRequest);
599 void sendSMS(CSCPMessage *pRequest);
600 void SendCommunityList(UINT32 dwRqId);
601 void UpdateCommunityList(CSCPMessage *pRequest);
602 void getSituationList(UINT32 dwRqId);
603 void createSituation(CSCPMessage *pRequest);
604 void updateSituation(CSCPMessage *pRequest);
605 void deleteSituation(CSCPMessage *pRequest);
606 void deleteSituationInstance(CSCPMessage *pRequest);
607 void setConfigCLOB(CSCPMessage *pRequest);
608 void getConfigCLOB(CSCPMessage *pRequest);
609 void registerAgent(CSCPMessage *pRequest);
610 void getServerFile(CSCPMessage *pRequest);
611 void cancelFileMonitoring(CSCPMessage *request);
612 void getAgentFile(CSCPMessage *pRequest);
613 void testDCITransformation(CSCPMessage *pRequest);
614 void sendJobList(UINT32 dwRqId);
615 void cancelJob(CSCPMessage *pRequest);
616 void holdJob(CSCPMessage *pRequest);
617 void unholdJob(CSCPMessage *pRequest);
618 void deployAgentPolicy(CSCPMessage *pRequest, bool uninstallFlag);
619 void getUserCustomAttribute(CSCPMessage *request);
620 void setUserCustomAttribute(CSCPMessage *request);
621 void openServerLog(CSCPMessage *request);
622 void closeServerLog(CSCPMessage *request);
623 void queryServerLog(CSCPMessage *request);
624 void getServerLogQueryData(CSCPMessage *request);
625 void sendUsmCredentials(UINT32 dwRqId);
626 void updateUsmCredentials(CSCPMessage *pRequest);
627 void sendDCIThresholds(CSCPMessage *request);
628 void addClusterNode(CSCPMessage *request);
629 void findNodeConnection(CSCPMessage *request);
630 void findMacAddress(CSCPMessage *request);
631 void findIpAddress(CSCPMessage *request);
632 void sendLibraryImage(CSCPMessage *request);
633 void updateLibraryImage(CSCPMessage *request);
634 void listLibraryImages(CSCPMessage *request);
635 void deleteLibraryImage(CSCPMessage *request);
636 void executeServerCommand(CSCPMessage *request);
637 void uploadFileToAgent(CSCPMessage *request);
638 void listServerFileStore(CSCPMessage *request);
639 void processConsoleCommand(CSCPMessage *msg);
640 void openConsole(UINT32 rqId);
641 void closeConsole(UINT32 rqId);
642 void getVlans(CSCPMessage *msg);
643 void receiveFile(CSCPMessage *request);
644 void deleteFile(CSCPMessage *request);
645 void getNetworkPath(CSCPMessage *request);
646 void getNodeComponents(CSCPMessage *request);
647 void getNodeSoftware(CSCPMessage *request);
648 void getWinPerfObjects(CSCPMessage *request);
649 void listMappingTables(CSCPMessage *request);
650 void getMappingTable(CSCPMessage *request);
651 void updateMappingTable(CSCPMessage *request);
652 void deleteMappingTable(CSCPMessage *request);
653 void getWirelessStations(CSCPMessage *request);
654 void getSummaryTables(UINT32 rqId);
655 void getSummaryTableDetails(CSCPMessage *request);
656 void modifySummaryTable(CSCPMessage *request);
657 void deleteSummaryTable(CSCPMessage *request);
658 void querySummaryTable(CSCPMessage *request);
659 void forwardToReportingServer(CSCPMessage *request);
660 void getSubnetAddressMap(CSCPMessage *request);
661 void getEffectiveRights(CSCPMessage *request);
662
663 public:
664 ClientSession(SOCKET hSocket, struct sockaddr *addr);
665 ~ClientSession();
666
667 void incRefCount() { m_dwRefCount++; }
668 void decRefCount() { if (m_dwRefCount > 0) m_dwRefCount--; }
669
670 void run();
671
672 void postMessage(CSCPMessage *pMsg) { m_pSendQueue->Put(pMsg->createMessage()); }
673 void sendMessage(CSCPMessage *pMsg);
674 void sendRawMessage(CSCP_MESSAGE *pMsg);
675 void sendPollerMsg(UINT32 dwRqId, const TCHAR *pszMsg);
676 BOOL sendFile(const TCHAR *file, UINT32 dwRqId, long offset);
677
678 UINT32 getIndex() { return m_dwIndex; }
679 void setIndex(UINT32 dwIndex) { if (m_dwIndex == INVALID_INDEX) m_dwIndex = dwIndex; }
680 int getState() { return m_iState; }
681 const TCHAR *getUserName() { return m_szUserName; }
682 const TCHAR *getClientInfo() { return m_szClientInfo; }
683 const TCHAR *getWorkstation() { return m_workstation; }
684 const TCHAR *getWebServerAddress() { return m_webServerAddress; }
685 UINT32 getUserId() { return m_dwUserId; }
686 UINT32 getSystemRights() { return m_dwSystemAccess; }
687 bool isAuthenticated() { return (m_dwFlags & CSF_AUTHENTICATED) ? true : false; }
688 bool isConsoleOpen() { return (m_dwFlags & CSF_CONSOLE_OPEN) ? true : false; }
689 bool isSubscribed(UINT32 dwChannel) { return (m_dwActiveChannels & dwChannel) ? true : false; }
690 WORD getCurrentCmd() { return m_wCurrentCmd; }
691 int getCipher() { return (m_pCtx == NULL) ? -1 : m_pCtx->getCipher(); }
692 int getClientType() { return m_clientType; }
693 time_t getLoginTime() { return m_loginTime; }
694
695 bool checkSysAccessRights(UINT32 requiredAccess)
696 {
697 return (m_dwUserId == 0) ? true :
698 ((requiredAccess & m_dwSystemAccess) == requiredAccess);
699 }
700
701 void kill();
702 void notify(UINT32 dwCode, UINT32 dwData = 0);
703
704 void queueUpdate(UPDATE_INFO *pUpdate) { m_pUpdateQueue->Put(pUpdate); }
705 void onNewEvent(Event *pEvent);
706 void onSyslogMessage(NX_SYSLOG_RECORD *pRec);
707 void onNewSNMPTrap(CSCPMessage *pMsg);
708 void onObjectChange(NetObj *pObject);
709 void onUserDBUpdate(int code, UINT32 id, UserDatabaseObject *user);
710 void onAlarmUpdate(UINT32 dwCode, NXC_ALARM *pAlarm);
711 void onActionDBUpdate(UINT32 dwCode, NXC_ACTION *pAction);
712 void onSituationChange(CSCPMessage *msg);
713 void onLibraryImageChange(uuid_t *guid, bool removed = false);
714 };
715
716 /**
717 * Delayed SQL request
718 */
719 typedef struct
720 {
721 TCHAR *query;
722 int bindCount;
723 BYTE *sqlTypes;
724 TCHAR *bindings[1]; /* actual size determined by bindCount field */
725 } DELAYED_SQL_REQUEST;
726
727 /**
728 * Delayed request for idata_ INSERT
729 */
730 typedef struct
731 {
732 time_t timestamp;
733 UINT32 nodeId;
734 UINT32 dciId;
735 TCHAR value[MAX_RESULT_LENGTH];
736 } DELAYED_IDATA_INSERT;
737
738 /**
739 * Graph ACL entry
740 */
741 struct GRAPH_ACL_ENTRY
742 {
743 UINT32 dwGraphId;
744 UINT32 dwUserId;
745 UINT32 dwAccess;
746 };
747
748 /**
749 * Information about graph with name existence and it's ID.
750 */
751 struct GRAPH_ACL_AND_ID
752 {
753 UINT32 graphId;
754 UINT32 status;
755 };
756
757 /**
758 * Functions
759 */
760 bool NXCORE_EXPORTABLE ConfigReadStr(const TCHAR *szVar, TCHAR *szBuffer, int iBufSize, const TCHAR *szDefault);
761 #ifdef UNICODE
762 bool NXCORE_EXPORTABLE ConfigReadStrA(const WCHAR *szVar, char *szBuffer, int iBufSize, const char *szDefault);
763 #else
764 #define ConfigReadStrA ConfigReadStr
765 #endif
766 bool NXCORE_EXPORTABLE ConfigReadStrUTF8(const TCHAR *szVar, char *szBuffer, int iBufSize, const char *szDefault);
767 int NXCORE_EXPORTABLE ConfigReadInt(const TCHAR *szVar, int iDefault);
768 UINT32 NXCORE_EXPORTABLE ConfigReadULong(const TCHAR *szVar, UINT32 dwDefault);
769 bool NXCORE_EXPORTABLE ConfigReadByteArray(const TCHAR *pszVar, int *pnArray, int nSize, int nDefault);
770 bool NXCORE_EXPORTABLE ConfigWriteStr(const TCHAR *szVar, const TCHAR *szValue, bool bCreate, bool isVisible = true, bool needRestart = false);
771 bool NXCORE_EXPORTABLE ConfigWriteInt(const TCHAR *szVar, int iValue, bool bCreate, bool isVisible = true, bool needRestart = false);
772 bool NXCORE_EXPORTABLE ConfigWriteULong(const TCHAR *szVar, UINT32 dwValue, bool bCreate, bool isVisible = true, bool needRestart = false);
773 bool NXCORE_EXPORTABLE ConfigWriteByteArray(const TCHAR *pszVar, int *pnArray, int nSize, bool bCreate, bool isVisible = true, bool needRestart = false);
774 TCHAR NXCORE_EXPORTABLE *ConfigReadCLOB(const TCHAR *var, const TCHAR *defValue);
775 bool NXCORE_EXPORTABLE ConfigWriteCLOB(const TCHAR *var, const TCHAR *value, bool bCreate);
776 bool NXCORE_EXPORTABLE ConfigDelete(const TCHAR *name);
777
778 bool NXCORE_EXPORTABLE MetaDataReadStr(const TCHAR *szVar, TCHAR *szBuffer, int iBufSize, const TCHAR *szDefault);
779 INT32 NXCORE_EXPORTABLE MetaDataReadInt(const TCHAR *var, UINT32 defaultValue);
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 ChangeObjectToolStatus(UINT32 toolId, bool enabled);
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(DB_HANDLE hdb, 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_ */