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