changed error logging in network map link
[public/netxms.git] / src / server / libnxsrv / agent.cpp
CommitLineData
cc022855 1/*
5039dede
AK
2** NetXMS - Network Management System
3** Server Library
0f506caa 4** Copyright (C) 2003-2013 Victor Kirhenshtein
5039dede
AK
5**
6** This program is free software; you can redistribute it and/or modify
0702ed69
VK
7** it under the terms of the GNU Lesser General Public License as published by
8** the Free Software Foundation; either version 3 of the License, or
5039dede
AK
9** (at your option) any later version.
10**
11** This program is distributed in the hope that it will be useful,
12** but WITHOUT ANY WARRANTY; without even the implied warranty of
13** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14** GNU General Public License for more details.
15**
0702ed69 16** You should have received a copy of the GNU Lesser General Public License
5039dede
AK
17** along with this program; if not, write to the Free Software
18** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19**
20** File: agent.cpp
21**
22**/
23
24#include "libnxsrv.h"
25#include <stdarg.h>
26
f00612ba
VK
27#ifdef _WIN32
28#define open _open
29#define close _close
30#define write _write
8c1befb6 31#else
ff198273 32#define _tell(f) lseek(f,0,SEEK_CUR)
f00612ba
VK
33#endif
34
a3050773
VK
35/**
36 * Constants
37 */
8f4f648d 38#define MAX_MSG_SIZE 8388608
5039dede 39
a3050773
VK
40/**
41 * Static data
42 */
5039dede
AK
43#ifdef _WITH_ENCRYPTION
44static int m_iDefaultEncryptionPolicy = ENCRYPTION_ALLOWED;
45#else
46static int m_iDefaultEncryptionPolicy = ENCRYPTION_DISABLED;
47#endif
48
a3050773
VK
49/**
50 * Set default encryption policy for agent communication
51 */
5039dede
AK
52void LIBNXSRV_EXPORTABLE SetAgentDEP(int iPolicy)
53{
54#ifdef _WITH_ENCRYPTION
55 m_iDefaultEncryptionPolicy = iPolicy;
56#endif
57}
58
a3050773
VK
59/**
60 * Receiver thread starter
61 */
62THREAD_RESULT THREAD_CALL AgentConnection::receiverThreadStarter(void *pArg)
5039dede 63{
a3050773 64 ((AgentConnection *)pArg)->receiverThread();
5039dede
AK
65 return THREAD_OK;
66}
67
a3050773
VK
68/**
69 * Constructor for AgentConnection
70 */
69c6604d 71AgentConnection::AgentConnection(UINT32 ipAddr, WORD port, int authMethod, const TCHAR *secret)
5039dede 72{
69c6604d
VK
73 m_dwAddr = ipAddr;
74 m_wPort = port;
75 m_iAuthMethod = authMethod;
76 if (secret != NULL)
5039dede
AK
77 {
78#ifdef UNICODE
69c6604d 79 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR, secret, -1, m_szSecret, MAX_SECRET_LENGTH, NULL, NULL);
08b214c6 80 m_szSecret[MAX_SECRET_LENGTH - 1] = 0;
5039dede 81#else
69c6604d 82 nx_strncpy(m_szSecret, secret, MAX_SECRET_LENGTH);
5039dede
AK
83#endif
84 }
85 else
86 {
87 m_szSecret[0] = 0;
88 }
89 m_hSocket = -1;
90 m_tLastCommandTime = 0;
91 m_dwNumDataLines = 0;
92 m_ppDataLines = NULL;
93 m_pMsgWaitQueue = new MsgWaitQueue;
94 m_dwRequestId = 1;
7c521895 95 m_connectionTimeout = 30000; // 30 seconds
5039dede
AK
96 m_dwCommandTimeout = 10000; // Default timeout 10 seconds
97 m_bIsConnected = FALSE;
98 m_mutexDataLock = MutexCreate();
d3a7cf4c 99 m_mutexSocketWrite = MutexCreate();
5039dede
AK
100 m_hReceiverThread = INVALID_THREAD_HANDLE;
101 m_pCtx = NULL;
102 m_iEncryptionPolicy = m_iDefaultEncryptionPolicy;
103 m_bUseProxy = FALSE;
104 m_dwRecvTimeout = 420000; // 7 minutes
105 m_nProtocolVersion = NXCP_VERSION;
106 m_hCurrFile = -1;
76b4edb5 107 m_deleteFileOnDownloadFailure = true;
bb85e341 108 m_condFileDownload = ConditionCreate(TRUE);
4685a2ad 109 m_fileUploadInProgress = false;
9630fcd1 110 m_sendToClientMessageCallback = NULL;
5039dede
AK
111}
112
a3050773
VK
113/**
114 * Destructor
115 */
5039dede
AK
116AgentConnection::~AgentConnection()
117{
118 // Disconnect from peer
7c521895 119 disconnect();
5039dede
AK
120
121 // Wait for receiver thread termination
122 ThreadJoin(m_hReceiverThread);
cc022855 123
5039dede 124 // Close socket if active
a3050773 125 lock();
5039dede
AK
126 if (m_hSocket != -1)
127 {
128 closesocket(m_hSocket);
129 m_hSocket = -1;
130 }
a3050773 131 unlock();
5039dede 132
a3050773 133 lock();
7c521895 134 destroyResultData();
a3050773 135 unlock();
5039dede
AK
136
137 delete m_pMsgWaitQueue;
98abc9f1
VK
138 if (m_pCtx != NULL)
139 m_pCtx->decRefCount();
5039dede
AK
140
141 if (m_hCurrFile != -1)
9f6d453a 142 {
5039dede 143 close(m_hCurrFile);
f480bdd4 144 onFileDownload(FALSE);
9f6d453a 145 }
5039dede
AK
146
147 MutexDestroy(m_mutexDataLock);
d3a7cf4c 148 MutexDestroy(m_mutexSocketWrite);
bb85e341 149 ConditionDestroy(m_condFileDownload);
5039dede
AK
150}
151
a3050773
VK
152/**
153 * Print message. This method is virtual and can be overrided in
154 * derived classes. Default implementation will print message to stdout.
155 */
af21affe 156void AgentConnection::printMsg(const TCHAR *format, ...)
5039dede
AK
157{
158 va_list args;
159
af21affe
VK
160 va_start(args, format);
161 _vtprintf(format, args);
5039dede
AK
162 va_end(args);
163 _tprintf(_T("\n"));
164}
165
a3050773
VK
166/**
167 * Receiver thread
168 */
169void AgentConnection::receiverThread()
5039dede 170{
967893bb 171 UINT32 msgBufferSize = 1024;
5039dede
AK
172 CSCPMessage *pMsg;
173 CSCP_MESSAGE *pRawMsg;
174 CSCP_BUFFER *pMsgBuffer;
175 BYTE *pDecryptionBuffer = NULL;
4685a2ad 176 int error;
5039dede
AK
177 TCHAR szBuffer[128], szIpAddr[16];
178 SOCKET nSocket;
179
180 // Initialize raw message receiving function
181 pMsgBuffer = (CSCP_BUFFER *)malloc(sizeof(CSCP_BUFFER));
182 RecvNXCPMessage(0, NULL, pMsgBuffer, 0, NULL, NULL, 0);
183
184 // Allocate space for raw message
8f4f648d 185 pRawMsg = (CSCP_MESSAGE *)malloc(msgBufferSize);
5039dede 186#ifdef _WITH_ENCRYPTION
8f4f648d 187 pDecryptionBuffer = (BYTE *)malloc(msgBufferSize);
5039dede
AK
188#endif
189
190 // Message receiving loop
191 while(1)
192 {
8f4f648d
VK
193 // Shrink buffer after receiving large message
194 if (msgBufferSize > 131072)
195 {
196 msgBufferSize = 131072;
197 pRawMsg = (CSCP_MESSAGE *)realloc(pRawMsg, msgBufferSize);
198 if (pDecryptionBuffer != NULL)
199 pDecryptionBuffer = (BYTE *)realloc(pDecryptionBuffer, msgBufferSize);
200 }
201
5039dede 202 // Receive raw message
a3050773 203 lock();
5039dede 204 nSocket = m_hSocket;
a3050773 205 unlock();
8f4f648d
VK
206 if ((error = RecvNXCPMessageEx(nSocket, &pRawMsg, pMsgBuffer, &msgBufferSize,
207 &m_pCtx, (pDecryptionBuffer != NULL) ? &pDecryptionBuffer : NULL,
208 m_dwRecvTimeout, MAX_MSG_SIZE)) <= 0)
5039dede 209 {
a2069340
VK
210 if (WSAGetLastError() != WSAESHUTDOWN)
211 DbgPrintf(6, _T("AgentConnection::ReceiverThread(): RecvNXCPMessage() failed: error=%d, socket_error=%d"), error, WSAGetLastError());
5039dede
AK
212 break;
213 }
214
215 // Check if we get too large message
4685a2ad 216 if (error == 1)
5039dede 217 {
cc022855 218 printMsg(_T("Received too large message %s (%d bytes)"),
5039dede
AK
219 NXCPMessageCodeName(ntohs(pRawMsg->wCode), szBuffer),
220 ntohl(pRawMsg->dwSize));
221 continue;
222 }
223
224 // Check if we are unable to decrypt message
4685a2ad 225 if (error == 2)
5039dede 226 {
a3050773 227 printMsg(_T("Unable to decrypt received message"));
5039dede
AK
228 continue;
229 }
230
231 // Check for timeout
4685a2ad 232 if (error == 3)
5039dede 233 {
4685a2ad
VK
234 if (m_fileUploadInProgress)
235 continue; // Receive timeout may occur when uploading large files via slow links
a3050773 236 printMsg(_T("Timed out waiting for message"));
5039dede
AK
237 break;
238 }
239
240 // Check that actual received packet size is equal to encoded in packet
4685a2ad 241 if ((int)ntohl(pRawMsg->dwSize) != error)
5039dede 242 {
a3050773 243 printMsg(_T("RecvMsg: Bad packet length [dwSize=%d ActualSize=%d]"), ntohl(pRawMsg->dwSize), error);
5039dede
AK
244 continue; // Bad packet, wait for next
245 }
246
247 if (ntohs(pRawMsg->wFlags) & MF_BINARY)
248 {
249 // Convert message header to host format
250 pRawMsg->dwId = ntohl(pRawMsg->dwId);
251 pRawMsg->wCode = ntohs(pRawMsg->wCode);
252 pRawMsg->dwNumVars = ntohl(pRawMsg->dwNumVars);
08b214c6 253 DbgPrintf(6, _T("Received raw message %s from agent at %s"),
7c521895 254 NXCPMessageCodeName(pRawMsg->wCode, szBuffer), IpToStr(getIpAddr(), szIpAddr));
5039dede 255
76b4edb5 256 if ((pRawMsg->wCode == CMD_FILE_DATA) && (pRawMsg->dwId == m_dwDownloadRequestId))
5039dede 257 {
76b4edb5 258 if (m_sendToClientMessageCallback != NULL)
5039dede 259 {
76b4edb5 260 pRawMsg->wCode = ntohs(pRawMsg->wCode);
261 pRawMsg->dwNumVars = ntohl(pRawMsg->dwNumVars);
262 m_sendToClientMessageCallback(pRawMsg, m_downloadProgressCallbackArg);
263
5039dede
AK
264 if (ntohs(pRawMsg->wFlags) & MF_END_OF_FILE)
265 {
f480bdd4 266 onFileDownload(TRUE);
5039dede 267 }
76b4edb5 268 else
269 {
270 if (m_downloadProgressCallback != NULL)
271 {
272 m_downloadProgressCallback(pRawMsg->dwSize - (CSCP_HEADER_SIZE + 8), m_downloadProgressCallbackArg);
273 }
274 }
5039dede
AK
275 }
276 else
277 {
76b4edb5 278 if (m_hCurrFile != -1)
279 {
280 if (write(m_hCurrFile, pRawMsg->df, pRawMsg->dwNumVars) == (int)pRawMsg->dwNumVars)
281 {
282 if (ntohs(pRawMsg->wFlags) & MF_END_OF_FILE)
283 {
284 close(m_hCurrFile);
285 m_hCurrFile = -1;
286
287 onFileDownload(TRUE);
288 }
289 else
290 {
291 if (m_downloadProgressCallback != NULL)
292 {
293 m_downloadProgressCallback(_tell(m_hCurrFile), m_downloadProgressCallbackArg);
294 }
295 }
296 }
297 }
298 else
299 {
300 // I/O error
301 close(m_hCurrFile);
302 m_hCurrFile = -1;
cc022855 303
76b4edb5 304 onFileDownload(FALSE);
305 }
9a895fd6 306 }
307 }
308
309 if((pRawMsg->wCode == CMD_ABORT_FILE_TRANSFER) && (pRawMsg->dwId == m_dwDownloadRequestId))
310 {
311 if (m_sendToClientMessageCallback != NULL)
312 {
313 pRawMsg->wCode = ntohs(pRawMsg->wCode);
314 pRawMsg->dwNumVars = ntohl(pRawMsg->dwNumVars);
315 m_sendToClientMessageCallback(pRawMsg, m_downloadProgressCallbackArg);
316
317 onFileDownload(FALSE);
318 }
319 else
320 {
321 //error on agent side
322 close(m_hCurrFile);
323 m_hCurrFile = -1;
324
325 onFileDownload(FALSE);
5039dede
AK
326 }
327 }
328 }
329 else
330 {
331 // Create message object from raw message
332 pMsg = new CSCPMessage(pRawMsg, m_nProtocolVersion);
f480bdd4 333 switch(pMsg->GetCode())
5039dede 334 {
f480bdd4
VK
335 case CMD_TRAP:
336 onTrap(pMsg);
337 delete pMsg;
338 break;
339 case CMD_PUSH_DCI_DATA:
340 onDataPush(pMsg);
341 delete pMsg;
342 break;
90284364 343 case CMD_REQUEST_COMPLETED:
c17f6cbc 344 m_pMsgWaitQueue->put(pMsg);
f480bdd4 345 break;
9fa031cd 346 case CMD_FILE_MONITORING:
347 onFileMonitoringData(pMsg);
348 delete pMsg;
349 break;
90284364
VK
350 default:
351 if (processCustomMessage(pMsg))
352 delete pMsg;
353 else
c17f6cbc 354 m_pMsgWaitQueue->put(pMsg);
90284364 355 break;
5039dede
AK
356 }
357 }
358 }
359
360 // Close socket and mark connection as disconnected
a3050773 361 lock();
f2665675
VK
362 if (m_hCurrFile != -1)
363 {
364 close(m_hCurrFile);
365 m_hCurrFile = -1;
f480bdd4 366 onFileDownload(FALSE);
f2665675 367 }
cc022855 368
4685a2ad 369 if (error == 0)
5039dede
AK
370 shutdown(m_hSocket, SHUT_RDWR);
371 closesocket(m_hSocket);
372 m_hSocket = -1;
98abc9f1
VK
373 if (m_pCtx != NULL)
374 {
375 m_pCtx->decRefCount();
376 m_pCtx = NULL;
377 }
5039dede 378 m_bIsConnected = FALSE;
a3050773 379 unlock();
5039dede
AK
380
381 free(pRawMsg);
382 free(pMsgBuffer);
383#ifdef _WITH_ENCRYPTION
384 free(pDecryptionBuffer);
385#endif
386}
387
a3050773
VK
388/**
389 * Connect to agent
390 */
967893bb 391BOOL AgentConnection::connect(RSA *pServerKey, BOOL bVerbose, UINT32 *pdwError, UINT32 *pdwSocketError)
5039dede
AK
392{
393 struct sockaddr_in sa;
394 TCHAR szBuffer[256];
395 BOOL bSuccess = FALSE, bForceEncryption = FALSE, bSecondPass = FALSE;
967893bb 396 UINT32 dwError = 0;
5039dede
AK
397
398 if (pdwError != NULL)
399 *pdwError = ERR_INTERNAL_ERROR;
400
c3acd0f6
VK
401 if (pdwSocketError != NULL)
402 *pdwSocketError = 0;
403
5039dede
AK
404 // Check if already connected
405 if (m_bIsConnected)
406 return FALSE;
407
408 // Wait for receiver thread from previous connection, if any
409 ThreadJoin(m_hReceiverThread);
410 m_hReceiverThread = INVALID_THREAD_HANDLE;
411
412 // Check if we need to close existing socket
413 if (m_hSocket != -1)
414 closesocket(m_hSocket);
415
416 // Create socket
417 m_hSocket = socket(AF_INET, SOCK_STREAM, 0);
4c0c75c7 418 if (m_hSocket == INVALID_SOCKET)
5039dede 419 {
a3050773 420 printMsg(_T("Call to socket() failed"));
5039dede
AK
421 goto connect_cleanup;
422 }
423
424 // Fill in address structure
425 memset(&sa, 0, sizeof(sa));
426 sa.sin_family = AF_INET;
427 if (m_bUseProxy)
428 {
429 sa.sin_addr.s_addr = m_dwProxyAddr;
430 sa.sin_port = htons(m_wProxyPort);
431 }
432 else
433 {
434 sa.sin_addr.s_addr = m_dwAddr;
435 sa.sin_port = htons(m_wPort);
436 }
437
438 // Connect to server
7c521895 439 if (ConnectEx(m_hSocket, (struct sockaddr *)&sa, sizeof(sa), m_connectionTimeout) == -1)
5039dede
AK
440 {
441 if (bVerbose)
a3050773 442 printMsg(_T("Cannot establish connection with agent %s"),
5039dede
AK
443 IpToStr(ntohl(m_bUseProxy ? m_dwProxyAddr : m_dwAddr), szBuffer));
444 dwError = ERR_CONNECT_FAILED;
445 goto connect_cleanup;
446 }
447
d3a7cf4c 448 if (!NXCPGetPeerProtocolVersion(m_hSocket, &m_nProtocolVersion, m_mutexSocketWrite))
5039dede
AK
449 {
450 dwError = ERR_INTERNAL_ERROR;
451 goto connect_cleanup;
452 }
453
454 // Start receiver thread
a3050773 455 m_hReceiverThread = ThreadCreateEx(receiverThreadStarter, 0, this);
5039dede
AK
456
457 // Setup encryption
458setup_encryption:
459 if ((m_iEncryptionPolicy == ENCRYPTION_PREFERRED) ||
460 (m_iEncryptionPolicy == ENCRYPTION_REQUIRED) ||
461 (bForceEncryption)) // Agent require encryption
462 {
463 if (pServerKey != NULL)
464 {
7c521895 465 dwError = setupEncryption(pServerKey);
5039dede
AK
466 if ((dwError != ERR_SUCCESS) &&
467 ((m_iEncryptionPolicy == ENCRYPTION_REQUIRED) || bForceEncryption))
468 goto connect_cleanup;
469 }
470 else
471 {
472 if ((m_iEncryptionPolicy == ENCRYPTION_REQUIRED) || bForceEncryption)
473 {
474 dwError = ERR_ENCRYPTION_REQUIRED;
475 goto connect_cleanup;
476 }
477 }
478 }
479
480 // Authenticate itself to agent
7c521895 481 if ((dwError = authenticate(m_bUseProxy && !bSecondPass)) != ERR_SUCCESS)
5039dede
AK
482 {
483 if ((dwError == ERR_ENCRYPTION_REQUIRED) &&
484 (m_iEncryptionPolicy != ENCRYPTION_DISABLED))
485 {
486 bForceEncryption = TRUE;
487 goto setup_encryption;
488 }
a3050773 489 printMsg(_T("Authentication to agent %s failed (%s)"), IpToStr(ntohl(m_dwAddr), szBuffer),
5039dede
AK
490 AgentErrorCodeToText(dwError));
491 goto connect_cleanup;
492 }
493
494 // Test connectivity
45d84f8a 495 if ((dwError = nop()) != ERR_SUCCESS)
5039dede
AK
496 {
497 if ((dwError == ERR_ENCRYPTION_REQUIRED) &&
498 (m_iEncryptionPolicy != ENCRYPTION_DISABLED))
499 {
500 bForceEncryption = TRUE;
501 goto setup_encryption;
502 }
a3050773 503 printMsg(_T("Communication with agent %s failed (%s)"), IpToStr(ntohl(m_dwAddr), szBuffer),
5039dede
AK
504 AgentErrorCodeToText(dwError));
505 goto connect_cleanup;
506 }
507
508 if (m_bUseProxy && !bSecondPass)
509 {
7c521895 510 dwError = setupProxyConnection();
5039dede
AK
511 if (dwError != ERR_SUCCESS)
512 goto connect_cleanup;
a3050773 513 lock();
98abc9f1
VK
514 if (m_pCtx != NULL)
515 {
516 m_pCtx->decRefCount();
517 m_pCtx = NULL;
518 }
a3050773 519 unlock();
5039dede
AK
520 bSecondPass = TRUE;
521 bForceEncryption = FALSE;
522 goto setup_encryption;
523 }
524
525 bSuccess = TRUE;
526 dwError = ERR_SUCCESS;
527
528connect_cleanup:
529 if (!bSuccess)
530 {
c3acd0f6 531 if (pdwSocketError != NULL)
967893bb 532 *pdwSocketError = (UINT32)WSAGetLastError();
c3acd0f6 533
a3050773 534 lock();
5039dede
AK
535 if (m_hSocket != -1)
536 shutdown(m_hSocket, SHUT_RDWR);
a3050773 537 unlock();
5039dede
AK
538 ThreadJoin(m_hReceiverThread);
539 m_hReceiverThread = INVALID_THREAD_HANDLE;
540
a3050773 541 lock();
5039dede
AK
542 if (m_hSocket != -1)
543 {
544 closesocket(m_hSocket);
545 m_hSocket = -1;
546 }
547
98abc9f1
VK
548 if (m_pCtx != NULL)
549 {
550 m_pCtx->decRefCount();
551 m_pCtx = NULL;
552 }
5039dede 553
a3050773 554 unlock();
5039dede
AK
555 }
556 m_bIsConnected = bSuccess;
557 if (pdwError != NULL)
558 *pdwError = dwError;
559 return bSuccess;
560}
561
af21affe
VK
562/**
563 * Disconnect from agent
564 */
7c521895 565void AgentConnection::disconnect()
5039dede 566{
a3050773 567 lock();
f2665675
VK
568 if (m_hCurrFile != -1)
569 {
570 close(m_hCurrFile);
571 m_hCurrFile = -1;
f480bdd4 572 onFileDownload(FALSE);
f2665675 573 }
9fa031cd 574
5039dede
AK
575 if (m_hSocket != -1)
576 {
577 shutdown(m_hSocket, SHUT_RDWR);
578 }
7c521895 579 destroyResultData();
5039dede 580 m_bIsConnected = FALSE;
a3050773 581 unlock();
5039dede
AK
582}
583
af21affe
VK
584/**
585 * Set authentication data
586 */
587void AgentConnection::setAuthData(int method, const TCHAR *secret)
cc022855 588{
af21affe
VK
589 m_iAuthMethod = method;
590#ifdef UNICODE
591 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR, secret, -1, m_szSecret, MAX_SECRET_LENGTH, NULL, NULL);
592 m_szSecret[MAX_SECRET_LENGTH - 1] = 0;
593#else
594 nx_strncpy(m_szSecret, secret, MAX_SECRET_LENGTH);
595#endif
596}
5039dede 597
af21affe
VK
598/**
599 * Destroy command execuion results data
600 */
7c521895 601void AgentConnection::destroyResultData()
5039dede 602{
967893bb 603 UINT32 i;
5039dede
AK
604
605 if (m_ppDataLines != NULL)
606 {
607 for(i = 0; i < m_dwNumDataLines; i++)
608 if (m_ppDataLines[i] != NULL)
609 free(m_ppDataLines[i]);
610 free(m_ppDataLines);
611 m_ppDataLines = NULL;
612 }
613 m_dwNumDataLines = 0;
614}
615
d51f2182
VK
616/**
617 * Get interface list from agent
618 */
98762401 619InterfaceList *AgentConnection::getInterfaceList()
5039dede 620{
98762401 621 InterfaceList *pIfList = NULL;
36e44abe 622 NX_INTERFACE_INFO iface;
967893bb 623 UINT32 i, dwBits;
5039dede
AK
624 TCHAR *pChar, *pBuf;
625
4687826e 626 if (getList(_T("Net.InterfaceList")) == ERR_SUCCESS)
5039dede 627 {
98762401 628 pIfList = new InterfaceList(m_dwNumDataLines);
5039dede
AK
629
630 // Parse result set. Each line should have the following format:
631 // index ip_address/mask_bits iftype mac_address name
632 for(i = 0; i < m_dwNumDataLines; i++)
633 {
634 pBuf = m_ppDataLines[i];
36e44abe 635 memset(&iface, 0, sizeof(NX_INTERFACE_INFO));
5039dede
AK
636
637 // Index
638 pChar = _tcschr(pBuf, ' ');
639 if (pChar != NULL)
640 {
641 *pChar = 0;
98762401 642 iface.dwIndex = _tcstoul(pBuf, NULL, 10);
5039dede
AK
643 pBuf = pChar + 1;
644 }
645
646 // Address and mask
647 pChar = _tcschr(pBuf, _T(' '));
648 if (pChar != NULL)
649 {
650 TCHAR *pSlash;
651 static TCHAR defaultMask[] = _T("24");
652
653 *pChar = 0;
654 pSlash = _tcschr(pBuf, _T('/'));
655 if (pSlash != NULL)
656 {
657 *pSlash = 0;
658 pSlash++;
659 }
660 else // Just a paranoia protection, should'n happen if agent working correctly
661 {
662 pSlash = defaultMask;
663 }
98762401 664 iface.dwIpAddr = ntohl(_t_inet_addr(pBuf));
5039dede 665 dwBits = _tcstoul(pSlash, NULL, 10);
98762401 666 iface.dwIpNetMask = (dwBits == 32) ? 0xFFFFFFFF : (~(0xFFFFFFFF >> dwBits));
5039dede
AK
667 pBuf = pChar + 1;
668 }
669
670 // Interface type
671 pChar = _tcschr(pBuf, ' ');
672 if (pChar != NULL)
673 {
674 *pChar = 0;
98762401 675 iface.dwType = _tcstoul(pBuf, NULL, 10);
5039dede
AK
676 pBuf = pChar + 1;
677 }
678
679 // MAC address
680 pChar = _tcschr(pBuf, ' ');
681 if (pChar != NULL)
682 {
683 *pChar = 0;
98762401 684 StrToBin(pBuf, iface.bMacAddr, MAC_ADDR_LENGTH);
5039dede
AK
685 pBuf = pChar + 1;
686 }
687
478d4ff4
VK
688 // Name (set description to name)
689 nx_strncpy(iface.szName, pBuf, MAX_DB_STRING);
690 nx_strncpy(iface.szDescription, pBuf, MAX_DB_STRING);
98762401
VK
691
692 pIfList->add(&iface);
5039dede
AK
693 }
694
a3050773 695 lock();
7c521895 696 destroyResultData();
a3050773 697 unlock();
5039dede
AK
698 }
699
700 return pIfList;
701}
702
703
704//
705// Get parameter value
706//
707
967893bb 708UINT32 AgentConnection::getParameter(const TCHAR *pszParam, UINT32 dwBufSize, TCHAR *pszBuffer)
5039dede
AK
709{
710 CSCPMessage msg(m_nProtocolVersion), *pResponse;
967893bb 711 UINT32 dwRqId, dwRetCode;
5039dede
AK
712
713 if (m_bIsConnected)
714 {
715 dwRqId = m_dwRequestId++;
716 msg.SetCode(CMD_GET_PARAMETER);
717 msg.SetId(dwRqId);
718 msg.SetVariable(VID_PARAMETER, pszParam);
7c521895 719 if (sendMessage(&msg))
5039dede 720 {
7c521895 721 pResponse = waitForMessage(CMD_REQUEST_COMPLETED, dwRqId, m_dwCommandTimeout);
5039dede
AK
722 if (pResponse != NULL)
723 {
724 dwRetCode = pResponse->GetVariableLong(VID_RCC);
725 if (dwRetCode == ERR_SUCCESS)
726 pResponse->GetVariableStr(VID_VALUE, pszBuffer, dwBufSize);
727 delete pResponse;
728 }
729 else
730 {
731 dwRetCode = ERR_REQUEST_TIMEOUT;
732 }
733 }
734 else
735 {
736 dwRetCode = ERR_CONNECTION_BROKEN;
737 }
738 }
739 else
740 {
741 dwRetCode = ERR_NOT_CONNECTED;
742 }
743
744 return dwRetCode;
745}
746
747
748//
749// Get ARP cache
750//
751
4687826e 752ARP_CACHE *AgentConnection::getArpCache()
5039dede
AK
753{
754 ARP_CACHE *pArpCache = NULL;
755 TCHAR szByte[4], *pBuf, *pChar;
967893bb 756 UINT32 i, j;
5039dede 757
4687826e 758 if (getList(_T("Net.ArpCache")) == ERR_SUCCESS)
5039dede
AK
759 {
760 // Create empty structure
761 pArpCache = (ARP_CACHE *)malloc(sizeof(ARP_CACHE));
762 pArpCache->dwNumEntries = m_dwNumDataLines;
763 pArpCache->pEntries = (ARP_ENTRY *)malloc(sizeof(ARP_ENTRY) * m_dwNumDataLines);
764 memset(pArpCache->pEntries, 0, sizeof(ARP_ENTRY) * m_dwNumDataLines);
765
766 szByte[2] = 0;
767
768 // Parse data lines
769 // Each line has form of XXXXXXXXXXXX a.b.c.d n
770 // where XXXXXXXXXXXX is a MAC address (12 hexadecimal digits)
771 // a.b.c.d is an IP address in decimal dotted notation
772 // n is an interface index
773 for(i = 0; i < m_dwNumDataLines; i++)
774 {
775 pBuf = m_ppDataLines[i];
776 if (_tcslen(pBuf) < 20) // Invalid line
777 continue;
778
779 // MAC address
780 for(j = 0; j < 6; j++)
781 {
782 memcpy(szByte, pBuf, sizeof(TCHAR) * 2);
783 pArpCache->pEntries[i].bMacAddr[j] = (BYTE)_tcstol(szByte, NULL, 16);
784 pBuf+=2;
785 }
786
787 // IP address
788 while(*pBuf == ' ')
789 pBuf++;
790 pChar = _tcschr(pBuf, _T(' '));
791 if (pChar != NULL)
792 *pChar = 0;
793 pArpCache->pEntries[i].dwIpAddr = ntohl(_t_inet_addr(pBuf));
794
795 // Interface index
796 if (pChar != NULL)
797 pArpCache->pEntries[i].dwIndex = _tcstoul(pChar + 1, NULL, 10);
798 }
799
a3050773 800 lock();
7c521895 801 destroyResultData();
a3050773 802 unlock();
5039dede
AK
803 }
804 return pArpCache;
805}
806
807
808//
809// Send dummy command to agent (can be used for keepalive)
810//
811
967893bb 812UINT32 AgentConnection::nop()
5039dede
AK
813{
814 CSCPMessage msg(m_nProtocolVersion);
967893bb 815 UINT32 dwRqId;
5039dede
AK
816
817 dwRqId = m_dwRequestId++;
818 msg.SetCode(CMD_KEEPALIVE);
819 msg.SetId(dwRqId);
7c521895
VK
820 if (sendMessage(&msg))
821 return waitForRCC(dwRqId, m_dwCommandTimeout);
5039dede
AK
822 else
823 return ERR_CONNECTION_BROKEN;
824}
825
826
827//
828// Wait for request completion code
829//
830
967893bb 831UINT32 AgentConnection::waitForRCC(UINT32 dwRqId, UINT32 dwTimeOut)
5039dede
AK
832{
833 CSCPMessage *pMsg;
967893bb 834 UINT32 dwRetCode;
5039dede 835
c17f6cbc 836 pMsg = m_pMsgWaitQueue->waitForMessage(CMD_REQUEST_COMPLETED, dwRqId, dwTimeOut);
5039dede
AK
837 if (pMsg != NULL)
838 {
839 dwRetCode = pMsg->GetVariableLong(VID_RCC);
840 delete pMsg;
841 }
842 else
843 {
844 dwRetCode = ERR_REQUEST_TIMEOUT;
845 }
846 return dwRetCode;
847}
848
5c44534b
VK
849/**
850 * Send message to agent
851 */
7c521895 852BOOL AgentConnection::sendMessage(CSCPMessage *pMsg)
5039dede 853{
5039dede
AK
854 BOOL bResult;
855
5c44534b 856 CSCP_MESSAGE *pRawMsg = pMsg->createMessage();
98abc9f1
VK
857 NXCPEncryptionContext *pCtx = acquireEncryptionContext();
858 if (pCtx != NULL)
5039dede 859 {
98abc9f1 860 CSCP_ENCRYPTED_MESSAGE *pEnMsg = CSCPEncryptMessage(pCtx, pRawMsg);
5039dede
AK
861 if (pEnMsg != NULL)
862 {
d3a7cf4c 863 bResult = (SendEx(m_hSocket, (char *)pEnMsg, ntohl(pEnMsg->dwSize), 0, m_mutexSocketWrite) == (int)ntohl(pEnMsg->dwSize));
5039dede
AK
864 free(pEnMsg);
865 }
866 else
867 {
868 bResult = FALSE;
869 }
98abc9f1 870 pCtx->decRefCount();
5039dede
AK
871 }
872 else
873 {
d3a7cf4c 874 bResult = (SendEx(m_hSocket, (char *)pRawMsg, ntohl(pRawMsg->dwSize), 0, m_mutexSocketWrite) == (int)ntohl(pRawMsg->dwSize));
5039dede
AK
875 }
876 free(pRawMsg);
877 return bResult;
878}
879
7cf549ad 880/**
881 * Send raw message to agent
882 */
883BOOL AgentConnection::sendRawMessage(CSCP_MESSAGE *pMsg)
884{
885 BOOL bResult;
886
887 CSCP_MESSAGE *pRawMsg = pMsg;
888 NXCPEncryptionContext *pCtx = acquireEncryptionContext();
889 if (pCtx != NULL)
890 {
891 CSCP_ENCRYPTED_MESSAGE *pEnMsg = CSCPEncryptMessage(pCtx, pRawMsg);
892 if (pEnMsg != NULL)
893 {
894 bResult = (SendEx(m_hSocket, (char *)pEnMsg, ntohl(pEnMsg->dwSize), 0, m_mutexSocketWrite) == (int)ntohl(pEnMsg->dwSize));
895 free(pEnMsg);
896 }
897 else
898 {
899 bResult = FALSE;
900 }
901 pCtx->decRefCount();
902 }
903 else
904 {
905 bResult = (SendEx(m_hSocket, (char *)pRawMsg, ntohl(pRawMsg->dwSize), 0, m_mutexSocketWrite) == (int)ntohl(pRawMsg->dwSize));
906 }
907 return bResult;
908}
909
d51f2182
VK
910/**
911 * Trap handler. Should be overriden in derived classes to implement
912 * actual trap processing. Default implementation do nothing.
913 */
f480bdd4
VK
914void AgentConnection::onTrap(CSCPMessage *pMsg)
915{
916}
917
d51f2182
VK
918/**
919 * Data push handler. Should be overriden in derived classes to implement
920 * actual data push processing. Default implementation do nothing.
921 */
f480bdd4 922void AgentConnection::onDataPush(CSCPMessage *pMsg)
5039dede
AK
923{
924}
925
9fa031cd 926/**
927 * Monitoring data handler. Should be overriden in derived classes to implement
928 * actual monitoring data processing. Default implementation do nothing.
929 */
930void AgentConnection::onFileMonitoringData(CSCPMessage *pMsg)
931{
932}
933
d51f2182
VK
934/**
935 * Custom message handler
936 * If returns true, message considered as processed and will not be placed in wait queue
937 */
90284364
VK
938bool AgentConnection::processCustomMessage(CSCPMessage *pMsg)
939{
940 return false;
941}
942
d51f2182
VK
943/**
944 * Get list of values
945 */
967893bb 946UINT32 AgentConnection::getList(const TCHAR *pszParam)
5039dede
AK
947{
948 CSCPMessage msg(m_nProtocolVersion), *pResponse;
967893bb 949 UINT32 i, dwRqId, dwRetCode;
5039dede
AK
950
951 if (m_bIsConnected)
952 {
7c521895 953 destroyResultData();
5039dede
AK
954 dwRqId = m_dwRequestId++;
955 msg.SetCode(CMD_GET_LIST);
956 msg.SetId(dwRqId);
957 msg.SetVariable(VID_PARAMETER, pszParam);
7c521895 958 if (sendMessage(&msg))
5039dede 959 {
7c521895 960 pResponse = waitForMessage(CMD_REQUEST_COMPLETED, dwRqId, m_dwCommandTimeout);
5039dede
AK
961 if (pResponse != NULL)
962 {
963 dwRetCode = pResponse->GetVariableLong(VID_RCC);
964 if (dwRetCode == ERR_SUCCESS)
965 {
966 m_dwNumDataLines = pResponse->GetVariableLong(VID_NUM_STRINGS);
967 m_ppDataLines = (TCHAR **)malloc(sizeof(TCHAR *) * m_dwNumDataLines);
968 for(i = 0; i < m_dwNumDataLines; i++)
969 m_ppDataLines[i] = pResponse->GetVariableStr(VID_ENUM_VALUE_BASE + i);
970 }
971 delete pResponse;
972 }
973 else
974 {
975 dwRetCode = ERR_REQUEST_TIMEOUT;
976 }
977 }
978 else
979 {
980 dwRetCode = ERR_CONNECTION_BROKEN;
981 }
982 }
983 else
984 {
985 dwRetCode = ERR_NOT_CONNECTED;
986 }
987
988 return dwRetCode;
989}
990
d51f2182
VK
991/**
992 * Get table
993 */
967893bb 994UINT32 AgentConnection::getTable(const TCHAR *pszParam, Table **table)
4687826e
VK
995{
996 CSCPMessage msg(m_nProtocolVersion), *pResponse;
967893bb 997 UINT32 dwRqId, dwRetCode;
4687826e
VK
998
999 *table = NULL;
1000 if (m_bIsConnected)
1001 {
1002 dwRqId = m_dwRequestId++;
1003 msg.SetCode(CMD_GET_TABLE);
1004 msg.SetId(dwRqId);
1005 msg.SetVariable(VID_PARAMETER, pszParam);
1006 if (sendMessage(&msg))
1007 {
1008 pResponse = waitForMessage(CMD_REQUEST_COMPLETED, dwRqId, m_dwCommandTimeout);
1009 if (pResponse != NULL)
1010 {
1011 dwRetCode = pResponse->GetVariableLong(VID_RCC);
1012 if (dwRetCode == ERR_SUCCESS)
1013 {
1014 *table = new Table(pResponse);
1015 }
1016 delete pResponse;
1017 }
1018 else
1019 {
1020 dwRetCode = ERR_REQUEST_TIMEOUT;
1021 }
1022 }
1023 else
1024 {
1025 dwRetCode = ERR_CONNECTION_BROKEN;
1026 }
1027 }
1028 else
1029 {
1030 dwRetCode = ERR_NOT_CONNECTED;
1031 }
1032
1033 return dwRetCode;
1034}
1035
975f38fc
VK
1036/**
1037 * Authenticate to agent
1038 */
967893bb 1039UINT32 AgentConnection::authenticate(BOOL bProxyData)
5039dede
AK
1040{
1041 CSCPMessage msg(m_nProtocolVersion);
967893bb 1042 UINT32 dwRqId;
5039dede
AK
1043 BYTE hash[32];
1044 int iAuthMethod = bProxyData ? m_iProxyAuth : m_iAuthMethod;
08b214c6 1045 const char *pszSecret = bProxyData ? m_szProxySecret : m_szSecret;
5039dede
AK
1046#ifdef UNICODE
1047 WCHAR szBuffer[MAX_SECRET_LENGTH];
1048#endif
1049
1050 if (iAuthMethod == AUTH_NONE)
1051 return ERR_SUCCESS; // No authentication required
1052
1053 dwRqId = m_dwRequestId++;
1054 msg.SetCode(CMD_AUTHENTICATE);
1055 msg.SetId(dwRqId);
1056 msg.SetVariable(VID_AUTH_METHOD, (WORD)iAuthMethod);
1057 switch(iAuthMethod)
1058 {
1059 case AUTH_PLAINTEXT:
1060#ifdef UNICODE
1061 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pszSecret, -1, szBuffer, MAX_SECRET_LENGTH);
1062 msg.SetVariable(VID_SHARED_SECRET, szBuffer);
1063#else
1064 msg.SetVariable(VID_SHARED_SECRET, pszSecret);
1065#endif
1066 break;
1067 case AUTH_MD5_HASH:
1068 CalculateMD5Hash((BYTE *)pszSecret, (int)strlen(pszSecret), hash);
1069 msg.SetVariable(VID_SHARED_SECRET, hash, MD5_DIGEST_SIZE);
1070 break;
1071 case AUTH_SHA1_HASH:
1072 CalculateSHA1Hash((BYTE *)pszSecret, (int)strlen(pszSecret), hash);
1073 msg.SetVariable(VID_SHARED_SECRET, hash, SHA1_DIGEST_SIZE);
1074 break;
1075 default:
1076 break;
1077 }
7c521895
VK
1078 if (sendMessage(&msg))
1079 return waitForRCC(dwRqId, m_dwCommandTimeout);
5039dede
AK
1080 else
1081 return ERR_CONNECTION_BROKEN;
1082}
1083
1084
1085//
1086// Execute action on agent
1087//
1088
967893bb 1089UINT32 AgentConnection::execAction(const TCHAR *pszAction, int argc, TCHAR **argv)
5039dede
AK
1090{
1091 CSCPMessage msg(m_nProtocolVersion);
967893bb 1092 UINT32 dwRqId;
5039dede
AK
1093 int i;
1094
1095 if (!m_bIsConnected)
1096 return ERR_NOT_CONNECTED;
1097
1098 dwRqId = m_dwRequestId++;
1099 msg.SetCode(CMD_ACTION);
1100 msg.SetId(dwRqId);
1101 msg.SetVariable(VID_ACTION_NAME, pszAction);
967893bb 1102 msg.SetVariable(VID_NUM_ARGS, (UINT32)argc);
5039dede
AK
1103 for(i = 0; i < argc; i++)
1104 msg.SetVariable(VID_ACTION_ARG_BASE + i, argv[i]);
1105
7c521895
VK
1106 if (sendMessage(&msg))
1107 return waitForRCC(dwRqId, m_dwCommandTimeout);
5039dede
AK
1108 else
1109 return ERR_CONNECTION_BROKEN;
1110}
1111
74d2f1ea 1112/**
1113 * Upload file to agent
1114 */
967893bb 1115UINT32 AgentConnection::uploadFile(const TCHAR *localFile, const TCHAR *destinationFile, void (* progressCallback)(INT64, void *), void *cbArg)
5039dede 1116{
967893bb 1117 UINT32 dwRqId, dwResult;
5039dede 1118 CSCPMessage msg(m_nProtocolVersion);
5039dede
AK
1119
1120 if (!m_bIsConnected)
1121 return ERR_NOT_CONNECTED;
1122
1123 dwRqId = m_dwRequestId++;
8581943e 1124 msg.SetId(dwRqId);
5039dede 1125
8581943e
VK
1126 // Use core agent if destination file name is not set and file manager subagent otherwise
1127 if ((destinationFile == NULL) || (*destinationFile == 0))
74d2f1ea 1128 {
1129 msg.SetCode(CMD_TRANSFER_FILE);
8581943e
VK
1130 int i;
1131 for(i = (int)_tcslen(localFile) - 1;
1132 (i >= 0) && (localFile[i] != '\\') && (localFile[i] != '/'); i--);
1133 msg.SetVariable(VID_FILE_NAME, &localFile[i + 1]);
74d2f1ea 1134 }
1135 else
1136 {
1137 msg.SetCode(CMD_FILEMGR_UPLOAD);
74d2f1ea 1138 msg.SetVariable(VID_FILE_NAME, destinationFile);
f0c1d2a4 1139 }
5039dede 1140
7c521895 1141 if (sendMessage(&msg))
5039dede 1142 {
7c521895 1143 dwResult = waitForRCC(dwRqId, m_dwCommandTimeout);
5039dede
AK
1144 }
1145 else
1146 {
1147 dwResult = ERR_CONNECTION_BROKEN;
1148 }
1149
1150 if (dwResult == ERR_SUCCESS)
1151 {
4685a2ad 1152 m_fileUploadInProgress = true;
98abc9f1 1153 NXCPEncryptionContext *ctx = acquireEncryptionContext();
cc022855 1154 if (SendFileOverNXCP(m_hSocket, dwRqId, localFile, ctx, 0, progressCallback, cbArg, m_mutexSocketWrite))
7c521895 1155 dwResult = waitForRCC(dwRqId, m_dwCommandTimeout);
5039dede
AK
1156 else
1157 dwResult = ERR_IO_FAILURE;
4685a2ad 1158 m_fileUploadInProgress = false;
5039dede
AK
1159 }
1160
1161 return dwResult;
1162}
1163
8581943e
VK
1164/**
1165 * Send upgrade command
1166 */
967893bb 1167UINT32 AgentConnection::startUpgrade(const TCHAR *pszPkgName)
5039dede 1168{
967893bb 1169 UINT32 dwRqId, dwResult;
5039dede
AK
1170 CSCPMessage msg(m_nProtocolVersion);
1171 int i;
1172
1173 if (!m_bIsConnected)
1174 return ERR_NOT_CONNECTED;
1175
1176 dwRqId = m_dwRequestId++;
1177
1178 msg.SetCode(CMD_UPGRADE_AGENT);
1179 msg.SetId(dwRqId);
cc022855 1180 for(i = (int)_tcslen(pszPkgName) - 1;
5039dede
AK
1181 (i >= 0) && (pszPkgName[i] != '\\') && (pszPkgName[i] != '/'); i--);
1182 msg.SetVariable(VID_FILE_NAME, &pszPkgName[i + 1]);
1183
7c521895 1184 if (sendMessage(&msg))
5039dede 1185 {
7c521895 1186 dwResult = waitForRCC(dwRqId, m_dwCommandTimeout);
5039dede
AK
1187 }
1188 else
1189 {
1190 dwResult = ERR_CONNECTION_BROKEN;
1191 }
1192
1193 return dwResult;
1194}
1195
a0e181dc
VK
1196/**
1197 * Check status of network service via agent
1198 */
cc022855 1199UINT32 AgentConnection::checkNetworkService(UINT32 *pdwStatus, UINT32 dwIpAddr, int iServiceType,
1200 WORD wPort, WORD wProto,
5039dede
AK
1201 const TCHAR *pszRequest, const TCHAR *pszResponse)
1202{
967893bb 1203 UINT32 dwRqId, dwResult;
5039dede 1204 CSCPMessage msg(m_nProtocolVersion), *pResponse;
a0e181dc 1205 static WORD m_wDefaultPort[] = { 7, 22, 110, 25, 21, 80, 443, 23 };
5039dede
AK
1206
1207 if (!m_bIsConnected)
1208 return ERR_NOT_CONNECTED;
1209
1210 dwRqId = m_dwRequestId++;
1211
1212 msg.SetCode(CMD_CHECK_NETWORK_SERVICE);
1213 msg.SetId(dwRqId);
1214 msg.SetVariable(VID_IP_ADDRESS, dwIpAddr);
1215 msg.SetVariable(VID_SERVICE_TYPE, (WORD)iServiceType);
cc022855 1216 msg.SetVariable(VID_IP_PORT,
1217 (wPort != 0) ? wPort :
1218 m_wDefaultPort[((iServiceType >= NETSRV_CUSTOM) &&
a0e181dc 1219 (iServiceType <= NETSRV_TELNET)) ? iServiceType : 0]);
5039dede
AK
1220 msg.SetVariable(VID_IP_PROTO, (wProto != 0) ? wProto : (WORD)IPPROTO_TCP);
1221 msg.SetVariable(VID_SERVICE_REQUEST, pszRequest);
1222 msg.SetVariable(VID_SERVICE_RESPONSE, pszResponse);
1223
7c521895 1224 if (sendMessage(&msg))
5039dede
AK
1225 {
1226 // Wait up to 90 seconds for results
7c521895 1227 pResponse = waitForMessage(CMD_REQUEST_COMPLETED, dwRqId, 90000);
5039dede
AK
1228 if (pResponse != NULL)
1229 {
1230 dwResult = pResponse->GetVariableLong(VID_RCC);
1231 if (dwResult == ERR_SUCCESS)
1232 {
1233 *pdwStatus = pResponse->GetVariableLong(VID_SERVICE_STATUS);
1234 }
1235 delete pResponse;
1236 }
1237 else
1238 {
1239 dwResult = ERR_REQUEST_TIMEOUT;
1240 }
1241 }
1242 else
1243 {
1244 dwResult = ERR_CONNECTION_BROKEN;
1245 }
1246
1247 return dwResult;
1248}
1249
074498ac 1250/**
86c126f5 1251 * Get list of supported parameters from agent
074498ac 1252 */
967893bb 1253UINT32 AgentConnection::getSupportedParameters(ObjectArray<AgentParameterDefinition> **paramList, ObjectArray<AgentTableDefinition> **tableList)
5039dede 1254{
967893bb 1255 UINT32 dwRqId, dwResult;
5039dede
AK
1256 CSCPMessage msg(m_nProtocolVersion), *pResponse;
1257
cc8ce218
VK
1258 *paramList = NULL;
1259 *tableList = NULL;
5039dede
AK
1260
1261 if (!m_bIsConnected)
1262 return ERR_NOT_CONNECTED;
1263
1264 dwRqId = m_dwRequestId++;
1265
1266 msg.SetCode(CMD_GET_PARAMETER_LIST);
1267 msg.SetId(dwRqId);
1268
7c521895 1269 if (sendMessage(&msg))
5039dede 1270 {
7c521895 1271 pResponse = waitForMessage(CMD_REQUEST_COMPLETED, dwRqId, m_dwCommandTimeout);
5039dede
AK
1272 if (pResponse != NULL)
1273 {
1274 dwResult = pResponse->GetVariableLong(VID_RCC);
cc8ce218 1275 DbgPrintf(6, _T("AgentConnection::getSupportedParameters(): RCC=%d"), dwResult);
5039dede
AK
1276 if (dwResult == ERR_SUCCESS)
1277 {
967893bb 1278 UINT32 count = pResponse->GetVariableLong(VID_NUM_PARAMETERS);
86c126f5 1279 ObjectArray<AgentParameterDefinition> *plist = new ObjectArray<AgentParameterDefinition>(count, 16, true);
967893bb 1280 for(UINT32 i = 0, dwId = VID_PARAM_LIST_BASE; i < count; i++)
5039dede 1281 {
86c126f5
VK
1282 plist->add(new AgentParameterDefinition(pResponse, dwId));
1283 dwId += 3;
5039dede 1284 }
86c126f5 1285 *paramList = plist;
cc8ce218
VK
1286 DbgPrintf(6, _T("AgentConnection::getSupportedParameters(): %d parameters received from agent"), count);
1287
1288 count = pResponse->GetVariableLong(VID_NUM_TABLES);
86c126f5 1289 ObjectArray<AgentTableDefinition> *tlist = new ObjectArray<AgentTableDefinition>(count, 16, true);
967893bb 1290 for(UINT32 i = 0, dwId = VID_TABLE_LIST_BASE; i < count; i++)
cc8ce218 1291 {
86c126f5
VK
1292 tlist->add(new AgentTableDefinition(pResponse, dwId));
1293 dwId += 3;
cc8ce218 1294 }
86c126f5 1295 *tableList = tlist;
cc8ce218
VK
1296 DbgPrintf(6, _T("AgentConnection::getSupportedParameters(): %d tables received from agent"), count);
1297 }
5039dede
AK
1298 delete pResponse;
1299 }
1300 else
1301 {
1302 dwResult = ERR_REQUEST_TIMEOUT;
1303 }
1304 }
1305 else
1306 {
1307 dwResult = ERR_CONNECTION_BROKEN;
1308 }
1309
1310 return dwResult;
1311}
1312
074498ac
VK
1313/**
1314 * Setup encryption
1315 */
967893bb 1316UINT32 AgentConnection::setupEncryption(RSA *pServerKey)
5039dede
AK
1317{
1318#ifdef _WITH_ENCRYPTION
1319 CSCPMessage msg(m_nProtocolVersion), *pResp;
967893bb 1320 UINT32 dwRqId, dwError, dwResult;
5039dede
AK
1321
1322 dwRqId = m_dwRequestId++;
1323
9e9d631e 1324 PrepareKeyRequestMsg(&msg, pServerKey, false);
5039dede 1325 msg.SetId(dwRqId);
7c521895 1326 if (sendMessage(&msg))
5039dede 1327 {
7c521895 1328 pResp = waitForMessage(CMD_SESSION_KEY, dwRqId, m_dwCommandTimeout);
5039dede
AK
1329 if (pResp != NULL)
1330 {
1331 dwResult = SetupEncryptionContext(pResp, &m_pCtx, NULL, pServerKey, m_nProtocolVersion);
1332 switch(dwResult)
1333 {
1334 case RCC_SUCCESS:
1335 dwError = ERR_SUCCESS;
1336 break;
1337 case RCC_NO_CIPHERS:
1338 dwError = ERR_NO_CIPHERS;
1339 break;
1340 case RCC_INVALID_PUBLIC_KEY:
1341 dwError = ERR_INVALID_PUBLIC_KEY;
1342 break;
1343 case RCC_INVALID_SESSION_KEY:
1344 dwError = ERR_INVALID_SESSION_KEY;
1345 break;
1346 default:
1347 dwError = ERR_INTERNAL_ERROR;
1348 break;
1349 }
1350 delete pResp;
1351 }
1352 else
1353 {
1354 dwError = ERR_REQUEST_TIMEOUT;
1355 }
1356 }
1357 else
1358 {
1359 dwError = ERR_CONNECTION_BROKEN;
1360 }
1361
1362 return dwError;
1363#else
1364 return ERR_NOT_IMPLEMENTED;
1365#endif
1366}
1367
1368
1369//
1370// Get configuration file from agent
1371//
1372
967893bb 1373UINT32 AgentConnection::getConfigFile(TCHAR **ppszConfig, UINT32 *pdwSize)
5039dede 1374{
967893bb 1375 UINT32 i, dwRqId, dwResult;
5039dede
AK
1376 CSCPMessage msg(m_nProtocolVersion), *pResponse;
1377#ifdef UNICODE
1378 BYTE *pBuffer;
1379#endif
1380
1381 *ppszConfig = NULL;
1382 *pdwSize = 0;
1383
1384 if (!m_bIsConnected)
1385 return ERR_NOT_CONNECTED;
1386
1387 dwRqId = m_dwRequestId++;
1388
1389 msg.SetCode(CMD_GET_AGENT_CONFIG);
1390 msg.SetId(dwRqId);
1391
7c521895 1392 if (sendMessage(&msg))
5039dede 1393 {
7c521895 1394 pResponse = waitForMessage(CMD_REQUEST_COMPLETED, dwRqId, m_dwCommandTimeout);
5039dede
AK
1395 if (pResponse != NULL)
1396 {
1397 dwResult = pResponse->GetVariableLong(VID_RCC);
1398 if (dwResult == ERR_SUCCESS)
1399 {
1400 *pdwSize = pResponse->GetVariableBinary(VID_CONFIG_FILE, NULL, 0);
1401 *ppszConfig = (TCHAR *)malloc((*pdwSize + 1) * sizeof(TCHAR));
1402#ifdef UNICODE
1403 pBuffer = (BYTE *)malloc(*pdwSize + 1);
1404 pResponse->GetVariableBinary(VID_CONFIG_FILE, pBuffer, *pdwSize);
08b214c6 1405 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (char *)pBuffer, *pdwSize, *ppszConfig, *pdwSize);
5039dede
AK
1406 free(pBuffer);
1407#else
1408 pResponse->GetVariableBinary(VID_CONFIG_FILE, (BYTE *)(*ppszConfig), *pdwSize);
1409#endif
1410 (*ppszConfig)[*pdwSize] = 0;
1411
1412 // We expect text file, so replace all non-printable characters with spaces
1413 for(i = 0; i < *pdwSize; i++)
cc022855 1414 if (((*ppszConfig)[i] < _T(' ')) &&
5039dede
AK
1415 ((*ppszConfig)[i] != _T('\t')) &&
1416 ((*ppszConfig)[i] != _T('\r')) &&
1417 ((*ppszConfig)[i] != _T('\n')))
1418 (*ppszConfig)[i] = _T(' ');
1419 }
1420 delete pResponse;
1421 }
1422 else
1423 {
1424 dwResult = ERR_REQUEST_TIMEOUT;
1425 }
1426 }
1427 else
1428 {
1429 dwResult = ERR_CONNECTION_BROKEN;
1430 }
1431
1432 return dwResult;
1433}
1434
1435
1436//
1437// Get configuration file from agent
1438//
1439
967893bb 1440UINT32 AgentConnection::updateConfigFile(const TCHAR *pszConfig)
5039dede 1441{
967893bb 1442 UINT32 dwRqId, dwResult;
5039dede
AK
1443 CSCPMessage msg(m_nProtocolVersion);
1444#ifdef UNICODE
1445 int nChars;
1446 BYTE *pBuffer;
1447#endif
1448
1449 if (!m_bIsConnected)
1450 return ERR_NOT_CONNECTED;
1451
1452 dwRqId = m_dwRequestId++;
1453
1454 msg.SetCode(CMD_UPDATE_AGENT_CONFIG);
1455 msg.SetId(dwRqId);
1456#ifdef UNICODE
465b3f2d 1457 nChars = (int)_tcslen(pszConfig);
5039dede
AK
1458 pBuffer = (BYTE *)malloc(nChars + 1);
1459 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR,
08b214c6 1460 pszConfig, nChars, (char *)pBuffer, nChars + 1, NULL, NULL);
5039dede
AK
1461 msg.SetVariable(VID_CONFIG_FILE, pBuffer, nChars);
1462 free(pBuffer);
1463#else
967893bb 1464 msg.SetVariable(VID_CONFIG_FILE, (BYTE *)pszConfig, (UINT32)strlen(pszConfig));
5039dede
AK
1465#endif
1466
7c521895 1467 if (sendMessage(&msg))
5039dede 1468 {
7c521895 1469 dwResult = waitForRCC(dwRqId, m_dwCommandTimeout);
5039dede
AK
1470 }
1471 else
1472 {
1473 dwResult = ERR_CONNECTION_BROKEN;
1474 }
1475
1476 return dwResult;
1477}
1478
1479
1480//
1481// Get routing table from agent
1482//
1483
4687826e 1484ROUTING_TABLE *AgentConnection::getRoutingTable()
5039dede
AK
1485{
1486 ROUTING_TABLE *pRT = NULL;
967893bb 1487 UINT32 i, dwBits;
5039dede
AK
1488 TCHAR *pChar, *pBuf;
1489
4687826e 1490 if (getList(_T("Net.IP.RoutingTable")) == ERR_SUCCESS)
5039dede
AK
1491 {
1492 pRT = (ROUTING_TABLE *)malloc(sizeof(ROUTING_TABLE));
1493 pRT->iNumEntries = m_dwNumDataLines;
1494 pRT->pRoutes = (ROUTE *)malloc(sizeof(ROUTE) * m_dwNumDataLines);
1495 memset(pRT->pRoutes, 0, sizeof(ROUTE) * m_dwNumDataLines);
1496 for(i = 0; i < m_dwNumDataLines; i++)
1497 {
1498 pBuf = m_ppDataLines[i];
1499
1500 // Destination address and mask
1501 pChar = _tcschr(pBuf, _T(' '));
1502 if (pChar != NULL)
1503 {
1504 TCHAR *pSlash;
1505 static TCHAR defaultMask[] = _T("24");
1506
1507 *pChar = 0;
1508 pSlash = _tcschr(pBuf, _T('/'));
1509 if (pSlash != NULL)
1510 {
1511 *pSlash = 0;
1512 pSlash++;
1513 }
1514 else // Just a paranoia protection, should'n happen if agent working correctly
1515 {
1516 pSlash = defaultMask;
1517 }
1518 pRT->pRoutes[i].dwDestAddr = ntohl(_t_inet_addr(pBuf));
1519 dwBits = _tcstoul(pSlash, NULL, 10);
1520 pRT->pRoutes[i].dwDestMask = (dwBits == 32) ? 0xFFFFFFFF : (~(0xFFFFFFFF >> dwBits));
1521 pBuf = pChar + 1;
1522 }
1523
1524 // Next hop address
1525 pChar = _tcschr(pBuf, _T(' '));
1526 if (pChar != NULL)
1527 {
1528 *pChar = 0;
1529 pRT->pRoutes[i].dwNextHop = ntohl(_t_inet_addr(pBuf));
1530 pBuf = pChar + 1;
1531 }
1532
1533 // Interface index
1534 pChar = _tcschr(pBuf, ' ');
1535 if (pChar != NULL)
1536 {
1537 *pChar = 0;
1538 pRT->pRoutes[i].dwIfIndex = _tcstoul(pBuf, NULL, 10);
1539 pBuf = pChar + 1;
1540 }
1541
1542 // Route type
1543 pRT->pRoutes[i].dwRouteType = _tcstoul(pBuf, NULL, 10);
1544 }
1545
a3050773 1546 lock();
7c521895 1547 destroyResultData();
a3050773 1548 unlock();
5039dede
AK
1549 }
1550
1551 return pRT;
1552}
1553
1554
1555//
1556// Set proxy information
1557//
1558
967893bb 1559void AgentConnection::setProxy(UINT32 dwAddr, WORD wPort, int iAuthMethod, const TCHAR *pszSecret)
5039dede
AK
1560{
1561 m_dwProxyAddr = dwAddr;
1562 m_wProxyPort = wPort;
1563 m_iProxyAuth = iAuthMethod;
1564 if (pszSecret != NULL)
1565 {
1566#ifdef UNICODE
cc022855 1567 WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR,
5039dede
AK
1568 pszSecret, -1, m_szProxySecret, MAX_SECRET_LENGTH, NULL, NULL);
1569#else
1570 nx_strncpy(m_szProxySecret, pszSecret, MAX_SECRET_LENGTH);
1571#endif
1572 }
1573 else
1574 {
1575 m_szProxySecret[0] = 0;
1576 }
1577 m_bUseProxy = TRUE;
1578}
1579
1580
1581//
1582// Setup proxy connection
1583//
1584
967893bb 1585UINT32 AgentConnection::setupProxyConnection()
5039dede
AK
1586{
1587 CSCPMessage msg(m_nProtocolVersion);
967893bb 1588 UINT32 dwRqId;
5039dede
AK
1589
1590 dwRqId = m_dwRequestId++;
1591 msg.SetCode(CMD_SETUP_PROXY_CONNECTION);
1592 msg.SetId(dwRqId);
967893bb 1593 msg.SetVariable(VID_IP_ADDRESS, (UINT32)ntohl(m_dwAddr));
5039dede 1594 msg.SetVariable(VID_AGENT_PORT, m_wPort);
7c521895
VK
1595 if (sendMessage(&msg))
1596 return waitForRCC(dwRqId, 60000); // Wait 60 seconds for remote connect
5039dede
AK
1597 else
1598 return ERR_CONNECTION_BROKEN;
1599}
1600
ef8278f0
VK
1601/**
1602 * Enable trap receiving on connection
1603 */
967893bb 1604UINT32 AgentConnection::enableTraps()
5039dede
AK
1605{
1606 CSCPMessage msg(m_nProtocolVersion);
967893bb 1607 UINT32 dwRqId;
5039dede
AK
1608
1609 dwRqId = m_dwRequestId++;
1610 msg.SetCode(CMD_ENABLE_AGENT_TRAPS);
1611 msg.SetId(dwRqId);
7c521895
VK
1612 if (sendMessage(&msg))
1613 return waitForRCC(dwRqId, m_dwCommandTimeout);
5039dede
AK
1614 else
1615 return ERR_CONNECTION_BROKEN;
1616}
1617
cc022855 1618/**
1619 * Send custom request to agent
1620 */
76b4edb5 1621CSCPMessage *AgentConnection::customRequest(CSCPMessage *pRequest, const TCHAR *recvFile, bool append, void (*downloadProgressCallback)(size_t, void *),
1622 void (*fileResendCallback)(CSCP_MESSAGE*, void *), void *cbArg)
5039dede 1623{
967893bb 1624 UINT32 dwRqId, rcc;
5039dede
AK
1625 CSCPMessage *msg = NULL;
1626
1627 dwRqId = m_dwRequestId++;
1628 pRequest->SetId(dwRqId);
1629 if (recvFile != NULL)
1630 {
76b4edb5 1631 rcc = prepareFileDownload(recvFile, dwRqId, append, downloadProgressCallback, fileResendCallback,cbArg);
5039dede
AK
1632 if (rcc != ERR_SUCCESS)
1633 {
1634 // Create fake response message
1635 msg = new CSCPMessage;
1636 msg->SetCode(CMD_REQUEST_COMPLETED);
1637 msg->SetId(dwRqId);
1638 msg->SetVariable(VID_RCC, rcc);
1639 }
1640 }
1641
1642 if (msg == NULL)
1643 {
7c521895 1644 if (sendMessage(pRequest))
5039dede 1645 {
7c521895 1646 msg = waitForMessage(CMD_REQUEST_COMPLETED, dwRqId, m_dwCommandTimeout);
5039dede
AK
1647 if ((msg != NULL) && (recvFile != NULL))
1648 {
1649 if (msg->GetVariableLong(VID_RCC) == ERR_SUCCESS)
1650 {
bb85e341 1651 if (ConditionWait(m_condFileDownload, 1800000)) // 30 min timeout
5039dede 1652 {
bb85e341 1653 if (!m_fileDownloadSucceeded)
5039dede
AK
1654 {
1655 msg->SetVariable(VID_RCC, ERR_IO_FAILURE);
901a5a9b 1656 if (m_deleteFileOnDownloadFailure)
08b214c6 1657 _tremove(recvFile);
5039dede
AK
1658 }
1659 }
1660 else
1661 {
1662 msg->SetVariable(VID_RCC, ERR_REQUEST_TIMEOUT);
1663 }
1664 }
1665 else
1666 {
ef8278f0 1667 if (fileResendCallback != NULL)
76b4edb5 1668 {
1669 close(m_hCurrFile);
1670 m_hCurrFile = -1;
1671 _tremove(recvFile);
1672 }
5039dede
AK
1673 }
1674 }
76b4edb5 1675
5039dede
AK
1676 }
1677 }
1678
1679 return msg;
1680}
1681
76b4edb5 1682/**
ef8278f0 1683 * Prepare for file download
76b4edb5 1684 */
76b4edb5 1685UINT32 AgentConnection::prepareFileDownload(const TCHAR *fileName, UINT32 rqId, bool append, void (*downloadProgressCallback)(size_t, void *),
ef8278f0 1686 void (*fileResendCallback)(CSCP_MESSAGE *, void *), void *cbArg)
5039dede 1687{
ef8278f0 1688 if (fileResendCallback == NULL)
76b4edb5 1689 {
1690 if (m_hCurrFile != -1)
1691 return ERR_RESOURCE_BUSY;
5039dede 1692
76b4edb5 1693 nx_strncpy(m_currentFileName, fileName, MAX_PATH);
1694 ConditionReset(m_condFileDownload);
1695 m_hCurrFile = _topen(fileName, (append ? 0 : (O_CREAT | O_TRUNC)) | O_RDWR | O_BINARY, S_IREAD | S_IWRITE);
1696 if (m_hCurrFile == -1)
1697 {
1698 DbgPrintf(4, _T("AgentConnection::PrepareFileDownload(): cannot open file %s (%s); append=%d rqId=%d"),
1699 fileName, _tcserror(errno), append, rqId);
1700 }
1701 else
1702 {
1703 if (append)
1704 lseek(m_hCurrFile, 0, SEEK_END);
1705 }
1706
1707 m_dwDownloadRequestId = rqId;
1708 m_downloadProgressCallback = downloadProgressCallback;
1709 m_downloadProgressCallbackArg = cbArg;
1710
9630fcd1
AK
1711 m_sendToClientMessageCallback = NULL;
1712
76b4edb5 1713 return (m_hCurrFile != -1) ? ERR_SUCCESS : ERR_FILE_OPEN_ERROR;
1714 }
1715 else
1716 {
1717 ConditionReset(m_condFileDownload);
76b4edb5 1718
1719 m_dwDownloadRequestId = rqId;
1720 m_downloadProgressCallback = downloadProgressCallback;
1721 m_downloadProgressCallbackArg = cbArg;
1722
9630fcd1
AK
1723 m_sendToClientMessageCallback = fileResendCallback;
1724
76b4edb5 1725 return ERR_SUCCESS;
1726 }
5039dede
AK
1727}
1728
76b4edb5 1729/**
1730 * File upload completion handler
1731 */
f480bdd4 1732void AgentConnection::onFileDownload(BOOL success)
5039dede 1733{
76b4edb5 1734 if (!success && m_deleteFileOnDownloadFailure)
901a5a9b 1735 _tremove(m_currentFileName);
bb85e341
VK
1736 m_fileDownloadSucceeded = success;
1737 ConditionSet(m_condFileDownload);
5039dede 1738}
1f385e47 1739
ef8278f0
VK
1740/**
1741 * Enable trap receiving on connection
1742 */
967893bb 1743UINT32 AgentConnection::getPolicyInventory(AgentPolicyInfo **info)
1f385e47
VK
1744{
1745 CSCPMessage msg(m_nProtocolVersion);
967893bb 1746 UINT32 dwRqId, rcc;
1f385e47
VK
1747
1748 *info = NULL;
1749 dwRqId = m_dwRequestId++;
1750 msg.SetCode(CMD_GET_POLICY_INVENTORY);
1751 msg.SetId(dwRqId);
1752 if (sendMessage(&msg))
1753 {
1754 CSCPMessage *response = waitForMessage(CMD_REQUEST_COMPLETED, dwRqId, m_dwCommandTimeout);
1755 if (response != NULL)
1756 {
1757 rcc = response->GetVariableLong(VID_RCC);
1758 if (rcc == ERR_SUCCESS)
1759 *info = new AgentPolicyInfo(response);
1760 delete response;
1761 }
1762 else
1763 {
1764 rcc = ERR_REQUEST_TIMEOUT;
1765 }
1766 }
1767 else
1768 {
1769 rcc = ERR_CONNECTION_BROKEN;
1770 }
1771 return rcc;
1772}
1773
ef8278f0
VK
1774/**
1775 * Uninstall policy by GUID
1776 */
967893bb 1777UINT32 AgentConnection::uninstallPolicy(uuid_t guid)
1f385e47 1778{
967893bb 1779 UINT32 rqId, rcc;
1f385e47
VK
1780 CSCPMessage msg(m_nProtocolVersion);
1781
1782 rqId = generateRequestId();
1783 msg.SetId(rqId);
1784 msg.SetCode(CMD_UNINSTALL_AGENT_POLICY);
1785 msg.SetVariable(VID_GUID, guid, UUID_LENGTH);
1786 if (sendMessage(&msg))
1787 {
1788 rcc = waitForRCC(rqId, m_dwCommandTimeout);
1789 }
1790 else
1791 {
1792 rcc = ERR_CONNECTION_BROKEN;
1793 }
1794 return rcc;
1795}
98abc9f1 1796
86c126f5
VK
1797/**
1798 * Acquire encryption context
1799 */
98abc9f1
VK
1800NXCPEncryptionContext *AgentConnection::acquireEncryptionContext()
1801{
a3050773 1802 lock();
98abc9f1
VK
1803 NXCPEncryptionContext *ctx = m_pCtx;
1804 if (ctx != NULL)
1805 ctx->incRefCount();
a3050773 1806 unlock();
98abc9f1
VK
1807 return ctx;
1808}
86c126f5
VK
1809
1810/**
1811 * Create new agent parameter definition from NXCP message
1812 */
967893bb 1813AgentParameterDefinition::AgentParameterDefinition(CSCPMessage *msg, UINT32 baseId)
86c126f5
VK
1814{
1815 m_name = msg->GetVariableStr(baseId);
1816 m_description = msg->GetVariableStr(baseId + 1);
1817 m_dataType = (int)msg->GetVariableShort(baseId + 2);
1818}
1819
1820/**
1821 * Create new agent parameter definition from another definition object
1822 */
1823AgentParameterDefinition::AgentParameterDefinition(AgentParameterDefinition *src)
1824{
1825 m_name = (src->m_name != NULL) ? _tcsdup(src->m_name) : NULL;
1826 m_description = (src->m_description != NULL) ? _tcsdup(src->m_description) : NULL;
1827 m_dataType = src->m_dataType;
1828}
1829
1830/**
1831 * Destructor for agent parameter definition
1832 */
1833AgentParameterDefinition::~AgentParameterDefinition()
1834{
1835 safe_free(m_name);
1836 safe_free(m_description);
1837}
1838
1839/**
1840 * Fill NXCP message
1841 */
967893bb 1842UINT32 AgentParameterDefinition::fillMessage(CSCPMessage *msg, UINT32 baseId)
86c126f5
VK
1843{
1844 msg->SetVariable(baseId, m_name);
1845 msg->SetVariable(baseId + 1, m_description);
1846 msg->SetVariable(baseId + 2, (WORD)m_dataType);
1847 return 3;
1848}
1849
1850/**
1851 * Create new agent table definition from NXCP message
1852 */
967893bb 1853AgentTableDefinition::AgentTableDefinition(CSCPMessage *msg, UINT32 baseId)
86c126f5
VK
1854{
1855 m_name = msg->GetVariableStr(baseId);
1856 m_description = msg->GetVariableStr(baseId + 2);
1857
1858 TCHAR *instanceColumns = msg->GetVariableStr(baseId + 1);
1859 if (instanceColumns != NULL)
1860 {
1861 m_instanceColumns = new StringList(instanceColumns, _T("|"));
1862 free(instanceColumns);
1863 }
1864 else
1865 {
1866 m_instanceColumns = new StringList;
1867 }
1868
1869 m_columns = new ObjectArray<AgentTableColumnDefinition>(16, 16, true);
1870}
1871
1872/**
1873 * Create new agent table definition from another definition object
1874 */
1875AgentTableDefinition::AgentTableDefinition(AgentTableDefinition *src)
1876{
1877 m_name = (src->m_name != NULL) ? _tcsdup(src->m_name) : NULL;
1878 m_description = (src->m_description != NULL) ? _tcsdup(src->m_description) : NULL;
1879 m_instanceColumns = new StringList(src->m_instanceColumns);
1880 m_columns = new ObjectArray<AgentTableColumnDefinition>(16, 16, true);
1881 for(int i = 0; i < src->m_columns->size(); i++)
1882 {
1883 m_columns->add(new AgentTableColumnDefinition(src->m_columns->get(i)));
1884 }
1885}
1886/**
1887 * Destructor for agent table definition
1888 */
1889AgentTableDefinition::~AgentTableDefinition()
1890{
1891 safe_free(m_name);
1892 safe_free(m_description);
1893 delete m_instanceColumns;
1894 delete m_columns;
1895}
1896
1897/**
1898 * Fill NXCP message
1899 */
967893bb 1900UINT32 AgentTableDefinition::fillMessage(CSCPMessage *msg, UINT32 baseId)
86c126f5
VK
1901{
1902 msg->SetVariable(baseId + 1, m_name);
1903 msg->SetVariable(baseId + 2, m_description);
1904
1905 TCHAR *instanceColumns = m_instanceColumns->join(_T("|"));
1906 msg->SetVariable(baseId + 3, instanceColumns);
1907 free(instanceColumns);
1908
967893bb 1909 UINT32 varId = baseId + 4;
86c126f5
VK
1910 for(int i = 0; i < m_columns->size(); i++)
1911 {
1912 msg->SetVariable(varId++, m_columns->get(i)->m_name);
1913 msg->SetVariable(varId++, (WORD)m_columns->get(i)->m_dataType);
1914 }
1915
1916 msg->SetVariable(baseId, varId - baseId);
1917 return varId - baseId;
1918}