retry SNMP status poll after proxy communication error
[public/netxms.git] / src / server / core / node.cpp
1 /*
2 ** NetXMS - Network Management System
3 ** Copyright (C) 2003-2017 Raden Solutions
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: node.cpp
20 **
21 **/
22
23 #include "nxcore.h"
24 #include <agent_tunnel.h>
25
26 /**
27 * Externals
28 */
29 extern UINT64 g_syslogMessagesReceived;
30 extern UINT64 g_snmpTrapsReceived;
31
32 /**
33 * Node class default constructor
34 */
35 Node::Node() : DataCollectionTarget()
36 {
37 m_primaryName[0] = 0;
38 m_status = STATUS_UNKNOWN;
39 m_type = NODE_TYPE_UNKNOWN;
40 m_subType[0] = 0;
41 m_dwDynamicFlags = 0;
42 m_zoneId = 0;
43 m_agentPort = AGENT_LISTEN_PORT;
44 m_agentAuthMethod = AUTH_NONE;
45 m_agentCacheMode = AGENT_CACHE_DEFAULT;
46 m_szSharedSecret[0] = 0;
47 m_iStatusPollType = POLL_ICMP_PING;
48 m_snmpVersion = SNMP_VERSION_1;
49 m_snmpPort = SNMP_DEFAULT_PORT;
50 m_snmpSecurity = new SNMP_SecurityContext("public");
51 m_snmpObjectId[0] = 0;
52 m_lastDiscoveryPoll = 0;
53 m_lastStatusPoll = 0;
54 m_lastConfigurationPoll = 0;
55 m_lastInstancePoll = 0;
56 m_lastTopologyPoll = 0;
57 m_lastRTUpdate = 0;
58 m_downSince = 0;
59 m_bootTime = 0;
60 m_agentUpTime = 0;
61 m_hPollerMutex = MutexCreate();
62 m_hAgentAccessMutex = MutexCreate();
63 m_hSmclpAccessMutex = MutexCreate();
64 m_mutexRTAccess = MutexCreate();
65 m_mutexTopoAccess = MutexCreate();
66 m_agentConnection = NULL;
67 m_proxyConnections = new ObjectLock<AgentConnectionEx>[MAX_PROXY_TYPE];
68 m_smclpConnection = NULL;
69 m_lastAgentTrapId = 0;
70 m_lastSNMPTrapId = 0;
71 m_lastSyslogMessageId = 0;
72 m_lastAgentPushRequestId = 0;
73 m_agentVersion[0] = 0;
74 m_platformName[0] = 0;
75 m_sysDescription = NULL;
76 m_sysName = NULL;
77 m_sysContact = NULL;
78 m_sysLocation = NULL;
79 m_lldpNodeId = NULL;
80 m_lldpLocalPortInfo = NULL;
81 m_paramList = NULL;
82 m_tableList = NULL;
83 m_pollerNode = 0;
84 m_agentProxy = 0;
85 m_snmpProxy = 0;
86 m_icmpProxy = 0;
87 memset(m_lastEvents, 0, sizeof(QWORD) * MAX_LAST_EVENTS);
88 m_routingLoopEvents = new ObjectArray<RoutingLoopEvent>(0, 16, true);
89 m_pRoutingTable = NULL;
90 m_failTimeSNMP = 0;
91 m_failTimeAgent = 0;
92 m_lastAgentCommTime = 0;
93 m_lastAgentConnectAttempt = 0;
94 m_linkLayerNeighbors = NULL;
95 m_vrrpInfo = NULL;
96 m_topology = NULL;
97 m_topologyRebuildTimestamp = 0;
98 m_iPendingStatus = -1;
99 m_iPollCount = 0;
100 m_iRequiredPollCount = 0; // Use system default
101 m_nUseIfXTable = IFXTABLE_DEFAULT; // Use system default
102 m_jobQueue = new ServerJobQueue();
103 m_fdb = NULL;
104 m_vlans = NULL;
105 m_wirelessStations = NULL;
106 m_adoptedApCount = 0;
107 m_totalApCount = 0;
108 m_driver = NULL;
109 m_driverData = NULL;
110 m_components = NULL;
111 m_softwarePackages = NULL;
112 m_winPerfObjects = NULL;
113 memset(m_baseBridgeAddress, 0, MAC_ADDR_LENGTH);
114 m_fileUpdateConn = NULL;
115 m_rackId = 0;
116 m_rackPosition = 0;
117 m_rackHeight = 1;
118 m_chassisId = 0;
119 m_syslogMessageCount = 0;
120 m_snmpTrapCount = 0;
121 m_sshLogin[0] = 0;
122 m_sshPassword[0] = 0;
123 m_sshProxy = 0;
124 m_portNumberingScheme = NDD_PN_UNKNOWN;
125 m_portRowCount = 0;
126 m_agentCompressionMode = NODE_AGENT_COMPRESSION_DEFAULT;
127 }
128
129 /**
130 * Constructor for new node object
131 */
132 Node::Node(const InetAddress& addr, UINT32 dwFlags, UINT32 agentProxy, UINT32 snmpProxy, UINT32 icmpProxy, UINT32 sshProxy, UINT32 zoneId) : DataCollectionTarget()
133 {
134 addr.toString(m_primaryName);
135 m_status = STATUS_UNKNOWN;
136 m_type = NODE_TYPE_UNKNOWN;
137 m_subType[0] = 0;
138 m_ipAddress = addr;
139 m_flags = dwFlags;
140 m_dwDynamicFlags = 0;
141 m_zoneId = zoneId;
142 m_agentPort = AGENT_LISTEN_PORT;
143 m_agentAuthMethod = AUTH_NONE;
144 m_agentCacheMode = AGENT_CACHE_DEFAULT;
145 m_szSharedSecret[0] = 0;
146 m_iStatusPollType = POLL_ICMP_PING;
147 m_snmpVersion = SNMP_VERSION_1;
148 m_snmpPort = SNMP_DEFAULT_PORT;
149 m_snmpSecurity = new SNMP_SecurityContext("public");
150 addr.toString(m_name); // Make default name from IP address
151 m_snmpObjectId[0] = 0;
152 m_lastDiscoveryPoll = 0;
153 m_lastStatusPoll = 0;
154 m_lastConfigurationPoll = 0;
155 m_lastInstancePoll = 0;
156 m_lastTopologyPoll = 0;
157 m_lastRTUpdate = 0;
158 m_downSince = 0;
159 m_bootTime = 0;
160 m_agentUpTime = 0;
161 m_hPollerMutex = MutexCreate();
162 m_hAgentAccessMutex = MutexCreate();
163 m_hSmclpAccessMutex = MutexCreate();
164 m_mutexRTAccess = MutexCreate();
165 m_mutexTopoAccess = MutexCreate();
166 m_agentConnection = NULL;
167 m_proxyConnections = new ObjectLock<AgentConnectionEx>[MAX_PROXY_TYPE];
168 m_smclpConnection = NULL;
169 m_lastAgentTrapId = 0;
170 m_lastSNMPTrapId = 0;
171 m_lastSyslogMessageId = 0;
172 m_lastAgentPushRequestId = 0;
173 m_agentVersion[0] = 0;
174 m_platformName[0] = 0;
175 m_sysDescription = NULL;
176 m_sysName = NULL;
177 m_sysContact = NULL;
178 m_sysLocation = NULL;
179 m_lldpNodeId = NULL;
180 m_lldpLocalPortInfo = NULL;
181 m_paramList = NULL;
182 m_tableList = NULL;
183 m_pollerNode = 0;
184 m_agentProxy = agentProxy;
185 m_snmpProxy = snmpProxy;
186 m_icmpProxy = icmpProxy;
187 memset(m_lastEvents, 0, sizeof(QWORD) * MAX_LAST_EVENTS);
188 m_routingLoopEvents = new ObjectArray<RoutingLoopEvent>(0, 16, true);
189 m_isHidden = true;
190 m_pRoutingTable = NULL;
191 m_failTimeSNMP = 0;
192 m_failTimeAgent = 0;
193 m_lastAgentCommTime = 0;
194 m_lastAgentConnectAttempt = 0;
195 m_linkLayerNeighbors = NULL;
196 m_vrrpInfo = NULL;
197 m_topology = NULL;
198 m_topologyRebuildTimestamp = 0;
199 m_iPendingStatus = -1;
200 m_iPollCount = 0;
201 m_iRequiredPollCount = 0; // Use system default
202 m_nUseIfXTable = IFXTABLE_DEFAULT; // Use system default
203 m_jobQueue = new ServerJobQueue();
204 m_fdb = NULL;
205 m_vlans = NULL;
206 m_wirelessStations = NULL;
207 m_adoptedApCount = 0;
208 m_totalApCount = 0;
209 m_driver = NULL;
210 m_driverData = NULL;
211 m_components = NULL;
212 m_softwarePackages = NULL;
213 m_winPerfObjects = NULL;
214 memset(m_baseBridgeAddress, 0, MAC_ADDR_LENGTH);
215 m_fileUpdateConn = NULL;
216 m_rackId = 0;
217 m_rackPosition = 0;
218 m_rackHeight = 1;
219 m_chassisId = 0;
220 m_syslogMessageCount = 0;
221 m_snmpTrapCount = 0;
222 m_sshLogin[0] = 0;
223 m_sshPassword[0] = 0;
224 m_sshProxy = sshProxy;
225 m_portNumberingScheme = NDD_PN_UNKNOWN;
226 m_portRowCount = 0;
227 m_agentCompressionMode = NODE_AGENT_COMPRESSION_DEFAULT;
228 }
229
230 /**
231 * Node destructor
232 */
233 Node::~Node()
234 {
235 delete m_driverData;
236 MutexDestroy(m_hPollerMutex);
237 MutexDestroy(m_hAgentAccessMutex);
238 MutexDestroy(m_hSmclpAccessMutex);
239 MutexDestroy(m_mutexRTAccess);
240 MutexDestroy(m_mutexTopoAccess);
241 if (m_agentConnection != NULL)
242 m_agentConnection->decRefCount();
243 for(int i = 0; i < MAX_PROXY_TYPE; i++)
244 if(m_proxyConnections[i].get() != NULL)
245 m_proxyConnections[i].get()->decRefCount();
246 delete[] m_proxyConnections;
247 delete m_smclpConnection;
248 delete m_paramList;
249 delete m_tableList;
250 free(m_sysDescription);
251 DestroyRoutingTable(m_pRoutingTable);
252 if (m_linkLayerNeighbors != NULL)
253 m_linkLayerNeighbors->decRefCount();
254 delete m_vrrpInfo;
255 delete m_topology;
256 delete m_jobQueue;
257 delete m_snmpSecurity;
258 if (m_fdb != NULL)
259 m_fdb->decRefCount();
260 if (m_vlans != NULL)
261 m_vlans->decRefCount();
262 delete m_wirelessStations;
263 if (m_components != NULL)
264 m_components->decRefCount();
265 delete m_lldpLocalPortInfo;
266 delete m_softwarePackages;
267 delete m_winPerfObjects;
268 free(m_sysName);
269 free(m_sysContact);
270 free(m_sysLocation);
271 delete m_routingLoopEvents;
272 }
273
274 /**
275 * Create object from database data
276 */
277 bool Node::loadFromDatabase(DB_HANDLE hdb, UINT32 dwId)
278 {
279 int i, iNumRows;
280 UINT32 dwSubnetId;
281 NetObj *pObject;
282 bool bResult = false;
283
284 m_id = dwId;
285
286 if (!loadCommonProperties(hdb))
287 {
288 DbgPrintf(2, _T("Cannot load common properties for node object %d"), dwId);
289 return false;
290 }
291
292 DB_STATEMENT hStmt = DBPrepare(hdb,
293 _T("SELECT primary_name,primary_ip,node_flags,")
294 _T("snmp_version,auth_method,secret,")
295 _T("agent_port,status_poll_type,snmp_oid,agent_version,")
296 _T("platform_name,poller_node_id,zone_guid,")
297 _T("proxy_node,snmp_proxy,required_polls,uname,")
298 _T("use_ifxtable,snmp_port,community,usm_auth_password,")
299 _T("usm_priv_password,usm_methods,snmp_sys_name,bridge_base_addr,")
300 _T("runtime_flags,down_since,boot_time,driver_name,icmp_proxy,")
301 _T("agent_cache_mode,snmp_sys_contact,snmp_sys_location,")
302 _T("rack_id,rack_image,rack_position,rack_height,")
303 _T("last_agent_comm_time,syslog_msg_count,snmp_trap_count,")
304 _T("node_type,node_subtype,ssh_login,ssh_password,ssh_proxy,")
305 _T("port_rows,port_numbering_scheme,agent_comp_mode,")
306 _T("tunnel_id,lldp_id FROM nodes WHERE id=?"));
307 if (hStmt == NULL)
308 return false;
309
310 DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, dwId);
311 DB_RESULT hResult = DBSelectPrepared(hStmt);
312 if (hResult == NULL)
313 {
314 DBFreeStatement(hStmt);
315 return false; // Query failed
316 }
317
318 if (DBGetNumRows(hResult) == 0)
319 {
320 DBFreeResult(hResult);
321 DBFreeStatement(hStmt);
322 DbgPrintf(2, _T("Missing record in \"nodes\" table for node object %d"), dwId);
323 return false;
324 }
325
326 DBGetField(hResult, 0, 0, m_primaryName, MAX_DNS_NAME);
327 m_ipAddress = DBGetFieldInetAddr(hResult, 0, 1);
328 m_flags = DBGetFieldULong(hResult, 0, 2);
329 m_snmpVersion = DBGetFieldLong(hResult, 0, 3);
330 m_agentAuthMethod = (WORD)DBGetFieldLong(hResult, 0, 4);
331 DBGetField(hResult, 0, 5, m_szSharedSecret, MAX_SECRET_LENGTH);
332 m_agentPort = (WORD)DBGetFieldLong(hResult, 0, 6);
333 m_iStatusPollType = DBGetFieldLong(hResult, 0, 7);
334 DBGetField(hResult, 0, 8, m_snmpObjectId, MAX_OID_LEN * 4);
335 DBGetField(hResult, 0, 9, m_agentVersion, MAX_AGENT_VERSION_LEN);
336 DBGetField(hResult, 0, 10, m_platformName, MAX_PLATFORM_NAME_LEN);
337 m_pollerNode = DBGetFieldULong(hResult, 0, 11);
338 m_zoneId = DBGetFieldULong(hResult, 0, 12);
339 m_agentProxy = DBGetFieldULong(hResult, 0, 13);
340 m_snmpProxy = DBGetFieldULong(hResult, 0, 14);
341 m_iRequiredPollCount = DBGetFieldLong(hResult, 0, 15);
342 m_sysDescription = DBGetField(hResult, 0, 16, NULL, 0);
343 m_nUseIfXTable = (BYTE)DBGetFieldLong(hResult, 0, 17);
344 m_snmpPort = (WORD)DBGetFieldLong(hResult, 0, 18);
345
346 // SNMP authentication parameters
347 char snmpAuthObject[256], snmpAuthPassword[256], snmpPrivPassword[256];
348 DBGetFieldA(hResult, 0, 19, snmpAuthObject, 256);
349 DBGetFieldA(hResult, 0, 20, snmpAuthPassword, 256);
350 DBGetFieldA(hResult, 0, 21, snmpPrivPassword, 256);
351 int snmpMethods = DBGetFieldLong(hResult, 0, 22);
352 delete m_snmpSecurity;
353 if (m_snmpVersion == SNMP_VERSION_3)
354 {
355 m_snmpSecurity = new SNMP_SecurityContext(snmpAuthObject, snmpAuthPassword, snmpPrivPassword, snmpMethods & 0xFF, snmpMethods >> 8);
356 }
357 else
358 {
359 // This will create security context with V2C security model
360 // USM fields will be loaded but keys will not be calculated
361 m_snmpSecurity = new SNMP_SecurityContext(snmpAuthObject);
362 m_snmpSecurity->setAuthMethod(snmpMethods & 0xFF);
363 m_snmpSecurity->setAuthPassword(snmpAuthPassword);
364 m_snmpSecurity->setPrivMethod(snmpMethods >> 8);
365 m_snmpSecurity->setPrivPassword(snmpPrivPassword);
366 }
367
368 m_sysName = DBGetField(hResult, 0, 23, NULL, 0);
369
370 TCHAR baseAddr[16];
371 TCHAR *value = DBGetField(hResult, 0, 24, baseAddr, 16);
372 if (value != NULL)
373 StrToBin(value, m_baseBridgeAddress, MAC_ADDR_LENGTH);
374
375 m_dwDynamicFlags = DBGetFieldULong(hResult, 0, 25);
376 m_dwDynamicFlags &= NDF_PERSISTENT; // Clear out all non-persistent runtime flags
377
378 m_downSince = DBGetFieldLong(hResult, 0, 26);
379 m_bootTime = DBGetFieldLong(hResult, 0, 27);
380
381 // Setup driver
382 TCHAR driverName[34];
383 DBGetField(hResult, 0, 28, driverName, 34);
384 StrStrip(driverName);
385 if (driverName[0] != 0)
386 m_driver = FindDriverByName(driverName);
387
388 m_icmpProxy = DBGetFieldULong(hResult, 0, 29);
389 m_agentCacheMode = (INT16)DBGetFieldLong(hResult, 0, 30);
390 if ((m_agentCacheMode != AGENT_CACHE_ON) && (m_agentCacheMode != AGENT_CACHE_OFF))
391 m_agentCacheMode = AGENT_CACHE_DEFAULT;
392
393 m_sysContact = DBGetField(hResult, 0, 31, NULL, 0);
394 m_sysLocation = DBGetField(hResult, 0, 32, NULL, 0);
395
396 m_rackId = DBGetFieldULong(hResult, 0, 33);
397 m_rackImage = DBGetFieldGUID(hResult, 0, 34);
398 m_rackPosition = (INT16)DBGetFieldLong(hResult, 0, 35);
399 m_rackHeight = (INT16)DBGetFieldLong(hResult, 0, 36);
400 m_lastAgentCommTime = DBGetFieldLong(hResult, 0, 37);
401 m_syslogMessageCount = DBGetFieldInt64(hResult, 0, 38);
402 m_snmpTrapCount = DBGetFieldInt64(hResult, 0, 39);
403 m_type = (NodeType)DBGetFieldLong(hResult, 0, 40);
404 DBGetField(hResult, 0, 41, m_subType, MAX_NODE_SUBTYPE_LENGTH);
405 DBGetField(hResult, 0, 42, m_sshLogin, MAX_SSH_LOGIN_LEN);
406 DBGetField(hResult, 0, 43, m_sshPassword, MAX_SSH_PASSWORD_LEN);
407 m_sshProxy = DBGetFieldULong(hResult, 0, 44);
408 m_portRowCount = DBGetFieldULong(hResult, 0, 45);
409 m_portNumberingScheme = DBGetFieldULong(hResult, 0, 46);
410 m_agentCompressionMode = (INT16)DBGetFieldLong(hResult, 0, 47);
411 m_tunnelId = DBGetFieldGUID(hResult, 0, 48);
412 m_lldpNodeId = DBGetField(hResult, 0, 49, NULL, 0);
413 if ((m_lldpNodeId != NULL) && (*m_lldpNodeId == 0))
414 safe_free_and_null(m_lldpNodeId);
415
416 DBFreeResult(hResult);
417 DBFreeStatement(hStmt);
418
419 if (!m_isDeleted)
420 {
421 // Link node to subnets
422 hStmt = DBPrepare(hdb, _T("SELECT subnet_id FROM nsmap WHERE node_id=?"));
423 if (hStmt == NULL)
424 return false;
425
426 DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
427 hResult = DBSelectPrepared(hStmt);
428 if (hResult == NULL)
429 {
430 DBFreeStatement(hStmt);
431 return false; // Query failed
432 }
433
434 iNumRows = DBGetNumRows(hResult);
435 for(i = 0; i < iNumRows; i++)
436 {
437 dwSubnetId = DBGetFieldULong(hResult, i, 0);
438 pObject = FindObjectById(dwSubnetId);
439 if (pObject == NULL)
440 {
441 nxlog_write(MSG_INVALID_SUBNET_ID, EVENTLOG_ERROR_TYPE, "dd", dwId, dwSubnetId);
442 break;
443 }
444 else if (pObject->getObjectClass() != OBJECT_SUBNET)
445 {
446 nxlog_write(MSG_SUBNET_NOT_SUBNET, EVENTLOG_ERROR_TYPE, "dd", dwId, dwSubnetId);
447 break;
448 }
449 else
450 {
451 pObject->addChild(this);
452 addParent(pObject);
453 }
454 }
455
456 DBFreeResult(hResult);
457 DBFreeStatement(hStmt);
458
459 loadItemsFromDB(hdb);
460 loadACLFromDB(hdb);
461
462 // Walk through all items in the node and load appropriate thresholds
463 bResult = true;
464 for(i = 0; i < m_dcObjects->size(); i++)
465 {
466 if (!m_dcObjects->get(i)->loadThresholdsFromDB(hdb))
467 {
468 DbgPrintf(3, _T("Cannot load thresholds for DCI %d of node %d (%s)"),
469 m_dcObjects->get(i)->getId(), dwId, m_name);
470 bResult = false;
471 }
472 }
473
474 updatePhysicalContainerBinding(OBJECT_RACK, m_rackId);
475 updatePhysicalContainerBinding(OBJECT_CHASSIS, m_chassisId);
476 }
477 else
478 {
479 bResult = true;
480 }
481
482 return bResult;
483 }
484
485 /**
486 * Save object to database
487 */
488 BOOL Node::saveToDatabase(DB_HANDLE hdb)
489 {
490 // Lock object's access
491 lockProperties();
492
493 if (!saveCommonProperties(hdb))
494 {
495 unlockProperties();
496 return FALSE;
497 }
498
499 // Form and execute INSERT or UPDATE query
500 int snmpMethods = m_snmpSecurity->getAuthMethod() | (m_snmpSecurity->getPrivMethod() << 8);
501 DB_STATEMENT hStmt;
502 if (IsDatabaseRecordExist(hdb, _T("nodes"), _T("id"), m_id))
503 {
504 hStmt = DBPrepare(hdb,
505 _T("UPDATE nodes SET primary_ip=?,primary_name=?,snmp_port=?,node_flags=?,snmp_version=?,community=?,")
506 _T("status_poll_type=?,agent_port=?,auth_method=?,secret=?,snmp_oid=?,uname=?,agent_version=?,")
507 _T("platform_name=?,poller_node_id=?,zone_guid=?,proxy_node=?,snmp_proxy=?,icmp_proxy=?,required_polls=?,")
508 _T("use_ifxtable=?,usm_auth_password=?,usm_priv_password=?,usm_methods=?,snmp_sys_name=?,bridge_base_addr=?,")
509 _T("runtime_flags=?,down_since=?,driver_name=?,rack_image=?,rack_position=?,rack_height=?,rack_id=?,boot_time=?,")
510 _T("agent_cache_mode=?,snmp_sys_contact=?,snmp_sys_location=?,last_agent_comm_time=?,")
511 _T("syslog_msg_count=?,snmp_trap_count=?,node_type=?,node_subtype=?,ssh_login=?,ssh_password=?,")
512 _T("ssh_proxy=?,chassis_id=?,port_rows=?,port_numbering_scheme=?,agent_comp_mode=?,tunnel_id=?,")
513 _T("lldp_id=? WHERE id=?"));
514 }
515 else
516 {
517 hStmt = DBPrepare(hdb,
518 _T("INSERT INTO nodes (primary_ip,primary_name,snmp_port,node_flags,snmp_version,community,status_poll_type,")
519 _T("agent_port,auth_method,secret,snmp_oid,uname,agent_version,platform_name,poller_node_id,zone_guid,")
520 _T("proxy_node,snmp_proxy,icmp_proxy,required_polls,use_ifxtable,usm_auth_password,usm_priv_password,usm_methods,")
521 _T("snmp_sys_name,bridge_base_addr,runtime_flags,down_since,driver_name,rack_image,rack_position,rack_height,rack_id,boot_time,")
522 _T("agent_cache_mode,snmp_sys_contact,snmp_sys_location,last_agent_comm_time,syslog_msg_count,snmp_trap_count,")
523 _T("node_type,node_subtype,ssh_login,ssh_password,ssh_proxy,chassis_id,port_rows,port_numbering_scheme,agent_comp_mode,")
524 _T("tunnel_id,lldp_id,id) ")
525 _T("VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
526 }
527 if (hStmt == NULL)
528 {
529 unlockProperties();
530 return FALSE;
531 }
532
533 TCHAR ipAddr[64], baseAddress[16], cacheMode[16], compressionMode[16];
534
535 DBBind(hStmt, 1, DB_SQLTYPE_VARCHAR, m_ipAddress.toString(ipAddr), DB_BIND_STATIC);
536 DBBind(hStmt, 2, DB_SQLTYPE_VARCHAR, m_primaryName, DB_BIND_STATIC);
537 DBBind(hStmt, 3, DB_SQLTYPE_INTEGER, (LONG)m_snmpPort);
538 DBBind(hStmt, 4, DB_SQLTYPE_INTEGER, m_flags);
539 DBBind(hStmt, 5, DB_SQLTYPE_INTEGER, (LONG)m_snmpVersion);
540 #ifdef UNICODE
541 DBBind(hStmt, 6, DB_SQLTYPE_VARCHAR, WideStringFromMBString(m_snmpSecurity->getCommunity()), DB_BIND_DYNAMIC);
542 #else
543 DBBind(hStmt, 6, DB_SQLTYPE_VARCHAR, m_snmpSecurity->getCommunity(), DB_BIND_STATIC);
544 #endif
545 DBBind(hStmt, 7, DB_SQLTYPE_INTEGER, (LONG)m_iStatusPollType);
546 DBBind(hStmt, 8, DB_SQLTYPE_INTEGER, (LONG)m_agentPort);
547 DBBind(hStmt, 9, DB_SQLTYPE_INTEGER, (LONG)m_agentAuthMethod);
548 DBBind(hStmt, 10, DB_SQLTYPE_VARCHAR, m_szSharedSecret, DB_BIND_STATIC);
549 DBBind(hStmt, 11, DB_SQLTYPE_VARCHAR, m_snmpObjectId, DB_BIND_STATIC);
550 DBBind(hStmt, 12, DB_SQLTYPE_VARCHAR, m_sysDescription, DB_BIND_STATIC);
551 DBBind(hStmt, 13, DB_SQLTYPE_VARCHAR, m_agentVersion, DB_BIND_STATIC);
552 DBBind(hStmt, 14, DB_SQLTYPE_VARCHAR, m_platformName, DB_BIND_STATIC);
553 DBBind(hStmt, 15, DB_SQLTYPE_INTEGER, m_pollerNode);
554 DBBind(hStmt, 16, DB_SQLTYPE_INTEGER, m_zoneId);
555 DBBind(hStmt, 17, DB_SQLTYPE_INTEGER, m_agentProxy);
556 DBBind(hStmt, 18, DB_SQLTYPE_INTEGER, m_snmpProxy);
557 DBBind(hStmt, 19, DB_SQLTYPE_INTEGER, m_icmpProxy);
558 DBBind(hStmt, 20, DB_SQLTYPE_INTEGER, (LONG)m_iRequiredPollCount);
559 DBBind(hStmt, 21, DB_SQLTYPE_INTEGER, (LONG)m_nUseIfXTable);
560 #ifdef UNICODE
561 DBBind(hStmt, 22, DB_SQLTYPE_VARCHAR, WideStringFromMBString(m_snmpSecurity->getAuthPassword()), DB_BIND_DYNAMIC);
562 DBBind(hStmt, 23, DB_SQLTYPE_VARCHAR, WideStringFromMBString(m_snmpSecurity->getPrivPassword()), DB_BIND_DYNAMIC);
563 #else
564 DBBind(hStmt, 22, DB_SQLTYPE_VARCHAR, m_snmpSecurity->getAuthPassword(), DB_BIND_STATIC);
565 DBBind(hStmt, 23, DB_SQLTYPE_VARCHAR, m_snmpSecurity->getPrivPassword(), DB_BIND_STATIC);
566 #endif
567 DBBind(hStmt, 24, DB_SQLTYPE_INTEGER, (LONG)snmpMethods);
568 DBBind(hStmt, 25, DB_SQLTYPE_VARCHAR, m_sysName, DB_BIND_STATIC);
569 DBBind(hStmt, 26, DB_SQLTYPE_VARCHAR, BinToStr(m_baseBridgeAddress, MAC_ADDR_LENGTH, baseAddress), DB_BIND_STATIC);
570 DBBind(hStmt, 27, DB_SQLTYPE_INTEGER, m_dwDynamicFlags);
571 DBBind(hStmt, 28, DB_SQLTYPE_INTEGER, (LONG)m_downSince);
572 DBBind(hStmt, 29, DB_SQLTYPE_VARCHAR, (m_driver != NULL) ? m_driver->getName() : _T(""), DB_BIND_STATIC);
573 DBBind(hStmt, 30, DB_SQLTYPE_VARCHAR, m_rackImage); // rack image
574 DBBind(hStmt, 31, DB_SQLTYPE_INTEGER, m_rackPosition); // rack position
575 DBBind(hStmt, 32, DB_SQLTYPE_INTEGER, m_rackHeight); // device height in rack units
576 DBBind(hStmt, 33, DB_SQLTYPE_INTEGER, m_rackId); // rack ID
577 DBBind(hStmt, 34, DB_SQLTYPE_INTEGER, (LONG)m_bootTime);
578 DBBind(hStmt, 35, DB_SQLTYPE_VARCHAR, _itot(m_agentCacheMode, cacheMode, 10), DB_BIND_STATIC, 1);
579 DBBind(hStmt, 36, DB_SQLTYPE_VARCHAR, m_sysContact, DB_BIND_STATIC);
580 DBBind(hStmt, 37, DB_SQLTYPE_VARCHAR, m_sysLocation, DB_BIND_STATIC);
581 DBBind(hStmt, 38, DB_SQLTYPE_INTEGER, (LONG)m_lastAgentCommTime);
582 DBBind(hStmt, 39, DB_SQLTYPE_BIGINT, m_syslogMessageCount);
583 DBBind(hStmt, 40, DB_SQLTYPE_BIGINT, m_snmpTrapCount);
584 DBBind(hStmt, 41, DB_SQLTYPE_INTEGER, (INT32)m_type);
585 DBBind(hStmt, 42, DB_SQLTYPE_VARCHAR, m_subType, DB_BIND_STATIC);
586 DBBind(hStmt, 43, DB_SQLTYPE_VARCHAR, m_sshLogin, DB_BIND_STATIC);
587 DBBind(hStmt, 44, DB_SQLTYPE_VARCHAR, m_sshPassword, DB_BIND_STATIC);
588 DBBind(hStmt, 45, DB_SQLTYPE_INTEGER, m_sshProxy);
589 DBBind(hStmt, 46, DB_SQLTYPE_INTEGER, m_chassisId);
590 DBBind(hStmt, 47, DB_SQLTYPE_INTEGER, m_portRowCount);
591 DBBind(hStmt, 48, DB_SQLTYPE_INTEGER, m_portNumberingScheme);
592 DBBind(hStmt, 49, DB_SQLTYPE_VARCHAR, _itot(m_agentCompressionMode, compressionMode, 10), DB_BIND_STATIC, 1);
593 DBBind(hStmt, 50, DB_SQLTYPE_VARCHAR, m_tunnelId);
594 DBBind(hStmt, 51, DB_SQLTYPE_VARCHAR, m_lldpNodeId, DB_BIND_STATIC);
595 DBBind(hStmt, 52, DB_SQLTYPE_INTEGER, m_id);
596
597 BOOL bResult = DBExecute(hStmt);
598 DBFreeStatement(hStmt);
599
600 // Save access list
601 saveACLToDB(hdb);
602
603 unlockProperties();
604
605 // Save data collection items
606 if (bResult)
607 {
608 lockDciAccess(false);
609 for(int i = 0; i < m_dcObjects->size(); i++)
610 m_dcObjects->get(i)->saveToDatabase(hdb);
611 unlockDciAccess();
612 }
613
614 // Clear modifications flag
615 lockProperties();
616 m_isModified = false;
617 unlockProperties();
618
619 return bResult;
620 }
621
622 /**
623 * Delete object from database
624 */
625 bool Node::deleteFromDatabase(DB_HANDLE hdb)
626 {
627 bool success = DataCollectionTarget::deleteFromDatabase(hdb);
628 if (success)
629 success = executeQueryOnObject(hdb, _T("DELETE FROM nodes WHERE id=?"));
630 if (success)
631 success = executeQueryOnObject(hdb, _T("DELETE FROM nsmap WHERE node_id=?"));
632 return success;
633 }
634
635 /**
636 * Get ARP cache from node
637 */
638 ARP_CACHE *Node::getArpCache()
639 {
640 ARP_CACHE *pArpCache = NULL;
641
642 if (m_flags & NF_IS_LOCAL_MGMT)
643 {
644 pArpCache = GetLocalArpCache();
645 }
646 else if (m_flags & NF_IS_NATIVE_AGENT)
647 {
648 agentLock();
649 if (connectToAgent())
650 pArpCache = m_agentConnection->getArpCache();
651 agentUnlock();
652 }
653 else if (m_flags & NF_IS_SNMP)
654 {
655 SNMP_Transport *pTransport;
656
657 pTransport = createSnmpTransport();
658 if (pTransport != NULL)
659 {
660 pArpCache = SnmpGetArpCache(m_snmpVersion, pTransport);
661 delete pTransport;
662 }
663 }
664
665 return pArpCache;
666 }
667
668 /**
669 * Get list of interfaces from node
670 */
671 InterfaceList *Node::getInterfaceList()
672 {
673 InterfaceList *pIfList = NULL;
674
675 if ((m_flags & NF_IS_NATIVE_AGENT) && (!(m_flags & NF_DISABLE_NXCP)))
676 {
677 agentLock();
678 if (connectToAgent())
679 {
680 pIfList = m_agentConnection->getInterfaceList();
681 }
682 agentUnlock();
683 }
684 if ((pIfList == NULL) && (m_flags & NF_IS_LOCAL_MGMT))
685 {
686 pIfList = GetLocalInterfaceList();
687 }
688 if ((pIfList == NULL) && (m_flags & NF_IS_SNMP) &&
689 (!(m_flags & NF_DISABLE_SNMP)) && (m_driver != NULL))
690 {
691 SNMP_Transport *pTransport = createSnmpTransport();
692 if (pTransport != NULL)
693 {
694 bool useIfXTable;
695 if (m_nUseIfXTable == IFXTABLE_DEFAULT)
696 {
697 useIfXTable = (ConfigReadInt(_T("UseIfXTable"), 1) != 0) ? true : false;
698 }
699 else
700 {
701 useIfXTable = (m_nUseIfXTable == IFXTABLE_ENABLED) ? true : false;
702 }
703
704 int useAliases = ConfigReadInt(_T("UseInterfaceAliases"), 0);
705 pIfList = m_driver->getInterfaces(pTransport, &m_customAttributes, m_driverData, useAliases, useIfXTable);
706
707 if ((pIfList != NULL) && (m_flags & NF_IS_BRIDGE))
708 {
709 BridgeMapPorts(pTransport, pIfList);
710 }
711 delete pTransport;
712 }
713 }
714
715 if (pIfList != NULL)
716 {
717 checkInterfaceNames(pIfList);
718 addVrrpInterfaces(pIfList);
719 }
720
721 return pIfList;
722 }
723
724 /**
725 * Add VRRP interfaces to interface list
726 */
727 void Node::addVrrpInterfaces(InterfaceList *ifList)
728 {
729 int i, j, k;
730 TCHAR buffer[32];
731
732 lockProperties();
733 if (m_vrrpInfo != NULL)
734 {
735 DbgPrintf(6, _T("Node::addVrrpInterfaces(node=%s [%d]): m_vrrpInfo->size()=%d"), m_name, (int)m_id, m_vrrpInfo->size());
736
737 for(i = 0; i < m_vrrpInfo->size(); i++)
738 {
739 VrrpRouter *router = m_vrrpInfo->getRouter(i);
740 DbgPrintf(6, _T("Node::addVrrpInterfaces(node=%s [%d]): vrouter %d state=%d"), m_name, (int)m_id, i, router->getState());
741 if (router->getState() != VRRP_STATE_MASTER)
742 continue; // Do not add interfaces if router is not in master state
743
744 // Get netmask for this VR
745 int maskBits = 0;
746 for(j = 0; j < ifList->size(); j++)
747 {
748 InterfaceInfo *iface = ifList->get(j);
749 if (iface->index == router->getIfIndex())
750 {
751 for(int k = 0; k < iface->ipAddrList.size(); k++)
752 {
753 const InetAddress& addr = iface->ipAddrList.get(k);
754 if (addr.getSubnetAddress().contain(router->getVip(0)))
755 {
756 maskBits = addr.getMaskBits();
757 }
758 }
759 break;
760 }
761 }
762
763 // Walk through all VR virtual IPs
764 for(j = 0; j < router->getVipCount(); j++)
765 {
766 UINT32 vip = router->getVip(j);
767 DbgPrintf(6, _T("Node::addVrrpInterfaces(node=%s [%d]): checking VIP %s@%d"), m_name, (int)m_id, IpToStr(vip, buffer), i);
768 if (vip != 0)
769 {
770 for(k = 0; k < ifList->size(); k++)
771 if (ifList->get(k)->hasAddress(vip))
772 break;
773 if (k == ifList->size())
774 {
775 InterfaceInfo *iface = new InterfaceInfo(0);
776 _sntprintf(iface->name, MAX_DB_STRING, _T("vrrp.%u.%u.%d"), router->getId(), router->getIfIndex(), j);
777 memcpy(iface->macAddr, router->getVirtualMacAddr(), MAC_ADDR_LENGTH);
778 InetAddress addr(vip);
779 addr.setMaskBits(maskBits);
780 iface->ipAddrList.add(addr);
781 ifList->add(iface);
782 DbgPrintf(6, _T("Node::addVrrpInterfaces(node=%s [%d]): added interface %s"), m_name, (int)m_id, iface->name);
783 }
784 }
785 }
786 }
787 }
788 unlockProperties();
789 }
790
791 /**
792 * Find interface by index.
793 *
794 * @param ifIndex interface index to match
795 * @return pointer to interface object or NULL if appropriate interface couldn't be found
796 */
797 Interface *Node::findInterfaceByIndex(UINT32 ifIndex)
798 {
799 lockChildList(false);
800 for(int i = 0; i < m_childList->size(); i++)
801 if (m_childList->get(i)->getObjectClass() == OBJECT_INTERFACE)
802 {
803 Interface *pInterface = (Interface *)m_childList->get(i);
804 if (pInterface->getIfIndex() == ifIndex)
805 {
806 unlockChildList();
807 return pInterface;
808 }
809 }
810 unlockChildList();
811 return NULL;
812 }
813
814 /**
815 * Find interface by name or description
816 * Returns pointer to interface object or NULL if appropriate interface couldn't be found
817 */
818 Interface *Node::findInterfaceByName(const TCHAR *name)
819 {
820 if ((name == NULL) || (name[0] == 0))
821 return NULL;
822
823 Interface *pInterface;
824
825 lockChildList(false);
826 for(int i = 0; i < m_childList->size(); i++)
827 if (m_childList->get(i)->getObjectClass() == OBJECT_INTERFACE)
828 {
829 pInterface = (Interface *)m_childList->get(i);
830 if (!_tcsicmp(pInterface->getName(), name) || !_tcsicmp(pInterface->getDescription(), name))
831 {
832 unlockChildList();
833 return pInterface;
834 }
835 }
836 unlockChildList();
837 return NULL;
838 }
839
840 /**
841 * Find interface by slot/port pair
842 * Returns pointer to interface object or NULL if appropriate interface couldn't be found
843 */
844 Interface *Node::findInterfaceBySlotAndPort(UINT32 slot, UINT32 port)
845 {
846 lockChildList(false);
847 for(int i = 0; i < m_childList->size(); i++)
848 if (m_childList->get(i)->getObjectClass() == OBJECT_INTERFACE)
849 {
850 Interface *pInterface = (Interface *)m_childList->get(i);
851 if (pInterface->isPhysicalPort() && (pInterface->getSlotNumber() == slot) && (pInterface->getPortNumber() == port))
852 {
853 unlockChildList();
854 return pInterface;
855 }
856 }
857 unlockChildList();
858 return NULL;
859 }
860
861 /**
862 * Find interface by MAC address
863 * Returns pointer to interface object or NULL if appropriate interface couldn't be found
864 */
865 Interface *Node::findInterfaceByMAC(const BYTE *macAddr)
866 {
867 Interface *iface = NULL;
868 lockChildList(false);
869 for(int i = 0; i < m_childList->size(); i++)
870 {
871 NetObj *curr = m_childList->get(i);
872 if (curr->getObjectClass() == OBJECT_INTERFACE)
873 {
874 if (!memcmp(((Interface *)curr)->getMacAddr(), macAddr, MAC_ADDR_LENGTH))
875 {
876 iface = (Interface *)curr;
877 break;
878 }
879 }
880 }
881 unlockChildList();
882 return iface;
883 }
884
885 /**
886 * Find interface by IP address
887 * Returns pointer to interface object or NULL if appropriate interface couldn't be found
888 */
889 Interface *Node::findInterfaceByIP(const InetAddress& addr)
890 {
891 if (!addr.isValid())
892 return NULL;
893
894 lockChildList(false);
895 for(int i = 0; i < m_childList->size(); i++)
896 if (m_childList->get(i)->getObjectClass() == OBJECT_INTERFACE)
897 {
898 Interface *pInterface = (Interface *)m_childList->get(i);
899 if (pInterface->getIpAddressList()->hasAddress(addr))
900 {
901 unlockChildList();
902 return pInterface;
903 }
904 }
905 unlockChildList();
906 return NULL;
907 }
908
909 /**
910 * Find interface by bridge port number
911 */
912 Interface *Node::findBridgePort(UINT32 bridgePortNumber)
913 {
914 lockChildList(false);
915 for(int i = 0; i < m_childList->size(); i++)
916 if (m_childList->get(i)->getObjectClass() == OBJECT_INTERFACE)
917 {
918 Interface *pInterface = (Interface *)m_childList->get(i);
919 if (pInterface->getBridgePortNumber() == bridgePortNumber)
920 {
921 unlockChildList();
922 return pInterface;
923 }
924 }
925 unlockChildList();
926 return NULL;
927 }
928
929 /**
930 * Find connection point for node
931 */
932 NetObj *Node::findConnectionPoint(UINT32 *localIfId, BYTE *localMacAddr, int *type)
933 {
934 NetObj *cp = NULL;
935 lockChildList(false);
936 for(int i = 0; i < m_childList->size(); i++)
937 {
938 if (m_childList->get(i)->getObjectClass() == OBJECT_INTERFACE)
939 {
940 Interface *iface = (Interface *)m_childList->get(i);
941 cp = FindInterfaceConnectionPoint(iface->getMacAddr(), type);
942 if (cp != NULL)
943 {
944 *localIfId = iface->getId();
945 memcpy(localMacAddr, iface->getMacAddr(), MAC_ADDR_LENGTH);
946 break;
947 }
948 }
949 }
950 unlockChildList();
951 return cp;
952 }
953
954 /**
955 * Find attached access point by MAC address
956 */
957 AccessPoint *Node::findAccessPointByMAC(const BYTE *macAddr)
958 {
959 AccessPoint *ap = NULL;
960 lockChildList(false);
961 for(int i = 0; i < m_childList->size(); i++)
962 {
963 NetObj *curr = m_childList->get(i);
964 if (curr->getObjectClass() == OBJECT_ACCESSPOINT)
965 {
966 if (!memcmp(((AccessPoint *)curr)->getMacAddr(), macAddr, MAC_ADDR_LENGTH))
967 {
968 ap = (AccessPoint *)curr;
969 break;
970 }
971 }
972 }
973 unlockChildList();
974 return ap;
975 }
976
977 /**
978 * Find access point by radio ID (radio interface index)
979 */
980 AccessPoint *Node::findAccessPointByRadioId(int rfIndex)
981 {
982 AccessPoint *ap = NULL;
983 lockChildList(false);
984 for(int i = 0; i < m_childList->size(); i++)
985 {
986 NetObj *curr = m_childList->get(i);
987 if (curr->getObjectClass() == OBJECT_ACCESSPOINT)
988 {
989 if (((AccessPoint *)curr)->isMyRadio(rfIndex))
990 {
991 ap = (AccessPoint *)curr;
992 break;
993 }
994 }
995 }
996 unlockChildList();
997 return ap;
998 }
999
1000 /**
1001 * Find attached access point by BSSID
1002 */
1003 AccessPoint *Node::findAccessPointByBSSID(const BYTE *bssid)
1004 {
1005 AccessPoint *ap = NULL;
1006 lockChildList(false);
1007 for(int i = 0; i < m_childList->size(); i++)
1008 {
1009 NetObj *curr = m_childList->get(i);
1010 if (curr->getObjectClass() == OBJECT_ACCESSPOINT)
1011 {
1012 if (!memcmp(((AccessPoint *)curr)->getMacAddr(), bssid, MAC_ADDR_LENGTH) ||
1013 ((AccessPoint *)curr)->isMyRadio(bssid))
1014 {
1015 ap = (AccessPoint *)curr;
1016 break;
1017 }
1018 }
1019 }
1020 unlockChildList();
1021 return ap;
1022 }
1023
1024 /**
1025 * Check if given IP address is one of node's interfaces
1026 */
1027 bool Node::isMyIP(const InetAddress& addr)
1028 {
1029 lockChildList(false);
1030 for(int i = 0; i < m_childList->size(); i++)
1031 if (m_childList->get(i)->getObjectClass() == OBJECT_INTERFACE)
1032 {
1033 if (((Interface *)m_childList->get(i))->getIpAddressList()->hasAddress(addr))
1034 {
1035 unlockChildList();
1036 return true;
1037 }
1038 }
1039 unlockChildList();
1040 return false;
1041 }
1042
1043 /**
1044 * Filter interface - should return true if system should proceed with interface creation
1045 */
1046 bool Node::filterInterface(InterfaceInfo *info)
1047 {
1048 NXSL_VM *vm = CreateServerScriptVM(_T("Hook::CreateInterface"));
1049 if (vm == NULL)
1050 {
1051 DbgPrintf(7, _T("Node::filterInterface(%s [%u]): hook script \"Hook::CreateInterface\" not found"), m_name, m_id);
1052 return true;
1053 }
1054
1055 Interface *iface;
1056 if (info->name[0] != 0)
1057 {
1058 iface = new Interface(info->name, (info->description[0] != 0) ? info->description : info->name,
1059 info->index, info->ipAddrList, info->type, m_zoneId);
1060 }
1061 else
1062 {
1063 iface = new Interface(info->ipAddrList, m_zoneId, false);
1064 }
1065 iface->setMacAddr(info->macAddr, false);
1066 iface->setBridgePortNumber(info->bridgePort);
1067 iface->setSlotNumber(info->slot);
1068 iface->setPortNumber(info->port);
1069 iface->setPhysicalPortFlag(info->isPhysicalPort);
1070 iface->setManualCreationFlag(false);
1071 iface->setSystemFlag(info->isSystem);
1072 iface->setMTU(info->mtu);
1073 iface->setSpeed(info->speed);
1074 iface->setIfTableSuffix(info->ifTableSuffixLength, info->ifTableSuffix);
1075
1076 bool pass = true;
1077 NXSL_Value *argv = new NXSL_Value(new NXSL_Object(&g_nxslInterfaceClass, iface));
1078 vm->setGlobalVariable(_T("$node"), new NXSL_Value(new NXSL_Object(&g_nxslNodeClass, this)));
1079 if (vm->run(1, &argv))
1080 {
1081 NXSL_Value *result = vm->getResult();
1082 if ((result != NULL) && result->isInteger())
1083 {
1084 pass = (result->getValueAsInt32() != 0);
1085 }
1086 }
1087 else
1088 {
1089 DbgPrintf(4, _T("Node::filterInterface(%s [%u]): hook script execution error: %s"), m_name, m_id, vm->getErrorText());
1090 }
1091 delete vm;
1092 delete iface;
1093
1094 DbgPrintf(6, _T("Node::filterInterface(%s [%u]): interface \"%s\" (ifIndex=%d) %s by filter"),
1095 m_name, m_id, info->name, info->index, pass ? _T("accepted") : _T("rejected"));
1096 return pass;
1097 }
1098
1099 /**
1100 * Create new interface - convenience wrapper
1101 */
1102 Interface *Node::createNewInterface(const InetAddress& ipAddr, BYTE *macAddr, bool fakeInterface)
1103 {
1104 InterfaceInfo info(1);
1105 info.ipAddrList.add(ipAddr);
1106 if (macAddr != NULL)
1107 memcpy(info.macAddr, macAddr, MAC_ADDR_LENGTH);
1108 return createNewInterface(&info, false, fakeInterface);
1109 }
1110
1111 /**
1112 * Create new interface
1113 */
1114 Interface *Node::createNewInterface(InterfaceInfo *info, bool manuallyCreated, bool fakeInterface)
1115 {
1116 bool bSyntheticMask = false;
1117 TCHAR buffer[64];
1118
1119 DbgPrintf(5, _T("Node::createNewInterface(\"%s\", %d, %d, bp=%d, slot=%d, port=%d) called for node %s [%d]"),
1120 info->name, info->index, info->type, info->bridgePort, info->slot, info->port, m_name, m_id);
1121 for(int i = 0; i < info->ipAddrList.size(); i++)
1122 {
1123 const InetAddress& addr = info->ipAddrList.get(i);
1124 DbgPrintf(5, _T("Node::createNewInterface(%s): IP address %s/%d"), info->name, addr.toString(buffer), addr.getMaskBits());
1125 }
1126
1127 // Find subnet to place interface object to
1128 if (info->type != IFTYPE_SOFTWARE_LOOPBACK)
1129 {
1130 Cluster *pCluster = getMyCluster();
1131 for(int i = 0; i < info->ipAddrList.size(); i++)
1132 {
1133 InetAddress addr = info->ipAddrList.get(i);
1134 bool addToSubnet = addr.isValidUnicast() && ((pCluster == NULL) || !pCluster->isSyncAddr(addr));
1135 DbgPrintf(5, _T("Node::createNewInterface: node=%s [%d] ip=%s/%d cluster=%s [%d] add=%s"),
1136 m_name, m_id, addr.toString(buffer), addr.getMaskBits(),
1137 (pCluster != NULL) ? pCluster->getName() : _T("(null)"),
1138 (pCluster != NULL) ? pCluster->getId() : 0, addToSubnet ? _T("yes") : _T("no"));
1139 if (addToSubnet)
1140 {
1141 Subnet *pSubnet = FindSubnetForNode(m_zoneId, addr);
1142 if (pSubnet == NULL)
1143 {
1144 // Check if netmask is 0 (detect), and if yes, create
1145 // new subnet with default mask
1146 if (addr.getMaskBits() == 0)
1147 {
1148 bSyntheticMask = true;
1149 addr.setMaskBits((addr.getFamily() == AF_INET) ? ConfigReadInt(_T("DefaultSubnetMaskIPv4"), 24) : ConfigReadInt(_T("DefaultSubnetMaskIPv6"), 64));
1150 info->ipAddrList.replace(addr);
1151 }
1152
1153 // Create new subnet object
1154 if (addr.getHostBits() >= 2)
1155 {
1156 pSubnet = createSubnet(addr, bSyntheticMask);
1157 if (bSyntheticMask)
1158 {
1159 // createSubnet may adjust address mask bits
1160 info->ipAddrList.replace(addr);
1161 }
1162 }
1163 }
1164 else
1165 {
1166 // Set correct netmask if we were asked for it
1167 if (addr.getMaskBits() == 0)
1168 {
1169 bSyntheticMask = pSubnet->isSyntheticMask();
1170 addr.setMaskBits(pSubnet->getIpAddress().getMaskBits());
1171 info->ipAddrList.replace(addr);
1172 }
1173 }
1174 if (pSubnet != NULL)
1175 {
1176 pSubnet->addNode(this);
1177 }
1178 } // addToSubnet
1179 } // loop by address list
1180 }
1181
1182 // Create interface object
1183 Interface *iface;
1184 if (info->name[0] != 0)
1185 iface = new Interface(info->name, (info->description[0] != 0) ? info->description : info->name,
1186 info->index, info->ipAddrList, info->type, m_zoneId);
1187 else
1188 iface = new Interface(info->ipAddrList, m_zoneId, bSyntheticMask);
1189 iface->setMacAddr(info->macAddr, false);
1190 iface->setBridgePortNumber(info->bridgePort);
1191 iface->setSlotNumber(info->slot);
1192 iface->setPortNumber(info->port);
1193 iface->setPhysicalPortFlag(info->isPhysicalPort);
1194 iface->setManualCreationFlag(manuallyCreated);
1195 iface->setSystemFlag(info->isSystem);
1196 iface->setMTU(info->mtu);
1197 iface->setSpeed(info->speed);
1198 iface->setIfTableSuffix(info->ifTableSuffixLength, info->ifTableSuffix);
1199
1200 int defaultExpectedState = ConfigReadInt(_T("DefaultInterfaceExpectedState"), IF_DEFAULT_EXPECTED_STATE_UP);
1201 switch(defaultExpectedState)
1202 {
1203 case IF_DEFAULT_EXPECTED_STATE_AUTO:
1204 iface->setExpectedState(fakeInterface ? IF_EXPECTED_STATE_UP : IF_EXPECTED_STATE_AUTO);
1205 break;
1206 case IF_DEFAULT_EXPECTED_STATE_IGNORE:
1207 iface->setExpectedState(IF_EXPECTED_STATE_IGNORE);
1208 break;
1209 default:
1210 iface->setExpectedState(IF_EXPECTED_STATE_UP);
1211 break;
1212 }
1213
1214 // Insert to objects' list and generate event
1215 NetObjInsert(iface, true, false);
1216 addInterface(iface);
1217 if (!m_isHidden)
1218 iface->unhide();
1219 if (!iface->isSystem())
1220 {
1221 const InetAddress& addr = iface->getFirstIpAddress();
1222 PostEvent(EVENT_INTERFACE_ADDED, m_id, "dsAdd", iface->getId(),
1223 iface->getName(), &addr, addr.getMaskBits(), iface->getIfIndex());
1224 }
1225
1226 return iface;
1227 }
1228
1229 /**
1230 * Delete interface from node
1231 */
1232 void Node::deleteInterface(Interface *iface)
1233 {
1234 DbgPrintf(5, _T("Node::deleteInterface(node=%s [%d], interface=%s [%d])"), m_name, m_id, iface->getName(), iface->getId());
1235
1236 // Check if we should unlink node from interface's subnet
1237 if (!iface->isExcludedFromTopology())
1238 {
1239 const ObjectArray<InetAddress> *list = iface->getIpAddressList()->getList();
1240 for(int i = 0; i < list->size(); i++)
1241 {
1242 bool doUnlink = true;
1243 const InetAddress *addr = list->get(i);
1244
1245 lockChildList(false);
1246 for(int j = 0; j < m_childList->size(); j++)
1247 {
1248 NetObj *curr = m_childList->get(j);
1249 if ((curr->getObjectClass() == OBJECT_INTERFACE) && (curr != iface) &&
1250 ((Interface *)curr)->getIpAddressList()->findSameSubnetAddress(*addr).isValid())
1251 {
1252 doUnlink = false;
1253 break;
1254 }
1255 }
1256 unlockChildList();
1257
1258 if (doUnlink)
1259 {
1260 // Last interface in subnet, should unlink node
1261 Subnet *pSubnet = FindSubnetByIP(m_zoneId, addr->getSubnetAddress());
1262 if (pSubnet != NULL)
1263 {
1264 deleteParent(pSubnet);
1265 pSubnet->deleteChild(this);
1266 }
1267 DbgPrintf(5, _T("Node::deleteInterface(node=%s [%d], interface=%s [%d]): unlinked from subnet %s [%d]"),
1268 m_name, m_id, iface->getName(), iface->getId(),
1269 (pSubnet != NULL) ? pSubnet->getName() : _T("(null)"),
1270 (pSubnet != NULL) ? pSubnet->getId() : 0);
1271 }
1272 }
1273 }
1274 iface->deleteObject();
1275 }
1276
1277 /**
1278 * Calculate node status based on child objects status
1279 */
1280 void Node::calculateCompoundStatus(BOOL bForcedRecalc)
1281 {
1282 int iOldStatus = m_status;
1283 static UINT32 dwEventCodes[] = { EVENT_NODE_NORMAL, EVENT_NODE_WARNING,
1284 EVENT_NODE_MINOR, EVENT_NODE_MAJOR, EVENT_NODE_CRITICAL,
1285 EVENT_NODE_UNKNOWN, EVENT_NODE_UNMANAGED };
1286
1287 DataCollectionTarget::calculateCompoundStatus(bForcedRecalc);
1288 if (m_status != iOldStatus)
1289 PostEvent(dwEventCodes[m_status], m_id, "d", iOldStatus);
1290 }
1291
1292 /**
1293 * Status poller entry point
1294 */
1295 void Node::statusPoll(PollerInfo *poller)
1296 {
1297 poller->startExecution();
1298 statusPoll(NULL, 0, poller);
1299
1300 // Check if the node has to be deleted due to long downtime
1301 time_t unreachableDeleteDays = (time_t)ConfigReadInt(_T("DeleteUnreachableNodesPeriod"), 0);
1302 if ((unreachableDeleteDays > 0) && (m_downSince > 0) &&
1303 (time(NULL) - m_downSince > unreachableDeleteDays * 24 * 3600))
1304 {
1305 deleteObject();
1306 }
1307 delete poller;
1308 }
1309
1310 /**
1311 * Perform status poll on node
1312 */
1313 void Node::statusPoll(ClientSession *pSession, UINT32 dwRqId, PollerInfo *poller)
1314 {
1315 if (m_dwDynamicFlags & NDF_DELETE_IN_PROGRESS)
1316 {
1317 if (dwRqId == 0)
1318 m_dwDynamicFlags &= ~NDF_QUEUED_FOR_STATUS_POLL;
1319 return;
1320 }
1321
1322 if (IsShutdownInProgress())
1323 return;
1324
1325 UINT32 dwOldFlags = m_flags;
1326 NetObj *pPollerNode = NULL, **ppPollList;
1327 SNMP_Transport *pTransport;
1328 Cluster *pCluster;
1329 time_t tNow, tExpire;
1330
1331 Queue *pQueue = new Queue; // Delayed event queue
1332 poller->setStatus(_T("wait for lock"));
1333 pollerLock();
1334
1335 if (IsShutdownInProgress())
1336 {
1337 delete pQueue;
1338 pollerUnlock();
1339 return;
1340 }
1341
1342 m_pollRequestor = pSession;
1343 sendPollerMsg(dwRqId, _T("Starting status poll for node %s\r\n"), m_name);
1344 nxlog_debug(5, _T("Starting status poll for node %s (ID: %d)"), m_name, m_id);
1345
1346 // Read capability expiration time and current time
1347 tExpire = (time_t)ConfigReadULong(_T("CapabilityExpirationTime"), 604800);
1348 tNow = time(NULL);
1349
1350 int retryCount = 5;
1351
1352 restart_agent_check:
1353 if (g_flags & AF_RESOLVE_IP_FOR_EACH_STATUS_POLL)
1354 {
1355 updatePrimaryIpAddr();
1356 }
1357
1358 // Check SNMP agent connectivity
1359 if ((m_flags & NF_IS_SNMP) && (!(m_flags & NF_DISABLE_SNMP)) && m_ipAddress.isValidUnicast())
1360 {
1361 TCHAR szBuffer[256];
1362 UINT32 dwResult;
1363
1364 nxlog_debug(6, _T("StatusPoll(%s): check SNMP"), m_name);
1365 pTransport = createSnmpTransport();
1366 if (pTransport != NULL)
1367 {
1368 poller->setStatus(_T("check SNMP"));
1369 sendPollerMsg(dwRqId, _T("Checking SNMP agent connectivity\r\n"));
1370 const TCHAR *testOid = m_customAttributes.get(_T("snmp.testoid"));
1371 if (testOid == NULL)
1372 {
1373 testOid = _T(".1.3.6.1.2.1.1.2.0");
1374 }
1375 dwResult = SnmpGet(m_snmpVersion, pTransport, testOid, NULL, 0, szBuffer, sizeof(szBuffer), 0);
1376 if ((dwResult == SNMP_ERR_SUCCESS) || (dwResult == SNMP_ERR_NO_OBJECT))
1377 {
1378 if (m_dwDynamicFlags & NDF_SNMP_UNREACHABLE)
1379 {
1380 m_dwDynamicFlags &= ~NDF_SNMP_UNREACHABLE;
1381 PostEventEx(pQueue, EVENT_SNMP_OK, m_id, NULL);
1382 sendPollerMsg(dwRqId, POLLER_INFO _T("Connectivity with SNMP agent restored\r\n"));
1383 }
1384
1385 // Update authoritative engine data for SNMPv3
1386 if ((pTransport->getSnmpVersion() == SNMP_VERSION_3) && (pTransport->getAuthoritativeEngine() != NULL))
1387 {
1388 lockProperties();
1389 m_snmpSecurity->setAuthoritativeEngine(*pTransport->getAuthoritativeEngine());
1390 unlockProperties();
1391 }
1392 }
1393 else if ((dwResult == SNMP_ERR_ENGINE_ID) && (m_snmpVersion == SNMP_VERSION_3) && (retryCount > 0))
1394 {
1395 // Reset authoritative engine data
1396 lockProperties();
1397 m_snmpSecurity->setAuthoritativeEngine(SNMP_Engine());
1398 unlockProperties();
1399 delete pTransport;
1400 retryCount--;
1401 goto restart_agent_check;
1402 }
1403 else
1404 {
1405 if (pTransport->isProxyTransport() && (dwResult == SNMP_ERR_COMM))
1406 {
1407 nxlog_debug(6, _T("StatusPoll(%s): got communication error on proxy transport, checking connection to proxy"), m_name);
1408 AgentConnectionEx *pconn = acquireProxyConnection(SNMP_PROXY, true);
1409 if (pconn != NULL)
1410 {
1411 pconn->decRefCount();
1412 if (retryCount > 0)
1413 {
1414 retryCount--;
1415 delete pTransport;
1416 goto restart_agent_check;
1417 }
1418 }
1419 }
1420
1421 sendPollerMsg(dwRqId, POLLER_ERROR _T("SNMP agent unreachable\r\n"));
1422 if (m_dwDynamicFlags & NDF_SNMP_UNREACHABLE)
1423 {
1424 if ((tNow > m_failTimeSNMP + tExpire) && (!(m_dwDynamicFlags & NDF_UNREACHABLE)))
1425 {
1426 m_flags &= ~NF_IS_SNMP;
1427 m_dwDynamicFlags &= ~NDF_SNMP_UNREACHABLE;
1428 m_snmpObjectId[0] = 0;
1429 sendPollerMsg(dwRqId, POLLER_WARNING _T("Attribute isSNMP set to FALSE\r\n"));
1430 }
1431 }
1432 else
1433 {
1434 m_dwDynamicFlags |= NDF_SNMP_UNREACHABLE;
1435 PostEventEx(pQueue, EVENT_SNMP_FAIL, m_id, NULL);
1436 m_failTimeSNMP = tNow;
1437 }
1438 }
1439 delete pTransport;
1440 }
1441 else
1442 {
1443 nxlog_debug(6, _T("StatusPoll(%s): cannot create SNMP transport"), m_name);
1444 }
1445 nxlog_debug(6, _T("StatusPoll(%s): SNMP check finished"), m_name);
1446 }
1447
1448 // Check native agent connectivity
1449 if ((m_flags & NF_IS_NATIVE_AGENT) && (!(m_flags & NF_DISABLE_NXCP)))
1450 {
1451 nxlog_debug(6, _T("StatusPoll(%s): checking agent"), m_name);
1452 poller->setStatus(_T("check agent"));
1453 sendPollerMsg(dwRqId, _T("Checking NetXMS agent connectivity\r\n"));
1454
1455 UINT32 error, socketError;
1456 bool newConnection;
1457 agentLock();
1458 if (connectToAgent(&error, &socketError, &newConnection, true))
1459 {
1460 nxlog_debug(7, _T("StatusPoll(%s): connected to agent"), m_name);
1461 if (m_dwDynamicFlags & NDF_AGENT_UNREACHABLE)
1462 {
1463 m_dwDynamicFlags &= ~NDF_AGENT_UNREACHABLE;
1464 PostEventEx(pQueue, EVENT_AGENT_OK, m_id, NULL);
1465 sendPollerMsg(dwRqId, POLLER_INFO _T("Connectivity with NetXMS agent restored\r\n"));
1466 }
1467 }
1468 else
1469 {
1470 nxlog_debug(6, _T("StatusPoll(%s): agent unreachable, error=%d, socketError=%d"), m_name, (int)error, (int)socketError);
1471 sendPollerMsg(dwRqId, POLLER_ERROR _T("NetXMS agent unreachable\r\n"));
1472 if (m_dwDynamicFlags & NDF_AGENT_UNREACHABLE)
1473 {
1474 if ((tNow > m_failTimeAgent + tExpire) && !(m_dwDynamicFlags & NDF_UNREACHABLE))
1475 {
1476 m_flags &= ~NF_IS_NATIVE_AGENT;
1477 m_dwDynamicFlags &= ~NDF_AGENT_UNREACHABLE;
1478 m_platformName[0] = 0;
1479 m_agentVersion[0] = 0;
1480 sendPollerMsg(dwRqId, POLLER_WARNING _T("Attribute isNetXMSAgent set to FALSE\r\n"));
1481 }
1482 }
1483 else
1484 {
1485 m_dwDynamicFlags |= NDF_AGENT_UNREACHABLE;
1486 PostEventEx(pQueue, EVENT_AGENT_FAIL, m_id, NULL);
1487 m_failTimeAgent = tNow;
1488 //cancel file monitoring locally(on agent it is canceled if agent have fallen)
1489 g_monitoringList.removeDisconnectedNode(m_id);
1490 }
1491 }
1492 agentUnlock();
1493 nxlog_debug(7, _T("StatusPoll(%s): agent check finished"), m_name);
1494
1495 // If file update connection is active, send NOP command to prevent disconnection by idle timeout
1496 AgentConnection *fileUpdateConnection;
1497 lockProperties();
1498 fileUpdateConnection = m_fileUpdateConn;
1499 if (fileUpdateConnection != NULL)
1500 fileUpdateConnection->incRefCount();
1501 unlockProperties();
1502 if (fileUpdateConnection != NULL)
1503 {
1504 nxlog_debug(6, _T("StatusPoll(%s): sending keepalive command on file monitoring connection"), m_name);
1505 fileUpdateConnection->nop();
1506 fileUpdateConnection->decRefCount();
1507 }
1508 }
1509
1510 poller->setStatus(_T("prepare polling list"));
1511
1512 // Find service poller node object
1513 lockProperties();
1514 if (m_pollerNode != 0)
1515 {
1516 UINT32 id = m_pollerNode;
1517 unlockProperties();
1518 pPollerNode = FindObjectById(id);
1519 if (pPollerNode != NULL)
1520 {
1521 if (pPollerNode->getObjectClass() != OBJECT_NODE)
1522 pPollerNode = NULL;
1523 }
1524 }
1525 else
1526 {
1527 unlockProperties();
1528 }
1529
1530 // If nothing found, use management server
1531 if (pPollerNode == NULL)
1532 {
1533 pPollerNode = FindObjectById(g_dwMgmtNode);
1534 if (pPollerNode != NULL)
1535 pPollerNode->incRefCount();
1536 }
1537 else
1538 {
1539 pPollerNode->incRefCount();
1540 }
1541
1542 // Create polling list
1543 ppPollList = (NetObj **)malloc(sizeof(NetObj *) * m_childList->size());
1544 lockChildList(false);
1545 int pollListSize = 0;
1546 for(int i = 0; i < m_childList->size(); i++)
1547 {
1548 NetObj *curr = m_childList->get(i);
1549 if (curr->getStatus() != STATUS_UNMANAGED)
1550 {
1551 curr->incRefCount();
1552 ppPollList[pollListSize++] = curr;
1553 }
1554 }
1555 unlockChildList();
1556
1557 // Poll interfaces and services
1558 poller->setStatus(_T("child poll"));
1559 DbgPrintf(7, _T("StatusPoll(%s): starting child object poll"), m_name);
1560 pCluster = getMyCluster();
1561 pTransport = createSnmpTransport();
1562 for(int i = 0; i < pollListSize; i++)
1563 {
1564 switch(ppPollList[i]->getObjectClass())
1565 {
1566 case OBJECT_INTERFACE:
1567 DbgPrintf(7, _T("StatusPoll(%s): polling interface %d [%s]"), m_name, ppPollList[i]->getId(), ppPollList[i]->getName());
1568 ((Interface *)ppPollList[i])->statusPoll(pSession, dwRqId, pQueue, pCluster, pTransport, m_icmpProxy);
1569 break;
1570 case OBJECT_NETWORKSERVICE:
1571 DbgPrintf(7, _T("StatusPoll(%s): polling network service %d [%s]"), m_name, ppPollList[i]->getId(), ppPollList[i]->getName());
1572 ((NetworkService *)ppPollList[i])->statusPoll(pSession, dwRqId, (Node *)pPollerNode, pQueue);
1573 break;
1574 case OBJECT_ACCESSPOINT:
1575 DbgPrintf(7, _T("StatusPoll(%s): polling access point %d [%s]"), m_name, ppPollList[i]->getId(), ppPollList[i]->getName());
1576 ((AccessPoint *)ppPollList[i])->statusPoll(pSession, dwRqId, pQueue, this, pTransport);
1577 break;
1578 default:
1579 DbgPrintf(7, _T("StatusPoll(%s): skipping object %d [%s] class %d"), m_name, ppPollList[i]->getId(), ppPollList[i]->getName(), ppPollList[i]->getObjectClass());
1580 break;
1581 }
1582 ppPollList[i]->decRefCount();
1583 }
1584 delete pTransport;
1585 free(ppPollList);
1586 DbgPrintf(7, _T("StatusPoll(%s): finished child object poll"), m_name);
1587
1588 // Check if entire node is down
1589 // This check is disabled for nodes without IP address
1590 if (m_ipAddress.isValidUnicast())
1591 {
1592 bool allDown = true;
1593 lockChildList(false);
1594 for(int i = 0; i < m_childList->size(); i++)
1595 {
1596 NetObj *curr = m_childList->get(i);
1597 if ((curr->getObjectClass() == OBJECT_INTERFACE) &&
1598 (((Interface *)curr)->getAdminState() != IF_ADMIN_STATE_DOWN) &&
1599 (((Interface *)curr)->getConfirmedOperState() == IF_OPER_STATE_UP) &&
1600 (curr->getStatus() != STATUS_UNMANAGED))
1601 {
1602 allDown = false;
1603 break;
1604 }
1605 }
1606 unlockChildList();
1607 if (allDown && (m_flags & NF_IS_NATIVE_AGENT) &&
1608 (!(m_flags & NF_DISABLE_NXCP)))
1609 if (!(m_dwDynamicFlags & NDF_AGENT_UNREACHABLE))
1610 allDown = false;
1611 if (allDown && (m_flags & NF_IS_SNMP) &&
1612 (!(m_flags & NF_DISABLE_SNMP)))
1613 if (!(m_dwDynamicFlags & NDF_SNMP_UNREACHABLE))
1614 allDown = false;
1615
1616 DbgPrintf(6, _T("StatusPoll(%s): allDown=%s, dynFlags=0x%08X"), m_name, allDown ? _T("true") : _T("false"), m_dwDynamicFlags);
1617 if (allDown)
1618 {
1619 if (!(m_dwDynamicFlags & NDF_UNREACHABLE))
1620 {
1621 m_dwDynamicFlags |= NDF_UNREACHABLE;
1622 m_downSince = time(NULL);
1623 poller->setStatus(_T("check network path"));
1624 if (checkNetworkPath(dwRqId))
1625 {
1626 m_dwDynamicFlags |= NDF_NETWORK_PATH_PROBLEM;
1627
1628 // Set interfaces and network services to UNKNOWN state
1629 lockChildList(false);
1630 for(int i = 0; i < m_childList->size(); i++)
1631 {
1632 NetObj *curr = m_childList->get(i);
1633 if ((curr->getObjectClass() == OBJECT_INTERFACE) || (curr->getObjectClass() == OBJECT_NETWORKSERVICE))
1634 {
1635 curr->resetStatus();
1636 }
1637 }
1638 unlockChildList();
1639
1640 // Clear delayed event queue
1641 while(true)
1642 {
1643 Event *e = (Event *)pQueue->get();
1644 if (e == NULL)
1645 break;
1646 delete e;
1647 }
1648 delete_and_null(pQueue);
1649
1650 PostEvent(EVENT_NODE_UNREACHABLE, m_id, NULL);
1651 }
1652 else
1653 {
1654 PostEvent(EVENT_NODE_DOWN, m_id, NULL);
1655 }
1656 g_monitoringList.removeDisconnectedNode(m_id);
1657 sendPollerMsg(dwRqId, POLLER_ERROR _T("Node is unreachable\r\n"));
1658 }
1659 else
1660 {
1661 sendPollerMsg(dwRqId, POLLER_WARNING _T("Node is still unreachable\r\n"));
1662 }
1663 }
1664 else
1665 {
1666 m_downSince = 0;
1667 if (m_dwDynamicFlags & NDF_UNREACHABLE)
1668 {
1669 int reason = (m_dwDynamicFlags & NDF_NETWORK_PATH_PROBLEM) ? 1 : 0;
1670 m_dwDynamicFlags &= ~(NDF_UNREACHABLE | NDF_SNMP_UNREACHABLE | NDF_AGENT_UNREACHABLE | NDF_NETWORK_PATH_PROBLEM);
1671 PostEvent(EVENT_NODE_UP, m_id, "d", reason);
1672 sendPollerMsg(dwRqId, POLLER_INFO _T("Node recovered from unreachable state\r\n"));
1673 goto restart_agent_check;
1674 }
1675 else
1676 {
1677 sendPollerMsg(dwRqId, POLLER_INFO _T("Node is connected\r\n"));
1678 }
1679 }
1680 }
1681
1682 // Get uptime and update boot time
1683 if (!(m_dwDynamicFlags & NDF_UNREACHABLE))
1684 {
1685 TCHAR buffer[MAX_RESULT_LENGTH];
1686 if (getItemFromAgent(_T("System.Uptime"), MAX_RESULT_LENGTH, buffer) == DCE_SUCCESS)
1687 {
1688 m_bootTime = time(NULL) - _tcstol(buffer, NULL, 0);
1689 DbgPrintf(5, _T("StatusPoll(%s [%d]): boot time set to %u from agent"), m_name, m_id, (UINT32)m_bootTime);
1690 }
1691 else if (getItemFromSNMP(m_snmpPort, _T(".1.3.6.1.2.1.1.3.0"), MAX_RESULT_LENGTH, buffer, SNMP_RAWTYPE_NONE) == DCE_SUCCESS)
1692 {
1693 m_bootTime = time(NULL) - _tcstol(buffer, NULL, 0) / 100; // sysUpTime is in hundredths of a second
1694 DbgPrintf(5, _T("StatusPoll(%s [%d]): boot time set to %u from SNMP"), m_name, m_id, (UINT32)m_bootTime);
1695 }
1696 else
1697 {
1698 DbgPrintf(5, _T("StatusPoll(%s [%d]): unable to get system uptime"), m_name, m_id);
1699 }
1700 }
1701 else
1702 {
1703 m_bootTime = 0;
1704 }
1705
1706 // Get agent uptime to check if it was restared
1707 if (!(m_dwDynamicFlags & NDF_UNREACHABLE) && isNativeAgent())
1708 {
1709 TCHAR buffer[MAX_RESULT_LENGTH];
1710 if (getItemFromAgent(_T("Agent.Uptime"), MAX_RESULT_LENGTH, buffer) == DCE_SUCCESS)
1711 {
1712 time_t oldAgentuptime = m_agentUpTime;
1713 m_agentUpTime = _tcstol(buffer, NULL, 0);
1714 if ((UINT32)oldAgentuptime > (UINT32)m_agentUpTime)
1715 {
1716 //cancel file monitoring locally(on agent it is canceled if agent have fallen)
1717 g_monitoringList.removeDisconnectedNode(m_id);
1718 }
1719 }
1720 else
1721 {
1722 DbgPrintf(5, _T("StatusPoll(%s [%d]): unable to get agent uptime"), m_name, m_id);
1723 g_monitoringList.removeDisconnectedNode(m_id);
1724 m_agentUpTime = 0;
1725 }
1726 }
1727 else
1728 {
1729 m_agentUpTime = 0;
1730 }
1731
1732 // Get geolocation
1733 if (!(m_dwDynamicFlags & NDF_UNREACHABLE) && isNativeAgent())
1734 {
1735 TCHAR buffer[MAX_RESULT_LENGTH];
1736 if (getItemFromAgent(_T("GPS.LocationData"), MAX_RESULT_LENGTH, buffer) == DCE_SUCCESS)
1737 {
1738 GeoLocation loc = GeoLocation::parseAgentData(buffer);
1739 if (loc.getType() != GL_UNSET)
1740 {
1741 DbgPrintf(5, _T("StatusPoll(%s [%d]): location set to %s, %s from agent"), m_name, m_id, loc.getLatitudeAsString(), loc.getLongitudeAsString());
1742 lockProperties();
1743 m_geoLocation = loc;
1744 setModified();
1745 unlockProperties();
1746 }
1747 }
1748 else
1749 {
1750 DbgPrintf(5, _T("StatusPoll(%s [%d]): unable to get system location"), m_name, m_id);
1751 }
1752 }
1753
1754 // Get agent log and agent local database status
1755 if (!(m_dwDynamicFlags & NDF_UNREACHABLE) && isNativeAgent())
1756 {
1757 TCHAR buffer[MAX_RESULT_LENGTH];
1758 if (getItemFromAgent(_T("Agent.LogFile.Status"), MAX_RESULT_LENGTH, buffer) == DCE_SUCCESS)
1759 {
1760 UINT32 status = _tcstol(buffer, NULL, 0);
1761 if (status != 0)
1762 PostEvent(EVENT_AGENT_LOG_PROBLEM, m_id, "ds", status, _T("could not open"));
1763 }
1764 else
1765 {
1766 nxlog_debug(5, _T("StatusPoll(%s [%d]): unable to get agent log status"), m_name, m_id);
1767 }
1768
1769 if (getItemFromAgent(_T("Agent.LocalDatabase.Status"), MAX_RESULT_LENGTH, buffer) == DCE_SUCCESS)
1770 {
1771 UINT32 status = _tcstol(buffer, NULL, 0);
1772 const TCHAR *statusDescription[3]= {
1773 _T("normal"),
1774 _T("could not open database"),
1775 _T("could not update database"),
1776 };
1777 if (status != 0)
1778 PostEvent(EVENT_AGENT_LOCAL_DATABASE_PROBLEM, m_id, "ds", status, statusDescription[status]);
1779 }
1780 else
1781 {
1782 nxlog_debug(5, _T("StatusPoll(%s [%d]): unable to get agent local database status"), m_name, m_id);
1783 }
1784 }
1785
1786 // Send delayed events and destroy delayed event queue
1787 if (pQueue != NULL)
1788 {
1789 ResendEvents(pQueue);
1790 delete pQueue;
1791 }
1792
1793 // Call hooks in loaded modules
1794 for(UINT32 i = 0; i < g_dwNumModules; i++)
1795 {
1796 if (g_pModuleList[i].pfStatusPollHook != NULL)
1797 {
1798 DbgPrintf(5, _T("StatusPoll(%s [%d]): calling hook in module %s"), m_name, m_id, g_pModuleList[i].szName);
1799 g_pModuleList[i].pfStatusPollHook(this, pSession, dwRqId, poller);
1800 }
1801 }
1802
1803 // Execute hook script
1804 poller->setStatus(_T("hook"));
1805 executeHookScript(_T("StatusPoll"));
1806
1807 poller->setStatus(_T("cleanup"));
1808 if (pPollerNode != NULL)
1809 pPollerNode->decRefCount();
1810
1811 if (dwOldFlags != m_flags)
1812 {
1813 PostEvent(EVENT_NODE_FLAGS_CHANGED, m_id, "xx", dwOldFlags, m_flags);
1814 lockProperties();
1815 setModified();
1816 unlockProperties();
1817 }
1818
1819 calculateCompoundStatus();
1820 m_lastStatusPoll = time(NULL);
1821 sendPollerMsg(dwRqId, _T("Finished status poll for node %s\r\n"), m_name);
1822 sendPollerMsg(dwRqId, _T("Node status after poll is %s\r\n"), GetStatusAsText(m_status, true));
1823 m_pollRequestor = NULL;
1824 if (dwRqId == 0)
1825 m_dwDynamicFlags &= ~NDF_QUEUED_FOR_STATUS_POLL;
1826 pollerUnlock();
1827 DbgPrintf(5, _T("Finished status poll for node %s (ID: %d)"), m_name, m_id);
1828 }
1829
1830 /**
1831 * Check single element of network path
1832 */
1833 bool Node::checkNetworkPathElement(UINT32 nodeId, const TCHAR *nodeType, bool isProxy, UINT32 requestId, bool secondPass)
1834 {
1835 Node *node = (Node *)FindObjectById(nodeId, OBJECT_NODE);
1836 if (node == NULL)
1837 return false;
1838
1839 nxlog_debug(6, _T("Node::checkNetworkPathElement(%s [%d]): found %s: %s [%d]"), m_name, m_id, nodeType, node->getName(), node->getId());
1840
1841 if (secondPass && (node->m_lastStatusPoll < time(NULL) - 1))
1842 {
1843 DbgPrintf(6, _T("Node::checkNetworkPathElement(%s [%d]): forced status poll on node %s [%d]"),
1844 m_name, m_id, node->getName(), node->getId());
1845 PollerInfo *poller = RegisterPoller(POLLER_TYPE_STATUS, node);
1846 poller->startExecution();
1847 node->statusPoll(NULL, 0, poller);
1848 delete poller;
1849 }
1850
1851 if (node->isDown())
1852 {
1853 DbgPrintf(5, _T("Node::checkNetworkPathElement(%s [%d]): %s %s [%d] is down"),
1854 m_name, m_id, nodeType, node->getName(), node->getId());
1855 sendPollerMsg(requestId, POLLER_WARNING _T(" %s %s is down\r\n"), nodeType, node->getName());
1856 return true;
1857 }
1858 if (isProxy && node->isNativeAgent() && (node->getRuntimeFlags() & NDF_AGENT_UNREACHABLE))
1859 {
1860 DbgPrintf(5, _T("Node::checkNetworkPathElement(%s [%d]): agent on %s %s [%d] is down"),
1861 m_name, m_id, nodeType, node->getName(), node->getId());
1862 sendPollerMsg(requestId, POLLER_WARNING _T(" Agent on %s %s is down\r\n"), nodeType, node->getName());
1863 return true;
1864 }
1865 return false;
1866 }
1867
1868 /**
1869 * Check network path between node and management server to detect possible intermediate node failure - layer 2
1870 *
1871 * @return true if network path problems found
1872 */
1873 bool Node::checkNetworkPathLayer2(UINT32 requestId, bool secondPass)
1874 {
1875 time_t now = time(NULL);
1876
1877 // Check proxy node(s)
1878 if (IsZoningEnabled() && (m_zoneId != 0))
1879 {
1880 Zone *zone = (Zone *)g_idxZoneByGUID.get(m_zoneId);
1881 if ((zone != NULL) && (zone->getProxyNodeId() != 0) && (zone->getProxyNodeId() != m_id))
1882 {
1883 if (checkNetworkPathElement(zone->getProxyNodeId(), _T("zone proxy"), true, requestId, secondPass))
1884 return true;
1885 }
1886 }
1887
1888 // Check directly connected switch
1889 sendPollerMsg(requestId, _T("Checking ethernet connectivity...\r\n"));
1890 Interface *iface = findInterfaceByIP(m_ipAddress);
1891 if (iface != NULL)
1892 {
1893 if (iface->getPeerNodeId() != 0)
1894 {
1895 nxlog_debug(6, _T("Node::checkNetworkPath(%s [%d]): found interface object for primary IP: %s [%d]"), m_name, m_id, iface->getName(), iface->getId());
1896 if (checkNetworkPathElement(iface->getPeerNodeId(), _T("upstream switch"), false, requestId, secondPass))
1897 return true;
1898
1899 Node *switchNode = (Node *)FindObjectById(iface->getPeerNodeId(), OBJECT_NODE);
1900 Interface *switchIface = (Interface *)FindObjectById(iface->getPeerInterfaceId(), OBJECT_INTERFACE);
1901 if ((switchNode != NULL) && (switchIface != NULL) && (switchIface->getExpectedState() != IF_EXPECTED_STATE_IGNORE) &&
1902 ((switchIface->getAdminState() == IF_ADMIN_STATE_DOWN) || (switchIface->getAdminState() == IF_ADMIN_STATE_TESTING) ||
1903 (switchIface->getOperState() == IF_OPER_STATE_DOWN) || (switchIface->getOperState() == IF_OPER_STATE_TESTING)))
1904 {
1905 nxlog_debug(5, _T("Node::checkNetworkPath(%s [%d]): upstream interface %s [%d] on switch %s [%d] is down"),
1906 m_name, m_id, switchIface->getName(), switchIface->getId(), switchNode->getName(), switchNode->getId());
1907 sendPollerMsg(requestId, POLLER_WARNING _T(" Upstream interface %s on node %s is down\r\n"), switchIface->getName(), switchNode->getName());
1908 return true;
1909 }
1910 }
1911 else
1912 {
1913 BYTE localMacAddr[MAC_ADDR_LENGTH];
1914 memcpy(localMacAddr, iface->getMacAddr(), MAC_ADDR_LENGTH);
1915 int type = 0;
1916 NetObj *cp = FindInterfaceConnectionPoint(localMacAddr, &type);
1917 if (cp != NULL)
1918 {
1919 nxlog_debug(6, _T("Node::checkNetworkPath(%s [%d]): found connection point: %s [%d]"), m_name, m_id, cp->getName(), cp->getId());
1920 if (secondPass)
1921 {
1922 Node *node = (cp->getObjectClass() == OBJECT_INTERFACE) ? ((Interface *)cp)->getParentNode() : ((AccessPoint *)cp)->getParentNode();
1923 if ((node != NULL) && !node->isDown() && (node->m_lastStatusPoll < now - 1))
1924 {
1925 nxlog_debug(6, _T("Node::checkNetworkPath(%s [%d]): forced status poll on node %s [%d]"),
1926 m_name, m_id, node->getName(), node->getId());
1927 PollerInfo *poller = RegisterPoller(POLLER_TYPE_STATUS, node);
1928 poller->startExecution();
1929 node->statusPoll(NULL, 0, poller);
1930 delete poller;
1931 }
1932 }
1933
1934 if (cp->getObjectClass() == OBJECT_INTERFACE)
1935 {
1936 Interface *iface = (Interface *)cp;
1937 if ((iface->getExpectedState() != IF_EXPECTED_STATE_IGNORE) &&
1938 ((iface->getAdminState() == IF_ADMIN_STATE_DOWN) || (iface->getAdminState() == IF_ADMIN_STATE_TESTING) ||
1939 (iface->getOperState() == IF_OPER_STATE_DOWN) || (iface->getOperState() == IF_OPER_STATE_TESTING)))
1940 {
1941 nxlog_debug(5, _T("Node::checkNetworkPath(%s [%d]): upstream interface %s [%d] on switch %s [%d] is down"),
1942 m_name, m_id, iface->getName(), iface->getId(), iface->getParentNode()->getName(), iface->getParentNode()->getId());
1943 sendPollerMsg(requestId, POLLER_WARNING _T(" Upstream interface %s on node %s is down\r\n"),
1944 iface->getName(), iface->getParentNode()->getName());
1945 return true;
1946 }
1947 }
1948 else if (cp->getObjectClass() == OBJECT_ACCESSPOINT)
1949 {
1950 AccessPoint *ap = (AccessPoint *)cp;
1951 if (ap->getStatus() == STATUS_CRITICAL) // FIXME: how to correctly determine if AP is down?
1952 {
1953 nxlog_debug(5, _T("Node::checkNetworkPath(%s [%d]): wireless access point %s [%d] is down"),
1954 m_name, m_id, ap->getName(), ap->getId());
1955 sendPollerMsg(requestId, POLLER_WARNING _T(" Wireless access point %s is down\r\n"), ap->getName());
1956 return true;
1957 }
1958 }
1959 }
1960 }
1961 }
1962 else
1963 {
1964 DbgPrintf(5, _T("Node::checkNetworkPath(%s [%d]): cannot find interface object for primary IP"), m_name, m_id);
1965 }
1966 return false;
1967 }
1968
1969 /**
1970 * Check network path between node and management server to detect possible intermediate node failure - layer 3
1971 *
1972 * @return true if network path problems found
1973 */
1974 bool Node::checkNetworkPathLayer3(UINT32 requestId, bool secondPass)
1975 {
1976 Node *mgmtNode = (Node *)FindObjectById(g_dwMgmtNode);
1977 if (mgmtNode == NULL)
1978 {
1979 DbgPrintf(5, _T("Node::checkNetworkPath(%s [%d]): cannot find management node"), m_name, m_id);
1980 return false;
1981 }
1982
1983 NetworkPath *trace = TraceRoute(mgmtNode, this);
1984 if (trace == NULL)
1985 {
1986 DbgPrintf(5, _T("Node::checkNetworkPath(%s [%d]): trace not available"), m_name, m_id);
1987 return false;
1988 }
1989 DbgPrintf(5, _T("Node::checkNetworkPath(%s [%d]): trace available, %d hops, %s"),
1990 m_name, m_id, trace->getHopCount(), trace->isComplete() ? _T("complete") : _T("incomplete"));
1991
1992 // We will do path check in two passes
1993 // If unreachable intermediate node will be found on first pass,
1994 // then method will just return true. Otherwise, we will do
1995 // second pass, this time forcing status poll on each node in the path.
1996 sendPollerMsg(requestId, _T("Checking network path (%s pass)...\r\n"), secondPass ? _T("second") : _T("first"));
1997 bool pathProblemFound = false;
1998 for(int i = 0; i < trace->getHopCount(); i++)
1999 {
2000 HOP_INFO *hop = trace->getHopInfo(i);
2001 if ((hop->object == NULL) || (hop->object == this) || (hop->object->getObjectClass() != OBJECT_NODE))
2002 continue;
2003
2004 // Check for loops
2005 if (i > 0)
2006 {
2007 for(int j = i - 1; j >= 0; j--)
2008 {
2009 HOP_INFO *prevHop = trace->getHopInfo(j);
2010 if (prevHop->object == hop->object)
2011 {
2012 prevHop = trace->getHopInfo(i - 1);
2013 nxlog_debug(5, _T("Node::checkNetworkPath(%s [%d]): routing loop detected on upstream node %s [%d]"),
2014 m_name, m_id, prevHop->object->getName(), prevHop->object->getId());
2015 sendPollerMsg(requestId, POLLER_WARNING _T(" Routing loop detected on upstream node %s\r\n"), prevHop->object->getName());
2016
2017 static const TCHAR *names[] =
2018 { _T("protocol"), _T("destNodeId"), _T("destAddress"),
2019 _T("sourceNodeId"), _T("sourceAddress"), _T("prefix"),
2020 _T("prefixLength"), _T("nextHopNodeId"), _T("nextHopAddress")
2021 };
2022 PostEventWithNames(EVENT_ROUTING_LOOP_DETECTED, prevHop->object->getId(), "siAiAAdiA", names,
2023 (trace->getSourceAddress().getFamily() == AF_INET6) ? _T("IPv6") : _T("IPv4"),
2024 m_id, &m_ipAddress, g_dwMgmtNode, &(trace->getSourceAddress()),
2025 &prevHop->route, prevHop->route.getMaskBits(), hop->object->getId(), &prevHop->nextHop);
2026
2027 pathProblemFound = true;
2028 break;
2029 }
2030 }
2031 if (pathProblemFound)
2032 break;
2033 }
2034
2035 nxlog_debug(6, _T("Node::checkNetworkPath(%s [%d]): checking upstream router %s [%d]"),
2036 m_name, m_id, hop->object->getName(), hop->object->getId());
2037 if (checkNetworkPathElement(hop->object->getId(), _T("upstream router"), false, requestId, secondPass))
2038 {
2039 pathProblemFound = true;
2040 break;
2041 }
2042
2043 if (hop->isVpn)
2044 {
2045 // Next hop is behind VPN tunnel
2046 VPNConnector *vpnConn = (VPNConnector *)FindObjectById(hop->ifIndex, OBJECT_VPNCONNECTOR);
2047 if ((vpnConn != NULL) && (vpnConn->getStatus() == STATUS_CRITICAL))
2048 {
2049 /* TODO: mark as path problem */
2050 }
2051 }
2052 else
2053 {
2054 Interface *iface = ((Node *)hop->object)->findInterfaceByIndex(hop->ifIndex);
2055 if ((iface != NULL) && (iface->getExpectedState() != IF_EXPECTED_STATE_IGNORE) &&
2056 ((iface->getAdminState() == IF_ADMIN_STATE_DOWN) || (iface->getAdminState() == IF_ADMIN_STATE_TESTING) ||
2057 (iface->getOperState() == IF_OPER_STATE_DOWN) || (iface->getOperState() == IF_OPER_STATE_TESTING)))
2058 {
2059 nxlog_debug(5, _T("Node::checkNetworkPath(%s [%d]): upstream interface %s [%d] on node %s [%d] is down"),
2060 m_name, m_id, iface->getName(), iface->getId(), hop->object->getName(), hop->object->getId());
2061 sendPollerMsg(requestId, POLLER_WARNING _T(" Upstream interface %s on node %s is down\r\n"), iface->getName(), hop->object->getName());
2062 break;
2063 }
2064 }
2065 }
2066
2067 delete trace;
2068 return pathProblemFound;
2069 }
2070
2071 /**
2072 * Check network path between node and management server to detect possible intermediate node failure
2073 *
2074 * @return true if network path problems found
2075 */
2076 bool Node::checkNetworkPath(UINT32 requestId)
2077 {
2078 if (checkNetworkPathLayer2(requestId, false))
2079 return true;
2080
2081 if (checkNetworkPathLayer3(requestId, false))
2082 return true;
2083
2084 nxlog_debug(5, _T("Node::checkNetworkPath(%s [%d]): will do second pass"), m_name, m_id);
2085
2086 if (checkNetworkPathLayer2(requestId, true))
2087 return true;
2088
2089 if (checkNetworkPathLayer3(requestId, true))
2090 return true;
2091
2092 return false;
2093 }
2094
2095 /**
2096 * Check agent policy binding
2097 * Intended to be called only from configuration poller
2098 */
2099 void Node::checkAgentPolicyBinding(AgentConnection *conn)
2100 {
2101 AgentPolicyInfo *ap;
2102 UINT32 rcc = conn->getPolicyInventory(&ap);
2103 if (rcc == ERR_SUCCESS)
2104 {
2105 // Check for unbound but installed policies
2106 for(int i = 0; i < ap->size(); i++)
2107 {
2108 uuid guid = ap->getGuid(i);
2109 NetObj *object = FindObjectByGUID(guid, -1);
2110 if ((object != NULL) && (!object->isChild(m_id)))
2111 {
2112 object->addChild(this);
2113 addParent(object);
2114 DbgPrintf(5, _T("ConfPoll(%s): bound to policy object %s [%d]"), m_name, object->getName(), object->getId());
2115 }
2116 }
2117
2118 // Check for bound but not installed policies and schedule it's installation again
2119 //Job will be unbound if it was not possible to add job
2120 lockParentList(false);
2121 NetObj **unbindList = (NetObj **)malloc(sizeof(NetObj *) * m_parentList->size());
2122 int unbindListSize = 0;
2123 for(int i = 0; i < m_parentList->size(); i++)
2124 {
2125 if (IsAgentPolicyObject(m_parentList->get(i)))
2126 {
2127 const uuid& guid = m_parentList->get(i)->getGuid();
2128 int j;
2129 for(j = 0; j < ap->size(); j++)
2130 {
2131 if (ap->getGuid(j).equals(guid))
2132 break;
2133 }
2134 if (j == ap->size())
2135 {
2136 ServerJob *job = new PolicyInstallJob(this, (AgentPolicy *)m_parentList->get(i), 0);
2137 if (AddJob(job))
2138 {
2139 DbgPrintf(5, _T("ConfPoll(%s): \"%s\" policy deploy scheduled for \"%s\" node"), m_name, m_parentList->get(i)->getName(), m_name );
2140 }
2141 else
2142 {
2143 DbgPrintf(5, _T("ConfPoll(%s): \"%s\" policy deploy is not possible to scheduled for \"%s\" node"), m_name, m_parentList->get(i)->getName(), m_name);
2144 delete job;
2145 unbindList[unbindListSize++] = m_parentList->get(i);
2146 }
2147 }
2148 }
2149 }
2150 unlockParentList();
2151
2152 for(int i = 0; i < unbindListSize; i++)
2153 {
2154 unbindList[i]->deleteChild(this);
2155 deleteParent(unbindList[i]);
2156 DbgPrintf(5, _T("ConfPoll(%s): unbound from policy object %s [%d]"), m_name, unbindList[i]->getName(), unbindList[i]->getId());
2157 }
2158 safe_free(unbindList);
2159
2160 delete ap;
2161 }
2162 else
2163 {
2164 DbgPrintf(5, _T("ConfPoll(%s): AgentConnection::getPolicyInventory() failed: rcc=%d"), m_name, rcc);
2165 }
2166 }
2167
2168 /**
2169 * Update primary IP address from primary name
2170 */
2171 void Node::updatePrimaryIpAddr()
2172 {
2173 if (m_primaryName[0] == 0)
2174 return;
2175
2176 InetAddress ipAddr = ResolveHostName(m_zoneId, m_primaryName);
2177 if (!ipAddr.equals(m_ipAddress) && (ipAddr.isValidUnicast() || !_tcscmp(m_primaryName, _T("0.0.0.0"))))
2178 {
2179 TCHAR buffer1[64], buffer2[64];
2180
2181 DbgPrintf(4, _T("IP address for node %s [%d] changed from %s to %s"),
2182 m_name, (int)m_id, m_ipAddress.toString(buffer1), ipAddr.toString(buffer2));
2183 PostEvent(EVENT_IP_ADDRESS_CHANGED, m_id, "AA", &ipAddr, &m_ipAddress);
2184
2185 if (m_flags & NF_REMOTE_AGENT)
2186 {
2187 lockProperties();
2188 m_ipAddress = ipAddr;
2189 setModified();
2190 unlockProperties();
2191 }
2192 else
2193 {
2194 setPrimaryIPAddress(ipAddr);
2195 }
2196
2197 agentLock();
2198 deleteAgentConnection();
2199 agentUnlock();
2200 }
2201 }
2202
2203 /**
2204 * Comparator for package names
2205 */
2206 static int PackageNameComparator(const SoftwarePackage **p1, const SoftwarePackage **p2)
2207 {
2208 return _tcscmp((*p1)->getName(), (*p2)->getName());
2209 }
2210
2211 /**
2212 * Update list of software packages for node
2213 */
2214 bool Node::updateSoftwarePackages(PollerInfo *poller, UINT32 requestId)
2215 {
2216 if (!(m_flags & NF_IS_NATIVE_AGENT))
2217 return false;
2218
2219 poller->setStatus(_T("software check"));
2220 sendPollerMsg(requestId, _T("Reading list of installed software packages\r\n"));
2221
2222 Table *table;
2223 if (getTableFromAgent(_T("System.InstalledProducts"), &table) != DCE_SUCCESS)
2224 {
2225 sendPollerMsg(requestId, POLLER_WARNING _T("Unable to get information about installed software packages\r\n"));
2226 return false;
2227 }
2228
2229 ObjectArray<SoftwarePackage> *packages = new ObjectArray<SoftwarePackage>(table->getNumRows(), 16, true);
2230 for(int i = 0; i < table->getNumRows(); i++)
2231 packages->add(new SoftwarePackage(table, i));
2232 packages->sort(PackageNameComparator);
2233 delete table;
2234 sendPollerMsg(requestId, POLLER_INFO _T("Got information about %d installed software packages\r\n"), packages->size());
2235
2236 lockProperties();
2237 if (m_softwarePackages != NULL)
2238 {
2239 // Check for removed and updated packages
2240 for(int i = 0; i < m_softwarePackages->size(); i++)
2241 {
2242 SoftwarePackage *p = m_softwarePackages->get(i);
2243 SoftwarePackage *np = (SoftwarePackage *)packages->find(p, PackageNameComparator);
2244 if (np != NULL)
2245 {
2246 if (_tcscmp(p->getVersion(), np->getVersion()))
2247 {
2248 nxlog_debug(5, _T("ConfPoll(%s): package %s updated (%s -> %s)"), m_name, p->getName(), p->getVersion(), np->getVersion());
2249 sendPollerMsg(requestId, _T(" Package %s updated (%s -> %s)\r\n"), p->getName(), p->getVersion(), np->getVersion());
2250
2251 static const TCHAR *names[] = { _T("name"), _T("version"), _T("previousVersion") };
2252 PostEventWithNames(EVENT_PACKAGE_UPDATED, m_id, "sss", names, p->getName(), np->getVersion(), p->getVersion());
2253 }
2254 }
2255 else
2256 {
2257 nxlog_debug(5, _T("ConfPoll(%s): package %s removed (last installed version was %s)"), m_name, p->getName(), p->getVersion());
2258 sendPollerMsg(requestId, _T(" Package %s removed (last installed version was %s)\r\n"), p->getName(), p->getVersion());
2259
2260 static const TCHAR *names[] = { _T("name"), _T("version") };
2261 PostEventWithNames(EVENT_PACKAGE_REMOVED, m_id, "ss", names, p->getName(), p->getVersion());
2262 }
2263 }
2264
2265 // Check for new packages
2266 for(int i = 0; i < packages->size(); i++)
2267 {
2268 SoftwarePackage *p = packages->get(i);
2269 if (m_softwarePackages->find(p, PackageNameComparator) == NULL)
2270 {
2271 nxlog_debug(5, _T("ConfPoll(%s): new package %s (version %s)"), m_name, p->getName(), p->getVersion());
2272 sendPollerMsg(requestId, _T(" New package %s (version %s)\r\n"), p->getName(), p->getVersion());
2273
2274 static const TCHAR *names[] = { _T("name"), _T("version") };
2275 PostEventWithNames(EVENT_PACKAGE_INSTALLED, m_id, "ss", names, p->getName(), p->getVersion());
2276 }
2277 }
2278
2279 delete m_softwarePackages;
2280 }
2281 m_softwarePackages = packages;
2282 unlockProperties();
2283 return true;
2284 }
2285
2286 /**
2287 * Entry point for configuration poller
2288 */
2289 void Node::configurationPoll(PollerInfo *poller)
2290 {
2291 poller->startExecution();
2292 ObjectTransactionStart();
2293 configurationPoll(NULL, 0, poller, 0);
2294 ObjectTransactionEnd();
2295 delete poller;
2296 }
2297
2298 /**
2299 * Perform configuration poll on node
2300 */
2301 void Node::configurationPoll(ClientSession *pSession, UINT32 dwRqId, PollerInfo *poller, int maskBits)
2302 {
2303 if (m_dwDynamicFlags & NDF_DELETE_IN_PROGRESS)
2304 {
2305 if (dwRqId == 0)
2306 m_dwDynamicFlags &= ~NDF_QUEUED_FOR_CONFIG_POLL;
2307 return;
2308 }
2309
2310 if (IsShutdownInProgress())
2311 return;
2312
2313 UINT32 dwOldFlags = m_flags;
2314 TCHAR szBuffer[4096];
2315 bool hasChanges = false;
2316
2317 poller->setStatus(_T("wait for lock"));
2318 pollerLock();
2319
2320 if (IsShutdownInProgress())
2321 {
2322 pollerUnlock();
2323 return;
2324 }
2325
2326 m_pollRequestor = pSession;
2327 sendPollerMsg(dwRqId, _T("Starting configuration poll for node %s\r\n"), m_name);
2328 nxlog_debug(4, _T("Starting configuration poll for node %s (ID: %d)"), m_name, m_id);
2329
2330 // Check for forced capabilities recheck
2331 if (m_dwDynamicFlags & NDF_RECHECK_CAPABILITIES)
2332 {
2333 sendPollerMsg(dwRqId, POLLER_WARNING _T("Capability reset\r\n"));
2334 m_flags &= ~(NF_IS_NATIVE_AGENT | NF_IS_SNMP | NF_IS_CPSNMP |
2335 NF_IS_BRIDGE | NF_IS_ROUTER | NF_IS_OSPF | NF_IS_PRINTER |
2336 NF_IS_CDP | NF_IS_LLDP | NF_IS_SONMP | NF_IS_VRRP | NF_HAS_VLANS |
2337 NF_IS_8021X | NF_IS_STP | NF_HAS_ENTITY_MIB | NF_HAS_IFXTABLE |
2338 NF_HAS_WINPDH);
2339 m_dwDynamicFlags &= ~NDF_CONFIGURATION_POLL_PASSED;
2340 m_snmpObjectId[0] = 0;
2341 m_platformName[0] = 0;
2342 m_agentVersion[0] = 0;
2343 safe_free_and_null(m_sysDescription);
2344 safe_free_and_null(m_sysName);
2345 safe_free_and_null(m_sysContact);
2346 safe_free_and_null(m_sysLocation);
2347 safe_free_and_null(m_lldpNodeId);
2348 }
2349
2350 // Check if node is marked as unreachable
2351 if ((m_dwDynamicFlags & NDF_UNREACHABLE) && !(m_dwDynamicFlags & NDF_RECHECK_CAPABILITIES))
2352 {
2353 sendPollerMsg(dwRqId, POLLER_WARNING _T("Node is marked as unreachable, configuration poll aborted\r\n"));
2354 DbgPrintf(4, _T("Node is marked as unreachable, configuration poll aborted"));
2355 m_lastConfigurationPoll = time(NULL);
2356 }
2357 else
2358 {
2359 updatePrimaryIpAddr();
2360
2361 poller->setStatus(_T("capability check"));
2362 sendPollerMsg(dwRqId, _T("Checking node's capabilities...\r\n"));
2363
2364 if (confPollAgent(dwRqId))
2365 hasChanges = true;
2366 if (confPollSnmp(dwRqId))
2367 hasChanges = true;
2368
2369 // Check for CheckPoint SNMP agent on port 260
2370 if (ConfigReadInt(_T("EnableCheckPointSNMP"), 0))
2371 {
2372 nxlog_debug(5, _T("ConfPoll(%s): checking for CheckPoint SNMP on port 260"), m_name);
2373 if (!((m_flags & NF_IS_CPSNMP) && (m_dwDynamicFlags & NDF_CPSNMP_UNREACHABLE)) && m_ipAddress.isValidUnicast())
2374 {
2375 SNMP_Transport *pTransport = new SNMP_UDPTransport;
2376 ((SNMP_UDPTransport *)pTransport)->createUDPTransport(m_ipAddress, CHECKPOINT_SNMP_PORT);
2377 if (SnmpGet(SNMP_VERSION_1, pTransport,
2378 _T(".1.3.6.1.4.1.2620.1.1.10.0"), NULL, 0, szBuffer, sizeof(szBuffer), 0) == SNMP_ERR_SUCCESS)
2379 {
2380 lockProperties();
2381 m_flags |= NF_IS_CPSNMP | NF_IS_ROUTER;
2382 m_dwDynamicFlags &= ~NDF_CPSNMP_UNREACHABLE;
2383 unlockProperties();
2384 sendPollerMsg(dwRqId, POLLER_INFO _T(" CheckPoint SNMP agent on port 260 is active\r\n"));
2385 }
2386 delete pTransport;
2387 }
2388 }
2389
2390 // Generate event if node flags has been changed
2391 if (dwOldFlags != m_flags)
2392 {
2393 PostEvent(EVENT_NODE_FLAGS_CHANGED, m_id, "xx", dwOldFlags, m_flags);
2394 hasChanges = true;
2395 }
2396
2397 // Retrieve interface list
2398 poller->setStatus(_T("interface check"));
2399 sendPollerMsg(dwRqId, _T("Capability check finished\r\n"));
2400
2401 if (updateInterfaceConfiguration(dwRqId, maskBits))
2402 hasChanges = true;
2403
2404 m_lastConfigurationPoll = time(NULL);
2405
2406 // Check node name
2407 sendPollerMsg(dwRqId, _T("Checking node name\r\n"));
2408 UINT32 dwAddr = ntohl(_t_inet_addr(m_name));
2409 if ((g_flags & AF_RESOLVE_NODE_NAMES) &&
2410 (dwAddr != INADDR_NONE) &&
2411 (dwAddr != INADDR_ANY) &&
2412 isMyIP(dwAddr))
2413 {
2414 sendPollerMsg(dwRqId, _T("Node name is an IP address and need to be resolved\r\n"));
2415 poller->setStatus(_T("resolving name"));
2416 if (resolveName(FALSE))
2417 {
2418 sendPollerMsg(dwRqId, POLLER_INFO _T("Node name resolved to %s\r\n"), m_name);
2419 hasChanges = true;
2420 }
2421 else
2422 {
2423 sendPollerMsg(dwRqId, POLLER_WARNING _T("Node name cannot be resolved\r\n"));
2424 }
2425 }
2426 else
2427 {
2428 if (g_flags & AF_SYNC_NODE_NAMES_WITH_DNS)
2429 {
2430 sendPollerMsg(dwRqId, _T("Syncing node name with DNS\r\n"));
2431 poller->setStatus(_T("resolving name"));
2432 if (resolveName(TRUE))
2433 {
2434 sendPollerMsg(dwRqId, POLLER_INFO _T("Node name resolved to %s\r\n"), m_name);
2435 hasChanges = true;
2436 }
2437 }
2438 else
2439 {
2440 sendPollerMsg(dwRqId, _T("Node name is OK\r\n"));
2441 }
2442 }
2443
2444 applyUserTemplates();
2445 updateContainerMembership();
2446 updateSoftwarePackages(poller, dwRqId);
2447
2448 // Call hooks in loaded modules
2449 for(UINT32 i = 0; i < g_dwNumModules; i++)
2450 {
2451 if (g_pModuleList[i].pfConfPollHook != NULL)
2452 {
2453 DbgPrintf(5, _T("ConfigurationPoll(%s [%d]): calling hook in module %s"), m_name, m_id, g_pModuleList[i].szName);
2454 if (g_pModuleList[i].pfConfPollHook(this, pSession, dwRqId, poller))
2455 hasChanges = true;
2456 }
2457 }
2458
2459 // Setup permanent connection to agent if not present (needed for proper configuration re-sync)
2460 if (m_flags & NF_IS_NATIVE_AGENT)
2461 {
2462 agentLock();
2463 connectToAgent();
2464 agentUnlock();
2465 }
2466
2467 // Update node type
2468 NodeType type = detectNodeType();
2469 nxlog_debug(5, _T("ConfPoll(%s): detected node type: %d (%s)"), m_name, type, typeName(type));
2470 lockProperties();
2471 if ((type != NODE_TYPE_UNKNOWN) && (type != m_type))
2472 {
2473 m_type = type;
2474 hasChanges = true;
2475 nxlog_debug(5, _T("ConfPoll(%s): node type set to %d (%s)"), m_name, type, typeName(type));
2476 sendPollerMsg(dwRqId, _T(" Node type changed to %s\r\n"), typeName(type));
2477 }
2478 unlockProperties();
2479
2480 // Execute hook script
2481 poller->setStatus(_T("hook"));
2482 executeHookScript(_T("ConfigurationPoll"));
2483
2484 sendPollerMsg(dwRqId, _T("Finished configuration poll for node %s\r\n"), m_name);
2485 sendPollerMsg(dwRqId, _T("Node configuration was%schanged after poll\r\n"), hasChanges ? _T(" ") : _T(" not "));
2486
2487 m_dwDynamicFlags |= NDF_CONFIGURATION_POLL_PASSED;
2488 }
2489
2490 // Finish configuration poll
2491 poller->setStatus(_T("cleanup"));
2492 if (dwRqId == 0)
2493 m_dwDynamicFlags &= ~NDF_QUEUED_FOR_CONFIG_POLL;
2494 m_dwDynamicFlags &= ~NDF_RECHECK_CAPABILITIES;
2495 pollerUnlock();
2496 DbgPrintf(4, _T("Finished configuration poll for node %s (ID: %d)"), m_name, m_id);
2497
2498 if (hasChanges)
2499 {
2500 lockProperties();
2501 setModified();
2502 unlockProperties();
2503 }
2504 }
2505
2506 /**
2507 * Detect node type
2508 */
2509 NodeType Node::detectNodeType()
2510 {
2511 NodeType type = NODE_TYPE_UNKNOWN;
2512 if (m_flags & NF_IS_SNMP)
2513 {
2514 nxlog_debug(6, _T("Node::detectNodeType(%s [%d]): SNMP node, driver name is %s"), m_name, m_id, m_driver->getName());
2515
2516 // Assume physical device if it supports SNMP and driver is not "GENERIC"
2517 // FIXME: add driver method to determine node type
2518 if (_tcscmp(m_driver->getName(), _T("GENERIC")))
2519 {
2520 type = NODE_TYPE_PHYSICAL;
2521 }
2522 else
2523 {
2524 if (m_flags & NF_IS_PRINTER)
2525 {
2526 // Assume that printers are physical devices
2527 type = NODE_TYPE_PHYSICAL;
2528 }
2529 }
2530 }
2531 return type;
2532 }
2533
2534 /**
2535 * Configuration poll: check for NetXMS agent
2536 */
2537 bool Node::confPollAgent(UINT32 dwRqId)
2538 {
2539 nxlog_debug(5, _T("ConfPoll(%s): checking for NetXMS agent Flags={%08X} DynamicFlags={%08X}"), m_name, m_flags, m_dwDynamicFlags);
2540 if (((m_flags & NF_IS_NATIVE_AGENT) && (m_dwDynamicFlags & NDF_AGENT_UNREACHABLE)) || (m_flags & NF_DISABLE_NXCP))
2541 return false;
2542
2543 bool hasChanges = false;
2544
2545 sendPollerMsg(dwRqId, _T(" Checking NetXMS agent...\r\n"));
2546 AgentTunnel *tunnel = GetTunnelForNode(m_id);
2547 AgentConnectionEx *pAgentConn;
2548 if (tunnel != NULL)
2549 {
2550 pAgentConn = new AgentConnectionEx(m_id, tunnel, m_agentAuthMethod, m_szSharedSecret, isAgentCompressionAllowed());
2551 tunnel->decRefCount();
2552 }
2553 else
2554 {
2555 if (!m_ipAddress.isValidUnicast())
2556 {
2557 sendPollerMsg(dwRqId, POLLER_ERROR _T(" Node primary IP is invalid and there are no active tunnels\r\n"));
2558 nxlog_debug(5, _T("ConfPoll(%s): node primary IP is invalid and there are no active tunnels"), m_name);
2559 return false;
2560 }
2561 pAgentConn = new AgentConnectionEx(m_id, m_ipAddress, m_agentPort, m_agentAuthMethod, m_szSharedSecret, isAgentCompressionAllowed());
2562 setAgentProxy(pAgentConn);
2563 }
2564 pAgentConn->setCommandTimeout(g_agentCommandTimeout);
2565 nxlog_debug(5, _T("ConfPoll(%s): checking for NetXMS agent - connecting"), m_name);
2566
2567 // Try to connect to agent
2568 UINT32 rcc;
2569 if (!pAgentConn->connect(g_pServerKey, &rcc))
2570 {
2571 // If there are authentication problem, try default shared secret
2572 if ((rcc == ERR_AUTH_REQUIRED) || (rcc == ERR_AUTH_FAILED))
2573 {
2574 TCHAR secret[MAX_SECRET_LENGTH];
2575 ConfigReadStr(_T("AgentDefaultSharedSecret"), secret, MAX_SECRET_LENGTH, _T("netxms"));
2576 DecryptPassword(_T("netxms"), secret, secret, MAX_SECRET_LENGTH);
2577 pAgentConn->setAuthData(AUTH_SHA1_HASH, secret);
2578 if (pAgentConn->connect(g_pServerKey, &rcc))
2579 {
2580 m_agentAuthMethod = AUTH_SHA1_HASH;
2581 nx_strncpy(m_szSharedSecret, secret, MAX_SECRET_LENGTH);
2582 nxlog_debug(5, _T("ConfPoll(%s): checking for NetXMS agent - shared secret changed to system default"), m_name);
2583 }
2584 }
2585 }
2586
2587 if (rcc == ERR_SUCCESS)
2588 {
2589 nxlog_debug(5, _T("ConfPoll(%s): checking for NetXMS agent - connected"), m_name);
2590 lockProperties();
2591 m_flags |= NF_IS_NATIVE_AGENT;
2592 if (m_dwDynamicFlags & NDF_AGENT_UNREACHABLE)
2593 {
2594 m_dwDynamicFlags &= ~NDF_AGENT_UNREACHABLE;
2595 PostEvent(EVENT_AGENT_OK, m_id, NULL);
2596 sendPollerMsg(dwRqId, POLLER_INFO _T(" Connectivity with NetXMS agent restored\r\n"));
2597 }
2598 else
2599 {
2600 sendPollerMsg(dwRqId, POLLER_INFO _T(" NetXMS native agent is active\r\n"));
2601 }
2602 unlockProperties();
2603
2604 TCHAR buffer[MAX_RESULT_LENGTH];
2605 if (pAgentConn->getParameter(_T("Agent.Version"), MAX_AGENT_VERSION_LEN, buffer) == ERR_SUCCESS)
2606 {
2607 lockProperties();
2608 if (_tcscmp(m_agentVersion, buffer))
2609 {
2610 _tcscpy(m_agentVersion, buffer);
2611 hasChanges = true;
2612 sendPollerMsg(dwRqId, _T(" NetXMS agent version changed to %s\r\n"), m_agentVersion);
2613 }
2614 unlockProperties();
2615 }
2616
2617 if (pAgentConn->getParameter(_T("System.PlatformName"), MAX_PLATFORM_NAME_LEN, buffer) == ERR_SUCCESS)
2618 {
2619 lockProperties();
2620 if (_tcscmp(m_platformName, buffer))
2621 {
2622 _tcscpy(m_platformName, buffer);
2623 hasChanges = true;
2624 sendPollerMsg(dwRqId, _T(" Platform name changed to %s\r\n"), m_platformName);
2625 }
2626 unlockProperties();
2627 }
2628
2629 // Check IP forwarding status
2630 if (pAgentConn->getParameter(_T("Net.IP.Forwarding"), 16, buffer) == ERR_SUCCESS)
2631 {
2632 if (_tcstoul(buffer, NULL, 10) != 0)
2633 m_flags |= NF_IS_ROUTER;
2634 else
2635 m_flags &= ~NF_IS_ROUTER;
2636 }
2637
2638 // Get uname
2639 if (pAgentConn->getParameter(_T("System.Uname"), MAX_DB_STRING, buffer) == ERR_SUCCESS)
2640 {
2641 TranslateStr(buffer, _T("\r\n"), _T(" "));
2642 TranslateStr(buffer, _T("\n"), _T(" "));
2643 TranslateStr(buffer, _T("\r"), _T(" "));
2644 lockProperties();
2645 if ((m_sysDescription == NULL) || _tcscmp(m_sysDescription, buffer))
2646 {
2647 safe_free(m_sysDescription);
2648 m_sysDescription = _tcsdup(buffer);
2649 hasChanges = true;
2650 sendPollerMsg(dwRqId, _T(" System description changed to %s\r\n"), m_sysDescription);
2651 }
2652 unlockProperties();
2653 }
2654
2655 // Check for 64 bit counter support.
2656 // if Net.Interface.64BitCounters not supported by agent then use
2657 // only presence of 64 bit parameters as indicator
2658 bool netIf64bitCounters = true;
2659 if (pAgentConn->getParameter(_T("Net.Interface.64BitCounters"), MAX_DB_STRING, buffer) == ERR_SUCCESS)
2660 {
2661 netIf64bitCounters = _tcstol(buffer, NULL, 10) ? true : false;
2662 }
2663
2664 ObjectArray<AgentParameterDefinition> *plist;
2665 ObjectArray<AgentTableDefinition> *tlist;
2666 UINT32 rcc = pAgentConn->getSupportedParameters(&plist, &tlist);
2667 if (rcc == ERR_SUCCESS)
2668 {
2669 lockProperties();
2670 delete m_paramList;
2671 delete m_tableList;
2672 m_paramList = plist;
2673 m_tableList = tlist;
2674
2675 // Check for 64-bit interface counters
2676 m_flags &= ~NF_HAS_AGENT_IFXCOUNTERS;
2677 if (netIf64bitCounters)
2678 {
2679 for(int i = 0; i < plist->size(); i++)
2680 {
2681 if (!_tcsicmp(plist->get(i)->getName(), _T("Net.Interface.BytesIn64(*)")))
2682 {
2683 m_flags |= NF_HAS_AGENT_IFXCOUNTERS;
2684 break;
2685 }
2686 }
2687 }
2688
2689 unlockProperties();
2690 }
2691 else
2692 {
2693 DbgPrintf(5, _T("ConfPoll(%s): AgentConnection::getSupportedParameters() failed: rcc=%d"), m_name, rcc);
2694 }
2695
2696 // Get supported Windows Performance Counters
2697 if (!_tcsncmp(m_platformName, _T("windows-"), 8))
2698 {
2699 sendPollerMsg(dwRqId, _T(" Reading list of available Windows Performance Counters...\r\n"));
2700 ObjectArray<WinPerfObject> *perfObjects = WinPerfObject::getWinPerfObjectsFromNode(this, pAgentConn);
2701 lockProperties();
2702 delete m_winPerfObjects;
2703 m_winPerfObjects = perfObjects;
2704 if (m_winPerfObjects != NULL)
2705 {
2706 sendPollerMsg(dwRqId, POLLER_INFO _T(" %d counters read\r\n"), m_winPerfObjects->size());
2707 if (!(m_flags & NF_HAS_WINPDH))
2708 {
2709 m_flags |= NF_HAS_WINPDH;
2710 hasChanges = true;
2711 }
2712 }
2713 else
2714 {
2715 sendPollerMsg(dwRqId, POLLER_ERROR _T(" unable to get Windows Performance Counters list\r\n"));
2716 if (m_flags & NF_HAS_WINPDH)
2717 {
2718 m_flags &= ~NF_HAS_WINPDH;
2719 hasChanges = true;
2720 }
2721 }
2722 unlockProperties();
2723 }
2724
2725 checkAgentPolicyBinding(pAgentConn);
2726
2727 pAgentConn->disconnect();
2728 }
2729 else
2730 {
2731 nxlog_debug(5, _T("ConfPoll(%s): checking for NetXMS agent - failed to connect (error %d)"), m_name, rcc);
2732 }
2733 pAgentConn->decRefCount();
2734 nxlog_debug(5, _T("ConfPoll(%s): checking for NetXMS agent - finished"), m_name);
2735 return hasChanges;
2736 }
2737
2738 /**
2739 * SNMP walker callback which sets indicator to true after first varbind and aborts walk
2740 */
2741 static UINT32 IndicatorSnmpWalkerCallback(SNMP_Variable *var, SNMP_Transport *transport, void *arg)
2742 {
2743 (*((bool *)arg)) = true;
2744 return SNMP_ERR_COMM;
2745 }
2746
2747 /**
2748 * Configuration poll: check for SNMP
2749 */
2750 bool Node::confPollSnmp(UINT32 dwRqId)
2751 {
2752 if (((m_flags & NF_IS_SNMP) && (m_dwDynamicFlags & NDF_SNMP_UNREACHABLE)) ||
2753 !m_ipAddress.isValidUnicast() || (m_flags & NF_DISABLE_SNMP))
2754 return false;
2755
2756 bool hasChanges = false;
2757
2758 sendPollerMsg(dwRqId, _T(" Checking SNMP...\r\n"));
2759 DbgPrintf(5, _T("ConfPoll(%s): calling SnmpCheckCommSettings()"), m_name);
2760 StringList oids;
2761 const TCHAR *customOid = m_customAttributes.get(_T("snmp.testoid"));
2762 if (customOid != NULL)
2763 oids.add(customOid);
2764 oids.add(_T(".1.3.6.1.2.1.1.2.0"));
2765 oids.add(_T(".1.3.6.1.2.1.1.1.0"));
2766 AddDriverSpecificOids(&oids);
2767 SNMP_Transport *pTransport = SnmpCheckCommSettings(getEffectiveSnmpProxy(), (getEffectiveSnmpProxy() == m_id) ? InetAddress::LOOPBACK : m_ipAddress, &m_snmpVersion, m_snmpPort, m_snmpSecurity, &oids);
2768 if (pTransport == NULL)
2769 {
2770 DbgPrintf(5, _T("ConfPoll(%s): unable to create SNMP transport"), m_name);
2771 return false;
2772 }
2773
2774 lockProperties();
2775 m_snmpPort = pTransport->getPort();
2776 delete m_snmpSecurity;
2777 m_snmpSecurity = new SNMP_SecurityContext(pTransport->getSecurityContext());
2778 m_flags |= NF_IS_SNMP;
2779 if (m_dwDynamicFlags & NDF_SNMP_UNREACHABLE)
2780 {
2781 m_dwDynamicFlags &= ~NDF_SNMP_UNREACHABLE;
2782 PostEvent(EVENT_SNMP_OK, m_id, NULL);
2783 sendPollerMsg(dwRqId, POLLER_INFO _T(" Connectivity with SNMP agent restored\r\n"));
2784 }
2785 unlockProperties();
2786 sendPollerMsg(dwRqId, _T(" SNMP agent is active (version %s)\r\n"),
2787 (m_snmpVersion == SNMP_VERSION_3) ? _T("3") : ((m_snmpVersion == SNMP_VERSION_2C) ? _T("2c") : _T("1")));
2788
2789 TCHAR szBuffer[4096];
2790 if (SnmpGet(m_snmpVersion, pTransport, _T(".1.3.6.1.2.1.1.2.0"), NULL, 0, szBuffer, sizeof(szBuffer), SG_STRING_RESULT) != SNMP_ERR_SUCCESS)
2791 {
2792 // Set snmp object ID to .0.0 if it cannot be read
2793 _tcscpy(szBuffer, _T(".0.0"));
2794 }
2795 lockProperties();
2796 if (_tcscmp(m_snmpObjectId, szBuffer))
2797 {
2798 nx_strncpy(m_snmpObjectId, szBuffer, MAX_OID_LEN * 4);
2799 hasChanges = true;
2800 }
2801 unlockProperties();
2802
2803 // Get system description
2804 if (SnmpGet(m_snmpVersion, pTransport, _T(".1.3.6.1.2.1.1.1.0"), NULL, 0, szBuffer, sizeof(szBuffer), SG_STRING_RESULT) == SNMP_ERR_SUCCESS)
2805 {
2806 TranslateStr(szBuffer, _T("\r\n"), _T(" "));
2807 TranslateStr(szBuffer, _T("\n"), _T(" "));
2808 TranslateStr(szBuffer, _T("\r"), _T(" "));
2809 lockProperties();
2810 if ((m_sysDescription == NULL) || _tcscmp(m_sysDescription, szBuffer))
2811 {
2812 free(m_sysDescription);
2813 m_sysDescription = _tcsdup(szBuffer);
2814 hasChanges = true;
2815 sendPollerMsg(dwRqId, _T(" System description changed to %s\r\n"), m_sysDescription);
2816 }
2817 unlockProperties();
2818 }
2819
2820 // Select device driver
2821 NetworkDeviceDriver *driver = FindDriverForNode(this, pTransport);
2822 DbgPrintf(5, _T("ConfPoll(%s): selected device driver %s"), m_name, driver->getName());
2823 lockProperties();
2824 if (driver != m_driver)
2825 {
2826 m_driver = driver;
2827 sendPollerMsg(dwRqId, _T(" New network device driver selected: %s\r\n"), m_driver->getName());
2828 }
2829 unlockProperties();
2830
2831 // Allow driver to gather additional info
2832 m_driver->analyzeDevice(pTransport, m_snmpObjectId, &m_customAttributes, &m_driverData);
2833 NDD_MODULE_LAYOUT layout;
2834 m_driver->getModuleLayout(pTransport, &m_customAttributes, m_driverData, 1, &layout); // TODO module set to 1
2835 if (layout.numberingScheme == NDD_PN_UNKNOWN)
2836 {
2837 // Try to find port numbering information in database
2838 LookupDevicePortLayout(SNMP_ObjectId::parse(m_snmpObjectId), &layout);
2839 }
2840 m_portRowCount = layout.rows;
2841 m_portNumberingScheme = layout.numberingScheme;
2842
2843 // Get sysName, sysContact, sysLocation
2844 if (querySnmpSysProperty(pTransport, _T(".1.3.6.1.2.1.1.5.0"), _T("name"), dwRqId, &m_sysName))
2845 hasChanges = true;
2846 if (querySnmpSysProperty(pTransport, _T(".1.3.6.1.2.1.1.4.0"), _T("contact"), dwRqId, &m_sysContact))
2847 hasChanges = true;
2848 if (querySnmpSysProperty(pTransport, _T(".1.3.6.1.2.1.1.6.0"), _T("location"), dwRqId, &m_sysLocation))
2849 hasChanges = true;
2850
2851 // Check IP forwarding
2852 if (checkSNMPIntegerValue(pTransport, _T(".1.3.6.1.2.1.4.1.0"), 1))
2853 {
2854 lockProperties();
2855 m_flags |= NF_IS_ROUTER;
2856 unlockProperties();
2857 }
2858 else
2859 {
2860 lockProperties();
2861 m_flags &= ~NF_IS_ROUTER;
2862 unlockProperties();
2863 }
2864
2865 checkIfXTable(pTransport);
2866 checkBridgeMib(pTransport);
2867
2868 // Check for ENTITY-MIB support
2869 if (SnmpGet(m_snmpVersion, pTransport, _T(".1.3.6.1.2.1.47.1.4.1.0"), NULL, 0, szBuffer, sizeof(szBuffer), SG_RAW_RESULT) == SNMP_ERR_SUCCESS)
2870 {
2871 lockProperties();
2872 m_flags |= NF_HAS_ENTITY_MIB;
2873 unlockProperties();
2874
2875 ComponentTree *components = BuildComponentTree(this, pTransport);
2876 lockProperties();
2877 if (m_components != NULL)
2878 m_components->decRefCount();
2879 m_components = components;
2880 unlockProperties();
2881 }
2882 else
2883 {
2884 lockProperties();
2885 m_flags &= ~NF_HAS_ENTITY_MIB;
2886 if (m_components != NULL)
2887 {
2888 m_components->decRefCount();
2889 m_components = NULL;
2890 }
2891 unlockProperties();
2892 }
2893
2894 // Check for printer MIB support
2895 bool present = false;
2896 SnmpWalk(pTransport, _T(".1.3.6.1.2.1.43"), IndicatorSnmpWalkerCallback, &present);
2897 if (present)
2898 {
2899 lockProperties();
2900 m_flags |= NF_IS_PRINTER;
2901 unlockProperties();
2902 }
2903 else
2904 {
2905 lockProperties();
2906 m_flags &= ~NF_IS_PRINTER;
2907 unlockProperties();
2908 }
2909
2910 // Check for CDP (Cisco Discovery Protocol) support
2911 if (checkSNMPIntegerValue(pTransport, _T(".1.3.6.1.4.1.9.9.23.1.3.1.0"), 1))
2912 {
2913 lockProperties();
2914 m_flags |= NF_IS_CDP;
2915 unlockProperties();
2916 }
2917 else
2918 {
2919 lockProperties();
2920 m_flags &= ~NF_IS_CDP;
2921 unlockProperties();
2922 }
2923
2924 // Check for NDP (Nortel Discovery Protocol) support
2925 if (checkSNMPIntegerValue(pTransport, _T(".1.3.6.1.4.1.45.1.6.13.1.2.0"), 1))
2926 {
2927 lockProperties();
2928 m_flags |= NF_IS_NDP;
2929 unlockProperties();
2930 }
2931 else
2932 {
2933 lockProperties();
2934 m_flags &= ~NF_IS_NDP;
2935 unlockProperties();
2936 }
2937
2938 // Check for LLDP (Link Layer Discovery Protocol) support
2939 if (SnmpGet(m_snmpVersion, pTransport, _T(".1.0.8802.1.1.2.1.3.2.0"), NULL, 0, szBuffer, sizeof(szBuffer), 0) == SNMP_ERR_SUCCESS)
2940 {
2941 lockProperties();
2942 m_flags |= NF_IS_LLDP;
2943 unlockProperties();
2944
2945 INT32 type;
2946 BYTE data[256];
2947 UINT32 dataLen;
2948 if ((SnmpGetEx(pTransport, _T(".1.0.8802.1.1.2.1.3.1.0"), NULL, 0, &type, sizeof(INT32), 0, NULL) == SNMP_ERR_SUCCESS) &&
2949 (SnmpGetEx(pTransport, _T(".1.0.8802.1.1.2.1.3.2.0"), NULL, 0, data, 256, SG_RAW_RESULT, &dataLen) == SNMP_ERR_SUCCESS))
2950 {
2951 BuildLldpId(type, data, dataLen, szBuffer, 1024);
2952 lockProperties();
2953 if ((m_lldpNodeId == NULL) || _tcscmp(m_lldpNodeId, szBuffer))
2954 {
2955 free(m_lldpNodeId);
2956 m_lldpNodeId = _tcsdup(szBuffer);
2957 hasChanges = true;
2958 sendPollerMsg(dwRqId, _T(" LLDP node ID changed to %s\r\n"), m_lldpNodeId);
2959 }
2960 unlockProperties();
2961 }
2962
2963 ObjectArray<LLDP_LOCAL_PORT_INFO> *lldpPorts = GetLLDPLocalPortInfo(pTransport);
2964 lockProperties();
2965 delete m_lldpLocalPortInfo;
2966 m_lldpLocalPortInfo = lldpPorts;
2967 unlockProperties();
2968 }
2969 else
2970 {
2971 lockProperties();
2972 m_flags &= ~NF_IS_LLDP;
2973 unlockProperties();
2974 }
2975
2976 // Check for 802.1x support
2977 if (checkSNMPIntegerValue(pTransport, _T(".1.0.8802.1.1.1.1.1.1.0"), 1))
2978 {
2979 lockProperties();
2980 m_flags |= NF_IS_8021X;
2981 unlockProperties();
2982 }
2983 else
2984 {
2985 lockProperties();
2986 m_flags &= ~NF_IS_8021X;
2987 unlockProperties();
2988 }
2989
2990 checkOSPFSupport(pTransport);
2991
2992 // Get VRRP information
2993 VrrpInfo *vrrpInfo = GetVRRPInfo(this);
2994 if (vrrpInfo != NULL)
2995 {
2996 lockProperties();
2997 m_flags |= NF_IS_VRRP;
2998 delete m_vrrpInfo;
2999 m_vrrpInfo = vrrpInfo;
3000 unlockProperties();
3001 }
3002 else
3003 {
3004 lockProperties();
3005 m_flags &= ~NF_IS_VRRP;
3006 unlockProperties();
3007 }
3008
3009 // Get wireless controller data
3010 if ((m_driver != NULL) && m_driver->isWirelessController(pTransport, &m_customAttributes, m_driverData))
3011 {
3012 DbgPrintf(5, _T("ConfPoll(%s): node is wireless controller, reading access point information"), m_name);
3013 sendPollerMsg(dwRqId, _T(" Reading wireless access point information\r\n"));
3014 lockProperties();
3015 m_flags |= NF_IS_WIFI_CONTROLLER;
3016 unlockProperties();
3017
3018 int clusterMode = m_driver->getClusterMode(pTransport, &m_customAttributes, m_driverData);
3019
3020 ObjectArray<AccessPointInfo> *aps = m_driver->getAccessPoints(pTransport, &m_customAttributes, m_driverData);
3021 if (aps != NULL)
3022 {
3023 sendPollerMsg(dwRqId, POLLER_INFO _T(" %d wireless access points found\r\n"), aps->size());
3024 DbgPrintf(5, _T("ConfPoll(%s): got information about %d access points"), m_name, aps->size());
3025 int adopted = 0;
3026 for(int i = 0; i < aps->size(); i++)
3027 {
3028 AccessPointInfo *info = aps->get(i);
3029 if (info->getState() == AP_ADOPTED)
3030 adopted++;
3031
3032 bool newAp = false;
3033 AccessPoint *ap = (clusterMode == CLUSTER_MODE_STANDALONE) ? findAccessPointByMAC(info->getMacAddr()) : FindAccessPointByMAC(info->getMacAddr());
3034 if (ap == NULL)
3035 {
3036 String name;
3037
3038 if (info->getName() != NULL)
3039 {
3040 name = info->getName();
3041 }
3042 else
3043 {
3044 for(int j = 0; j < info->getRadioInterfaces()->size(); j++)
3045 {
3046 if (j > 0)
3047 name += _T("/");
3048 name += info->getRadioInterfaces()->get(j)->name;
3049 }
3050 }
3051 ap = new AccessPoint((const TCHAR *)name, info->getIndex(), info->getMacAddr());
3052 NetObjInsert(ap, true, false);
3053 DbgPrintf(5, _T("ConfPoll(%s): created new access point object %s [%d]"), m_name, ap->getName(), ap->getId());
3054 newAp = true;
3055 }
3056 ap->attachToNode(m_id);
3057 ap->setIpAddress(info->getIpAddr());
3058 if ((info->getState() == AP_ADOPTED) || newAp)
3059 {
3060 ap->updateRadioInterfaces(info->getRadioInterfaces());
3061 ap->updateInfo(info->getVendor(), info->getModel(), info->getSerial());
3062 }
3063 ap->unhide();
3064 ap->updateState(info->getState());
3065 }
3066
3067 lockProperties();
3068 m_adoptedApCount = adopted;
3069 m_totalApCount = aps->size();
3070 unlockProperties();
3071
3072 delete aps;
3073 }
3074 else
3075 {
3076 DbgPrintf(5, _T("ConfPoll(%s): failed to read access point information"), m_name);
3077 sendPollerMsg(dwRqId, POLLER_ERROR _T(" Failed to read access point information\r\n"));
3078 }
3079 }
3080 else
3081 {
3082 lockProperties();
3083 m_flags &= ~NF_IS_WIFI_CONTROLLER;
3084 unlockProperties();
3085 }
3086
3087 if (ConfigReadInt(_T("EnableCheckPointSNMP"), 0))
3088 {
3089 // Check for CheckPoint SNMP agent on port 161
3090 DbgPrintf(5, _T("ConfPoll(%s): checking for CheckPoint SNMP"), m_name);
3091 TCHAR szBuffer[4096];
3092 if (SnmpGet(SNMP_VERSION_1, pTransport, _T(".1.3.6.1.4.1.2620.1.1.10.0"), NULL, 0, szBuffer, sizeof(szBuffer), 0) == SNMP_ERR_SUCCESS)
3093 {
3094 lockProperties();
3095 if (_tcscmp(m_snmpObjectId, _T(".1.3.6.1.4.1.2620.1.1")))
3096 {
3097 nx_strncpy(m_snmpObjectId, _T(".1.3.6.1.4.1.2620.1.1"), MAX_OID_LEN * 4);
3098 hasChanges = true;
3099 }
3100
3101 m_flags |= NF_IS_SNMP | NF_IS_ROUTER;
3102 m_dwDynamicFlags &= ~NDF_SNMP_UNREACHABLE;
3103 unlockProperties();
3104 sendPollerMsg(dwRqId, POLLER_INFO _T(" CheckPoint SNMP agent on port 161 is active\r\n"));
3105 }
3106 }
3107 delete pTransport;
3108 return hasChanges;
3109 }
3110
3111 /**
3112 * Query SNMP sys property (sysName, sysLocation, etc.)
3113 */
3114 bool Node::querySnmpSysProperty(SNMP_Transport *snmp, const TCHAR *oid, const TCHAR *propName, UINT32 pollRqId, TCHAR **value)
3115 {
3116 TCHAR buffer[256];
3117 bool hasChanges = false;
3118
3119 if (SnmpGet(m_snmpVersion, snmp, oid, NULL, 0, buffer, sizeof(buffer), SG_STRING_RESULT) == SNMP_ERR_SUCCESS)
3120 {
3121 lockProperties();
3122 if ((*value == NULL) || _tcscmp(*value, buffer))
3123 {
3124 safe_free(*value);
3125 *value = _tcsdup(buffer);
3126 hasChanges = true;
3127 sendPollerMsg(pollRqId, _T(" System %s changed to %s\r\n"), propName, *value);
3128 }
3129 unlockProperties();
3130 }
3131 return hasChanges;
3132 }
3133
3134 /**
3135 * Configuration poll: check for BRIDGE MIB
3136 */
3137 void Node::checkBridgeMib(SNMP_Transport *pTransport)
3138 {
3139 TCHAR szBuffer[4096];
3140 if (SnmpGet(m_snmpVersion, pTransport, _T(".1.3.6.1.2.1.17.1.1.0"), NULL, 0, szBuffer, sizeof(szBuffer), SG_RAW_RESULT) == SNMP_ERR_SUCCESS)
3141 {
3142 lockProperties();
3143 m_flags |= NF_IS_BRIDGE;
3144 memcpy(m_baseBridgeAddress, szBuffer, 6);
3145 unlockProperties();
3146
3147 // Check for Spanning Tree (IEEE 802.1d) MIB support
3148 if (checkSNMPIntegerValue(pTransport, _T(".1.3.6.1.2.1.17.2.1.0"), 3))
3149 {
3150 lockProperties();
3151 m_flags |= NF_IS_STP;
3152 unlockProperties();
3153 }
3154 else
3155 {
3156 lockProperties();
3157 m_flags &= ~NF_IS_STP;
3158 unlockProperties();
3159 }
3160 }
3161 else
3162 {
3163 lockProperties();
3164 m_flags &= ~(NF_IS_BRIDGE | NF_IS_STP);
3165 unlockProperties();
3166 }
3167 }
3168
3169 /**
3170 * Configuration poll: check for ifXTable
3171 */
3172 void Node::checkIfXTable(SNMP_Transport *pTransport)
3173 {
3174 bool present = false;
3175 SnmpWalk(pTransport, _T(".1.3.6.1.2.1.31.1.1.1.1"), IndicatorSnmpWalkerCallback, &present);
3176 if (present)
3177 {
3178 lockProperties();
3179 m_flags |= NF_HAS_IFXTABLE;
3180 unlockProperties();
3181 }
3182 else
3183 {
3184 lockProperties();
3185 m_flags &= ~NF_HAS_IFXTABLE;
3186 unlockProperties();
3187 }
3188 }
3189
3190 /**
3191 * Delete duplicate interfaces
3192 * (find and delete multiple interfaces with same ifIndex value created by version prior to 2.0-M3)
3193 */
3194 bool Node::deleteDuplicateInterfaces(UINT32 rqid)
3195 {
3196 ObjectArray<Interface> deleteList(16, 16, false);
3197
3198 lockChildList(false);
3199 for(int i = 0; i < m_childList->size(); i++)
3200 {
3201 NetObj *curr = m_childList->get(i);
3202
3203 if ((curr->getObjectClass() != OBJECT_INTERFACE) ||
3204 ((Interface *)curr)->isManuallyCreated())
3205 continue;
3206 Interface *iface = (Interface *)curr;
3207 for(int j = i + 1; j < m_childList->size(); j++)
3208 {
3209 NetObj *next = m_childList->get(j);
3210
3211 if ((next->getObjectClass() != OBJECT_INTERFACE) ||
3212 ((Interface *)next)->isManuallyCreated() ||
3213 (deleteList.contains((Interface *)next)))
3214 continue;
3215 if (iface->getIfIndex() == ((Interface *)next)->getIfIndex())
3216 {
3217 deleteList.add((Interface *)next);
3218 DbgPrintf(6, _T("Node::deleteDuplicateInterfaces(%s [%d]): found duplicate interface %s [%d], original %s [%d], ifIndex=%d"),
3219 m_name, m_id, next->getName(), next->getId(), iface->getName(), iface->getId(), iface->getIfIndex());
3220 }
3221 }
3222 }
3223 unlockChildList();
3224
3225 for(int i = 0; i < deleteList.size(); i++)
3226 {
3227 Interface *iface = deleteList.get(i);
3228 sendPollerMsg(rqid, POLLER_WARNING _T(" Duplicate interface \"%s\" deleted\r\n"), iface->getName());
3229 deleteInterface(iface);
3230 }
3231
3232 return deleteList.size() > 0;
3233 }
3234
3235 /**
3236 * Update interface configuration
3237 */
3238 bool Node::updateInterfaceConfiguration(UINT32 rqid, int maskBits)
3239 {
3240 sendPollerMsg(rqid, _T("Checking interface configuration...\r\n"));
3241
3242 bool hasChanges = deleteDuplicateInterfaces(rqid);
3243
3244 InterfaceList *ifList = getInterfaceList();
3245 if (ifList != NULL)
3246 {
3247 nxlog_debug(6, _T("Node::updateInterfaceConfiguration(%s [%u]): got %d interfaces"), m_name, m_id, ifList->size());
3248
3249 // Find non-existing interfaces
3250 lockChildList(false);
3251 ObjectArray<Interface> deleteList(m_childList->size(), 8, false);
3252 for(int i = 0; i < m_childList->size(); i++)
3253 {
3254 if (m_childList->get(i)->getObjectClass() == OBJECT_INTERFACE)
3255 {
3256 Interface *iface = (Interface *)m_childList->get(i);
3257 if (iface->isFake())
3258 {
3259 // always delete fake interfaces if we got actual interface list
3260 deleteList.add(iface);
3261 continue;
3262 }
3263
3264 if (!iface->isManuallyCreated())
3265 {
3266 int j;
3267 for(j = 0; j < ifList->size(); j++)
3268 {
3269 if (ifList->get(j)->index == iface->getIfIndex())
3270 break;
3271 }
3272
3273 if (j == ifList->size())
3274 {
3275 // No such interface in current configuration, add it to delete list
3276 deleteList.add(iface);
3277 }
3278 }
3279 }
3280 }
3281 unlockChildList();
3282
3283 // Delete non-existent interfaces
3284 if (deleteList.size() > 0)
3285 {
3286 for(int j = 0; j < deleteList.size(); j++)
3287 {
3288 Interface *iface = deleteList.get(j);
3289 sendPollerMsg(rqid, POLLER_WARNING _T(" Interface \"%s\" is no longer exist\r\n"), iface->getName());
3290 const InetAddress& addr = iface->getFirstIpAddress();
3291 PostEvent(EVENT_INTERFACE_DELETED, m_id, "dsAd", iface->getIfIndex(), iface->getName(), &addr, addr.getMaskBits());
3292 deleteInterface(iface);
3293 }
3294 hasChanges = true;
3295 }
3296
3297 // Add new interfaces and check configuration of existing
3298 for(int j = 0; j < ifList->size(); j++)
3299 {
3300 InterfaceInfo *ifInfo = ifList->get(j);
3301 bool isNewInterface = true;
3302
3303 lockChildList(false);
3304 for(int i = 0; i < m_childList->size(); i++)
3305 {
3306 if (m_childList->get(i)->getObjectClass() == OBJECT_INTERFACE)
3307 {
3308 Interface *pInterface = (Interface *)m_childList->get(i);
3309
3310 if (ifInfo->index == pInterface->getIfIndex())
3311 {
3312 // Existing interface, check configuration
3313 if (memcmp(ifInfo->macAddr, "\x00\x00\x00\x00\x00\x00", MAC_ADDR_LENGTH) &&
3314 memcmp(ifInfo->macAddr, pInterface->getMacAddr(), MAC_ADDR_LENGTH))
3315 {
3316 TCHAR szOldMac[16], szNewMac[16];
3317
3318 BinToStr((BYTE *)pInterface->getMacAddr(), MAC_ADDR_LENGTH, szOldMac);
3319 BinToStr(ifInfo->macAddr, MAC_ADDR_LENGTH, szNewMac);
3320 PostEvent(EVENT_MAC_ADDR_CHANGED, m_id, "idsss",
3321 pInterface->getId(), pInterface->getIfIndex(),
3322 pInterface->getName(), szOldMac, szNewMac);
3323 pInterface->setMacAddr(ifInfo->macAddr, true);
3324 }
3325 if (_tcscmp(ifInfo->name, pInterface->getName()))
3326 {
3327 pInterface->setName(ifInfo->name);
3328 }
3329 if (_tcscmp(ifInfo->description, pInterface->getDescription()))
3330 {
3331 pInterface->setDescription(ifInfo->description);
3332 }
3333 if (_tcscmp(ifInfo->alias, pInterface->getAlias()))
3334 {
3335 pInterface->setAlias(ifInfo->alias);
3336 }
3337 if (ifInfo->bridgePort != pInterface->getBridgePortNumber())
3338 {
3339 pInterface->setBridgePortNumber(ifInfo->bridgePort);
3340 }
3341 if (ifInfo->slot != pInterface->getSlotNumber())
3342 {
3343 pInterface->setSlotNumber(ifInfo->slot);
3344 }
3345 if (ifInfo->port != pInterface->getPortNumber())
3346 {
3347 pInterface->setPortNumber(ifInfo->port);
3348 }
3349 if (ifInfo->isPhysicalPort != pInterface->isPhysicalPort())
3350 {
3351 pInterface->setPhysicalPortFlag(ifInfo->isPhysicalPort);
3352 }
3353 if (ifInfo->mtu != pInterface->getMTU())
3354 {
3355 pInterface->setMTU(ifInfo->mtu);
3356 }
3357 if (ifInfo->speed != pInterface->getSpeed())
3358 {
3359 pInterface->setSpeed(ifInfo->speed);
3360 }
3361 if ((ifInfo->ifTableSuffixLength != pInterface->getIfTableSuffixLen()) ||
3362 memcmp(ifInfo->ifTableSuffix, pInterface->getIfTableSuffix(),
3363 min(ifInfo->ifTableSuffixLength, pInterface->getIfTableSuffixLen())))
3364 {
3365 pInterface->setIfTableSuffix(ifInfo->ifTableSuffixLength, ifInfo->ifTableSuffix);
3366 }
3367
3368 // Check for deleted IPs and changed masks
3369 const InetAddressList *ifList = pInterface->getIpAddressList();
3370 for(int n = 0; n < ifList->size(); n++)
3371 {
3372 const InetAddress& ifAddr = ifList->get(n);
3373 const InetAddress& addr = ifInfo->ipAddrList.findAddress(ifAddr);
3374 if (addr.isValid())
3375 {
3376 if (addr.getMaskBits() != ifAddr.getMaskBits())
3377 {
3378 PostEvent(EVENT_IF_MASK_CHANGED, m_id, "dsAddd", pInterface->getId(), pInterface->getName(),
3379 &addr, addr.getMaskBits(), pInterface->getIfIndex(), ifAddr.getMaskBits());
3380 pInterface->setNetMask(addr);
3381 sendPollerMsg(rqid, POLLER_INFO _T(" IP network mask changed to /%d on interface \"%s\" address %s\r\n"),
3382 addr.getMaskBits(), pInterface->getName(), (const TCHAR *)ifAddr.toString());
3383 }
3384 }
3385 else
3386 {
3387 sendPollerMsg(rqid, POLLER_WARNING _T(" IP address %s removed from interface \"%s\"\r\n"),
3388 (const TCHAR *)ifAddr.toString(), pInterface->getName());
3389 PostEvent(EVENT_IF_IPADDR_DELETED, m_id, "dsAdd", pInterface->getId(), pInterface->getName(),
3390 &ifAddr, ifAddr.getMaskBits(), pInterface->getIfIndex());
3391 pInterface->deleteIpAddress(ifAddr);
3392 }
3393 }
3394
3395 // Check for added IPs
3396 for(int m = 0; m < ifInfo->ipAddrList.size(); m++)
3397 {
3398 const InetAddress& addr = ifInfo->ipAddrList.get(m);
3399 if (!ifList->hasAddress(addr))
3400 {
3401 pInterface->addIpAddress(addr);
3402 PostEvent(EVENT_IF_IPADDR_ADDED, m_id, "dsAdd", pInterface->getId(), pInterface->getName(),
3403 &addr, addr.getMaskBits(), pInterface->getIfIndex());
3404 sendPollerMsg(rqid, POLLER_INFO _T(" IP address %s added to interface \"%s\"\r\n"),
3405 (const TCHAR *)addr.toString(), pInterface->getName());
3406 }
3407 }
3408
3409 isNewInterface = false;
3410 break;
3411 }
3412 }
3413 }
3414 unlockChildList();
3415
3416 if (isNewInterface)
3417 {
3418 // New interface
3419 sendPollerMsg(rqid, POLLER_INFO _T(" Found new interface \"%s\"\r\n"), ifInfo->name);
3420 if (filterInterface(ifInfo))
3421 {
3422 createNewInterface(ifInfo, false, false);
3423 hasChanges = true;
3424 }
3425 else
3426 {
3427 sendPollerMsg(rqid, POLLER_WARNING _T(" Creation of interface object \"%s\" blocked by filter\r\n"), ifInfo->name);
3428 }
3429 }
3430 }
3431
3432 // Set parent interfaces
3433 for(int j = 0; j < ifList->size(); j++)
3434 {
3435 InterfaceInfo *ifInfo = ifList->get(j);
3436 if (ifInfo->parentIndex != 0)
3437 {
3438 Interface *parent = findInterfaceByIndex(ifInfo->parentIndex);
3439 if (parent != NULL)