Collected DCI data recalculation based on stored raw values and current transformatio...
[public/netxms.git] / src / server / include / nms_core.h
1 /*
2 ** NetXMS - Network Management System
3 ** Copyright (C) 2003-2016 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 //
65 // Common includes
66 //
67
68 #include <nms_util.h>
69 #include <dbdrv.h>
70 #include <nms_cscp.h>
71 #include <uuid.h>
72 #include <nxsrvapi.h>
73 #include <nxqueue.h>
74 #include <nxsnmp.h>
75 #include <nxmodule.h>
76 #include <nxsl.h>
77 #include <nxdbapi.h>
78 #include <nddrv.h>
79 #include <npe.h>
80 #include <nxcore_smclp.h>
81
82 /**
83 * Console context
84 */
85 struct __console_ctx
86 {
87 SOCKET hSocket;
88 MUTEX socketMutex;
89 NXCPMessage *pMsg;
90 ClientSession *session;
91 String *output;
92 };
93
94 typedef __console_ctx * CONSOLE_CTX;
95
96 /**
97 * Server includes
98 */
99 #include "nms_dcoll.h"
100 #include "nms_users.h"
101 #include "nxcore_winperf.h"
102 #include "nms_objects.h"
103 #include "nms_locks.h"
104 #include "nms_pkg.h"
105 #include "nms_topo.h"
106 #include "nms_script.h"
107 #include "nxcore_ps.h"
108 #include "nxcore_jobs.h"
109 #include "nxcore_logs.h"
110 #include "nxcore_schedule.h"
111 #ifdef WITH_ZMQ
112 #include "zeromq.h"
113 #endif
114
115 /**
116 * Common constants and macros
117 */
118 #define MAX_LINE_SIZE 4096
119 #define GROUP_FLAG_BIT ((UINT32)0x80000000)
120 #define CHECKPOINT_SNMP_PORT 260
121 #define DEFAULT_AFFINITY_MASK 0xFFFFFFFF
122
123 #define MAX_CLIENT_SESSIONS 128
124 #define MAX_DEVICE_SESSIONS 256
125
126 #define PING_TIME_TIMEOUT 10000
127
128 typedef void * HSNMPSESSION;
129
130 /**
131 * Prefixes for poller messages
132 */
133 #define POLLER_ERROR _T("\x7F") _T("e")
134 #define POLLER_WARNING _T("\x7Fw")
135 #define POLLER_INFO _T("\x7Fi")
136
137 /**
138 * Unique identifier group codes
139 */
140 #define IDG_NETWORK_OBJECT 0
141 #define IDG_EVENT 1
142 #define IDG_ITEM 2
143 #define IDG_SNMP_TRAP 3
144 #define IDG_JOB 4
145 #define IDG_ACTION 5
146 #define IDG_EVENT_GROUP 6
147 #define IDG_THRESHOLD 7
148 #define IDG_USER 8
149 #define IDG_USER_GROUP 9
150 #define IDG_ALARM 10
151 #define IDG_ALARM_NOTE 11
152 #define IDG_PACKAGE 12
153 #define IDG_SLM_TICKET 13
154 #define IDG_OBJECT_TOOL 14
155 #define IDG_SCRIPT 15
156 #define IDG_AGENT_CONFIG 16
157 #define IDG_GRAPH 17
158 #define IDG_CERTIFICATE 18
159 #define IDG_DCT_COLUMN 19
160 #define IDG_MAPPING_TABLE 20
161 #define IDG_DCI_SUMMARY_TABLE 21
162 #define IDG_SCHEDULED_TASK 22
163 #define IDG_ALARM_CATEGORY 23
164
165 /**
166 * Exit codes for console commands
167 */
168 #define CMD_EXIT_CONTINUE 0
169 #define CMD_EXIT_CLOSE_SESSION 1
170 #define CMD_EXIT_SHUTDOWN 2
171
172 /**
173 * Network discovery mode
174 */
175 #define DISCOVERY_DISABLED 0
176 #define DISCOVERY_PASSIVE_ONLY 1
177 #define DISCOVERY_ACTIVE 2
178
179 /**
180 * Client session flags
181 */
182 #define CSF_TERMINATED ((UINT32)0x00000001)
183 #define CSF_EPP_LOCKED ((UINT32)0x00000002)
184 #define CSF_PACKAGE_DB_LOCKED ((UINT32)0x00000004)
185 #define CSF_USER_DB_LOCKED ((UINT32)0x00000008)
186 #define CSF_EPP_UPLOAD ((UINT32)0x00000010)
187 #define CSF_CONSOLE_OPEN ((UINT32)0x00000020)
188 #define CSF_AUTHENTICATED ((UINT32)0x00000080)
189 #define CSF_COMPRESSION_ENABLED ((UINT32)0x00000100)
190 #define CSF_RECEIVING_MAP_DATA ((UINT32)0x00000200)
191 #define CSF_SYNC_OBJECT_COMMENTS ((UINT32)0x00000400)
192 #define CSF_CUSTOM_LOCK_1 ((UINT32)0x01000000)
193 #define CSF_CUSTOM_LOCK_2 ((UINT32)0x02000000)
194 #define CSF_CUSTOM_LOCK_3 ((UINT32)0x04000000)
195 #define CSF_CUSTOM_LOCK_4 ((UINT32)0x08000000)
196 #define CSF_CUSTOM_LOCK_5 ((UINT32)0x10000000)
197 #define CSF_CUSTOM_LOCK_6 ((UINT32)0x20000000)
198 #define CSF_CUSTOM_LOCK_7 ((UINT32)0x40000000)
199 #define CSF_CUSTOM_LOCK_8 ((UINT32)0x80000000)
200
201 /**
202 * Client session states
203 */
204 #define SESSION_STATE_INIT 0
205 #define SESSION_STATE_IDLE 1
206 #define SESSION_STATE_PROCESSING 2
207
208 /**
209 * Certificate types
210 */
211 enum CertificateType
212 {
213 CERT_TYPE_TRUSTED_CA = 0,
214 CERT_TYPE_USER = 1,
215 CERT_TYPE_AGENT = 2,
216 CERT_TYPE_SERVER = 3
217 };
218
219 /**
220 * Audit subsystems
221 */
222 #define AUDIT_SECURITY _T("SECURITY")
223 #define AUDIT_OBJECTS _T("OBJECTS")
224 #define AUDIT_SYSCFG _T("SYSCFG")
225 #define AUDIT_CONSOLE _T("CONSOLE")
226
227 #define AUDIT_SYSTEM_SID (-1)
228
229 /**
230 * Event handling subsystem definitions
231 */
232 #include "nms_events.h"
233 #include "nms_actions.h"
234 #include "nms_alarm.h"
235
236 /**
237 * New node information
238 */
239 typedef struct
240 {
241 InetAddress ipAddr;
242 UINT32 zoneUIN;
243 BOOL ignoreFilter;
244 BYTE bMacAddr[MAC_ADDR_LENGTH];
245 } NEW_NODE;
246
247 /**
248 * New node flags
249 */
250 #define NNF_IS_SNMP 0x0001
251 #define NNF_IS_AGENT 0x0002
252 #define NNF_IS_ROUTER 0x0004
253 #define NNF_IS_BRIDGE 0x0008
254 #define NNF_IS_PRINTER 0x0010
255 #define NNF_IS_CDP 0x0020
256 #define NNF_IS_SONMP 0x0040
257 #define NNF_IS_LLDP 0x0080
258
259 /**
260 * Address list element types
261 */
262 #define InetAddressListElement_SUBNET 0
263 #define InetAddressListElement_RANGE 1
264
265 /**
266 * SNMP config global ID
267 */
268 #define SNMP_CONFIG_GLOBAL -1
269
270 /**
271 * IP address list element
272 */
273 class NXCORE_EXPORTABLE InetAddressListElement
274 {
275 private:
276 int m_type;
277 InetAddress m_baseAddress;
278 InetAddress m_endAddress;
279
280 public:
281 InetAddressListElement(NXCPMessage *msg, UINT32 baseId);
282 InetAddressListElement(const InetAddress& baseAddr, const InetAddress& endAddr);
283 InetAddressListElement(const InetAddress& baseAddr, int maskBits);
284 InetAddressListElement(DB_RESULT hResult, int row);
285
286 void fillMessage(NXCPMessage *msg, UINT32 baseId) const;
287
288 bool contains(const InetAddress& addr) const;
289
290 int getType() const { return m_type; }
291 const InetAddress& getBaseAddress() const { return m_baseAddress; }
292 const InetAddress& getEndAddress() const { return m_endAddress; }
293
294 String toString() const;
295 };
296
297 /**
298 * Node information for autodiscovery filter
299 */
300 typedef struct
301 {
302 InetAddress ipAddr;
303 UINT32 dwFlags;
304 int nSNMPVersion;
305 TCHAR szObjectId[MAX_OID_LEN * 4]; // SNMP OID
306 TCHAR szAgentVersion[MAX_AGENT_VERSION_LEN];
307 TCHAR szPlatform[MAX_PLATFORM_NAME_LEN];
308 } DISCOVERY_FILTER_DATA;
309
310 /**
311 * Data update structure for client sessions
312 */
313 typedef struct
314 {
315 UINT32 dwCategory; // Data category - event, network object, etc.
316 UINT32 dwCode; // Data-specific update code
317 void *pData; // Pointer to data block
318 } UPDATE_INFO;
319
320 /**
321 * Mobile device session
322 */
323 class NXCORE_EXPORTABLE MobileDeviceSession
324 {
325 private:
326 SOCKET m_hSocket;
327 Queue *m_pSendQueue;
328 Queue *m_pMessageQueue;
329 int m_id;
330 int m_state;
331 WORD m_wCurrentCmd;
332 UINT32 m_dwUserId;
333 UINT32 m_deviceObjectId;
334 NXCP_BUFFER *m_pMsgBuffer;
335 NXCPEncryptionContext *m_pCtx;
336 BYTE m_challenge[CLIENT_CHALLENGE_SIZE];
337 THREAD m_hWriteThread;
338 THREAD m_hProcessingThread;
339 MUTEX m_mutexSocketWrite;
340 InetAddress m_clientAddr;
341 TCHAR m_szHostName[256]; // IP address of name of conneced host in textual form
342 TCHAR m_szUserName[MAX_SESSION_NAME]; // String in form login_name@host
343 TCHAR m_szClientInfo[96]; // Client app info string
344 UINT32 m_dwEncryptionRqId;
345 UINT32 m_dwEncryptionResult;
346 CONDITION m_condEncryptionSetup;
347 UINT32 m_dwRefCount;
348 bool m_isAuthenticated;
349
350 static THREAD_RESULT THREAD_CALL readThreadStarter(void *);
351 static THREAD_RESULT THREAD_CALL writeThreadStarter(void *);
352 static THREAD_RESULT THREAD_CALL processingThreadStarter(void *);
353
354 void readThread();
355 void writeThread();
356 void processingThread();
357
358 void setupEncryption(NXCPMessage *request);
359 void respondToKeepalive(UINT32 dwRqId);
360 void debugPrintf(int level, const TCHAR *format, ...);
361 void sendServerInfo(UINT32 dwRqId);
362 void login(NXCPMessage *pRequest);
363 void updateDeviceInfo(NXCPMessage *pRequest);
364 void updateDeviceStatus(NXCPMessage *pRequest);
365 void pushData(NXCPMessage *request);
366
367 public:
368 MobileDeviceSession(SOCKET hSocket, const InetAddress& addr);
369 ~MobileDeviceSession();
370
371 void run();
372
373 void postMessage(NXCPMessage *pMsg) { m_pSendQueue->put(pMsg->serialize()); }
374 void sendMessage(NXCPMessage *pMsg);
375
376 int getId() { return m_id; }
377 void setId(int id) { if (m_id == -1) m_id = id; }
378 int getState() { return m_state; }
379 const TCHAR *getUserName() { return m_szUserName; }
380 const TCHAR *getClientInfo() { return m_szClientInfo; }
381 const TCHAR *getHostName() { return m_szHostName; }
382 UINT32 getUserId() { return m_dwUserId; }
383 bool isAuthenticated() { return m_isAuthenticated; }
384 WORD getCurrentCmd() { return m_wCurrentCmd; }
385 int getCipher() { return (m_pCtx == NULL) ? -1 : m_pCtx->getCipher(); }
386 };
387
388 /**
389 * Processing thread starter declaration for client session
390 */
391 #define DECLARE_THREAD_STARTER(func) static void ThreadStarter_##func(void *);
392
393 /**
394 * Class that stores information about file that will be received
395 */
396 class ServerDownloadFileInfo : public DownloadFileInfo
397 {
398 protected:
399 UINT32 m_uploadCommand;
400 UINT32 m_uploadData;
401 uuid m_uploadImageGuid;
402
403 public:
404 ServerDownloadFileInfo(const TCHAR *name, UINT32 uploadCommand, time_t lastModTime = 0);
405 virtual ~ServerDownloadFileInfo();
406
407 virtual void close(bool success);
408
409 void setUploadData(UINT32 data) { m_uploadData = data; }
410 void setImageGuid(const uuid& guid) { m_uploadImageGuid = guid; }
411 void updateAgentPkgDBInfo(const TCHAR *description, const TCHAR *pkgName, const TCHAR *pkgVersion, const TCHAR *platform, const TCHAR *cleanFileName);
412 };
413
414 /**
415 * Client (user) session
416 */
417 class NXCORE_EXPORTABLE ClientSession
418 {
419 private:
420 SOCKET m_hSocket;
421 Queue *m_sendQueue;
422 Queue *m_requestQueue;
423 int m_id;
424 int m_state;
425 WORD m_wCurrentCmd;
426 UINT32 m_dwUserId;
427 UINT64 m_dwSystemAccess; // User's system access rights
428 UINT32 m_dwFlags; // Session flags
429 int m_clientType; // Client system type - desktop, web, mobile, etc.
430 NXCPEncryptionContext *m_pCtx;
431 BYTE m_challenge[CLIENT_CHALLENGE_SIZE];
432 THREAD m_hWriteThread;
433 THREAD m_hProcessingThread;
434 MUTEX m_mutexSocketWrite;
435 MUTEX m_mutexSendObjects;
436 MUTEX m_mutexSendAlarms;
437 MUTEX m_mutexSendActions;
438 MUTEX m_mutexSendAuditLog;
439 MUTEX m_mutexPollerInit;
440 InetAddress m_clientAddr;
441 TCHAR m_workstation[256]; // IP address or name of connected host in textual form
442 TCHAR m_webServerAddress[256]; // IP address or name of web server for web sessions
443 TCHAR m_loginName[MAX_USER_NAME];
444 TCHAR m_sessionName[MAX_SESSION_NAME]; // String in form login_name@host
445 TCHAR m_clientInfo[96]; // Client app info string
446 TCHAR m_language[8]; // Client's desired language
447 time_t m_loginTime;
448 UINT32 m_dwOpenDCIListSize; // Number of open DCI lists
449 UINT32 *m_pOpenDCIList; // List of nodes with DCI lists open
450 UINT32 m_dwNumRecordsToUpload; // Number of records to be uploaded
451 UINT32 m_dwRecordsUploaded;
452 EPRule **m_ppEPPRuleList; // List of loaded EPP rules
453 HashMap<UINT32, ServerDownloadFileInfo> *m_downloadFileMap;
454 VolatileCounter m_refCount;
455 UINT32 m_dwEncryptionRqId;
456 UINT32 m_dwEncryptionResult;
457 CONDITION m_condEncryptionSetup;
458 CONSOLE_CTX m_console; // Server console context
459 StringList m_musicTypeList;
460 ObjectIndex m_agentConn;
461 StringObjectMap<UINT32> *m_subscriptions;
462 MUTEX m_subscriptionLock;
463 HashMap<UINT32, CommandExec> *m_serverCommands;
464
465 static THREAD_RESULT THREAD_CALL readThreadStarter(void *);
466 static THREAD_RESULT THREAD_CALL writeThreadStarter(void *);
467 static THREAD_RESULT THREAD_CALL processingThreadStarter(void *);
468 static void pollerThreadStarter(void *);
469
470 DECLARE_THREAD_STARTER(cancelFileMonitoring)
471 DECLARE_THREAD_STARTER(clearDCIData)
472 DECLARE_THREAD_STARTER(createObject)
473 DECLARE_THREAD_STARTER(executeAction)
474 DECLARE_THREAD_STARTER(executeScript)
475 DECLARE_THREAD_STARTER(executeLibraryScript)
476 DECLARE_THREAD_STARTER(fileManagerControl)
477 DECLARE_THREAD_STARTER(findIpAddress)
478 DECLARE_THREAD_STARTER(findMacAddress)
479 DECLARE_THREAD_STARTER(findHostname)
480 DECLARE_THREAD_STARTER(findNodeConnection)
481 DECLARE_THREAD_STARTER(forceDCIPoll)
482 DECLARE_THREAD_STARTER(forwardToReportingServer)
483 DECLARE_THREAD_STARTER(getAgentFile)
484 DECLARE_THREAD_STARTER(getAlarmEvents)
485 DECLARE_THREAD_STARTER(getAlarms)
486 DECLARE_THREAD_STARTER(getCollectedData)
487 DECLARE_THREAD_STARTER(getPredictedData)
488 DECLARE_THREAD_STARTER(getLocationHistory)
489 DECLARE_THREAD_STARTER(getNetworkPath)
490 DECLARE_THREAD_STARTER(getRoutingTable)
491 DECLARE_THREAD_STARTER(getServerFile)
492 DECLARE_THREAD_STARTER(getServerLogQueryData)
493 DECLARE_THREAD_STARTER(getSwitchForwardingDatabase)
494 DECLARE_THREAD_STARTER(getTableCollectedData)
495 DECLARE_THREAD_STARTER(importConfiguration)
496 DECLARE_THREAD_STARTER(openHelpdeskIssue)
497 DECLARE_THREAD_STARTER(processConsoleCommand)
498 DECLARE_THREAD_STARTER(queryAgentTable)
499 DECLARE_THREAD_STARTER(queryL2Topology)
500 DECLARE_THREAD_STARTER(queryParameter)
501 DECLARE_THREAD_STARTER(queryServerLog)
502 DECLARE_THREAD_STARTER(recalculateDCIValues)
503 DECLARE_THREAD_STARTER(sendMib)
504 DECLARE_THREAD_STARTER(uploadUserFileToAgent)
505 DECLARE_THREAD_STARTER(getRepositories)
506 DECLARE_THREAD_STARTER(addRepository)
507 DECLARE_THREAD_STARTER(modifyRepository)
508 DECLARE_THREAD_STARTER(deleteRepository)
509
510 void readThread();
511 void writeThread();
512 void processingThread();
513 void pollerThread(DataCollectionTarget *pNode, int iPollType, UINT32 dwRqId);
514
515 void debugPrintf(int level, const TCHAR *format, ...);
516
517 void setupEncryption(NXCPMessage *request);
518 void respondToKeepalive(UINT32 dwRqId);
519 void onFileUpload(BOOL bSuccess);
520 void sendServerInfo(UINT32 dwRqId);
521 void login(NXCPMessage *pRequest);
522 void sendAllObjects(NXCPMessage *pRequest);
523 void sendSelectedObjects(NXCPMessage *pRequest);
524 void getConfigurationVariables(UINT32 dwRqId);
525 void getPublicConfigurationVariable(NXCPMessage *request);
526 void setDefaultConfigurationVariableValues(NXCPMessage *pRequest);
527 void setConfigurationVariable(NXCPMessage *pRequest);
528 void deleteConfigurationVariable(NXCPMessage *pRequest);
529 void sendUserDB(UINT32 dwRqId);
530 void createUser(NXCPMessage *pRequest);
531 void updateUser(NXCPMessage *pRequest);
532 void detachLdapUser(NXCPMessage *pRequest);
533 void deleteUser(NXCPMessage *pRequest);
534 void setPassword(NXCPMessage *request);
535 void validatePassword(NXCPMessage *request);
536 void lockUserDB(UINT32 dwRqId, BOOL bLock);
537 void getAlarmCategories(UINT32 requestId);
538 void modifyAlarmCategory(NXCPMessage *pRequest);
539 void deleteAlarmCategory(NXCPMessage *pRequest);
540 void sendEventDB(NXCPMessage *pRequest);
541 void modifyEventTemplate(NXCPMessage *pRequest);
542 void deleteEventTemplate(NXCPMessage *pRequest);
543 void generateEventCode(UINT32 dwRqId);
544 void modifyObject(NXCPMessage *pRequest);
545 void changeObjectMgmtStatus(NXCPMessage *pRequest);
546 void enterMaintenanceMode(NXCPMessage *request);
547 void leaveMaintenanceMode(NXCPMessage *request);
548 void openNodeDCIList(NXCPMessage *pRequest);
549 void closeNodeDCIList(NXCPMessage *pRequest);
550 void modifyNodeDCI(NXCPMessage *pRequest);
551 void copyDCI(NXCPMessage *pRequest);
552 void applyTemplate(NXCPMessage *pRequest);
553 void getCollectedData(NXCPMessage *pRequest);
554 void getTableCollectedData(NXCPMessage *pRequest);
555 bool getCollectedDataFromDB(NXCPMessage *request, NXCPMessage *response, DataCollectionTarget *object, int dciType, bool withRawValues);
556 void clearDCIData(NXCPMessage *pRequest);
557 void forceDCIPoll(NXCPMessage *pRequest);
558 void recalculateDCIValues(NXCPMessage *request);
559 void changeDCIStatus(NXCPMessage *pRequest);
560 void getLastValues(NXCPMessage *pRequest);
561 void getLastValuesByDciId(NXCPMessage *pRequest);
562 void getTableLastValues(NXCPMessage *pRequest);
563 void getThresholdSummary(NXCPMessage *request);
564 void openEPP(NXCPMessage *request);
565 void closeEPP(UINT32 dwRqId);
566 void saveEPP(NXCPMessage *pRequest);
567 void processEPPRecord(NXCPMessage *pRequest);
568 void sendMIBTimestamp(UINT32 dwRqId);
569 void sendMib(NXCPMessage *request);
570 void createObject(NXCPMessage *request);
571 void changeObjectBinding(NXCPMessage *request, BOOL bBind);
572 void deleteObject(NXCPMessage *request);
573 void getAlarms(NXCPMessage *request);
574 void getAlarm(NXCPMessage *request);
575 void getAlarmEvents(NXCPMessage *request);
576 void acknowledgeAlarm(NXCPMessage *request);
577 void resolveAlarm(NXCPMessage *request, bool terminate);
578 void bulkResolveAlarms(NXCPMessage *pRequest, bool terminate);
579 void deleteAlarm(NXCPMessage *request);
580 void openHelpdeskIssue(NXCPMessage *request);
581 void getHelpdeskUrl(NXCPMessage *request);
582 void unlinkHelpdeskIssue(NXCPMessage *request);
583 void getAlarmComments(NXCPMessage *pRequest);
584 void updateAlarmComment(NXCPMessage *pRequest);
585 void deleteAlarmComment(NXCPMessage *request);
586 void updateAlarmStatusFlow(NXCPMessage *request);
587 void createAction(NXCPMessage *pRequest);
588 void updateAction(NXCPMessage *pRequest);
589 void deleteAction(NXCPMessage *pRequest);
590 void sendAllActions(UINT32 dwRqId);
591 void forcedNodePoll(NXCPMessage *pRequest);
592 void onTrap(NXCPMessage *pRequest);
593 void onWakeUpNode(NXCPMessage *pRequest);
594 void queryParameter(NXCPMessage *pRequest);
595 void queryAgentTable(NXCPMessage *pRequest);
596 void editTrap(int iOperation, NXCPMessage *pRequest);
597 void LockTrapCfg(UINT32 dwRqId, BOOL bLock);
598 void sendAllTraps(UINT32 dwRqId);
599 void sendAllTraps2(UINT32 dwRqId);
600 void LockPackageDB(UINT32 dwRqId, BOOL bLock);
601 void SendAllPackages(UINT32 dwRqId);
602 void InstallPackage(NXCPMessage *pRequest);
603 void RemovePackage(NXCPMessage *pRequest);
604 void DeployPackage(NXCPMessage *pRequest);
605 void getParametersList(NXCPMessage *pRequest);
606 void getUserVariable(NXCPMessage *pRequest);
607 void setUserVariable(NXCPMessage *pRequest);
608 void copyUserVariable(NXCPMessage *pRequest);
609 void enumUserVariables(NXCPMessage *pRequest);
610 void deleteUserVariable(NXCPMessage *pRequest);
611 void changeObjectZone(NXCPMessage *pRequest);
612 void getAgentConfig(NXCPMessage *pRequest);
613 void updateAgentConfig(NXCPMessage *pRequest);
614 void executeAction(NXCPMessage *pRequest);
615 void getObjectTools(UINT32 requestId);
616 void getObjectToolDetails(NXCPMessage *request);
617 void updateObjectTool(NXCPMessage *pRequest);
618 void deleteObjectTool(NXCPMessage *pRequest);
619 void changeObjectToolStatus(NXCPMessage *pRequest);
620 void generateObjectToolId(UINT32 dwRqId);
621 void execTableTool(NXCPMessage *pRequest);
622 void changeSubscription(NXCPMessage *pRequest);
623 void sendServerStats(UINT32 dwRqId);
624 void sendScriptList(UINT32 dwRqId);
625 void sendScript(NXCPMessage *pRequest);
626 void updateScript(NXCPMessage *pRequest);
627 void renameScript(NXCPMessage *pRequest);
628 void deleteScript(NXCPMessage *pRequest);
629 void SendSessionList(UINT32 dwRqId);
630 void KillSession(NXCPMessage *pRequest);
631 void StartSnmpWalk(NXCPMessage *pRequest);
632 void resolveDCINames(NXCPMessage *pRequest);
633 UINT32 resolveDCIName(UINT32 dwNode, UINT32 dwItem, TCHAR *ppszName);
634 void sendConfigForAgent(NXCPMessage *pRequest);
635 void sendAgentCfgList(UINT32 dwRqId);
636 void OpenAgentConfig(NXCPMessage *pRequest);
637 void SaveAgentConfig(NXCPMessage *pRequest);
638 void DeleteAgentConfig(NXCPMessage *pRequest);
639 void SwapAgentConfigs(NXCPMessage *pRequest);
640 void SendObjectComments(NXCPMessage *pRequest);
641 void updateObjectComments(NXCPMessage *pRequest);
642 void pushDCIData(NXCPMessage *pRequest);
643 void getAddrList(NXCPMessage *request);
644 void setAddrList(NXCPMessage *request);
645 void resetComponent(NXCPMessage *pRequest);
646 void getDCIEventList(NXCPMessage *request);
647 void getDCIScriptList(NXCPMessage *request);
648 void SendDCIInfo(NXCPMessage *pRequest);
649 void sendPerfTabDCIList(NXCPMessage *pRequest);
650 void exportConfiguration(NXCPMessage *pRequest);
651 void importConfiguration(NXCPMessage *pRequest);
652 void sendGraphList(NXCPMessage *request);
653 void saveGraph(NXCPMessage *pRequest);
654 void deleteGraph(NXCPMessage *pRequest);
655 void addCACertificate(NXCPMessage *pRequest);
656 void deleteCertificate(NXCPMessage *pRequest);
657 void updateCertificateComments(NXCPMessage *pRequest);
658 void getCertificateList(UINT32 dwRqId);
659 void queryL2Topology(NXCPMessage *pRequest);
660 void sendSMS(NXCPMessage *pRequest);
661 void SendCommunityList(UINT32 dwRqId);
662 void UpdateCommunityList(NXCPMessage *pRequest);
663 void getPersistantStorage(UINT32 dwRqId);
664 void setPstorageValue(NXCPMessage *pRequest);
665 void deletePstorageValue(NXCPMessage *pRequest);
666 void setConfigCLOB(NXCPMessage *pRequest);
667 void getConfigCLOB(NXCPMessage *pRequest);
668 void registerAgent(NXCPMessage *pRequest);
669 void getServerFile(NXCPMessage *pRequest);
670 void cancelFileMonitoring(NXCPMessage *request);
671 void getAgentFile(NXCPMessage *pRequest);
672 void testDCITransformation(NXCPMessage *pRequest);
673 void sendJobList(UINT32 dwRqId);
674 void cancelJob(NXCPMessage *pRequest);
675 void holdJob(NXCPMessage *pRequest);
676 void unholdJob(NXCPMessage *pRequest);
677 void deployAgentPolicy(NXCPMessage *pRequest, bool uninstallFlag);
678 void getUserCustomAttribute(NXCPMessage *request);
679 void setUserCustomAttribute(NXCPMessage *request);
680 void openServerLog(NXCPMessage *request);
681 void closeServerLog(NXCPMessage *request);
682 void queryServerLog(NXCPMessage *request);
683 void getServerLogQueryData(NXCPMessage *request);
684 void sendUsmCredentials(UINT32 dwRqId);
685 void updateUsmCredentials(NXCPMessage *pRequest);
686 void sendDCIThresholds(NXCPMessage *request);
687 void addClusterNode(NXCPMessage *request);
688 void findNodeConnection(NXCPMessage *request);
689 void findMacAddress(NXCPMessage *request);
690 void findIpAddress(NXCPMessage *request);
691 void findHostname(NXCPMessage *request);
692 void sendLibraryImage(NXCPMessage *request);
693 void updateLibraryImage(NXCPMessage *request);
694 void listLibraryImages(NXCPMessage *request);
695 void deleteLibraryImage(NXCPMessage *request);
696 void executeServerCommand(NXCPMessage *request);
697 void stopServerCommand(NXCPMessage *request);
698 void uploadFileToAgent(NXCPMessage *request);
699 void listServerFileStore(NXCPMessage *request);
700 void processConsoleCommand(NXCPMessage *msg);
701 void openConsole(UINT32 rqId);
702 void closeConsole(UINT32 rqId);
703 void getVlans(NXCPMessage *msg);
704 void receiveFile(NXCPMessage *request);
705 void deleteFile(NXCPMessage *request);
706 void getNetworkPath(NXCPMessage *request);
707 void getNodeComponents(NXCPMessage *request);
708 void getNodeSoftware(NXCPMessage *request);
709 void getWinPerfObjects(NXCPMessage *request);
710 void listMappingTables(NXCPMessage *request);
711 void getMappingTable(NXCPMessage *request);
712 void updateMappingTable(NXCPMessage *request);
713 void deleteMappingTable(NXCPMessage *request);
714 void getWirelessStations(NXCPMessage *request);
715 void getSummaryTables(UINT32 rqId);
716 void getSummaryTableDetails(NXCPMessage *request);
717 void modifySummaryTable(NXCPMessage *request);
718 void deleteSummaryTable(NXCPMessage *request);
719 void querySummaryTable(NXCPMessage *request);
720 void queryAdHocSummaryTable(NXCPMessage *request);
721 void forwardToReportingServer(NXCPMessage *request);
722 void getSubnetAddressMap(NXCPMessage *request);
723 void getEffectiveRights(NXCPMessage *request);
724 void fileManagerControl(NXCPMessage *request);
725 void uploadUserFileToAgent(NXCPMessage *request);
726 void getSwitchForwardingDatabase(NXCPMessage *request);
727 void getRoutingTable(NXCPMessage *request);
728 void getLocationHistory(NXCPMessage *request);
729 void getScreenshot(NXCPMessage *request);
730 void executeScript(NXCPMessage *request);
731 void executeLibraryScript(NXCPMessage *request);
732 void compileScript(NXCPMessage *request);
733 void resyncAgentDciConfiguration(NXCPMessage *request);
734 void cleanAgentDciConfiguration(NXCPMessage *request);
735 void getSchedulerTaskHandlers(NXCPMessage *request);
736 void getScheduledTasks(NXCPMessage *request);
737 void addScheduledTask(NXCPMessage *request);
738 void updateScheduledTask(NXCPMessage *request);
739 void removeScheduledTask(NXCPMessage *request);
740 void getRepositories(NXCPMessage *request);
741 void addRepository(NXCPMessage *request);
742 void modifyRepository(NXCPMessage *request);
743 void deleteRepository(NXCPMessage *request);
744 void getAgentTunnels(NXCPMessage *request);
745 void bindAgentTunnel(NXCPMessage *request);
746 void unbindAgentTunnel(NXCPMessage *request);
747 void getPredictionEngines(NXCPMessage *request);
748 void getPredictedData(NXCPMessage *request);
749 void expandMacros(NXCPMessage *request);
750 #ifdef WITH_ZMQ
751 void zmqManageSubscription(NXCPMessage *request, zmq::SubscriptionType type, bool subscribe);
752 void zmqListSubscriptions(NXCPMessage *request, zmq::SubscriptionType type);
753 #endif
754 void registerServerCommand(CommandExec *command) { m_serverCommands->set(command->getStreamId(), command); }
755
756 void alarmUpdateWorker(Alarm *alarm);
757 void sendActionDBUpdateMessage(NXCP_MESSAGE *msg);
758 void sendObjectUpdate(NetObj *object);
759
760 public:
761 ClientSession(SOCKET hSocket, const InetAddress& addr);
762 ~ClientSession();
763
764 void incRefCount() { InterlockedIncrement(&m_refCount); }
765 void decRefCount() { InterlockedDecrement(&m_refCount); }
766
767 void run();
768
769 void postMessage(NXCPMessage *pMsg) { if (!isTerminated()) m_sendQueue->put(pMsg->serialize((m_dwFlags & CSF_COMPRESSION_ENABLED) != 0)); }
770 bool sendMessage(NXCPMessage *pMsg);
771 void sendRawMessage(NXCP_MESSAGE *pMsg);
772 void sendPollerMsg(UINT32 dwRqId, const TCHAR *pszMsg);
773 BOOL sendFile(const TCHAR *file, UINT32 dwRqId, long offset);
774
775 void writeAuditLog(const TCHAR *subsys, bool success, UINT32 objectId, const TCHAR *format, ...);
776 void writeAuditLogWithValues(const TCHAR *subsys, bool success, UINT32 objectId, const TCHAR *oldValue, const TCHAR *newValue, const TCHAR *format, ...);
777 void writeAuditLogWithValues(const TCHAR *subsys, bool success, UINT32 objectId, json_t *oldValue, json_t *newValue, const TCHAR *format, ...);
778
779 int getId() const { return m_id; }
780 void setId(int id) { if (m_id == -1) m_id = id; }
781
782 int getState() const { return m_state; }
783 const TCHAR *getLoginName() const { return m_loginName; }
784 const TCHAR *getSessionName() const { return m_sessionName; }
785 const TCHAR *getClientInfo() const { return m_clientInfo; }
786 const TCHAR *getWorkstation() const { return m_workstation; }
787 const TCHAR *getWebServerAddress() const { return m_webServerAddress; }
788 UINT32 getUserId() const { return m_dwUserId; }
789 UINT64 getSystemRights() const { return m_dwSystemAccess; }
790 UINT32 getFlags() const { return m_dwFlags; }
791 bool isAuthenticated() const { return (m_dwFlags & CSF_AUTHENTICATED) ? true : false; }
792 bool isTerminated() const { return (m_dwFlags & CSF_TERMINATED) ? true : false; }
793 bool isConsoleOpen() const { return (m_dwFlags & CSF_CONSOLE_OPEN) ? true : false; }
794 bool isCompressionEnabled() const { return (m_dwFlags & CSF_COMPRESSION_ENABLED) ? true : false; }
795 UINT16 getCurrentCmd() const { return m_wCurrentCmd; }
796 int getCipher() const { return (m_pCtx == NULL) ? -1 : m_pCtx->getCipher(); }
797 int getClientType() const { return m_clientType; }
798 time_t getLoginTime() const { return m_loginTime; }
799 bool isSubscribedTo(const TCHAR *channel) const;
800
801 bool checkSysAccessRights(UINT64 requiredAccess) const
802 {
803 return (m_dwUserId == 0) ? true :
804 ((requiredAccess & m_dwSystemAccess) == requiredAccess);
805 }
806
807 void setCustomLock(UINT32 bit, bool value)
808 {
809 if (value)
810 m_dwFlags |= (bit & 0xFF000000);
811 else
812 m_dwFlags &= ~(bit & 0xFF000000);
813 }
814
815 void kill();
816 void notify(UINT32 dwCode, UINT32 dwData = 0);
817
818 void onNewEvent(Event *pEvent);
819 void onSyslogMessage(NX_SYSLOG_RECORD *pRec);
820 void onNewSNMPTrap(NXCPMessage *pMsg);
821 void onObjectChange(NetObj *pObject);
822 void onAlarmUpdate(UINT32 dwCode, const Alarm *alarm);
823 void onActionDBUpdate(UINT32 dwCode, NXC_ACTION *pAction);
824 void onLibraryImageChange(const uuid& guid, bool removed = false);
825 };
826
827 /**
828 * Graph ACL entry
829 */
830 struct GRAPH_ACL_ENTRY
831 {
832 UINT32 dwGraphId;
833 UINT32 dwUserId;
834 UINT32 dwAccess;
835 };
836
837 /**
838 * Information about graph with name existence and it's ID.
839 */
840 struct GRAPH_ACL_AND_ID
841 {
842 UINT32 graphId;
843 UINT32 status;
844 };
845
846 /**
847 * Thread pool stats
848 */
849 enum ThreadPoolStat
850 {
851 THREAD_POOL_CURR_SIZE,
852 THREAD_POOL_MIN_SIZE,
853 THREAD_POOL_MAX_SIZE,
854 THREAD_POOL_REQUESTS,
855 THREAD_POOL_LOAD,
856 THREAD_POOL_USAGE,
857 THREAD_POOL_LOADAVG_1,
858 THREAD_POOL_LOADAVG_5,
859 THREAD_POOL_LOADAVG_15
860 };
861
862 /**
863 * Server command execution data
864 */
865 class ServerCommandExec : public CommandExec
866 {
867 private:
868 UINT32 m_requestId;
869 ClientSession *m_session;
870
871 virtual void onOutput(const char *text);
872 virtual void endOfOutput();
873
874 public:
875 ServerCommandExec(NXCPMessage *msg, ClientSession *session);
876 ~ServerCommandExec();
877 };
878
879 /**
880 * SNMP Trap parameter map object
881 */
882 class SNMPTrapParameterMapping
883 {
884 private:
885 SNMP_ObjectId *m_objectId; // Trap OID
886 UINT32 m_position; // Trap position
887 UINT32 m_flags;
888 TCHAR m_description[MAX_DB_STRING];
889
890 public:
891 SNMPTrapParameterMapping();
892 SNMPTrapParameterMapping(DB_RESULT mapResult, int row);
893 SNMPTrapParameterMapping(ConfigEntry *entry);
894 SNMPTrapParameterMapping(SNMP_ObjectId *oid, UINT32 flags, TCHAR *description);
895 SNMPTrapParameterMapping(NXCPMessage *msg, UINT32 base);
896 ~SNMPTrapParameterMapping();
897
898 void fillMessage(NXCPMessage *msg, UINT32 base) const;
899
900 SNMP_ObjectId *getOid() const { return m_objectId; }
901 int getPosition() const { return m_position; }
902 bool isPositional() const { return m_objectId == NULL; }
903
904 UINT32 getFlags() const { return m_flags; }
905
906 const TCHAR *getDescription() const { return m_description; }
907 };
908
909 /**
910 * SNMP Trap configuration object
911 */
912 class SNMPTrapConfiguration
913 {
914 private:
915 uuid m_guid; // Trap guid
916 UINT32 m_id; // Entry ID
917 SNMP_ObjectId m_objectId; // Trap OID
918 UINT32 m_eventCode; // Event code
919 ObjectArray<SNMPTrapParameterMapping> m_mappings;
920 TCHAR m_description[MAX_DB_STRING];
921 TCHAR m_userTag[MAX_USERTAG_LENGTH];
922
923 public:
924 SNMPTrapConfiguration();
925 SNMPTrapConfiguration(DB_RESULT trapResult, DB_STATEMENT stmt, int row);
926 SNMPTrapConfiguration(ConfigEntry *entry, const uuid& guid, UINT32 id, UINT32 eventCode);
927 SNMPTrapConfiguration(NXCPMessage *msg);
928 ~SNMPTrapConfiguration();
929
930 void fillMessage(NXCPMessage *msg) const;
931 void fillMessage(NXCPMessage *msg, UINT32 base) const;
932 bool saveParameterMapping(DB_HANDLE hdb);
933 void notifyOnTrapCfgChange(UINT32 code);
934
935 UINT32 getId() const { return m_id; }
936 const uuid& getGuid() const { return m_guid; }
937 const SNMP_ObjectId& getOid() const { return m_objectId; }
938 const SNMPTrapParameterMapping *getParameterMapping(int index) const { return m_mappings.get(index); }
939 int getParameterMappingCount() const { return m_mappings.size(); }
940 UINT32 getEventCode() const { return m_eventCode; }
941 const TCHAR *getDescription() const { return m_description; }
942 const TCHAR *getUserTag() const { return m_userTag; }
943 };
944
945 /**
946 * Watchdog thread state codes
947 */
948 enum WatchdogState
949 {
950 WATCHDOG_UNKNOWN = -1,
951 WATCHDOG_RUNNING = 0,
952 WATCHDOG_SLEEPING = 1,
953 WATCHDOG_NOT_RESPONDING = 2
954 };
955
956 /**
957 * Functions
958 */
959 bool NXCORE_EXPORTABLE ConfigReadStr(const TCHAR *szVar, TCHAR *szBuffer, int iBufSize, const TCHAR *szDefault);
960 bool NXCORE_EXPORTABLE ConfigReadStrEx(DB_HANDLE hdb, const TCHAR *szVar, TCHAR *szBuffer, int iBufSize, const TCHAR *szDefault);
961 #ifdef UNICODE
962 bool NXCORE_EXPORTABLE ConfigReadStrA(const WCHAR *szVar, char *szBuffer, int iBufSize, const char *szDefault);
963 #else
964 #define ConfigReadStrA ConfigReadStr
965 #endif
966 bool NXCORE_EXPORTABLE ConfigReadStrUTF8(const TCHAR *szVar, char *szBuffer, int iBufSize, const char *szDefault);
967 int NXCORE_EXPORTABLE ConfigReadInt(const TCHAR *szVar, int iDefault);
968 int NXCORE_EXPORTABLE ConfigReadIntEx(DB_HANDLE hdb, const TCHAR *szVar, int iDefault);
969 UINT32 NXCORE_EXPORTABLE ConfigReadULong(const TCHAR *szVar, UINT32 dwDefault);
970 bool NXCORE_EXPORTABLE ConfigReadByteArray(const TCHAR *pszVar, int *pnArray, int nSize, int nDefault);
971 bool NXCORE_EXPORTABLE ConfigWriteStr(const TCHAR *szVar, const TCHAR *szValue, bool bCreate, bool isVisible = true, bool needRestart = false);
972 bool NXCORE_EXPORTABLE ConfigWriteInt(const TCHAR *szVar, int iValue, bool bCreate, bool isVisible = true, bool needRestart = false);
973 bool NXCORE_EXPORTABLE ConfigWriteULong(const TCHAR *szVar, UINT32 dwValue, bool bCreate, bool isVisible = true, bool needRestart = false);
974 bool NXCORE_EXPORTABLE ConfigWriteByteArray(const TCHAR *pszVar, int *pnArray, int nSize, bool bCreate, bool isVisible = true, bool needRestart = false);
975 TCHAR NXCORE_EXPORTABLE *ConfigReadCLOB(const TCHAR *var, const TCHAR *defValue);
976 bool NXCORE_EXPORTABLE ConfigWriteCLOB(const TCHAR *var, const TCHAR *value, bool bCreate);
977 bool NXCORE_EXPORTABLE ConfigDelete(const TCHAR *name);
978
979 void MetaDataPreLoad();
980 bool NXCORE_EXPORTABLE MetaDataReadStr(const TCHAR *szVar, TCHAR *szBuffer, int iBufSize, const TCHAR *szDefault);
981 INT32 NXCORE_EXPORTABLE MetaDataReadInt32(const TCHAR *var, INT32 defaultValue);
982 bool NXCORE_EXPORTABLE MetaDataWriteStr(const TCHAR *varName, const TCHAR *value);
983 bool NXCORE_EXPORTABLE MetaDataWriteInt32(const TCHAR *name, INT32 value);
984
985 bool NXCORE_EXPORTABLE LoadConfig(int *debugLevel);
986
987 void NXCORE_EXPORTABLE Shutdown();
988 void NXCORE_EXPORTABLE FastShutdown();
989 BOOL NXCORE_EXPORTABLE Initialize();
990 THREAD_RESULT NXCORE_EXPORTABLE THREAD_CALL Main(void *);
991 void NXCORE_EXPORTABLE ShutdownDB();
992 void InitiateShutdown();
993
994 bool NXCORE_EXPORTABLE SleepAndCheckForShutdown(int iSeconds);
995
996 void ConsolePrintf(CONSOLE_CTX pCtx, const TCHAR *pszFormat, ...)
997 #if !defined(UNICODE) && (defined(__GNUC__) || defined(__clang__))
998 __attribute__ ((format(printf, 2, 3)))
999 #endif
1000 ;
1001 void ConsoleWrite(CONSOLE_CTX pCtx, const TCHAR *text);
1002 int ProcessConsoleCommand(const TCHAR *pszCmdLine, CONSOLE_CTX pCtx);
1003
1004 void SaveObjects(DB_HANDLE hdb, UINT32 watchdogId, bool saveRuntimeData);
1005 void NXCORE_EXPORTABLE ObjectTransactionStart();
1006 void NXCORE_EXPORTABLE ObjectTransactionEnd();
1007
1008 void NXCORE_EXPORTABLE QueueSQLRequest(const TCHAR *query);
1009 void NXCORE_EXPORTABLE QueueSQLRequest(const TCHAR *query, int bindCount, int *sqlTypes, const TCHAR **values);
1010 void QueueIDataInsert(time_t timestamp, UINT32 nodeId, UINT32 dciId, const TCHAR *rawValue, const TCHAR *transformedValue);
1011 void QueueRawDciDataUpdate(time_t timestamp, UINT32 dciId, const TCHAR *rawValue, const TCHAR *transformedValue);
1012 void StartDBWriter();
1013 void StopDBWriter();
1014
1015 void PerfDataStorageRequest(DCItem *dci, time_t timestamp, const TCHAR *value);
1016 void PerfDataStorageRequest(DCTable *dci, time_t timestamp, Table *value);
1017
1018 void DecodeSQLStringAndSetVariable(NXCPMessage *pMsg, UINT32 dwVarId, TCHAR *pszStr);
1019
1020 SNMP_Transport *SnmpCheckCommSettings(UINT32 snmpProxy, const InetAddress& ipAddr, INT16 *version, UINT16 originalPort, SNMP_SecurityContext *originalContext, StringList *customTestOids, UINT32 zoneUIN);
1021 void StrToMac(const TCHAR *pszStr, BYTE *pBuffer);
1022
1023 void InitLocalNetInfo();
1024
1025 ARP_CACHE *GetLocalArpCache();
1026 ARP_CACHE *SnmpGetArpCache(UINT32 dwVersion, SNMP_Transport *pTransport);
1027
1028 InterfaceList *GetLocalInterfaceList();
1029
1030 ROUTING_TABLE *SnmpGetRoutingTable(UINT32 dwVersion, SNMP_Transport *pTransport);
1031
1032 void LoadNetworkDeviceDrivers();
1033 NetworkDeviceDriver *FindDriverForNode(Node *node, SNMP_Transport *pTransport);
1034 NetworkDeviceDriver *FindDriverByName(const TCHAR *name);
1035 void AddDriverSpecificOids(StringList *list);
1036
1037 bool LookupDevicePortLayout(const SNMP_ObjectId& objectId, NDD_MODULE_LAYOUT *layout);
1038
1039 void CheckForMgmtNode();
1040 void CheckPotentialNode(const InetAddress& ipAddr, UINT32 zoneUIN);
1041 Node NXCORE_EXPORTABLE *PollNewNode(const InetAddress& ipAddr, UINT32 creationFlags, UINT16 agentPort,
1042 UINT16 snmpPort, const TCHAR *name, UINT32 agentProxyId, UINT32 snmpProxyId,
1043 UINT32 icmpProxyId, UINT32 sshProxyId, const TCHAR *sshLogin, const TCHAR *sshPassword,
1044 Cluster *cluster, UINT32 zoneUIN, bool doConfPoll, bool discoveredNode);
1045
1046 void NXCORE_EXPORTABLE EnumerateClientSessions(void (*pHandler)(ClientSession *, void *), void *pArg);
1047 void NXCORE_EXPORTABLE NotifyClientSessions(UINT32 dwCode, UINT32 dwData);
1048 void NXCORE_EXPORTABLE NotifyClientSession(UINT32 sessionId, UINT32 dwCode, UINT32 dwData);
1049 void NXCORE_EXPORTABLE NotifyClientGraphUpdate(NXCPMessage *update, UINT32 graphId);
1050 int GetSessionCount(bool includeSystemAccount);
1051 bool IsLoggedIn(UINT32 dwUserId);
1052 bool NXCORE_EXPORTABLE KillClientSession(int id);
1053 void CloseOtherSessions(UINT32 userId, UINT32 thisSession);
1054
1055 void GetSysInfoStr(TCHAR *pszBuffer, int nMaxSize);
1056 InetAddress GetLocalIpAddr();
1057 TCHAR *GetLocalHostName(TCHAR *buffer, size_t bufSize);
1058
1059 InetAddress NXCORE_EXPORTABLE ResolveHostName(UINT32 zoneUIN, const TCHAR *hostname);
1060
1061 BOOL ExecCommand(TCHAR *pszCommand);
1062 BOOL SendMagicPacket(UINT32 dwIpAddr, BYTE *pbMacAddr, int iNumPackets);
1063
1064 BOOL InitIdTable();
1065 UINT32 CreateUniqueId(int iGroup);
1066 QWORD CreateUniqueEventId();
1067 void SaveCurrentFreeId();
1068
1069 void InitMailer();
1070 void ShutdownMailer();
1071 void NXCORE_EXPORTABLE PostMail(const TCHAR *pszRcpt, const TCHAR *pszSubject, const TCHAR *pszText, bool isHtml = false);
1072
1073 void InitSMSSender();
1074 void ShutdownSMSSender();
1075 void NXCORE_EXPORTABLE PostSMS(const TCHAR *pszRcpt, const TCHAR *pszText);
1076
1077 void InitTraps();
1078 void SendTrapsToClient(ClientSession *pSession, UINT32 dwRqId);
1079 void CreateTrapCfgMessage(NXCPMessage *msg);
1080 UINT32 CreateNewTrap(UINT32 *pdwTrapId);
1081 UINT32 UpdateTrapFromMsg(NXCPMessage *pMsg);
1082 UINT32 DeleteTrap(UINT32 dwId);
1083 void CreateTrapExportRecord(String &xml, UINT32 id);
1084 UINT32 ResolveTrapGuid(const uuid& guid);
1085 void AddTrapCfgToList(SNMPTrapConfiguration *trapCfg);
1086
1087 BOOL IsTableTool(UINT32 dwToolId);
1088 BOOL CheckObjectToolAccess(UINT32 dwToolId, UINT32 dwUserId);
1089 UINT32 ExecuteTableTool(UINT32 dwToolId, Node *pNode, UINT32 dwRqId, ClientSession *pSession);
1090 UINT32 DeleteObjectToolFromDB(UINT32 dwToolId);
1091 UINT32 ChangeObjectToolStatus(UINT32 toolId, bool enabled);
1092 UINT32 UpdateObjectToolFromMessage(NXCPMessage *pMsg);
1093 void CreateObjectToolExportRecord(String &xml, UINT32 id);
1094 bool ImportObjectTool(ConfigEntry *config);
1095 UINT32 GetObjectToolsIntoMessage(NXCPMessage *msg, UINT32 userId, bool fullAccess);
1096 UINT32 GetObjectToolDetailsIntoMessage(UINT32 toolId, NXCPMessage *msg);
1097
1098 UINT32 ModifySummaryTable(NXCPMessage *msg, LONG *newId);
1099 UINT32 DeleteSummaryTable(LONG tableId);
1100 Table *QuerySummaryTable(LONG tableId, SummaryTable *adHocDefinition, UINT32 baseObjectId, UINT32 userId, UINT32 *rcc);
1101 bool CreateSummaryTableExportRecord(INT32 id, String &xml);
1102 bool ImportSummaryTable(ConfigEntry *config);
1103
1104 void CreateMessageFromSyslogMsg(NXCPMessage *pMsg, NX_SYSLOG_RECORD *pRec);
1105 void ReinitializeSyslogParser();
1106 void OnSyslogConfigurationChange(const TCHAR *name, const TCHAR *value);
1107
1108 void EscapeString(String &str);
1109
1110 void InitAuditLog();
1111 void NXCORE_EXPORTABLE WriteAuditLog(const TCHAR *subsys, bool isSuccess, UINT32 userId,
1112 const TCHAR *workstation, int sessionId, UINT32 objectId,
1113 const TCHAR *format, ...);
1114 void NXCORE_EXPORTABLE WriteAuditLog2(const TCHAR *subsys, bool isSuccess, UINT32 userId,
1115 const TCHAR *workstation, int sessionId, UINT32 objectId,
1116 const TCHAR *format, va_list args);
1117 void NXCORE_EXPORTABLE WriteAuditLogWithValues(const TCHAR *subsys, bool isSuccess, UINT32 userId,
1118 const TCHAR *workstation, int sessionId, UINT32 objectId,
1119 const TCHAR *oldValue, const TCHAR *newValue,
1120 const TCHAR *format, ...);
1121 void NXCORE_EXPORTABLE WriteAuditLogWithJsonValues(const TCHAR *subsys, bool isSuccess, UINT32 userId,
1122 const TCHAR *workstation, int sessionId, UINT32 objectId,
1123 json_t *oldValue, json_t *newValue,
1124 const TCHAR *format, ...);
1125 void NXCORE_EXPORTABLE WriteAuditLogWithValues2(const TCHAR *subsys, bool isSuccess, UINT32 userId,
1126 const TCHAR *workstation, int sessionId, UINT32 objectId,
1127 const TCHAR *oldValue, const TCHAR *newValue,
1128 const TCHAR *format, va_list args);
1129 void NXCORE_EXPORTABLE WriteAuditLogWithJsonValues2(const TCHAR *subsys, bool isSuccess, UINT32 userId,
1130 const TCHAR *workstation, int sessionId, UINT32 objectId,
1131 json_t *oldValue, json_t *newValue,
1132 const TCHAR *format, va_list args);
1133
1134 bool ValidateConfig(Config *config, UINT32 flags, TCHAR *errorText, int errorTextLen);
1135 UINT32 ImportConfig(Config *config, UINT32 flags);
1136
1137 #ifdef _WITH_ENCRYPTION
1138 X509 *CertificateFromLoginMessage(NXCPMessage *pMsg);
1139 bool ValidateUserCertificate(X509 *cert, const TCHAR *login, const BYTE *challenge,
1140 const BYTE *signature, size_t sigLen, int mappingMethod,
1141 const TCHAR *mappingData);
1142 bool ValidateAgentCertificate(X509 *cert);
1143 void ReloadCertificates();
1144 bool GetCertificateSubjectField(X509 *cert, int nid, TCHAR *buffer, size_t size);
1145 bool GetCertificateCN(X509 *cert, TCHAR *buffer, size_t size);
1146 bool GetCertificateOU(X509 *cert, TCHAR *buffer, size_t size);
1147 String GetCertificateSubjectString(X509 *cert);
1148 bool GetServerCertificateCountry(TCHAR *buffer, size_t size);
1149 bool GetServerCertificateOrganization(TCHAR *buffer, size_t size);
1150 X509 *IssueCertificate(X509_REQ *request, const char *ou, const char *cn, int days);
1151 #endif
1152
1153 #ifndef _WIN32
1154 THREAD_RESULT NXCORE_EXPORTABLE THREAD_CALL SignalHandler(void *);
1155 #endif /* not _WIN32 */
1156
1157 void DbgTestRWLock(RWLOCK hLock, const TCHAR *szName, CONSOLE_CTX console);
1158 void DumpClientSessions(CONSOLE_CTX console);
1159 void DumpMobileDeviceSessions(CONSOLE_CTX console);
1160 void ShowServerStats(CONSOLE_CTX console);
1161 void ShowQueueStats(CONSOLE_CTX console, Queue *pQueue, const TCHAR *pszName);
1162 void ShowThreadPoolPendingQueue(CONSOLE_CTX console, ThreadPool *p, const TCHAR *pszName);
1163 void ShowThreadPool(CONSOLE_CTX console, ThreadPool *p);
1164 LONG GetThreadPoolStat(ThreadPoolStat stat, const TCHAR *param, TCHAR *value);
1165 void DumpProcess(CONSOLE_CTX console);
1166
1167 #define GRAPH_FLAG_TEMPLATE 1
1168
1169 GRAPH_ACL_ENTRY *LoadGraphACL(DB_HANDLE hdb, UINT32 graphId, int *pnACLSize);
1170 GRAPH_ACL_ENTRY *LoadAllGraphACL(DB_HANDLE hdb, int *pnACLSize);
1171 BOOL CheckGraphAccess(GRAPH_ACL_ENTRY *pACL, int nACLSize, UINT32 graphId, UINT32 graphUserId, UINT32 graphDesiredAccess);
1172 UINT32 GetGraphAccessCheckResult(UINT32 graphId, UINT32 graphUserId);
1173 GRAPH_ACL_AND_ID IsGraphNameExists(const TCHAR *graphName);
1174 void FillGraphListMsg(NXCPMessage *msg, UINT32 userId, bool templageGraphs);
1175 void SaveGraph(NXCPMessage *pRequest, UINT32 userId, NXCPMessage *msg);
1176 UINT32 DeleteGraph(UINT32 graphId, UINT32 userId);
1177
1178 #if XMPP_SUPPORTED
1179 void SendXMPPMessage(const TCHAR *rcpt, const TCHAR *text);
1180 #endif
1181
1182 const TCHAR NXCORE_EXPORTABLE *CountryAlphaCode(const TCHAR *code);
1183 const TCHAR NXCORE_EXPORTABLE *CountryName(const TCHAR *code);
1184 const TCHAR NXCORE_EXPORTABLE *CurrencyAlphaCode(const TCHAR *numericCode);
1185 int NXCORE_EXPORTABLE CurrencyExponent(const TCHAR *code);
1186 const TCHAR NXCORE_EXPORTABLE *CurrencyName(const TCHAR *code);
1187
1188 void NXCORE_EXPORTABLE RegisterComponent(const TCHAR *id);
1189 bool NXCORE_EXPORTABLE IsComponentRegistered(const TCHAR *id);
1190
1191 /**
1192 * Watchdog API
1193 */
1194 void WatchdogInit();
1195 void WatchdogShutdown();
1196 UINT32 WatchdogAddThread(const TCHAR *name, time_t notifyInterval);
1197 void WatchdogNotify(UINT32 id);
1198 void WatchdogStartSleep(UINT32 id);
1199 void WatchdogPrintStatus(CONSOLE_CTX console);
1200 WatchdogState WatchdogGetState(const TCHAR *name);
1201 void WatchdogGetThreads(StringList *out);
1202
1203 /**
1204 * Housekeeper control
1205 */
1206 void StartHouseKeeper();
1207 void StopHouseKeeper();
1208 void RunHouseKeeper();
1209
1210 /**
1211 * Alarm category functions
1212 */
1213 void GetAlarmCategories(NXCPMessage *msg);
1214 UINT32 UpdateAlarmCategory(const NXCPMessage *request, UINT32 *returnId);
1215 UINT32 DeleteAlarmCategory(UINT32 id);
1216 bool CheckAlarmCategoryAccess(UINT32 userId, UINT32 categoryId);
1217 void LoadAlarmCategories();
1218
1219 /**
1220 * Alarm summary emails
1221 */
1222 void SendAlarmSummaryEmail(const ScheduledTaskParameters *params);
1223 void EnableAlarmSummaryEmails();
1224
1225 /**
1226 * NXSL script functions
1227 */
1228 UINT32 UpdateScript(const NXCPMessage *request, UINT32 *scriptId);
1229 UINT32 RenameScript(const NXCPMessage *request);
1230 UINT32 DeleteScript(const NXCPMessage *request);
1231
1232 /**
1233 * File monitoring
1234 */
1235 struct MONITORED_FILE
1236 {
1237 TCHAR fileName[MAX_PATH];
1238 ClientSession *session;
1239 UINT32 nodeID;
1240 };
1241
1242 class FileMonitoringList
1243 {
1244 private:
1245 MUTEX m_mutex;
1246 ObjectArray<MONITORED_FILE> m_monitoredFiles;
1247
1248 public:
1249 FileMonitoringList();
1250 ~FileMonitoringList();
1251 void addMonitoringFile(MONITORED_FILE *fileForAdd, Node *obj, AgentConnection *conn);
1252 bool checkDuplicate(MONITORED_FILE *fileForAdd);
1253 ObjectArray<ClientSession>* findClientByFNameAndNodeID(const TCHAR *fileName, UINT32 nodeID);
1254 bool removeMonitoringFile(MONITORED_FILE *fileForRemove);
1255 void removeDisconnectedNode(UINT32 nodeId);
1256
1257 private:
1258 void lock();
1259 void unlock();
1260 };
1261
1262 /**********************
1263 * Distance calculation
1264 **********************/
1265
1266 /**
1267 * Class stores object and distance to it from provided node
1268 */
1269 class ObjectsDistance
1270 {
1271 public:
1272 NetObj *m_obj;
1273 int m_distance;
1274
1275 ObjectsDistance(NetObj *obj, int distance) { m_obj = obj; m_distance = distance; }
1276 ~ObjectsDistance() { m_obj->decRefCount(); }
1277 };
1278
1279 /**
1280 * Calculate nearest objects from current one
1281 * Object ref count will be automatically decreased on array delete
1282 */
1283 ObjectArray<ObjectsDistance> *FindNearestObjects(UINT32 currObjectId, int maxDistance, bool (* filter)(NetObj *object, void *data), void *sortData, int (* calculateRealDistance)(GeoLocation &loc1, GeoLocation &loc2));
1284
1285 /**
1286 * Global variables
1287 */
1288 extern TCHAR NXCORE_EXPORTABLE g_szConfigFile[];
1289 extern TCHAR NXCORE_EXPORTABLE g_szLogFile[];
1290 extern UINT32 g_logRotationMode;
1291 extern UINT64 g_maxLogSize;
1292 extern UINT32 g_logHistorySize;
1293 extern TCHAR g_szDailyLogFileSuffix[64];
1294 extern TCHAR NXCORE_EXPORTABLE g_szDumpDir[];
1295 extern TCHAR NXCORE_EXPORTABLE g_szListenAddress[];
1296 #ifndef _WIN32
1297 extern TCHAR NXCORE_EXPORTABLE g_szPIDFile[];
1298 #endif
1299 extern TCHAR NXCORE_EXPORTABLE g_netxmsdDataDir[];
1300 extern TCHAR NXCORE_EXPORTABLE g_netxmsdLibDir[];
1301 extern UINT32 NXCORE_EXPORTABLE g_processAffinityMask;
1302 extern UINT64 g_serverId;
1303 extern RSA *g_pServerKey;
1304 extern UINT32 g_icmpPingSize;
1305 extern UINT32 g_icmpPingTimeout;
1306 extern UINT32 g_auditFlags;
1307 extern time_t g_serverStartTime;
1308 extern UINT32 g_lockTimeout;
1309 extern UINT32 g_agentCommandTimeout;
1310 extern UINT32 g_thresholdRepeatInterval;
1311 extern int g_requiredPolls;
1312 extern UINT32 g_slmPollingInterval;
1313 extern UINT32 g_offlineDataRelevanceTime;
1314
1315 extern TCHAR g_szDbDriver[];
1316 extern TCHAR g_szDbDrvParams[];
1317 extern TCHAR g_szDbServer[];
1318 extern TCHAR g_szDbLogin[];
1319 extern TCHAR g_szDbPassword[];
1320 extern TCHAR g_szDbName[];
1321 extern TCHAR g_szDbSchema[];
1322 extern DB_DRIVER g_dbDriver;
1323 extern Queue *g_dbWriterQueue;
1324 extern Queue *g_dciDataWriterQueue;
1325 extern Queue *g_dciRawDataWriterQueue;
1326 extern UINT64 g_idataWriteRequests;
1327 extern UINT64 g_rawDataWriteRequests;
1328 extern UINT64 g_otherWriteRequests;
1329
1330 extern int NXCORE_EXPORTABLE g_dbSyntax;
1331 extern FileMonitoringList g_monitoringList;
1332
1333 extern ThreadPool NXCORE_EXPORTABLE *g_mainThreadPool;
1334
1335 #endif /* _nms_core_h_ */