implemented new tdata format
[public/netxms.git] / src / server / core / session.cpp
1 /*
2 ** NetXMS - Network Management System
3 ** Copyright (C) 2003-2016 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: session.cpp
20 **
21 **/
22
23 #include "nxcore.h"
24 #include <netxms_mt.h>
25 #include <nxtools.h>
26 #include <nxstat.h>
27
28 #ifdef _WIN32
29 #include <psapi.h>
30 #define write _write
31 #define close _close
32 #else
33 #include <dirent.h>
34 #endif
35
36 #ifdef WITH_ZMQ
37 #include "zeromq.h"
38 #endif
39
40 #ifndef min
41 #define min(a,b) ((a) < (b) ? (a) : (b))
42 #endif
43
44 // WARNING! this hack works only for d2i_X509(); be carefull when adding new code
45 #ifdef OPENSSL_CONST
46 # undef OPENSSL_CONST
47 #endif
48 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
49 # define OPENSSL_CONST const
50 #else
51 # define OPENSSL_CONST
52 #endif
53
54 /**
55 * Constants
56 */
57 #define TRAP_CREATE 1
58 #define TRAP_UPDATE 2
59 #define TRAP_DELETE 3
60
61 #define MAX_MSG_SIZE 4194304
62
63 /**
64 * Externals
65 */
66 extern Queue g_nodePollerQueue;
67 extern Queue g_dataCollectionQueue;
68 extern Queue g_dciCacheLoaderQueue;
69
70 void UnregisterClientSession(int id);
71 void ResetDiscoveryPoller();
72 NXCPMessage *ForwardMessageToReportingServer(NXCPMessage *request, ClientSession *session);
73 void RemovePendingFileTransferRequests(ClientSession *session);
74 bool UpdateAddressListFromMessage(NXCPMessage *msg);
75
76 /**
77 * Node poller start data
78 */
79 typedef struct
80 {
81 ClientSession *pSession;
82 Node *pNode;
83 int iPollType;
84 UINT32 dwRqId;
85 } POLLER_START_DATA;
86
87 /**
88 * Additional processing thread start data
89 */
90 typedef struct
91 {
92 ClientSession *pSession;
93 NXCPMessage *pMsg;
94 } PROCTHREAD_START_DATA;
95
96 /**
97 *
98 */
99 typedef struct
100 {
101 uuid_t *guid;
102 bool removed;
103 } LIBRARY_IMAGE_UPDATE_INFO;
104
105 /**
106 * Callback to delete agent connections for loading files in destructor
107 */
108 static void DeleteCallback(NetObj* obj, void *data)
109 {
110 ((AgentConnection *)obj)->decRefCount();
111 }
112
113 /**
114 * Callback for sending image library update notifications
115 */
116 static void ImageLibraryUpdateCallback(ClientSession *pSession, void *pArg)
117 {
118 pSession->onLibraryImageChange((uuid_t *)pArg, false);
119 }
120
121 /**
122 * Callback for sending image library delete notifications
123 */
124 static void ImageLibraryDeleteCallback(ClientSession *pSession, void *pArg)
125 {
126 pSession->onLibraryImageChange((uuid_t *)pArg, true);
127 }
128
129 /**
130 * Additional message processing thread starters
131 */
132 #define CALL_IN_NEW_THREAD(func, msg) \
133 { \
134 PROCTHREAD_START_DATA *pData = (PROCTHREAD_START_DATA *)malloc(sizeof(PROCTHREAD_START_DATA)); \
135 pData->pSession = this; \
136 pData->pMsg = msg; \
137 msg = NULL; /* prevent deletion by main processing thread*/ \
138 InterlockedIncrement(&m_refCount); \
139 ThreadPoolExecute(g_mainThreadPool, ThreadStarter_##func, pData); \
140 }
141
142 #define DEFINE_THREAD_STARTER(func) \
143 void ClientSession::ThreadStarter_##func(void *pArg) \
144 { \
145 ((PROCTHREAD_START_DATA *)pArg)->pSession->debugPrintf(6, _T("Method ") _T(#func) _T(" called on background thread")); \
146 ((PROCTHREAD_START_DATA *)pArg)->pSession->func(((PROCTHREAD_START_DATA *)pArg)->pMsg); \
147 InterlockedDecrement(&((PROCTHREAD_START_DATA *)pArg)->pSession->m_refCount); \
148 delete ((PROCTHREAD_START_DATA *)pArg)->pMsg; \
149 free(pArg); \
150 }
151
152 DEFINE_THREAD_STARTER(cancelFileMonitoring)
153 DEFINE_THREAD_STARTER(clearDCIData)
154 DEFINE_THREAD_STARTER(createObject)
155 DEFINE_THREAD_STARTER(executeAction)
156 DEFINE_THREAD_STARTER(executeScript)
157 DEFINE_THREAD_STARTER(fileManagerControl)
158 DEFINE_THREAD_STARTER(findIpAddress)
159 DEFINE_THREAD_STARTER(findMacAddress)
160 DEFINE_THREAD_STARTER(findNodeConnection)
161 DEFINE_THREAD_STARTER(forceDCIPoll)
162 DEFINE_THREAD_STARTER(forwardToReportingServer)
163 DEFINE_THREAD_STARTER(getAgentFile)
164 DEFINE_THREAD_STARTER(getAlarms)
165 DEFINE_THREAD_STARTER(getAlarmEvents)
166 DEFINE_THREAD_STARTER(getCollectedData)
167 DEFINE_THREAD_STARTER(getLocationHistory)
168 DEFINE_THREAD_STARTER(getNetworkPath)
169 DEFINE_THREAD_STARTER(getRoutingTable)
170 DEFINE_THREAD_STARTER(getServerFile)
171 DEFINE_THREAD_STARTER(getServerLogQueryData)
172 DEFINE_THREAD_STARTER(getSwitchForwardingDatabase)
173 DEFINE_THREAD_STARTER(getTableCollectedData)
174 DEFINE_THREAD_STARTER(importConfiguration)
175 DEFINE_THREAD_STARTER(openHelpdeskIssue)
176 DEFINE_THREAD_STARTER(processConsoleCommand)
177 DEFINE_THREAD_STARTER(queryAgentTable)
178 DEFINE_THREAD_STARTER(queryL2Topology)
179 DEFINE_THREAD_STARTER(queryParameter)
180 DEFINE_THREAD_STARTER(queryServerLog)
181 DEFINE_THREAD_STARTER(sendEventLog)
182 DEFINE_THREAD_STARTER(sendMib)
183 DEFINE_THREAD_STARTER(sendSyslog)
184 DEFINE_THREAD_STARTER(uploadUserFileToAgent)
185 DEFINE_THREAD_STARTER(getRepositories)
186 DEFINE_THREAD_STARTER(addRepository)
187 DEFINE_THREAD_STARTER(modifyRepository)
188 DEFINE_THREAD_STARTER(deleteRepository)
189
190 /**
191 * Client communication read thread starter
192 */
193 THREAD_RESULT THREAD_CALL ClientSession::readThreadStarter(void *pArg)
194 {
195 ((ClientSession *)pArg)->readThread();
196
197 // When ClientSession::ReadThread exits, all other session
198 // threads are already stopped, so we can safely destroy
199 // session object
200 UnregisterClientSession(((ClientSession *)pArg)->getId());
201 delete (ClientSession *)pArg;
202 return THREAD_OK;
203 }
204
205 /**
206 * Client communication write thread starter
207 */
208 THREAD_RESULT THREAD_CALL ClientSession::writeThreadStarter(void *pArg)
209 {
210 ((ClientSession *)pArg)->writeThread();
211 return THREAD_OK;
212 }
213
214 /**
215 * Received message processing thread starter
216 */
217 THREAD_RESULT THREAD_CALL ClientSession::processingThreadStarter(void *pArg)
218 {
219 ((ClientSession *)pArg)->processingThread();
220 return THREAD_OK;
221 }
222
223 /**
224 * Information update processing thread starter
225 */
226 THREAD_RESULT THREAD_CALL ClientSession::updateThreadStarter(void *pArg)
227 {
228 ((ClientSession *)pArg)->updateThread();
229 return THREAD_OK;
230 }
231
232 /**
233 * Client session class constructor
234 */
235 ClientSession::ClientSession(SOCKET hSocket, struct sockaddr *addr)
236 {
237 m_pSendQueue = new Queue;
238 m_pMessageQueue = new Queue;
239 m_pUpdateQueue = new Queue;
240 m_hSocket = hSocket;
241 m_id = -1;
242 m_state = SESSION_STATE_INIT;
243 m_pCtx = NULL;
244 m_hWriteThread = INVALID_THREAD_HANDLE;
245 m_hProcessingThread = INVALID_THREAD_HANDLE;
246 m_hUpdateThread = INVALID_THREAD_HANDLE;
247 m_mutexSocketWrite = MutexCreate();
248 m_mutexSendEvents = MutexCreate();
249 m_mutexSendSyslog = MutexCreate();
250 m_mutexSendTrapLog = MutexCreate();
251 m_mutexSendObjects = MutexCreate();
252 m_mutexSendAlarms = MutexCreate();
253 m_mutexSendActions = MutexCreate();
254 m_mutexSendAuditLog = MutexCreate();
255 m_mutexSendSituations = MutexCreate();
256 m_mutexPollerInit = MutexCreate();
257 m_subscriptionLock = MutexCreate();
258 m_subscriptions = new StringObjectMap<UINT32>(true);
259 m_dwFlags = 0;
260 m_clientType = CLIENT_TYPE_DESKTOP;
261 m_clientAddr = (struct sockaddr *)nx_memdup(addr, (addr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6));
262 if (addr->sa_family == AF_INET)
263 IpToStr(ntohl(((struct sockaddr_in *)m_clientAddr)->sin_addr.s_addr), m_workstation);
264 #ifdef WITH_IPV6
265 else
266 Ip6ToStr(((struct sockaddr_in6 *)m_clientAddr)->sin6_addr.s6_addr, m_workstation);
267 #endif
268 m_webServerAddress[0] = 0;
269 m_loginName[0] = 0;
270 _tcscpy(m_sessionName, _T("<not logged in>"));
271 _tcscpy(m_clientInfo, _T("n/a"));
272 m_dwUserId = INVALID_INDEX;
273 m_dwSystemAccess = 0;
274 m_dwOpenDCIListSize = 0;
275 m_pOpenDCIList = NULL;
276 m_ppEPPRuleList = NULL;
277 m_wCurrentCmd = 0;
278 m_hCurrFile = -1;
279 m_dwFileRqId = 0;
280 m_dwUploadCommand = 0;
281 m_dwNumRecordsToUpload = 0;
282 m_dwRecordsUploaded = 0;
283 m_refCount = 0;
284 m_dwEncryptionRqId = 0;
285 m_dwEncryptionResult = 0;
286 m_dwUploadData = 0;
287 m_condEncryptionSetup = INVALID_CONDITION_HANDLE;
288 m_console = NULL;
289 m_loginTime = time(NULL);
290 m_musicTypeList.add(_T("wav"));
291 _tcscpy(m_language, _T("en"));
292 }
293
294 /**
295 * Destructor
296 */
297 ClientSession::~ClientSession()
298 {
299 if (m_hSocket != -1)
300 closesocket(m_hSocket);
301 delete m_pSendQueue;
302 delete m_pMessageQueue;
303 delete m_pUpdateQueue;
304 safe_free(m_clientAddr);
305 MutexDestroy(m_mutexSocketWrite);
306 MutexDestroy(m_mutexSendEvents);
307 MutexDestroy(m_mutexSendSyslog);
308 MutexDestroy(m_mutexSendTrapLog);
309 MutexDestroy(m_mutexSendObjects);
310 MutexDestroy(m_mutexSendAlarms);
311 MutexDestroy(m_mutexSendActions);
312 MutexDestroy(m_mutexSendAuditLog);
313 MutexDestroy(m_mutexSendSituations);
314 MutexDestroy(m_mutexPollerInit);
315 MutexDestroy(m_subscriptionLock);
316 delete m_subscriptions;
317 free(m_pOpenDCIList);
318 if (m_ppEPPRuleList != NULL)
319 {
320 UINT32 i;
321
322 if (m_dwFlags & CSF_EPP_UPLOAD) // Aborted in the middle of EPP transfer
323 for(i = 0; i < m_dwRecordsUploaded; i++)
324 delete m_ppEPPRuleList[i];
325 free(m_ppEPPRuleList);
326 }
327 if (m_pCtx != NULL)
328 m_pCtx->decRefCount();
329 if (m_condEncryptionSetup != INVALID_CONDITION_HANDLE)
330 ConditionDestroy(m_condEncryptionSetup);
331
332 if (m_console != NULL)
333 {
334 delete m_console->pMsg;
335 free(m_console);
336 }
337 m_musicTypeList.clear();
338 if (m_agentConn.size() > 0)
339 {
340 m_agentConn.forEach(&DeleteCallback, NULL);
341 }
342 }
343
344 /**
345 * Start all threads
346 */
347 void ClientSession::run()
348 {
349 m_hWriteThread = ThreadCreateEx(writeThreadStarter, 0, this);
350 m_hProcessingThread = ThreadCreateEx(processingThreadStarter, 0, this);
351 m_hUpdateThread = ThreadCreateEx(updateThreadStarter, 0, this);
352 ThreadCreate(readThreadStarter, 0, this);
353 }
354
355 /**
356 * Print debug information
357 */
358 void ClientSession::debugPrintf(int level, const TCHAR *format, ...)
359 {
360 if (level <= nxlog_get_debug_level())
361 {
362 va_list args;
363 TCHAR buffer[8192];
364
365 va_start(args, format);
366 _vsntprintf(buffer, 8192, format, args);
367 va_end(args);
368 DbgPrintf(level, _T("[CLSN-%d] %s"), m_id, buffer);
369 }
370 }
371
372 /**
373 * Write audit log
374 */
375 void ClientSession::writeAuditLog(const TCHAR *subsys, bool success, UINT32 objectId, const TCHAR *format, ...)
376 {
377 va_list args;
378 va_start(args, format);
379 WriteAuditLog2(subsys, success, m_dwUserId, m_workstation, m_id, objectId, format, args);
380 va_end(args);
381 }
382
383 /**
384 * Check channel subscription
385 */
386 bool ClientSession::isSubscribedTo(const TCHAR *channel) const
387 {
388 MutexLock(m_subscriptionLock);
389 bool subscribed = m_subscriptions->contains(channel);
390 MutexUnlock(m_subscriptionLock);
391 return subscribed;
392 }
393
394 /**
395 * Read thread
396 */
397 void ClientSession::readThread()
398 {
399 TCHAR szBuffer[256];
400 UINT32 i;
401 NetObj *object;
402
403 SocketMessageReceiver receiver(m_hSocket, 4096, MAX_MSG_SIZE);
404 while(true)
405 {
406 MessageReceiverResult result;
407 NXCPMessage *msg = receiver.readMessage(900000, &result);
408
409 // Check for decryption error
410 if (result == MSGRECV_DECRYPTION_FAILURE)
411 {
412 debugPrintf(4, _T("readThread: Unable to decrypt received message"));
413 continue;
414 }
415
416 // Receive error
417 if (msg == NULL)
418 {
419 if (result == MSGRECV_CLOSED)
420 debugPrintf(5, _T("readThread: connection closed"));
421 else
422 debugPrintf(5, _T("readThread: message receiving error (%s)"), AbstractMessageReceiver::resultToText(result));
423 break;
424 }
425
426 if (nxlog_get_debug_level() >= 8)
427 {
428 String msgDump = NXCPMessage::dump(receiver.getRawMessageBuffer(), NXCP_VERSION);
429 debugPrintf(8, _T("Message dump:\n%s"), (const TCHAR *)msgDump);
430 }
431
432 // Special handling for raw messages
433 if (msg->isBinary())
434 {
435 debugPrintf(6, _T("Received raw message %s"), NXCPMessageCodeName(msg->getCode(), szBuffer));
436
437 if ((msg->getCode() == CMD_FILE_DATA) ||
438 (msg->getCode() == CMD_ABORT_FILE_TRANSFER))
439 {
440 if ((m_hCurrFile != -1) && (m_dwFileRqId == msg->getId()))
441 {
442 if (msg->getCode() == CMD_FILE_DATA)
443 {
444 if (write(m_hCurrFile, msg->getBinaryData(), (int)msg->getBinaryDataSize()) == (int)msg->getBinaryDataSize())
445 {
446 if (msg->isEndOfFile())
447 {
448 debugPrintf(6, _T("Got end of file marker"));
449 NXCPMessage response;
450
451 close(m_hCurrFile);
452 m_hCurrFile = -1;
453
454 response.setCode(CMD_REQUEST_COMPLETED);
455 response.setId(msg->getId());
456 response.setField(VID_RCC, RCC_SUCCESS);
457 sendMessage(&response);
458
459 onFileUpload(TRUE);
460 }
461 }
462 else
463 {
464 debugPrintf(6, _T("I/O error"));
465 // I/O error
466 NXCPMessage response;
467
468 close(m_hCurrFile);
469 m_hCurrFile = -1;
470
471 response.setCode(CMD_REQUEST_COMPLETED);
472 response.setId(msg->getId());
473 response.setField(VID_RCC, RCC_IO_ERROR);
474 sendMessage(&response);
475
476 onFileUpload(FALSE);
477 }
478 }
479 else
480 {
481 // Abort current file transfer because of client's problem
482 close(m_hCurrFile);
483 m_hCurrFile = -1;
484
485 onFileUpload(FALSE);
486 }
487 }
488 else
489 {
490 AgentConnection *conn = (AgentConnection *)m_agentConn.get(msg->getId());
491 if (conn != NULL)
492 {
493 if (msg->getCode() == CMD_FILE_DATA)
494 {
495 if (conn->sendMessage(msg)) //send raw message
496 {
497 if (msg->isEndOfFile())
498 {
499 debugPrintf(6, _T("Got end of file marker"));
500 //get response with specific ID if ok< then send ok, else send error
501 m_agentConn.remove(msg->getId());
502 conn->decRefCount();
503
504 NXCPMessage response;
505 response.setCode(CMD_REQUEST_COMPLETED);
506 response.setId(msg->getId());
507 response.setField(VID_RCC, RCC_SUCCESS);
508 sendMessage(&response);
509 }
510 }
511 else
512 {
513 debugPrintf(6, _T("Error while sending to agent"));
514 // I/O error
515 m_agentConn.remove(msg->getId());
516 conn->decRefCount();
517
518 NXCPMessage response;
519 response.setCode(CMD_REQUEST_COMPLETED);
520 response.setId(msg->getId());
521 response.setField(VID_RCC, RCC_IO_ERROR); //set result that came from agent
522 sendMessage(&response);
523 }
524 }
525 else
526 {
527 // Resend abort message
528 conn->sendMessage(msg);
529 m_agentConn.remove(msg->getId());
530 conn->decRefCount();
531 }
532 }
533 else
534 {
535 debugPrintf(4, _T("Out of state message (ID: %d)"), msg->getId());
536 }
537 }
538 }
539 delete msg;
540 }
541 else
542 {
543 if ((msg->getCode() == CMD_SESSION_KEY) && (msg->getId() == m_dwEncryptionRqId))
544 {
545 debugPrintf(6, _T("Received message %s"), NXCPMessageCodeName(msg->getCode(), szBuffer));
546 m_dwEncryptionResult = SetupEncryptionContext(msg, &m_pCtx, NULL, g_pServerKey, NXCP_VERSION);
547 receiver.setEncryptionContext(m_pCtx);
548 ConditionSet(m_condEncryptionSetup);
549 m_dwEncryptionRqId = 0;
550 delete msg;
551 }
552 else if (msg->getCode() == CMD_KEEPALIVE)
553 {
554 debugPrintf(6, _T("Received message %s"), NXCPMessageCodeName(msg->getCode(), szBuffer));
555 respondToKeepalive(msg->getId());
556 delete msg;
557 }
558 else
559 {
560 m_pMessageQueue->put(msg);
561 }
562 }
563 }
564
565 // Mark as terminated (sendMessage calls will not work after that point)
566 m_dwFlags |= CSF_TERMINATED;
567
568 // Finish update thread first
569 m_pUpdateQueue->put(INVALID_POINTER_VALUE);
570 ThreadJoin(m_hUpdateThread);
571
572 // Notify other threads to exit
573 NXCP_MESSAGE *rawMsg;
574 while((rawMsg = (NXCP_MESSAGE *)m_pSendQueue->get()) != NULL)
575 free(rawMsg);
576 m_pSendQueue->put(INVALID_POINTER_VALUE);
577
578 NXCPMessage *msg;
579 while((msg = (NXCPMessage *)m_pMessageQueue->get()) != NULL)
580 delete msg;
581 m_pMessageQueue->put(INVALID_POINTER_VALUE);
582
583 // Wait for other threads to finish
584 ThreadJoin(m_hWriteThread);
585 ThreadJoin(m_hProcessingThread);
586
587 // Abort current file upload operation, if any
588 if (m_hCurrFile != -1)
589 {
590 close(m_hCurrFile);
591 m_hCurrFile = -1;
592 onFileUpload(FALSE);
593 }
594
595 // remove all pending file transfers from reporting server
596 RemovePendingFileTransferRequests(this);
597
598 // Remove all locks created by this session
599 RemoveAllSessionLocks(m_id);
600 for(i = 0; i < m_dwOpenDCIListSize; i++)
601 {
602 object = FindObjectById(m_pOpenDCIList[i]);
603 if (object != NULL)
604 if (object->isDataCollectionTarget() || (object->getObjectClass() == OBJECT_TEMPLATE))
605 ((Template *)object)->unlockDCIList(m_id);
606 }
607
608 // Waiting while reference count becomes 0
609 if (m_refCount > 0)
610 {
611 debugPrintf(3, _T("Waiting for pending requests..."));
612 do
613 {
614 ThreadSleep(1);
615 } while(m_refCount > 0);
616 }
617
618 if (m_dwFlags & CSF_AUTHENTICATED)
619 {
620 CALL_ALL_MODULES(pfClientSessionClose, (this));
621 WriteAuditLog(AUDIT_SECURITY, TRUE, m_dwUserId, m_workstation, m_id, 0, _T("User logged out (client: %s)"), m_clientInfo);
622 }
623 debugPrintf(3, _T("Session closed"));
624 }
625
626 /**
627 * Network write thread
628 */
629 void ClientSession::writeThread()
630 {
631 while(true)
632 {
633 NXCP_MESSAGE *rawMsg = (NXCP_MESSAGE *)m_pSendQueue->getOrBlock();
634 if (rawMsg == INVALID_POINTER_VALUE) // Session termination indicator
635 break;
636
637 sendRawMessage(rawMsg);
638 free(rawMsg);
639 }
640 }
641
642 /**
643 * Update processing thread
644 */
645 void ClientSession::updateThread()
646 {
647 UPDATE_INFO *pUpdate;
648 NXCPMessage msg;
649
650 while(1)
651 {
652 pUpdate = (UPDATE_INFO *)m_pUpdateQueue->getOrBlock();
653 if (pUpdate == INVALID_POINTER_VALUE) // Session termination indicator
654 break;
655
656 switch(pUpdate->dwCategory)
657 {
658 case INFO_CAT_EVENT:
659 MutexLock(m_mutexSendEvents);
660 sendMessage((NXCPMessage *)pUpdate->pData);
661 MutexUnlock(m_mutexSendEvents);
662 delete (NXCPMessage *)pUpdate->pData;
663 break;
664 case INFO_CAT_SYSLOG_MSG:
665 MutexLock(m_mutexSendSyslog);
666 msg.setCode(CMD_SYSLOG_RECORDS);
667 CreateMessageFromSyslogMsg(&msg, (NX_SYSLOG_RECORD *)pUpdate->pData);
668 sendMessage(&msg);
669 MutexUnlock(m_mutexSendSyslog);
670 free(pUpdate->pData);
671 break;
672 case INFO_CAT_SNMP_TRAP:
673 MutexLock(m_mutexSendTrapLog);
674 sendMessage((NXCPMessage *)pUpdate->pData);
675 MutexUnlock(m_mutexSendTrapLog);
676 delete (NXCPMessage *)pUpdate->pData;
677 break;
678 case INFO_CAT_AUDIT_RECORD:
679 MutexLock(m_mutexSendAuditLog);
680 sendMessage((NXCPMessage *)pUpdate->pData);
681 MutexUnlock(m_mutexSendAuditLog);
682 delete (NXCPMessage *)pUpdate->pData;
683 break;
684 case INFO_CAT_OBJECT_CHANGE:
685 MutexLock(m_mutexSendObjects);
686 msg.setCode(CMD_OBJECT_UPDATE);
687 if (!((NetObj *)pUpdate->pData)->isDeleted())
688 {
689 ((NetObj *)pUpdate->pData)->fillMessage(&msg);
690 if (m_dwFlags & CSF_SYNC_OBJECT_COMMENTS)
691 ((NetObj *)pUpdate->pData)->commentsToMessage(&msg);
692 }
693 else
694 {
695 msg.setField(VID_OBJECT_ID, ((NetObj *)pUpdate->pData)->getId());
696 msg.setField(VID_IS_DELETED, (WORD)1);
697 }
698 sendMessage(&msg);
699 MutexUnlock(m_mutexSendObjects);
700 msg.deleteAllFields();
701 ((NetObj *)pUpdate->pData)->decRefCount();
702 break;
703 case INFO_CAT_ALARM:
704 MutexLock(m_mutexSendAlarms);
705 msg.setCode(CMD_ALARM_UPDATE);
706 msg.setField(VID_NOTIFICATION_CODE, pUpdate->dwCode);
707 ((Alarm *)pUpdate->pData)->fillMessage(&msg);
708 sendMessage(&msg);
709 MutexUnlock(m_mutexSendAlarms);
710 msg.deleteAllFields();
711 delete (Alarm *)pUpdate->pData;
712 break;
713 case INFO_CAT_ACTION:
714 MutexLock(m_mutexSendActions);
715 msg.setCode(CMD_ACTION_DB_UPDATE);
716 msg.setField(VID_NOTIFICATION_CODE, pUpdate->dwCode);
717 msg.setField(VID_ACTION_ID, ((NXC_ACTION *)pUpdate->pData)->dwId);
718 if (pUpdate->dwCode != NX_NOTIFY_ACTION_DELETED)
719 FillActionInfoMessage(&msg, (NXC_ACTION *)pUpdate->pData);
720 sendMessage(&msg);
721 MutexUnlock(m_mutexSendActions);
722 msg.deleteAllFields();
723 free(pUpdate->pData);
724 break;
725 case INFO_CAT_SITUATION:
726 MutexLock(m_mutexSendSituations);
727 sendMessage((NXCPMessage *)pUpdate->pData);
728 MutexUnlock(m_mutexSendSituations);
729 delete (NXCPMessage *)pUpdate->pData;
730 break;
731 case INFO_CAT_LIBRARY_IMAGE:
732 {
733 LIBRARY_IMAGE_UPDATE_INFO *info = (LIBRARY_IMAGE_UPDATE_INFO *)pUpdate->pData;
734 msg.setCode(CMD_IMAGE_LIBRARY_UPDATE);
735 msg.setField(VID_GUID, (BYTE *)info->guid, UUID_LENGTH);
736 if (info->removed)
737 {
738 msg.setField(VID_FLAGS, (UINT32)1);
739 }
740 else
741 {
742 msg.setField(VID_FLAGS, (UINT32)0);
743 }
744 sendMessage(&msg);
745 msg.deleteAllFields();
746 free(info->guid);
747 free(info);
748 }
749 break;
750 default:
751 break;
752 }
753
754 free(pUpdate);
755 }
756 }
757
758 /**
759 * Message processing thread
760 */
761 void ClientSession::processingThread()
762 {
763 NXCPMessage *pMsg;
764 TCHAR szBuffer[128];
765 UINT32 i;
766 int status;
767
768 while(1)
769 {
770 pMsg = (NXCPMessage *)m_pMessageQueue->getOrBlock();
771 if (pMsg == INVALID_POINTER_VALUE) // Session termination indicator
772 break;
773
774 m_wCurrentCmd = pMsg->getCode();
775 debugPrintf(6, _T("Received message %s"), NXCPMessageCodeName(m_wCurrentCmd, szBuffer));
776 if (!(m_dwFlags & CSF_AUTHENTICATED) &&
777 (m_wCurrentCmd != CMD_LOGIN) &&
778 (m_wCurrentCmd != CMD_GET_SERVER_INFO) &&
779 (m_wCurrentCmd != CMD_REQUEST_ENCRYPTION) &&
780 (m_wCurrentCmd != CMD_GET_MY_CONFIG) &&
781 (m_wCurrentCmd != CMD_REGISTER_AGENT))
782 {
783 delete pMsg;
784 continue;
785 }
786
787 m_state = SESSION_STATE_PROCESSING;
788 switch(m_wCurrentCmd)
789 {
790 case CMD_LOGIN:
791 login(pMsg);
792 break;
793 case CMD_GET_SERVER_INFO:
794 sendServerInfo(pMsg->getId());
795 break;
796 case CMD_GET_MY_CONFIG:
797 sendConfigForAgent(pMsg);
798 break;
799 case CMD_GET_OBJECTS:
800 sendAllObjects(pMsg);
801 break;
802 case CMD_GET_SELECTED_OBJECTS:
803 sendSelectedObjects(pMsg);
804 break;
805 case CMD_GET_EVENTS:
806 CALL_IN_NEW_THREAD(sendEventLog, pMsg);
807 break;
808 case CMD_GET_CONFIG_VARLIST:
809 getConfigurationVariables(pMsg->getId());
810 break;
811 case CMD_GET_PUBLIC_CONFIG_VAR:
812 getPublicConfigurationVariable(pMsg);
813 break;
814 case CMD_SET_CONFIG_VARIABLE:
815 setConfigurationVariable(pMsg);
816 break;
817 case CMD_DELETE_CONFIG_VARIABLE:
818 deleteConfigurationVariable(pMsg);
819 break;
820 case CMD_CONFIG_GET_CLOB:
821 getConfigCLOB(pMsg);
822 break;
823 case CMD_CONFIG_SET_CLOB:
824 setConfigCLOB(pMsg);
825 break;
826 case CMD_LOAD_EVENT_DB:
827 sendEventDB(pMsg->getId());
828 break;
829 case CMD_SET_EVENT_INFO:
830 modifyEventTemplate(pMsg);
831 break;
832 case CMD_DELETE_EVENT_TEMPLATE:
833 deleteEventTemplate(pMsg);
834 break;
835 case CMD_GENERATE_EVENT_CODE:
836 generateEventCode(pMsg->getId());
837 break;
838 case CMD_MODIFY_OBJECT:
839 modifyObject(pMsg);
840 break;
841 case CMD_SET_OBJECT_MGMT_STATUS:
842 changeObjectMgmtStatus(pMsg);
843 break;
844 case CMD_ENTER_MAINT_MODE:
845 enterMaintenanceMode(pMsg);
846 break;
847 case CMD_LEAVE_MAINT_MODE:
848 leaveMaintenanceMode(pMsg);
849 break;
850 case CMD_LOAD_USER_DB:
851 sendUserDB(pMsg->getId());
852 break;
853 case CMD_CREATE_USER:
854 createUser(pMsg);
855 break;
856 case CMD_UPDATE_USER:
857 updateUser(pMsg);
858 break;
859 case CMD_DETACH_LDAP_USER:
860 detachLdapUser(pMsg);
861 break;
862 case CMD_DELETE_USER:
863 deleteUser(pMsg);
864 break;
865 case CMD_LOCK_USER_DB:
866 lockUserDB(pMsg->getId(), TRUE);
867 break;
868 case CMD_UNLOCK_USER_DB:
869 lockUserDB(pMsg->getId(), FALSE);
870 break;
871 case CMD_SET_PASSWORD:
872 setPassword(pMsg);
873 break;
874 case CMD_VALIDATE_PASSWORD:
875 validatePassword(pMsg);
876 break;
877 case CMD_GET_NODE_DCI_LIST:
878 openNodeDCIList(pMsg);
879 break;
880 case CMD_UNLOCK_NODE_DCI_LIST:
881 closeNodeDCIList(pMsg);
882 break;
883 case CMD_CREATE_NEW_DCI:
884 case CMD_MODIFY_NODE_DCI:
885 case CMD_DELETE_NODE_DCI:
886 modifyNodeDCI(pMsg);
887 break;
888 case CMD_SET_DCI_STATUS:
889 changeDCIStatus(pMsg);
890 break;
891 case CMD_COPY_DCI:
892 copyDCI(pMsg);
893 break;
894 case CMD_APPLY_TEMPLATE:
895 applyTemplate(pMsg);
896 break;
897 case CMD_GET_DCI_DATA:
898 CALL_IN_NEW_THREAD(getCollectedData, pMsg);
899 break;
900 case CMD_GET_TABLE_DCI_DATA:
901 CALL_IN_NEW_THREAD(getTableCollectedData, pMsg);
902 break;
903 case CMD_CLEAR_DCI_DATA:
904 CALL_IN_NEW_THREAD(clearDCIData, pMsg);
905 break;
906 case CMD_FORCE_DCI_POLL:
907 CALL_IN_NEW_THREAD(forceDCIPoll, pMsg);
908 break;
909 case CMD_OPEN_EPP:
910 openEPP(pMsg);
911 break;
912 case CMD_CLOSE_EPP:
913 closeEPP(pMsg->getId());
914 break;
915 case CMD_SAVE_EPP:
916 saveEPP(pMsg);
917 break;
918 case CMD_EPP_RECORD:
919 processEPPRecord(pMsg);
920 break;
921 case CMD_GET_MIB_TIMESTAMP:
922 sendMIBTimestamp(pMsg->getId());
923 break;
924 case CMD_GET_MIB:
925 CALL_IN_NEW_THREAD(sendMib, pMsg);
926 break;
927 case CMD_CREATE_OBJECT:
928 CALL_IN_NEW_THREAD(createObject, pMsg);
929 break;
930 case CMD_BIND_OBJECT:
931 changeObjectBinding(pMsg, TRUE);
932 break;
933 case CMD_UNBIND_OBJECT:
934 changeObjectBinding(pMsg, FALSE);
935 break;
936 case CMD_ADD_CLUSTER_NODE:
937 addClusterNode(pMsg);
938 break;
939 case CMD_GET_ALL_ALARMS:
940 CALL_IN_NEW_THREAD(getAlarms, pMsg);
941 break;
942 case CMD_GET_ALARM_COMMENTS:
943 getAlarmComments(pMsg);
944 break;
945 case CMD_SET_ALARM_STATUS_FLOW:
946 updateAlarmStatusFlow(pMsg);
947 break;
948 case CMD_UPDATE_ALARM_COMMENT:
949 updateAlarmComment(pMsg);
950 break;
951 case CMD_DELETE_ALARM_COMMENT:
952 deleteAlarmComment(pMsg);
953 break;
954 case CMD_GET_ALARM:
955 getAlarm(pMsg);
956 break;
957 case CMD_GET_ALARM_EVENTS:
958 CALL_IN_NEW_THREAD(getAlarmEvents, pMsg);
959 break;
960 case CMD_ACK_ALARM:
961 acknowledgeAlarm(pMsg);
962 break;
963 case CMD_RESOLVE_ALARM:
964 resolveAlarm(pMsg, false);
965 break;
966 case CMD_TERMINATE_ALARM:
967 resolveAlarm(pMsg, true);
968 break;
969 case CMD_DELETE_ALARM:
970 deleteAlarm(pMsg);
971 break;
972 case CMD_OPEN_HELPDESK_ISSUE:
973 CALL_IN_NEW_THREAD(openHelpdeskIssue, pMsg);
974 break;
975 case CMD_GET_HELPDESK_URL:
976 getHelpdeskUrl(pMsg);
977 break;
978 case CMD_UNLINK_HELPDESK_ISSUE:
979 unlinkHelpdeskIssue(pMsg);
980 break;
981 case CMD_CREATE_ACTION:
982 createAction(pMsg);
983 break;
984 case CMD_MODIFY_ACTION:
985 updateAction(pMsg);
986 break;
987 case CMD_DELETE_ACTION:
988 deleteAction(pMsg);
989 break;
990 case CMD_LOAD_ACTIONS:
991 sendAllActions(pMsg->getId());
992 break;
993 case CMD_DELETE_OBJECT:
994 deleteObject(pMsg);
995 break;
996 case CMD_POLL_NODE:
997 forcedNodePoll(pMsg);
998 break;
999 case CMD_TRAP:
1000 onTrap(pMsg);
1001 break;
1002 case CMD_WAKEUP_NODE:
1003 onWakeUpNode(pMsg);
1004 break;
1005 case CMD_CREATE_TRAP:
1006 editTrap(TRAP_CREATE, pMsg);
1007 break;
1008 case CMD_MODIFY_TRAP:
1009 editTrap(TRAP_UPDATE, pMsg);
1010 break;
1011 case CMD_DELETE_TRAP:
1012 editTrap(TRAP_DELETE, pMsg);
1013 break;
1014 case CMD_LOAD_TRAP_CFG:
1015 sendAllTraps(pMsg->getId());
1016 break;
1017 case CMD_GET_TRAP_CFG_RO:
1018 sendAllTraps2(pMsg->getId());
1019 break;
1020 case CMD_QUERY_PARAMETER:
1021 CALL_IN_NEW_THREAD(queryParameter, pMsg);
1022 break;
1023 case CMD_QUERY_TABLE:
1024 CALL_IN_NEW_THREAD(queryAgentTable, pMsg);
1025 break;
1026 case CMD_LOCK_PACKAGE_DB:
1027 LockPackageDB(pMsg->getId(), TRUE);
1028 break;
1029 case CMD_UNLOCK_PACKAGE_DB:
1030 LockPackageDB(pMsg->getId(), FALSE);
1031 break;
1032 case CMD_GET_PACKAGE_LIST:
1033 SendAllPackages(pMsg->getId());
1034 break;
1035 case CMD_INSTALL_PACKAGE:
1036 InstallPackage(pMsg);
1037 break;
1038 case CMD_REMOVE_PACKAGE:
1039 RemovePackage(pMsg);
1040 break;
1041 case CMD_GET_PARAMETER_LIST:
1042 getParametersList(pMsg);
1043 break;
1044 case CMD_DEPLOY_PACKAGE:
1045 DeployPackage(pMsg);
1046 break;
1047 case CMD_GET_LAST_VALUES:
1048 getLastValues(pMsg);
1049 break;
1050 case CMD_GET_DCI_VALUES:
1051 getLastValuesByDciId(pMsg);
1052 break;
1053 case CMD_GET_TABLE_LAST_VALUES:
1054 getTableLastValues(pMsg);
1055 break;
1056 case CMD_GET_THRESHOLD_SUMMARY:
1057 getThresholdSummary(pMsg);
1058 break;
1059 case CMD_GET_USER_VARIABLE:
1060 getUserVariable(pMsg);
1061 break;
1062 case CMD_SET_USER_VARIABLE:
1063 setUserVariable(pMsg);
1064 break;
1065 case CMD_DELETE_USER_VARIABLE:
1066 deleteUserVariable(pMsg);
1067 break;
1068 case CMD_ENUM_USER_VARIABLES:
1069 enumUserVariables(pMsg);
1070 break;
1071 case CMD_COPY_USER_VARIABLE:
1072 copyUserVariable(pMsg);
1073 break;
1074 case CMD_CHANGE_ZONE:
1075 changeObjectZone(pMsg);
1076 break;
1077 case CMD_REQUEST_ENCRYPTION:
1078 setupEncryption(pMsg);
1079 break;
1080 case CMD_GET_AGENT_CONFIG:
1081 getAgentConfig(pMsg);
1082 break;
1083 case CMD_UPDATE_AGENT_CONFIG:
1084 updateAgentConfig(pMsg);
1085 break;
1086 case CMD_EXECUTE_ACTION:
1087 CALL_IN_NEW_THREAD(executeAction, pMsg);
1088 break;
1089 case CMD_GET_OBJECT_TOOLS:
1090 getObjectTools(pMsg->getId());
1091 break;
1092 case CMD_EXEC_TABLE_TOOL:
1093 execTableTool(pMsg);
1094 break;
1095 case CMD_GET_OBJECT_TOOL_DETAILS:
1096 getObjectToolDetails(pMsg);
1097 break;
1098 case CMD_UPDATE_OBJECT_TOOL:
1099 updateObjectTool(pMsg);
1100 break;
1101 case CMD_DELETE_OBJECT_TOOL:
1102 deleteObjectTool(pMsg);
1103 break;
1104 case CMD_CHANGE_OBJECT_TOOL_STATUS:
1105 changeObjectToolStatus(pMsg);
1106 break;
1107 case CMD_GENERATE_OBJECT_TOOL_ID:
1108 generateObjectToolId(pMsg->getId());
1109 break;
1110 case CMD_CHANGE_SUBSCRIPTION:
1111 changeSubscription(pMsg);
1112 break;
1113 case CMD_GET_SYSLOG:
1114 CALL_IN_NEW_THREAD(sendSyslog, pMsg);
1115 break;
1116 case CMD_GET_SERVER_STATS:
1117 sendServerStats(pMsg->getId());
1118 break;
1119 case CMD_GET_SCRIPT_LIST:
1120 sendScriptList(pMsg->getId());
1121 break;
1122 case CMD_GET_SCRIPT:
1123 sendScript(pMsg);
1124 break;
1125 case CMD_UPDATE_SCRIPT:
1126 updateScript(pMsg);
1127 break;
1128 case CMD_RENAME_SCRIPT:
1129 renameScript(pMsg);
1130 break;
1131 case CMD_DELETE_SCRIPT:
1132 deleteScript(pMsg);
1133 break;
1134 case CMD_GET_SESSION_LIST:
1135 SendSessionList(pMsg->getId());
1136 break;
1137 case CMD_KILL_SESSION:
1138 KillSession(pMsg);
1139 break;
1140 case CMD_GET_TRAP_LOG:
1141 SendTrapLog(pMsg);
1142 break;
1143 case CMD_START_SNMP_WALK:
1144 StartSnmpWalk(pMsg);
1145 break;
1146 case CMD_RESOLVE_DCI_NAMES:
1147 resolveDCINames(pMsg);
1148 break;
1149 case CMD_GET_DCI_INFO:
1150 SendDCIInfo(pMsg);
1151 break;
1152 case CMD_GET_DCI_THRESHOLDS:
1153 sendDCIThresholds(pMsg);
1154 break;
1155 case CMD_GET_DCI_EVENTS_LIST:
1156 getDCIEventList(pMsg);
1157 break;
1158 case CMD_GET_DCI_SCRIPT_LIST:
1159 getDCIScriptList(pMsg);
1160 break;
1161 case CMD_GET_PERFTAB_DCI_LIST:
1162 sendPerfTabDCIList(pMsg);
1163 break;
1164 case CMD_PUSH_DCI_DATA:
1165 pushDCIData(pMsg);
1166 break;
1167 case CMD_GET_AGENT_CFG_LIST:
1168 sendAgentCfgList(pMsg->getId());
1169 break;
1170 case CMD_OPEN_AGENT_CONFIG:
1171 OpenAgentConfig(pMsg);
1172 break;
1173 case CMD_SAVE_AGENT_CONFIG:
1174 SaveAgentConfig(pMsg);
1175 break;
1176 case CMD_DELETE_AGENT_CONFIG:
1177 DeleteAgentConfig(pMsg);
1178 break;
1179 case CMD_SWAP_AGENT_CONFIGS:
1180 SwapAgentConfigs(pMsg);
1181 break;
1182 case CMD_GET_OBJECT_COMMENTS:
1183 SendObjectComments(pMsg);
1184 break;
1185 case CMD_UPDATE_OBJECT_COMMENTS:
1186 updateObjectComments(pMsg);
1187 break;
1188 case CMD_GET_ADDR_LIST:
1189 getAddrList(pMsg);
1190 break;
1191 case CMD_SET_ADDR_LIST:
1192 setAddrList(pMsg);
1193 break;
1194 case CMD_RESET_COMPONENT:
1195 resetComponent(pMsg);
1196 break;
1197 case CMD_EXPORT_CONFIGURATION:
1198 exportConfiguration(pMsg);
1199 break;
1200 case CMD_IMPORT_CONFIGURATION:
1201 CALL_IN_NEW_THREAD(importConfiguration, pMsg);
1202 break;
1203 case CMD_GET_GRAPH_LIST:
1204 sendGraphList(pMsg);
1205 break;
1206 case CMD_SAVE_GRAPH:
1207 saveGraph(pMsg);
1208 break;
1209 case CMD_DELETE_GRAPH:
1210 deleteGraph(pMsg);
1211 break;
1212 case CMD_ADD_CA_CERTIFICATE:
1213 addCACertificate(pMsg);
1214 break;
1215 case CMD_DELETE_CERTIFICATE:
1216 deleteCertificate(pMsg);
1217 break;
1218 case CMD_UPDATE_CERT_COMMENTS:
1219 updateCertificateComments(pMsg);
1220 break;
1221 case CMD_GET_CERT_LIST:
1222 getCertificateList(pMsg->getId());
1223 break;
1224 case CMD_QUERY_L2_TOPOLOGY:
1225 CALL_IN_NEW_THREAD(queryL2Topology, pMsg);
1226 break;
1227 case CMD_SEND_SMS:
1228 sendSMS(pMsg);
1229 break;
1230 case CMD_GET_COMMUNITY_LIST:
1231 SendCommunityList(pMsg->getId());
1232 break;
1233 case CMD_UPDATE_COMMUNITY_LIST:
1234 UpdateCommunityList(pMsg);
1235 break;
1236 case CMD_GET_USM_CREDENTIALS:
1237 sendUsmCredentials(pMsg->getId());
1238 break;
1239 case CMD_UPDATE_USM_CREDENTIALS:
1240 updateUsmCredentials(pMsg);
1241 break;
1242 case CMD_GET_SITUATION_LIST:
1243 getSituationList(pMsg->getId());
1244 break;
1245 case CMD_CREATE_SITUATION:
1246 createSituation(pMsg);
1247 break;
1248 case CMD_UPDATE_SITUATION:
1249 updateSituation(pMsg);
1250 break;
1251 case CMD_DELETE_SITUATION:
1252 deleteSituation(pMsg);
1253 break;
1254 case CMD_DEL_SITUATION_INSTANCE:
1255 deleteSituationInstance(pMsg);
1256 break;
1257 case CMD_REGISTER_AGENT:
1258 registerAgent(pMsg);
1259 break;
1260 case CMD_GET_SERVER_FILE:
1261 CALL_IN_NEW_THREAD(getServerFile, pMsg);
1262 break;
1263 case CMD_GET_AGENT_FILE:
1264 CALL_IN_NEW_THREAD(getAgentFile, pMsg);
1265 break;
1266 case CMD_CANCEL_FILE_MONITORING:
1267 CALL_IN_NEW_THREAD(cancelFileMonitoring, pMsg);
1268 break;
1269 case CMD_TEST_DCI_TRANSFORMATION:
1270 testDCITransformation(pMsg);
1271 break;
1272 case CMD_EXECUTE_SCRIPT:
1273 CALL_IN_NEW_THREAD(executeScript, pMsg);
1274 break;
1275 case CMD_GET_JOB_LIST:
1276 sendJobList(pMsg->getId());
1277 break;
1278 case CMD_CANCEL_JOB:
1279 cancelJob(pMsg);
1280 break;
1281 case CMD_HOLD_JOB:
1282 holdJob(pMsg);
1283 break;
1284 case CMD_UNHOLD_JOB:
1285 unholdJob(pMsg);
1286 break;
1287 case CMD_DEPLOY_AGENT_POLICY:
1288 deployAgentPolicy(pMsg, false);
1289 break;
1290 case CMD_UNINSTALL_AGENT_POLICY:
1291 deployAgentPolicy(pMsg, true);
1292 break;
1293 case CMD_GET_CURRENT_USER_ATTR:
1294 getUserCustomAttribute(pMsg);
1295 break;
1296 case CMD_SET_CURRENT_USER_ATTR:
1297 setUserCustomAttribute(pMsg);
1298 break;
1299 case CMD_OPEN_SERVER_LOG:
1300 openServerLog(pMsg);
1301 break;
1302 case CMD_CLOSE_SERVER_LOG:
1303 closeServerLog(pMsg);
1304 break;
1305 case CMD_QUERY_LOG:
1306 CALL_IN_NEW_THREAD(queryServerLog, pMsg);
1307 break;
1308 case CMD_GET_LOG_DATA:
1309 CALL_IN_NEW_THREAD(getServerLogQueryData, pMsg);
1310 break;
1311 case CMD_FIND_NODE_CONNECTION:
1312 CALL_IN_NEW_THREAD(findNodeConnection, pMsg);
1313 break;
1314 case CMD_FIND_MAC_LOCATION:
1315 CALL_IN_NEW_THREAD(findMacAddress, pMsg);
1316 break;
1317 case CMD_FIND_IP_LOCATION:
1318 CALL_IN_NEW_THREAD(findIpAddress, pMsg);
1319 break;
1320 case CMD_GET_IMAGE:
1321 sendLibraryImage(pMsg);
1322 break;
1323 case CMD_CREATE_IMAGE:
1324 updateLibraryImage(pMsg);
1325 break;
1326 case CMD_DELETE_IMAGE:
1327 deleteLibraryImage(pMsg);
1328 break;
1329 case CMD_MODIFY_IMAGE:
1330 updateLibraryImage(pMsg);
1331 break;
1332 case CMD_LIST_IMAGES:
1333 listLibraryImages(pMsg);
1334 break;
1335 case CMD_EXECUTE_SERVER_COMMAND:
1336 executeServerCommand(pMsg);
1337 break;
1338 case CMD_LIST_SERVER_FILES:
1339 listServerFileStore(pMsg);
1340 break;
1341 case CMD_UPLOAD_FILE_TO_AGENT:
1342 uploadFileToAgent(pMsg);
1343 break;
1344 case CMD_UPLOAD_FILE:
1345 receiveFile(pMsg);
1346 break;
1347 case CMD_DELETE_FILE:
1348 deleteFile(pMsg);
1349 break;
1350 case CMD_OPEN_CONSOLE:
1351 openConsole(pMsg->getId());
1352 break;
1353 case CMD_CLOSE_CONSOLE:
1354 closeConsole(pMsg->getId());
1355 break;
1356 case CMD_ADM_REQUEST:
1357 CALL_IN_NEW_THREAD(processConsoleCommand, pMsg);
1358 break;
1359 case CMD_GET_VLANS:
1360 getVlans(pMsg);
1361 break;
1362 case CMD_GET_NETWORK_PATH:
1363 CALL_IN_NEW_THREAD(getNetworkPath, pMsg);
1364 break;
1365 case CMD_GET_NODE_COMPONENTS:
1366 getNodeComponents(pMsg);
1367 break;
1368 case CMD_GET_NODE_SOFTWARE:
1369 getNodeSoftware(pMsg);
1370 break;
1371 case CMD_GET_WINPERF_OBJECTS:
1372 getWinPerfObjects(pMsg);
1373 break;
1374 case CMD_LIST_MAPPING_TABLES:
1375 listMappingTables(pMsg);
1376 break;
1377 case CMD_GET_MAPPING_TABLE:
1378 getMappingTable(pMsg);
1379 break;
1380 case CMD_UPDATE_MAPPING_TABLE:
1381 updateMappingTable(pMsg);
1382 break;
1383 case CMD_DELETE_MAPPING_TABLE:
1384 deleteMappingTable(pMsg);
1385 break;
1386 case CMD_GET_WIRELESS_STATIONS:
1387 getWirelessStations(pMsg);
1388 break;
1389 case CMD_GET_SUMMARY_TABLES:
1390 getSummaryTables(pMsg->getId());
1391 break;
1392 case CMD_GET_SUMMARY_TABLE_DETAILS:
1393 getSummaryTableDetails(pMsg);
1394 break;
1395 case CMD_MODIFY_SUMMARY_TABLE:
1396 modifySummaryTable(pMsg);
1397 break;
1398 case CMD_DELETE_SUMMARY_TABLE:
1399 deleteSummaryTable(pMsg);
1400 break;
1401 case CMD_QUERY_SUMMARY_TABLE:
1402 querySummaryTable(pMsg);
1403 break;
1404 case CMD_QUERY_ADHOC_SUMMARY_TABLE:
1405 queryAdHocSummaryTable(pMsg);
1406 break;
1407 case CMD_GET_SUBNET_ADDRESS_MAP:
1408 getSubnetAddressMap(pMsg);
1409 break;
1410 case CMD_GET_EFFECTIVE_RIGHTS:
1411 getEffectiveRights(pMsg);
1412 break;
1413 case CMD_GET_FOLDER_CONTENT:
1414 case CMD_FILEMGR_DELETE_FILE:
1415 case CMD_FILEMGR_RENAME_FILE:
1416 case CMD_FILEMGR_MOVE_FILE:
1417 case CMD_FILEMGR_CREATE_FOLDER:
1418 CALL_IN_NEW_THREAD(fileManagerControl, pMsg);
1419 break;
1420 case CMD_FILEMGR_UPLOAD:
1421 CALL_IN_NEW_THREAD(uploadUserFileToAgent, pMsg);
1422 break;
1423 case CMD_GET_SWITCH_FDB:
1424 CALL_IN_NEW_THREAD(getSwitchForwardingDatabase, pMsg);
1425 break;
1426 case CMD_GET_ROUTING_TABLE:
1427 CALL_IN_NEW_THREAD(getRoutingTable, pMsg);
1428 break;
1429 case CMD_GET_LOC_HISTORY:
1430 CALL_IN_NEW_THREAD(getLocationHistory, pMsg);
1431 break;
1432 case CMD_TAKE_SCREENSHOT:
1433 getScreenshot(pMsg);
1434 break;
1435 case CMD_COMPILE_SCRIPT:
1436 compileScript(pMsg);
1437 break;
1438 case CMD_CLEAN_AGENT_DCI_CONF:
1439 cleanAgentDciConfiguration(pMsg);
1440 break;
1441 case CMD_RESYNC_AGENT_DCI_CONF:
1442 resyncAgentDciConfiguration(pMsg);
1443 break;
1444 case CMD_LIST_SCHEDULE_CALLBACKS:
1445 getSchedulerTaskHandlers(pMsg);
1446 break;
1447 case CMD_LIST_SCHEDULES:
1448 getScheduledTasks(pMsg);
1449 break;
1450 case CMD_ADD_SCHEDULE:
1451 addScheduledTask(pMsg);
1452 break;
1453 case CMD_UPDATE_SCHEDULE:
1454 updateScheduledTask(pMsg);
1455 break;
1456 case CMD_REMOVE_SCHEDULE:
1457 removeScheduledTask(pMsg);
1458 break;
1459 case CMD_GET_REPOSITORIES:
1460 CALL_IN_NEW_THREAD(getRepositories, pMsg);
1461 break;
1462 case CMD_ADD_REPOSITORY:
1463 CALL_IN_NEW_THREAD(addRepository, pMsg);
1464 break;
1465 case CMD_MODIFY_REPOSITORY:
1466 CALL_IN_NEW_THREAD(modifyRepository, pMsg);
1467 break;
1468 case CMD_DELETE_REPOSITORY:
1469 CALL_IN_NEW_THREAD(deleteRepository, pMsg);
1470 break;
1471 #ifdef WITH_ZMQ
1472 case CMD_ZMQ_SUBSCRIBE_EVENT:
1473 zmqManageSubscription(pMsg, zmq::EVENT, true);
1474 break;
1475 case CMD_ZMQ_UNSUBSCRIBE_EVENT:
1476 zmqManageSubscription(pMsg, zmq::EVENT, false);
1477 break;
1478 case CMD_ZMQ_SUBSCRIBE_DATA:
1479 zmqManageSubscription(pMsg, zmq::DATA, true);
1480 break;
1481 case CMD_ZMQ_UNSUBSCRIBE_DATA:
1482 zmqManageSubscription(pMsg, zmq::DATA, false);
1483 break;
1484 case CMD_ZMQ_LIST_EVENT_SUBSCRIPTIONS:
1485 zmqListSubscriptions(pMsg, zmq::EVENT);
1486 break;
1487 case CMD_ZMQ_LIST_DATA_SUBSCRIPTIONS:
1488 zmqListSubscriptions(pMsg, zmq::DATA);
1489 break;
1490 #endif
1491 default:
1492 if ((m_wCurrentCmd >> 8) == 0x11)
1493 {
1494 // Reporting Server range (0x1100 - 0x11FF)
1495 CALL_IN_NEW_THREAD(forwardToReportingServer, pMsg);
1496 break;
1497 }
1498
1499 // Pass message to loaded modules
1500 for(i = 0; i < g_dwNumModules; i++)
1501 {
1502 if (g_pModuleList[i].pfClientCommandHandler != NULL)
1503 {
1504 status = g_pModuleList[i].pfClientCommandHandler(m_wCurrentCmd, pMsg, this);
1505 if (status != NXMOD_COMMAND_IGNORED)
1506 {
1507 if (status == NXMOD_COMMAND_ACCEPTED_ASYNC)
1508 {
1509 pMsg = NULL; // Prevent deletion
1510 InterlockedIncrement(&m_refCount);
1511 }
1512 break; // Message was processed by the module
1513 }
1514 }
1515 }
1516 if (i == g_dwNumModules)
1517 {
1518 NXCPMessage response;
1519
1520 response.setId(pMsg->getId());
1521 response.setCode(CMD_REQUEST_COMPLETED);
1522 response.setField(VID_RCC, RCC_NOT_IMPLEMENTED);
1523 sendMessage(&response);
1524 }
1525 break;
1526 }
1527 delete pMsg;
1528 m_state = (m_dwFlags & CSF_AUTHENTICATED) ? SESSION_STATE_IDLE : SESSION_STATE_INIT;
1529 }
1530 }
1531
1532 /**
1533 * Respond to client's keepalive message
1534 */
1535 void ClientSession::respondToKeepalive(UINT32 dwRqId)
1536 {
1537 NXCPMessage msg;
1538
1539 msg.setCode(CMD_REQUEST_COMPLETED);
1540 msg.setId(dwRqId);
1541 msg.setField(VID_RCC, RCC_SUCCESS);
1542 sendMessage(&msg);
1543 }
1544
1545 /**
1546 * Process received file
1547 */
1548 void ClientSession::onFileUpload(BOOL bSuccess)
1549 {
1550 // Do processing specific to command initiated file upload
1551 switch(m_dwUploadCommand)
1552 {
1553 case CMD_INSTALL_PACKAGE:
1554 if (!bSuccess)
1555 {
1556 DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
1557 TCHAR szQuery[256];
1558 _sntprintf(szQuery, 256, _T("DELETE FROM agent_pkg WHERE pkg_id=%d"), m_dwUploadData);
1559 DBQuery(hdb, szQuery);
1560 DBConnectionPoolReleaseConnection(hdb);
1561 }
1562 break;
1563 case CMD_MODIFY_IMAGE:
1564 EnumerateClientSessions(ImageLibraryUpdateCallback, (void *)&m_uploadImageGuid);
1565 break;
1566 default:
1567 break;
1568 }
1569
1570 // Remove received file in case of failure
1571 if (!bSuccess)
1572 _tunlink(m_szCurrFileName);
1573 }
1574
1575 /**
1576 * Send message to client
1577 */
1578 bool ClientSession::sendMessage(NXCPMessage *msg)
1579 {
1580 if (isTerminated())
1581 return false;
1582
1583 if (msg->getCode() != CMD_ADM_MESSAGE)
1584 {
1585 TCHAR buffer[128];
1586 debugPrintf(6, _T("Sending message %s"), NXCPMessageCodeName(msg->getCode(), buffer));
1587 }
1588
1589 NXCP_MESSAGE *rawMsg = msg->createMessage();
1590 if ((nxlog_get_debug_level() >= 8) && (msg->getCode() != CMD_ADM_MESSAGE))
1591 {
1592 String msgDump = NXCPMessage::dump(rawMsg, NXCP_VERSION);
1593 debugPrintf(8, _T("Message dump:\n%s"), (const TCHAR *)msgDump);
1594 }
1595
1596 bool result;
1597 if (m_pCtx != NULL)
1598 {
1599 NXCP_ENCRYPTED_MESSAGE *enMsg = m_pCtx->encryptMessage(rawMsg);
1600 if (enMsg != NULL)
1601 {
1602 result = (SendEx(m_hSocket, (char *)enMsg, ntohl(enMsg->size), 0, m_mutexSocketWrite) == (int)ntohl(enMsg->size));
1603 free(enMsg);
1604 }
1605 else
1606 {
1607 result = false;
1608 }
1609 }
1610 else
1611 {
1612 result = (SendEx(m_hSocket, (const char *)rawMsg, ntohl(rawMsg->size), 0, m_mutexSocketWrite) == (int)ntohl(rawMsg->size));
1613 }
1614 free(rawMsg);
1615
1616 if (!result)
1617 {
1618 closesocket(m_hSocket);
1619 m_hSocket = -1;
1620 }
1621 return result;
1622 }
1623
1624 /**
1625 * Send raw message to client
1626 */
1627 void ClientSession::sendRawMessage(NXCP_MESSAGE *msg)
1628 {
1629 if (isTerminated())
1630 return;
1631
1632 UINT16 code = htons(msg->code);
1633 if (code != CMD_ADM_MESSAGE)
1634 {
1635 TCHAR buffer[128];
1636 debugPrintf(6, _T("Sending message %s"), NXCPMessageCodeName(ntohs(msg->code), buffer));
1637 }
1638
1639 if ((code != CMD_ADM_MESSAGE) && (nxlog_get_debug_level() >= 8))
1640 {
1641 String msgDump = NXCPMessage::dump(msg, NXCP_VERSION);
1642 debugPrintf(8, _T("Message dump:\n%s"), (const TCHAR *)msgDump);
1643 }
1644
1645 bool result;
1646 if (m_pCtx != NULL)
1647 {
1648 NXCP_ENCRYPTED_MESSAGE *enMsg = m_pCtx->encryptMessage(msg);
1649 if (enMsg != NULL)
1650 {
1651 result = (SendEx(m_hSocket, (char *)enMsg, ntohl(enMsg->size), 0, m_mutexSocketWrite) == (int)ntohl(enMsg->size));
1652 free(enMsg);
1653 }
1654 else
1655 {
1656 result = false;
1657 }
1658 }
1659 else
1660 {
1661 result = (SendEx(m_hSocket, (const char *)msg, ntohl(msg->size), 0, m_mutexSocketWrite) == (int)ntohl(msg->size));
1662 }
1663
1664 if (!result)
1665 {
1666 closesocket(m_hSocket);
1667 m_hSocket = -1;
1668 }
1669 }
1670
1671 /**
1672 * Send file to client
1673 */
1674 BOOL ClientSession::sendFile(const TCHAR *file, UINT32 dwRqId, long ofset)
1675 {
1676 return !isTerminated() ? SendFileOverNXCP(m_hSocket, dwRqId, file, m_pCtx, ofset, NULL, NULL, m_mutexSocketWrite) : FALSE;
1677 }
1678
1679 /**
1680 * Send server information to client
1681 */
1682 void ClientSession::sendServerInfo(UINT32 dwRqId)
1683 {
1684 static UINT32 protocolVersions[] = {
1685 CLIENT_PROTOCOL_VERSION_BASE,
1686 CLIENT_PROTOCOL_VERSION_ALARMS,
1687 CLIENT_PROTOCOL_VERSION_PUSH,
1688 CLIENT_PROTOCOL_VERSION_TRAP,
1689 CLIENT_PROTOCOL_VERSION_MOBILE,
1690 CLIENT_PROTOCOL_VERSION_FULL
1691 };
1692 NXCPMessage msg;
1693 TCHAR szBuffer[MAX_CONFIG_VALUE];
1694 String strURL;
1695
1696 // Prepare response message
1697 msg.setCode(CMD_REQUEST_COMPLETED);
1698 msg.setId(dwRqId);
1699
1700 // Generate challenge for certificate authentication
1701 #ifdef _WITH_ENCRYPTION
1702 RAND_bytes(m_challenge, CLIENT_CHALLENGE_SIZE);
1703 #else
1704 memset(m_challenge, 0, CLIENT_CHALLENGE_SIZE);
1705 #endif
1706
1707 // Fill message with server info
1708 msg.setField(VID_RCC, RCC_SUCCESS);
1709 msg.setField(VID_SERVER_VERSION, NETXMS_VERSION_STRING);
1710 msg.setField(VID_SERVER_ID, g_serverId);
1711 msg.setField(VID_SUPPORTED_ENCRYPTION, (UINT32)0);
1712 msg.setField(VID_PROTOCOL_VERSION, (UINT32)CLIENT_PROTOCOL_VERSION_BASE);
1713 msg.setFieldFromInt32Array(VID_PROTOCOL_VERSION_EX, sizeof(protocolVersions) / sizeof(UINT32), protocolVersions);
1714 msg.setField(VID_CHALLENGE, m_challenge, CLIENT_CHALLENGE_SIZE);
1715 msg.setField(VID_TIMESTAMP, (UINT32)time(NULL));
1716
1717 #if defined(_WIN32)
1718 TIME_ZONE_INFORMATION tz;
1719 WCHAR wst[4], wdt[8], *curr;
1720 int i;
1721
1722 DWORD tzType = GetTimeZoneInformation(&tz);
1723
1724 // Create 3 letter abbreviation for standard name
1725 for(i = 0, curr = tz.StandardName; (*curr != 0) && (i < 3); curr++)
1726 if (iswupper(*curr))
1727 wst[i++] = *curr;
1728 while(i < 3)
1729 wst[i++] = L'X';
1730 wst[i] = 0;
1731
1732 // Create abbreviation for DST name
1733 for(i = 0, curr = tz.DaylightName; (*curr != 0) && (i < 7); curr++)
1734 if (iswupper(*curr))
1735 wdt[i++] = *curr;
1736 while(i < 3)
1737 wdt[i++] = L'X';
1738 wdt[i] = 0;
1739
1740 LONG effectiveBias;
1741 switch(tzType)
1742 {
1743 case TIME_ZONE_ID_STANDARD:
1744 effectiveBias = tz.Bias + tz.StandardBias;
1745 break;
1746 case TIME_ZONE_ID_DAYLIGHT:
1747 effectiveBias = tz.Bias + tz.DaylightBias;
1748 break;
1749 case TIME_ZONE_ID_UNKNOWN:
1750 effectiveBias = tz.Bias;
1751 break;
1752 default: // error
1753 effectiveBias = 0;
1754 debugPrintf(4, _T("GetTimeZoneInformation() call failed"));
1755 break;
1756 }
1757
1758 #ifdef UNICODE
1759 swprintf(szBuffer, 1024, L"%s%c%02d%s", wst, (effectiveBias > 0) ? '-' : '+',
1760 abs(effectiveBias) / 60, (tz.DaylightBias != 0) ? wdt : L"");
1761 #else
1762 sprintf(szBuffer, "%S%c%02d%S", wst, (effectiveBias > 0) ? '-' : '+',
1763 abs(effectiveBias) / 60, (tz.DaylightBias != 0) ? wdt : L"");
1764 #endif
1765
1766 #elif HAVE_TM_GMTOFF /* not Windows but have tm_gmtoff */
1767
1768 time_t t = time(NULL);
1769 int gmtOffset;
1770 #if HAVE_LOCALTIME_R
1771 struct tm tmbuff;
1772 struct tm *loc = localtime_r(&t, &tmbuff);
1773 #else
1774 struct tm *loc = localtime(&t);
1775 #endif
1776 gmtOffset = loc->tm_gmtoff / 3600;
1777 #ifdef UNICODE
1778 swprintf(szBuffer, 1024, L"%hs%hc%02d%hs", tzname[0], (gmtOffset >= 0) ? '+' : '-',
1779 abs(gmtOffset), (tzname[1] != NULL) ? tzname[1] : "");
1780 #else
1781 sprintf(szBuffer, "%s%c%02d%s", tzname[0], (gmtOffset >= 0) ? '+' : '-',
1782 abs(gmtOffset), (tzname[1] != NULL) ? tzname[1] : "");
1783 #endif
1784
1785 #else /* not Windows and no tm_gmtoff */
1786
1787 time_t t = time(NULL);
1788 #if HAVE_GMTIME_R
1789 struct tm tmbuff;
1790 struct tm *gmt = gmtime_r(&t, &tmbuff);
1791 #else
1792 struct tm *gmt = gmtime(&t);
1793 #endif
1794 gmt->tm_isdst = -1;
1795 int gmtOffset = (int)((t - mktime(gmt)) / 3600);
1796 #ifdef UNICODE
1797 swprintf(szBuffer, 1024, L"%hs%hc%02d%hs", tzname[0], (gmtOffset >= 0) ? '+' : '-',
1798 abs(gmtOffset), (tzname[1] != NULL) ? tzname[1] : "");
1799 #else
1800 sprintf(szBuffer, "%s%c%02d%s", tzname[0], (gmtOffset >= 0) ? '+' : '-',
1801 abs(gmtOffset), (tzname[1] != NULL) ? tzname[1] : "");
1802 #endif
1803
1804 #endif
1805
1806 msg.setField(VID_TIMEZONE, szBuffer);
1807 debugPrintf(2, _T("Server time zone: %s"), szBuffer);
1808
1809 ConfigReadStr(_T("TileServerURL"), szBuffer, MAX_CONFIG_VALUE, _T("http://tile.openstreetmap.org/"));
1810 msg.setField(VID_TILE_SERVER_URL, szBuffer);
1811
1812 ConfigReadStr(_T("DefaultConsoleDateFormat"), szBuffer, MAX_CONFIG_VALUE, _T("dd.MM.yyyy"));
1813 msg.setField(VID_DATE_FORMAT, szBuffer);
1814
1815 ConfigReadStr(_T("DefaultConsoleTimeFormat"), szBuffer, MAX_CONFIG_VALUE, _T("HH:mm:ss"));
1816 msg.setField(VID_TIME_FORMAT, szBuffer);
1817
1818 ConfigReadStr(_T("DefaultConsoleShortTimeFormat"), szBuffer, MAX_CONFIG_VALUE, _T("HH:mm"));
1819 msg.setField(VID_SHORT_TIME_FORMAT, szBuffer);
1820
1821 // Send response
1822 sendMessage(&msg);
1823 }
1824
1825 /**
1826 * Authenticate client
1827 */
1828 void ClientSession::login(NXCPMessage *pRequest)
1829 {
1830 NXCPMessage msg;
1831 TCHAR szLogin[MAX_USER_NAME], szPassword[1024];
1832 int nAuthType;
1833 bool changePasswd = false, intruderLockout = false;
1834 UINT32 dwResult;
1835 #ifdef _WITH_ENCRYPTION
1836 X509 *pCert;
1837 #endif
1838
1839 // Prepare response message
1840 msg.setCode(CMD_LOGIN_RESP);
1841 msg.setId(pRequest->getId());
1842
1843 // Get client info string
1844 if (pRequest->isFieldExist(VID_CLIENT_INFO))
1845 {
1846 TCHAR szClientInfo[32], szOSInfo[32], szLibVersion[16];
1847
1848 pRequest->getFieldAsString(VID_CLIENT_INFO, szClientInfo, 32);
1849 pRequest->getFieldAsString(VID_OS_INFO, szOSInfo, 32);
1850 pRequest->getFieldAsString(VID_LIBNXCL_VERSION, szLibVersion, 16);
1851 _sntprintf(m_clientInfo, 96, _T("%s (%s; libnxcl %s)"), szClientInfo, szOSInfo, szLibVersion);
1852 }
1853
1854 m_clientType = pRequest->getFieldAsUInt16(VID_CLIENT_TYPE);
1855 if ((m_clientType < 0) || (m_clientType > CLIENT_TYPE_APPLICATION))
1856 m_clientType = CLIENT_TYPE_DESKTOP;
1857
1858 if (m_clientType == CLIENT_TYPE_WEB)
1859 {
1860 _tcscpy(m_webServerAddress, m_workstation);
1861 if (pRequest->isFieldExist(VID_CLIENT_ADDRESS))
1862 {
1863 pRequest->getFieldAsString(VID_CLIENT_ADDRESS, m_workstation, 256);
1864 debugPrintf(5, _T("Real web client address is %s"), m_workstation);
1865 }
1866 }
1867
1868 if (pRequest->isFieldExist(VID_LANGUAGE))
1869 {
1870 pRequest->getFieldAsString(VID_LANGUAGE, m_language, 8);
1871 }
1872
1873 if (!(m_dwFlags & CSF_AUTHENTICATED))
1874 {
1875 bool closeOtherSessions = false;
1876 pRequest->getFieldAsString(VID_LOGIN_NAME, szLogin, MAX_USER_NAME);
1877 nAuthType = (int)pRequest->getFieldAsUInt16(VID_AUTH_TYPE);
1878 debugPrintf(6, _T("authentication type %d"), nAuthType);
1879 switch(nAuthType)
1880 {
1881 case NETXMS_AUTH_TYPE_PASSWORD:
1882 #ifdef UNICODE
1883 pRequest->getFieldAsString(VID_PASSWORD, szPassword, 256);
1884 #else
1885 pRequest->getFieldAsUtf8String(VID_PASSWORD, szPassword, 1024);
1886 #endif
1887 dwResult = AuthenticateUser(szLogin, szPassword, 0, NULL, NULL, &m_dwUserId,
1888 &m_dwSystemAccess, &changePasswd, &intruderLockout,
1889 &closeOtherSessions, false);
1890 break;
1891 case NETXMS_AUTH_TYPE_CERTIFICATE:
1892 #ifdef _WITH_ENCRYPTION
1893 pCert = CertificateFromLoginMessage(pRequest);
1894 if (pCert != NULL)
1895 {
1896 BYTE signature[256];
1897 UINT32 dwSigLen;
1898
1899 dwSigLen = pRequest->getFieldAsBinary(VID_SIGNATURE, signature, 256);
1900 dwResult = AuthenticateUser(szLogin, (TCHAR *)signature, dwSigLen, pCert,
1901 m_challenge, &m_dwUserId, &m_dwSystemAccess,
1902 &changePasswd, &intruderLockout,
1903 &closeOtherSessions, false);
1904 X509_free(pCert);
1905 }
1906 else
1907 {
1908 dwResult = RCC_BAD_CERTIFICATE;
1909 }
1910 #else
1911 dwResult = RCC_NOT_IMPLEMENTED;
1912 #endif
1913 break;
1914 case NETXMS_AUTH_TYPE_SSO_TICKET:
1915 char ticket[1024];
1916 pRequest->getFieldAsMBString(VID_PASSWORD, ticket, 1024);
1917 if (CASAuthenticate(ticket, szLogin))
1918 {
1919 debugPrintf(5, _T("SSO ticket %hs is valid, login name %s"), ticket, szLogin);
1920 dwResult = AuthenticateUser(szLogin, NULL, 0, NULL, NULL, &m_dwUserId,
1921 &m_dwSystemAccess, &changePasswd, &intruderLockout,
1922 &closeOtherSessions, true);
1923 }
1924 else
1925 {
1926 debugPrintf(5, _T("SSO ticket %hs is invalid"), ticket);
1927 dwResult = RCC_ACCESS_DENIED;
1928 }
1929 break;
1930 default:
1931 dwResult = RCC_UNSUPPORTED_AUTH_TYPE;
1932 break;
1933 }
1934
1935 // Additional validation by loaded modules
1936 if (dwResult == RCC_SUCCESS)
1937 {
1938 for(UINT32 i = 0; i < g_dwNumModules; i++)
1939 {
1940 if (g_pModuleList[i].pfAdditionalLoginCheck != NULL)
1941 {
1942 dwResult = g_pModuleList[i].pfAdditionalLoginCheck(m_dwUserId, pRequest);
1943 if (dwResult != RCC_SUCCESS)
1944 {
1945 debugPrintf(4, _T("Login blocked by module %s (rcc=%d)"), g_pModuleList[i].szName, dwResult);
1946 break;
1947 }
1948 }
1949 }
1950 }
1951
1952 if (dwResult == RCC_SUCCESS)
1953 {
1954 m_dwFlags |= CSF_AUTHENTICATED;
1955 nx_strncpy(m_loginName, szLogin, MAX_USER_NAME);
1956 _sntprintf(m_sessionName, MAX_SESSION_NAME, _T("%s@%s"), szLogin, m_workstation);
1957 m_loginTime = time(NULL);
1958 msg.setField(VID_RCC, RCC_SUCCESS);
1959 msg.setField(VID_USER_SYS_RIGHTS, m_dwSystemAccess);
1960 msg.setField(VID_USER_ID, m_dwUserId);
1961 msg.setField(VID_SESSION_ID, (UINT32)m_id);
1962 msg.setField(VID_CHANGE_PASSWD_FLAG, (WORD)changePasswd);
1963 msg.setField(VID_DBCONN_STATUS, (UINT16)((g_flags & AF_DB_CONNECTION_LOST) ? 0 : 1));
1964 msg.setField(VID_ZONING_ENABLED, (UINT16)((g_flags & AF_ENABLE_ZONING) ? 1 : 0));
1965 msg.setField(VID_POLLING_INTERVAL, (INT32)DCObject::m_defaultPollingInterval);
1966 msg.setField(VID_RETENTION_TIME, (INT32)DCObject::m_defaultRetentionTime);
1967 msg.setField(VID_ALARM_STATUS_FLOW_STATE, (UINT16)ConfigReadInt(_T("StrictAlarmStatusFlow"), 0));
1968 msg.setField(VID_TIMED_ALARM_ACK_ENABLED, (UINT16)ConfigReadInt(_T("EnableTimedAlarmAck"), 0));
1969 msg.setField(VID_VIEW_REFRESH_INTERVAL, (UINT16)ConfigReadInt(_T("MinViewRefreshInterval"), 200));
1970 msg.setField(VID_HELPDESK_LINK_ACTIVE, (UINT16)((g_flags & AF_HELPDESK_LINK_ACTIVE) ? 1 : 0));
1971 msg.setField(VID_ALARM_LIST_DISP_LIMIT, ConfigReadULong(_T("AlarmListDisplayLimit"), 4096));
1972 msg.setField(VID_SERVERCMD_TIMEOUT, ConfigReadULong(_T("ServerCommandOutputTimeout"), 60));
1973 debugPrintf(3, _T("User %s authenticated (language=%s clientInfo=\"%s\")"), m_sessionName, m_language, m_clientInfo);
1974 WriteAuditLog(AUDIT_SECURITY, TRUE, m_dwUserId, m_workstation, m_id, 0,
1975 _T("User \"%s\" logged in (language: %s; client info: %s)"), szLogin, m_language, m_clientInfo);
1976
1977 if (closeOtherSessions)
1978 {
1979 debugPrintf(5, _T("Closing other sessions for user %s"), m_loginName);
1980 CloseOtherSessions(m_dwUserId, m_id);
1981 }
1982 }
1983 else
1984 {
1985 msg.setField(VID_RCC, dwResult);
1986 WriteAuditLog(AUDIT_SECURITY, FALSE, m_dwUserId, m_workstation, m_id, 0,
1987 _T("User \"%s\" login failed with error code %d (client info: %s)"),
1988 szLogin, dwResult, m_clientInfo);
1989 if (intruderLockout)
1990 {
1991 WriteAuditLog(AUDIT_SECURITY, FALSE, m_dwUserId, m_workstation, m_id, 0,
1992 _T("User account \"%s\" temporary disabled due to excess count of failed authentication attempts"), szLogin);
1993 }
1994 }
1995 }
1996 else
1997 {
1998 msg.setField(VID_RCC, RCC_OUT_OF_STATE_REQUEST);
1999 }
2000
2001 // Send response
2002 sendMessage(&msg);
2003 }
2004
2005 /**
2006 * Send event configuration to client
2007 */
2008 void ClientSession::sendEventDB(UINT32 dwRqId)
2009 {
2010 NXCPMessage msg;
2011 TCHAR szBuffer[4096];
2012
2013 // Prepare response message
2014 msg.setCode(CMD_REQUEST_COMPLETED);
2015 msg.setId(dwRqId);
2016
2017 if (checkSysAccessRights(SYSTEM_ACCESS_VIEW_EVENT_DB) || checkSysAccessRights(SYSTEM_ACCESS_EDIT_EVENT_DB) || checkSysAccessRights(SYSTEM_ACCESS_EPP))
2018 {
2019 if (!(g_flags & AF_DB_CONNECTION_LOST))
2020 {
2021 msg.setField(VID_RCC, RCC_SUCCESS);
2022 sendMessage(&msg);
2023 msg.deleteAllFields();
2024
2025 // Prepare data message
2026 msg.setCode(CMD_EVENT_DB_RECORD);
2027 msg.setId(dwRqId);
2028
2029 DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
2030 DB_UNBUFFERED_RESULT hResult = DBSelectUnbuffered(hdb, _T("SELECT event_code,event_name,severity,flags,message,description FROM event_cfg"));
2031 if (hResult != NULL)
2032 {
2033 while(DBFetch(hResult))
2034 {
2035 msg.setField(VID_EVENT_CODE, DBGetFieldULong(hResult, 0));
2036 msg.setField(VID_NAME, DBGetField(hResult, 1, szBuffer, 1024));
2037 msg.setField(VID_SEVERITY, DBGetFieldULong(hResult, 2));
2038 msg.setField(VID_FLAGS, DBGetFieldULong(hResult, 3));
2039
2040 DBGetField(hResult, 4, szBuffer, 4096);
2041 msg.setField(VID_MESSAGE, szBuffer);
2042
2043 DBGetField(hResult, 5, szBuffer, 4096);
2044 msg.setField(VID_DESCRIPTION, szBuffer);
2045
2046 sendMessage(&msg);
2047 msg.deleteAllFields();
2048 }
2049 DBFreeResult(hResult);
2050 }
2051 DBConnectionPoolReleaseConnection(hdb);
2052
2053 // End-of-list indicator
2054 msg.setField(VID_EVENT_CODE, (UINT32)0);
2055 msg.setEndOfSequence();
2056 }
2057 else
2058 {
2059 msg.setField(VID_RCC, RCC_DB_CONNECTION_LOST);
2060 }
2061 }
2062 else
2063 {
2064 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
2065 }
2066 sendMessage(&msg);
2067 }
2068
2069 /**
2070 * Callback for sending event configuration change notifications
2071 */
2072 static void SendEventDBChangeNotification(ClientSession *session, void *arg)
2073 {
2074 if (session->isAuthenticated() &&
2075 (session->checkSysAccessRights(SYSTEM_ACCESS_VIEW_EVENT_DB) ||
2076 session->checkSysAccessRights(SYSTEM_ACCESS_EDIT_EVENT_DB) ||
2077 session->checkSysAccessRights(SYSTEM_ACCESS_EPP)))
2078 session->postMessage((NXCPMessage *)arg);
2079 }
2080
2081 /**
2082 * Update event template
2083 */
2084 void ClientSession::modifyEventTemplate(NXCPMessage *pRequest)
2085 {
2086 NXCPMessage msg;
2087
2088 // Prepare reply message
2089 msg.setCode(CMD_REQUEST_COMPLETED);
2090 msg.setId(pRequest->getId());
2091
2092 // Check access rights
2093 if (checkSysAccessRights(SYSTEM_ACCESS_EDIT_EVENT_DB))
2094 {
2095 DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
2096
2097 // Check if event with specific code exists
2098 UINT32 dwEventCode = pRequest->getFieldAsUInt32(VID_EVENT_CODE);
2099 bool bEventExist = IsDatabaseRecordExist(hdb, _T("event_cfg"), _T("event_code"), dwEventCode);
2100
2101 // Check that we are not trying to create event below 100000
2102 if (bEventExist || (dwEventCode >= FIRST_USER_EVENT_ID))
2103 {
2104 // Prepare and execute SQL query
2105 TCHAR name[MAX_EVENT_NAME];
2106 pRequest->getFieldAsString(VID_NAME, name, MAX_EVENT_NAME);
2107 if (IsValidObjectName(name, TRUE))
2108 {
2109 DB_STATEMENT hStmt;
2110 if (bEventExist)
2111 {
2112 hStmt = DBPrepare(hdb, _T("UPDATE event_cfg SET event_name=?,severity=?,flags=?,message=?,description=? WHERE event_code=?"));
2113 }
2114 else
2115 {
2116 hStmt = DBPrepare(hdb, _T("INSERT INTO event_cfg (event_name,severity,flags,message,description,event_code,guid) VALUES (?,?,?,?,?,?,?)"));
2117 }
2118
2119 if (hStmt != NULL)
2120 {
2121 DBBind(hStmt, 1, DB_SQLTYPE_VARCHAR, name, DB_BIND_STATIC);
2122 DBBind(hStmt, 2, DB_SQLTYPE_INTEGER, pRequest->getFieldAsInt32(VID_SEVERITY));
2123 DBBind(hStmt, 3, DB_SQLTYPE_INTEGER, pRequest->getFieldAsInt32(VID_FLAGS));
2124 DBBind(hStmt, 4, DB_SQLTYPE_VARCHAR, pRequest->getFieldAsString(VID_MESSAGE), DB_BIND_DYNAMIC, MAX_EVENT_MSG_LENGTH - 1);
2125 DBBind(hStmt, 5, DB_SQLTYPE_TEXT, pRequest->getFieldAsString(VID_DESCRIPTION), DB_BIND_DYNAMIC);
2126 DBBind(hStmt, 6, DB_SQLTYPE_INTEGER, dwEventCode);
2127 if (!bEventExist)
2128 {
2129 DBBind(hStmt, 7, DB_SQLTYPE_VARCHAR, uuid::generate());
2130 }
2131
2132 if (DBExecute(hStmt))
2133 {
2134 msg.setField(VID_RCC, RCC_SUCCESS);
2135 ReloadEvents();
2136
2137 NXCPMessage nmsg(pRequest);
2138 nmsg.setCode(CMD_EVENT_DB_UPDATE);
2139 nmsg.setField(VID_NOTIFICATION_CODE, (WORD)NX_NOTIFY_ETMPL_CHANGED);
2140 EnumerateClientSessions(SendEventDBChangeNotification, &nmsg);
2141 }
2142 else
2143 {
2144 msg.setField(VID_RCC, RCC_DB_FAILURE);
2145 }
2146 DBFreeStatement(hStmt);
2147 }
2148 else
2149 {
2150 msg.setField(VID_RCC, RCC_DB_FAILURE);
2151 }
2152 }
2153 else
2154 {
2155 msg.setField(VID_RCC, RCC_INVALID_OBJECT_NAME);
2156 }
2157 }
2158 else
2159 {
2160 msg.setField(VID_RCC, RCC_INVALID_EVENT_CODE);
2161 }
2162 DBConnectionPoolReleaseConnection(hdb);
2163 }
2164 else
2165 {
2166 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
2167 }
2168
2169 // Send response
2170 sendMessage(&msg);
2171 }
2172
2173 /**
2174 * Delete event template
2175 */
2176 void ClientSession::deleteEventTemplate(NXCPMessage *pRequest)
2177 {
2178 NXCPMessage msg;
2179 UINT32 dwEventCode;
2180
2181 // Prepare reply message
2182 msg.setCode(CMD_REQUEST_COMPLETED);
2183 msg.setId(pRequest->getId());
2184
2185 dwEventCode = pRequest->getFieldAsUInt32(VID_EVENT_CODE);
2186
2187 // Check access rights
2188 if (checkSysAccessRights(SYSTEM_ACCESS_EDIT_EVENT_DB) && (dwEventCode >= FIRST_USER_EVENT_ID))
2189 {
2190 DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
2191 TCHAR szQuery[256];
2192 _sntprintf(szQuery, 256, _T("DELETE FROM event_cfg WHERE event_code=%d"), dwEventCode);
2193 if (DBQuery(hdb, szQuery))
2194 {
2195 DeleteEventTemplateFromList(dwEventCode);
2196
2197 NXCPMessage nmsg;
2198 nmsg.setCode(CMD_EVENT_DB_UPDATE);
2199 nmsg.setField(VID_NOTIFICATION_CODE, (WORD)NX_NOTIFY_ETMPL_DELETED);
2200 nmsg.setField(VID_EVENT_CODE, dwEventCode);
2201 EnumerateClientSessions(SendEventDBChangeNotification, &nmsg);
2202
2203 msg.setField(VID_RCC, RCC_SUCCESS);
2204
2205 WriteAuditLog(AUDIT_SYSCFG, TRUE, m_dwUserId, m_workstation, m_id, 0, _T("Event template %d deleted"), dwEventCode);
2206 }
2207 else
2208 {
2209 msg.setField(VID_RCC, RCC_DB_FAILURE);
2210 }
2211 DBConnectionPoolReleaseConnection(hdb);
2212 }
2213 else
2214 {
2215 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
2216 }
2217
2218 // Send response
2219 sendMessage(&msg);
2220 }
2221
2222 /**
2223 * Generate event code for new event template
2224 */
2225 void ClientSession::generateEventCode(UINT32 dwRqId)
2226 {
2227 NXCPMessage msg;
2228
2229 // Prepare reply message
2230 msg.setCode(CMD_REQUEST_COMPLETED);
2231 msg.setId(dwRqId);
2232
2233 // Check access rights
2234 if (checkSysAccessRights(SYSTEM_ACCESS_EDIT_EVENT_DB))
2235 {
2236 msg.setField(VID_EVENT_CODE, CreateUniqueId(IDG_EVENT));
2237 }
2238 else
2239 {
2240 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
2241 }
2242
2243 // Send response
2244 sendMessage(&msg);
2245 }
2246
2247 /**
2248 * Data for session object filter
2249 */
2250 struct SessionObjectFilterData
2251 {
2252 ClientSession *session;
2253 time_t baseTimeStamp;
2254 };
2255
2256 /**
2257 * Object filter for ClientSession::sendAllObjects
2258 */
2259 static bool SessionObjectFilter(NetObj *object, void *data)
2260 {
2261 return !object->isHidden() && !object->isSystem() && !object->isDeleted() &&
2262 (object->getTimeStamp() >= ((SessionObjectFilterData *)data)->baseTimeStamp) &&
2263 object->checkAccessRights(((SessionObjectFilterData *)data)->session->getUserId(), OBJECT_ACCESS_READ);
2264 }
2265
2266 /**
2267 * Send all objects to client
2268 */
2269 void ClientSession::sendAllObjects(NXCPMessage *pRequest)
2270 {
2271 NXCPMessage msg;
2272
2273 // Send confirmation message
2274 msg.setCode(CMD_REQUEST_COMPLETED);
2275 msg.setId(pRequest->getId());
2276 msg.setField(VID_RCC, RCC_SUCCESS);
2277 sendMessage(&msg);
2278 msg.deleteAllFields();
2279
2280 // Change "sync comments" flag
2281 if (pRequest->getFieldAsUInt16(VID_SYNC_COMMENTS))
2282 m_dwFlags |= CSF_SYNC_OBJECT_COMMENTS;
2283 else
2284 m_dwFlags &= ~CSF_SYNC_OBJECT_COMMENTS;
2285
2286 // Prepare message
2287 msg.setCode(CMD_OBJECT);
2288
2289 // Send objects, one per message
2290 SessionObjectFilterData data;
2291 data.session = this;
2292 data.baseTimeStamp = pRequest->getFieldAsTime(VID_TIMESTAMP);
2293 ObjectArray<NetObj> *objects = g_idxObjectById.getObjects(true, SessionObjectFilter, &data);
2294 MutexLock(m_mutexSendObjects);
2295 for(int i = 0; i < objects->size(); i++)
2296 {
2297 NetObj *object = objects->get(i);
2298 object->fillMessage(&msg);
2299 if (m_dwFlags & CSF_SYNC_OBJECT_COMMENTS)
2300 object->commentsToMessage(&msg);
2301 if (!object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_MODIFY))
2302 {
2303 // mask passwords
2304 msg.setField(VID_SHARED_SECRET, _T("********"));
2305 msg.setField(VID_SNMP_AUTH_PASSWORD, _T("********"));
2306 msg.setField(VID_SNMP_PRIV_PASSWORD, _T("********"));
2307 }
2308 sendMessage(&msg);
2309 msg.deleteAllFields();
2310 object->decRefCount();
2311 }
2312 delete objects;
2313
2314 // Send end of list notification
2315 msg.setCode(CMD_OBJECT_LIST_END);
2316 sendMessage(&msg);
2317
2318 MutexUnlock(m_mutexSendObjects);
2319 }
2320
2321 /**
2322 * Send selected objects to client
2323 */
2324 void ClientSession::sendSelectedObjects(NXCPMessage *pRequest)
2325 {
2326 NXCPMessage msg;
2327
2328 // Send confirmation message
2329 msg.setCode(CMD_REQUEST_COMPLETED);
2330 msg.setId(pRequest->getId());
2331 msg.setField(VID_RCC, RCC_SUCCESS);
2332 sendMessage(&msg);
2333 msg.deleteAllFields();
2334
2335 // Change "sync comments" flag
2336 if (pRequest->getFieldAsBoolean(VID_SYNC_COMMENTS))
2337 m_dwFlags |= CSF_SYNC_OBJECT_COMMENTS;
2338 else
2339 m_dwFlags &= ~CSF_SYNC_OBJECT_COMMENTS;
2340
2341 UINT32 dwTimeStamp = pRequest->getFieldAsUInt32(VID_TIMESTAMP);
2342 UINT32 numObjects = pRequest->getFieldAsUInt32(VID_NUM_OBJECTS);
2343 UINT32 *objects = (UINT32 *)malloc(sizeof(UINT32) * numObjects);
2344 pRequest->getFieldAsInt32Array(VID_OBJECT_LIST, numObjects, objects);
2345 UINT32 options = pRequest->getFieldAsUInt16(VID_FLAGS);
2346
2347 MutexLock(m_mutexSendObjects);
2348
2349 // Prepare message
2350 msg.setCode((options & OBJECT_SYNC_SEND_UPDATES) ? CMD_OBJECT_UPDATE : CMD_OBJECT);
2351
2352 // Send objects, one per message
2353 for(UINT32 i = 0; i < numObjects; i++)
2354 {
2355 NetObj *object = FindObjectById(objects[i]);
2356 if ((object != NULL) &&
2357 object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_READ) &&
2358 (object->getTimeStamp() >= dwTimeStamp) &&
2359 !object->isHidden() && !object->isSystem())
2360 {
2361 object->fillMessage(&msg);
2362 if (m_dwFlags & CSF_SYNC_OBJECT_COMMENTS)
2363 object->commentsToMessage(&msg);
2364 if (!object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_MODIFY))
2365 {
2366 // mask passwords
2367 msg.setField(VID_SHARED_SECRET, _T("********"));
2368 msg.setField(VID_SNMP_AUTH_PASSWORD, _T("********"));
2369 msg.setField(VID_SNMP_PRIV_PASSWORD, _T("********"));
2370 }
2371 sendMessage(&msg);
2372 msg.deleteAllFields();
2373 }
2374 }
2375
2376 MutexUnlock(m_mutexSendObjects);
2377 safe_free(objects);
2378
2379 if (options & OBJECT_SYNC_DUAL_CONFIRM)
2380 {
2381 msg.setCode(CMD_REQUEST_COMPLETED);
2382 msg.setField(VID_RCC, RCC_SUCCESS);
2383 sendMessage(&msg);
2384 }
2385 }
2386
2387 /**
2388 * Send event log records to client
2389 */
2390 void ClientSession::sendEventLog(NXCPMessage *pRequest)
2391 {
2392 NXCPMessage msg;
2393 DB_RESULT hTempResult;
2394 UINT32 dwRqId, dwMaxRecords, dwNumRows, dwId;
2395 TCHAR szQuery[1024], szBuffer[1024];
2396 WORD wRecOrder;
2397
2398 dwRqId = pRequest->getId();
2399 dwMaxRecords = pRequest->getFieldAsUInt32(VID_MAX_RECORDS);
2400 wRecOrder = ((g_dbSyntax == DB_SYNTAX_MSSQL) || (g_dbSyntax == DB_SYNTAX_ORACLE)) ? RECORD_ORDER_REVERSED : RECORD_ORDER_NORMAL;
2401
2402 // Prepare confirmation message
2403 msg.setCode(CMD_REQUEST_COMPLETED);
2404 msg.setId(dwRqId);
2405
2406 MutexLock(m_mutexSendEvents);
2407 DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
2408
2409 // Retrieve events from database
2410 switch(g_dbSyntax)
2411 {
2412 case DB_SYNTAX_MYSQL:
2413 case DB_SYNTAX_PGSQL:
2414 case DB_SYNTAX_SQLITE:
2415 dwNumRows = 0;
2416 hTempResult = DBSelect(hdb, _T("SELECT count(*) FROM event_log"));
2417 if (hTempResult != NULL)
2418 {
2419 if (DBGetNumRows(hTempResult) > 0)
2420 {
2421 dwNumRows = DBGetFieldULong(hTempResult, 0, 0);
2422 }
2423 DBFreeResult(hTempResult);
2424 }
2425 _sntprintf(szQuery, 1024,
2426 _T("SELECT event_id,event_code,event_timestamp,event_source,")
2427 _T("event_severity,event_message,user_tag FROM event_log ")
2428 _T("ORDER BY event_id LIMIT %u OFFSET %u"),
2429 dwMaxRecords, dwNumRows - min(dwNumRows, dwMaxRecords));
2430 break;
2431 case DB_SYNTAX_MSSQL:
2432 _sntprintf(szQuery, 1024,
2433 _T("SELECT TOP %u event_id,event_code,event_timestamp,event_source,")
2434 _T("event_severity,event_message,user_tag FROM event_log ")
2435 _T("ORDER BY event_id DESC"), dwMaxRecords);
2436 break;
2437 case DB_SYNTAX_ORACLE:
2438 _sntprintf(szQuery, 1024,
2439 _T("SELECT event_id,event_code,event_timestamp,event_source,")
2440 _T("event_severity,event_message,user_tag FROM event_log ")
2441 _T("WHERE ROWNUM <= %u ORDER BY event_id DESC"), dwMaxRecords);
2442 break;
2443 case DB_SYNTAX_DB2:
2444 _sntprintf(szQuery, 1024,
2445 _T("SELECT event_id,event_code,event_timestamp,event_source,")
2446 _T("event_severity,event_message,user_tag FROM event_log ")
2447 _T("ORDER BY event_id DESC FETCH FIRST %u ROWS ONLY"), dwMaxRecords);
2448 break;
2449 default:
2450 szQuery[0] = 0;
2451 break;
2452 }
2453 DB_UNBUFFERED_RESULT hResult = DBSelectUnbuffered(hdb, szQuery);
2454 if (hResult != NULL)
2455 {
2456 msg.setField(VID_RCC, RCC_SUCCESS);
2457 sendMessage(&msg);
2458 msg.deleteAllFields();
2459 msg.setCode(CMD_EVENTLOG_RECORDS);
2460
2461 for(dwId = VID_EVENTLOG_MSG_BASE, dwNumRows = 0; DBFetch(hResult); dwNumRows++)
2462 {
2463 if (dwNumRows == 10)
2464 {
2465 msg.setField(VID_NUM_RECORDS, dwNumRows);
2466 msg.setField(VID_RECORDS_ORDER, wRecOrder);
2467 sendMessage(&msg);
2468 msg.deleteAllFields();
2469 dwNumRows = 0;
2470 dwId = VID_EVENTLOG_MSG_BASE;
2471 }
2472 msg.setField(dwId++, DBGetFieldUInt64(hResult, 0));
2473 msg.setField(dwId++, DBGetFieldULong(hResult, 1));
2474 msg.setField(dwId++, DBGetFieldULong(hResult, 2));
2475 msg.setField(dwId++, DBGetFieldULong(hResult, 3));
2476 msg.setField(dwId++, (WORD)DBGetFieldLong(hResult, 4));
2477 DBGetField(hResult, 5, szBuffer, 1024);
2478 msg.setField(dwId++, szBuffer);
2479 DBGetField(hResult, 6, szBuffer, 1024);
2480 msg.setField(dwId++, szBuffer);
2481 msg.setField(dwId++, (UINT32)0); // Do not send parameters
2482 }
2483 DBFreeResult(hResult);
2484
2485 // Send remaining records with End-Of-Sequence notification
2486 msg.setField(VID_NUM_RECORDS, dwNumRows);
2487 msg.setField(VID_RECORDS_ORDER, wRecOrder);
2488 msg.setEndOfSequence();
2489 sendMessage(&msg);
2490 }
2491 else
2492 {
2493 msg.setField(VID_RCC, RCC_DB_FAILURE);
2494 sendMessage(&msg);
2495 }
2496
2497 DBConnectionPoolReleaseConnection(hdb);
2498 MutexUnlock(m_mutexSendEvents);
2499 }
2500
2501 /**
2502 * Send all configuration variables to client
2503 */
2504 void ClientSession::getConfigurationVariables(UINT32 dwRqId)
2505 {
2506 UINT32 i, dwId, dwNumRecords;
2507 NXCPMessage msg;
2508 TCHAR szBuffer[MAX_CONFIG_VALUE];
2509
2510 // Prepare message
2511 msg.setCode(CMD_REQUEST_COMPLETED);
2512 msg.setId(dwRqId);
2513
2514 // Check user rights
2515 if ((m_dwUserId == 0) || (m_dwSystemAccess & SYSTEM_ACCESS_SERVER_CONFIG))
2516 {
2517 DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
2518
2519 // Retrieve configuration variables from database
2520 DB_RESULT hResult = DBSelect(hdb, _T("SELECT var_name,var_value,need_server_restart FROM config WHERE is_visible=1"));
2521 if (hResult != NULL)
2522 {
2523 // Send events, one per message
2524 dwNumRecords = DBGetNumRows(hResult);
2525 msg.setField(VID_NUM_VARIABLES, dwNumRecords);
2526 for(i = 0, dwId = VID_VARLIST_BASE; i < dwNumRecords; i++)
2527 {
2528 msg.setField(dwId++, DBGetField(hResult, i, 0, szBuffer, MAX_DB_STRING));
2529 DBGetField(hResult, i, 1, szBuffer, MAX_CONFIG_VALUE);
2530 DecodeSQLString(szBuffer);
2531 msg.setField(dwId++, szBuffer);
2532 msg.setField(dwId++, (WORD)DBGetFieldLong(hResult, i, 2));
2533 }
2534 DBFreeResult(hResult);
2535 }
2536 DBConnectionPoolReleaseConnection(hdb);
2537 msg.setField(VID_RCC, RCC_SUCCESS);
2538 }
2539 else
2540 {
2541 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
2542 }
2543
2544 // Send response
2545 sendMessage(&msg);
2546 }
2547
2548 /**
2549 * Get public configuration variable by name
2550 */
2551 void ClientSession::getPublicConfigurationVariable(NXCPMessage *request)
2552 {
2553 NXCPMessage msg;
2554 msg.setCode(CMD_REQUEST_COMPLETED);
2555 msg.setId(request->getId());
2556
2557 DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
2558
2559 DB_STATEMENT hStmt = DBPrepare(hdb, _T("SELECT var_value FROM config WHERE var_name=? AND is_public='Y'"));
2560 if (hStmt != NULL)
2561 {
2562 TCHAR name[64];
2563 request->getFieldAsString(VID_NAME, name, 64);
2564 DBBind(hStmt, 1, DB_SQLTYPE_VARCHAR, name, DB_BIND_STATIC);
2565
2566 DB_RESULT hResult = DBSelectPrepared(hStmt);
2567 if (hResult != NULL)
2568 {
2569 if (DBGetNumRows(hResult) > 0)
2570 {
2571 TCHAR value[MAX_CONFIG_VALUE];
2572 msg.setField(VID_VALUE, DBGetField(hResult, 0, 0, value, MAX_CONFIG_VALUE));
2573 msg.setField(VID_RCC, RCC_SUCCESS);
2574 }
2575 else
2576 {
2577 msg.setField(VID_RCC, RCC_UNKNOWN_CONFIG_VARIABLE);
2578 }
2579 DBFreeResult(hResult);
2580 }
2581 else
2582 {
2583 msg.setField(VID_RCC, RCC_DB_FAILURE);
2584 }
2585 DBFreeStatement(hStmt);
2586 }
2587 else
2588 {
2589 msg.setField(VID_RCC, RCC_DB_FAILURE);
2590 }
2591
2592 sendMessage(&msg);
2593 }
2594
2595 /**
2596 * Set configuration variable's value
2597 */
2598 void ClientSession::setConfigurationVariable(NXCPMessage *pRequest)
2599 {
2600 NXCPMessage msg;
2601 TCHAR szName[MAX_OBJECT_NAME], szValue[MAX_CONFIG_VALUE];
2602
2603 // Prepare response message
2604 msg.setCode(CMD_REQUEST_COMPLETED);
2605 msg.setId(pRequest->getId());
2606
2607 // Check user rights
2608 if ((m_dwUserId == 0) || (m_dwSystemAccess & SYSTEM_ACCESS_SERVER_CONFIG))
2609 {
2610 pRequest->getFieldAsString(VID_NAME, szName, MAX_OBJECT_NAME);
2611 pRequest->getFieldAsString(VID_VALUE, szValue, MAX_CONFIG_VALUE);
2612 if (ConfigWriteStr(szName, szValue, true))
2613 {
2614 msg.setField(VID_RCC, RCC_SUCCESS);
2615 WriteAuditLog(AUDIT_SYSCFG, TRUE, m_dwUserId, m_workstation, m_id, 0,
2616 _T("Server configuration variable \"%s\" set to \"%s\""), szName, szValue);
2617 }
2618 else
2619 {
2620 msg.setField(VID_RCC, RCC_DB_FAILURE);
2621 }
2622 }
2623 else
2624 {
2625 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
2626 }
2627
2628 // Send response
2629 sendMessage(&msg);
2630 }
2631
2632 /**
2633 * Delete configuration variable
2634 */
2635 void ClientSession::deleteConfigurationVariable(NXCPMessage *pRequest)
2636 {
2637 NXCPMessage msg;
2638
2639 // Prepare response message
2640 msg.setCode(CMD_REQUEST_COMPLETED);
2641 msg.setId(pRequest->getId());
2642
2643 // Check user rights
2644 if ((m_dwUserId == 0) || (m_dwSystemAccess & SYSTEM_ACCESS_SERVER_CONFIG))
2645 {
2646 TCHAR name[MAX_OBJECT_NAME];
2647 pRequest->getFieldAsString(VID_NAME, name, MAX_OBJECT_NAME);
2648 if (ConfigDelete(name))
2649 {
2650 msg.setField(VID_RCC, RCC_SUCCESS);
2651 WriteAuditLog(AUDIT_SYSCFG, TRUE, m_dwUserId, m_workstation, m_id, 0, _T("Server configuration variable \"%s\" deleted"), name);
2652 }
2653 else
2654 {
2655 msg.setField(VID_RCC, RCC_DB_FAILURE);
2656 }
2657 }
2658 else
2659 {
2660 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
2661 }
2662
2663 // Send response
2664 sendMessage(&msg);
2665 }
2666
2667 /**
2668 * Set configuration clob
2669 */
2670 void ClientSession::setConfigCLOB(NXCPMessage *pRequest)
2671 {
2672 NXCPMessage msg;
2673 TCHAR name[MAX_OBJECT_NAME], *value;
2674
2675 msg.setId(pRequest->getId());
2676 msg.setCode(CMD_REQUEST_COMPLETED);
2677
2678 if (m_dwSystemAccess & SYSTEM_ACCESS_SERVER_CONFIG)
2679 {
2680 pRequest->getFieldAsString(VID_NAME, name, MAX_OBJECT_NAME);
2681 value = pRequest->getFieldAsString(VID_VALUE);
2682 if (value != NULL)
2683 {
2684 if (ConfigWriteCLOB(name, value, TRUE))
2685 {
2686 msg.setField(VID_RCC, RCC_SUCCESS);
2687 WriteAuditLog(AUDIT_SYSCFG, TRUE, m_dwUserId, m_workstation, m_id, 0,
2688 _T("Server configuration variable \"%s\" set to \"%s\""), name, value);
2689 free(value);
2690 }
2691 else
2692 {
2693 msg.setField(VID_RCC, RCC_DB_FAILURE);
2694 }
2695 }
2696 else
2697 {
2698 msg.setField(VID_RCC, RCC_INVALID_REQUEST);
2699 }
2700 }
2701 else
2702 {
2703 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
2704 }
2705
2706 sendMessage(&msg);
2707 }
2708
2709 /**
2710 * Get value of configuration clob
2711 */
2712 void ClientSession::getConfigCLOB(NXCPMessage *pRequest)
2713 {
2714 NXCPMessage msg;
2715 TCHAR name[MAX_OBJECT_NAME], *value;
2716
2717 msg.setId(pRequest->getId());
2718 msg.setCode(CMD_REQUEST_COMPLETED);
2719
2720 if (m_dwSystemAccess & SYSTEM_ACCESS_SERVER_CONFIG)
2721 {
2722 pRequest->getFieldAsString(VID_NAME, name, MAX_OBJECT_NAME);
2723 value = ConfigReadCLOB(name, NULL);
2724 if (value != NULL)
2725 {
2726 msg.setField(VID_VALUE, value);
2727 msg.setField(VID_RCC, RCC_SUCCESS);
2728 free(value);
2729 }
2730 else
2731 {
2732 msg.setField(VID_RCC, RCC_UNKNOWN_VARIABLE);
2733 }
2734 }
2735 else
2736 {
2737 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
2738 }
2739
2740 sendMessage(&msg);
2741 }
2742
2743 /**
2744 * Close session
2745 */
2746 void ClientSession::kill()
2747 {
2748 notify(NX_NOTIFY_SESSION_KILLED);
2749
2750 // We shutdown socket connection, which will cause
2751 // read thread to stop, and other threads will follow
2752 shutdown(m_hSocket, 2);
2753 }
2754
2755 /**
2756 * Handler for new events
2757 */
2758 void ClientSession::onNewEvent(Event *pEvent)
2759 {
2760 UPDATE_INFO *pUpdate;
2761 NXCPMessage *msg;
2762 if (isAuthenticated() && isSubscribedTo(NXC_CHANNEL_EVENTS) && (m_dwSystemAccess & SYSTEM_ACCESS_VIEW_EVENT_LOG))
2763 {
2764 NetObj *object = FindObjectById(pEvent->getSourceId());
2765 //If can't find object - just send to all events, if object found send to thous who have rights
2766 if (object == NULL || object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_READ))
2767 {
2768 pUpdate = (UPDATE_INFO *)malloc(sizeof(UPDATE_INFO));
2769 pUpdate->dwCategory = INFO_CAT_EVENT;
2770 msg = new NXCPMessage;
2771 msg->setCode(CMD_EVENTLOG_RECORDS);
2772 pEvent->prepareMessage(msg);
2773 pUpdate->pData = msg;
2774 m_pUpdateQueue->put(pUpdate);
2775 }
2776 }
2777 }
2778
2779 /**
2780 * Handler for object changes
2781 */
2782 void ClientSession::onObjectChange(NetObj *object)
2783 {
2784 UPDATE_INFO *pUpdate;
2785
2786 if (isAuthenticated() && isSubscribedTo(NXC_CHANNEL_OBJECTS))
2787 if (object->isDeleted() || object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_READ))
2788 {
2789 pUpdate = (UPDATE_INFO *)malloc(sizeof(UPDATE_INFO));
2790 pUpdate->dwCategory = INFO_CAT_OBJECT_CHANGE;
2791 pUpdate->pData = object;
2792 object->incRefCount();
2793 m_pUpdateQueue->put(pUpdate);
2794 }
2795 }
2796
2797 /**
2798 * Send notification message to server
2799 */
2800 void ClientSession::notify(UINT32 dwCode, UINT32 dwData)
2801 {
2802 NXCPMessage msg;
2803
2804 msg.setCode(CMD_NOTIFY);
2805 msg.setField(VID_NOTIFICATION_CODE, dwCode);
2806 msg.setField(VID_NOTIFICATION_DATA, dwData);
2807 sendMessage(&msg);
2808 }
2809
2810 static void SetNodesConflictString(NXCPMessage *msg, UINT32 zoneId, InetAddress ipAddr)
2811 {
2812 if(ipAddr.isValid())
2813 {
2814 TCHAR value[512];
2815
2816 Node *sameNode = FindNodeByIP(zoneId, ipAddr);
2817 Subnet *sameSubnet = FindSubnetByIP(zoneId, ipAddr);
2818 if(sameNode != NULL)
2819 {
2820 _sntprintf(value, 512, _T("%s"), sameNode->getName());
2821 }
2822 else if (sameSubnet != NULL)
2823 {
2824 _sntprintf(value, 512, _T("%s"), sameSubnet->getName());
2825 }
2826 else
2827 {
2828 _tcscpy(value, _T(""));
2829 }
2830 msg->setField(VID_VALUE, value);
2831 }
2832 }
2833
2834 /**
2835 * Modify object
2836 */
2837 void ClientSession::modifyObject(NXCPMessage *pRequest)
2838 {
2839 UINT32 dwObjectId, dwResult = RCC_SUCCESS;
2840 NetObj *object;
2841 NXCPMessage msg;
2842
2843 // Prepare reply message
2844 msg.setCode(CMD_REQUEST_COMPLETED);
2845 msg.setId(pRequest->getId());
2846
2847 dwObjectId = pRequest->getFieldAsUInt32(VID_OBJECT_ID);
2848 object = FindObjectById(dwObjectId);
2849 if (object != NULL)
2850 {
2851 if (object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_MODIFY))
2852 {
2853 // If user attempts to change object's ACL, check
2854 // if he has OBJECT_ACCESS_ACL permission
2855 if (pRequest->isFieldExist(VID_ACL_SIZE))
2856 if (!object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_ACL))
2857 dwResult = RCC_ACCESS_DENIED;
2858
2859 // If user attempts to rename object, check object's name
2860 if (pRequest->isFieldExist(VID_OBJECT_NAME))
2861 {
2862 TCHAR name[256];
2863 pRequest->getFieldAsString(VID_OBJECT_NAME, name, 256);
2864 if (!IsValidObjectName(name, TRUE))
2865 dwResult = RCC_INVALID_OBJECT_NAME;
2866 }
2867
2868 // If allowed, change object and set completion code
2869 if (dwResult == RCC_SUCCESS)
2870 {
2871 dwResult = object->modifyFromMessage(pRequest);
2872 if (dwResult == RCC_SUCCESS)
2873 {
2874 object->postModify();
2875 }
2876 else if (dwResult == RCC_ALREADY_EXIST)
2877 {
2878 //Add information about conflicting nodes
2879 InetAddress ipAddr;
2880
2881 if (pRequest->isFieldExist(VID_IP_ADDRESS))
2882 {
2883 ipAddr = pRequest->getFieldAsInetAddress(VID_IP_ADDRESS);
2884 } else if (pRequest->isFieldExist(VID_PRIMARY_NAME))
2885 {
2886 TCHAR primaryName[MAX_DNS_NAME];
2887 pRequest->getFieldAsString(VID_PRIMARY_NAME, primaryName, MAX_DNS_NAME);
2888 ipAddr = InetAddress::resolveHostName(primaryName);
2889 }
2890 SetNodesConflictString(&msg, ((Node*)object)->getZoneId(), ipAddr);
2891 }
2892 }
2893 msg.setField(VID_RCC, dwResult);
2894
2895 if (dwResult == RCC_SUCCESS)
2896 {
2897 WriteAuditLog(AUDIT_OBJECTS, TRUE, m_dwUserId, m_workstation, m_id, dwObjectId,
2898 _T("Object %s modified from client"), object->getName());
2899 }
2900 else
2901 {
2902 WriteAuditLog(AUDIT_OBJECTS, FALSE, m_dwUserId, m_workstation, m_id, dwObjectId,
2903 _T("Failed to modify object from client - error %d"), dwResult);
2904 }
2905 }
2906 else
2907 {
2908 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
2909 WriteAuditLog(AUDIT_OBJECTS, FALSE, m_dwUserId, m_workstation, m_id, dwObjectId,
2910 _T("Failed to modify object from client - access denied"), dwResult);
2911 }
2912 }
2913 else
2914 {
2915 msg.setField(VID_RCC, RCC_INVALID_OBJECT_ID);
2916 }
2917
2918 // Send response
2919 sendMessage(&msg);
2920 }
2921
2922 /**
2923 * Send users database to client
2924 */
2925 void ClientSession::sendUserDB(UINT32 dwRqId)
2926 {
2927 NXCPMessage msg;
2928 msg.setCode(CMD_REQUEST_COMPLETED);
2929 msg.setId(dwRqId);
2930 msg.setField(VID_RCC, RCC_SUCCESS);
2931 sendMessage(&msg);
2932 msg.deleteAllFields();
2933
2934 // Send user database
2935 Iterator<UserDatabaseObject> *users = OpenUserDatabase();
2936 while(users->hasNext())
2937 {
2938 UserDatabaseObject *object = users->next();
2939 msg.setCode(object->isGroup() ? CMD_GROUP_DATA : CMD_USER_DATA);
2940 object->fillMessage(&msg);
2941 sendMessage(&msg);
2942 msg.deleteAllFields();
2943 }
2944 CloseUserDatabase(users);
2945
2946 // Send end-of-database notification
2947 msg.setCode(CMD_USER_DB_EOF);
2948 sendMessage(&msg);
2949 }
2950
2951 /**
2952 * Create new user
2953 */
2954 void ClientSession::createUser(NXCPMessage *pRequest)
2955 {
2956 NXCPMessage msg;
2957
2958 // Prepare response message
2959 msg.setCode(CMD_REQUEST_COMPLETED);
2960 msg.setId(pRequest->getId());
2961
2962 // Check user rights
2963 if (!(m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_USERS))
2964 {
2965 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
2966 }
2967 else if (!(m_dwFlags & CSF_USER_DB_LOCKED))
2968 {
2969 // User database have to be locked before any
2970 // changes to user database can be made
2971 msg.setField(VID_RCC, RCC_OUT_OF_STATE_REQUEST);
2972 }
2973 else
2974 {
2975 UINT32 dwResult, dwUserId;
2976 TCHAR szUserName[MAX_USER_NAME];
2977
2978 pRequest->getFieldAsString(VID_USER_NAME, szUserName, MAX_USER_NAME);
2979 if (IsValidObjectName(szUserName))
2980 {
2981 bool isGroup = pRequest->getFieldAsBoolean(VID_IS_GROUP);
2982 dwResult = CreateNewUser(szUserName, isGroup, &dwUserId);
2983 msg.setField(VID_RCC, dwResult);
2984 if (dwResult == RCC_SUCCESS)
2985 {
2986 msg.setField(VID_USER_ID, dwUserId); // Send id of new user to client
2987 WriteAuditLog(AUDIT_SECURITY, TRUE, m_dwUserId, m_workstation, m_id, dwUserId, _T("%s %s created"), isGroup ? _T("Group") : _T("User"), szUserName);
2988 }
2989 }
2990 else
2991 {
2992 msg.setField(VID_RCC, RCC_INVALID_OBJECT_NAME);
2993 }
2994 }
2995
2996 // Send response
2997 sendMessage(&msg);
2998 }
2999
3000 /**
3001 * Update existing user's data
3002 */
3003 void ClientSession::updateUser(NXCPMessage *pRequest)
3004 {
3005 NXCPMessage msg;
3006
3007 // Prepare response message
3008 msg.setCode(CMD_REQUEST_COMPLETED);
3009 msg.setId(pRequest->getId());
3010
3011 // Check user rights
3012 if (!(m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_USERS))
3013 {
3014 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
3015 }
3016 else if (!(m_dwFlags & CSF_USER_DB_LOCKED))
3017 {
3018 // User database have to be locked before any
3019 // changes to user database can be made
3020 msg.setField(VID_RCC, RCC_OUT_OF_STATE_REQUEST);
3021 }
3022 else
3023 {
3024 UINT32 result = ModifyUserDatabaseObject(pRequest);
3025 if (result == RCC_SUCCESS)
3026 {
3027 TCHAR name[MAX_DB_STRING];
3028 UINT32 id = pRequest->getFieldAsUInt32(VID_USER_ID);
3029 ResolveUserId(id, name, MAX_DB_STRING);
3030 WriteAuditLog(AUDIT_SECURITY, TRUE, m_dwUserId, m_workstation, m_id, id,
3031 _T("%s %s modified"), (id & GROUP_FLAG) ? _T("Group") : _T("User"), name);
3032 }
3033 msg.setField(VID_RCC, result);
3034 }
3035
3036 // Send response
3037 sendMessage(&msg);
3038 }
3039
3040 /**
3041 * Delete user
3042 */
3043 void ClientSession::detachLdapUser(NXCPMessage *pRequest)
3044 {
3045 NXCPMessage msg;
3046
3047 // Prepare response message
3048 msg.setCode(CMD_REQUEST_COMPLETED);
3049 msg.setId(pRequest->getId());
3050 UINT32 id = pRequest->getFieldAsUInt32(VID_USER_ID);
3051
3052 // Check user rights
3053 if (!(m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_USERS))
3054 {
3055 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
3056 }
3057 else if (!(m_dwFlags & CSF_USER_DB_LOCKED))
3058 {
3059 // User database have to be locked before any
3060 // changes to user database can be made
3061 msg.setField(VID_RCC, RCC_OUT_OF_STATE_REQUEST);
3062 }
3063 else
3064 {
3065 UINT32 result = DetachLdapUser(id);
3066 if (result == RCC_SUCCESS)
3067 {
3068 TCHAR name[MAX_DB_STRING];
3069 ResolveUserId(id, name, MAX_DB_STRING);
3070 WriteAuditLog(AUDIT_SECURITY, TRUE, m_dwUserId, m_workstation, m_id, id,
3071 _T("%s %s modified"), (id & GROUP_FLAG) ? _T("Group") : _T("User"), name);
3072 }
3073 msg.setField(VID_RCC, result);
3074 }
3075
3076 // Send response
3077 sendMessage(&msg);
3078 }
3079
3080 /**
3081 * Delete user
3082 */
3083 void ClientSession::deleteUser(NXCPMessage *pRequest)
3084 {
3085 NXCPMessage msg;
3086 UINT32 dwUserId;
3087
3088 // Prepare response message
3089 msg.setCode(CMD_REQUEST_COMPLETED);
3090 msg.setId(pRequest->getId());
3091
3092 // Check user rights
3093 if (!(m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_USERS))
3094 {
3095 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
3096 }
3097 else if (!(m_dwFlags & CSF_USER_DB_LOCKED))
3098 {
3099 // User database have to be locked before any
3100 // changes to user database can be made
3101 msg.setField(VID_RCC, RCC_OUT_OF_STATE_REQUEST);
3102 }
3103 else
3104 {
3105 // Get Id of user to be deleted
3106 dwUserId = pRequest->getFieldAsUInt32(VID_USER_ID);
3107
3108 if ((dwUserId != 0) && (dwUserId != GROUP_EVERYONE))
3109 {
3110 if (!IsLoggedIn(dwUserId))
3111 {
3112 TCHAR name[MAX_DB_STRING];
3113 ResolveUserId(dwUserId, name, MAX_DB_STRING);
3114 UINT32 rcc = DeleteUserDatabaseObject(dwUserId);
3115 msg.setField(VID_RCC, rcc);
3116 if(rcc == RCC_SUCCESS)
3117 {
3118 WriteAuditLog(AUDIT_SECURITY, TRUE, m_dwUserId, m_workstation, m_id, dwUserId,
3119 _T("%s %s [%d] deleted"), (dwUserId & GROUP_FLAG) ? _T("Group") : _T("User"), name, dwUserId);
3120 }
3121 }
3122 else
3123 {
3124 // logger in users cannot be deleted
3125 msg.setField(VID_RCC, RCC_USER_LOGGED_IN);
3126 }
3127 }
3128 else
3129 {
3130 // System administrator account and everyone group cannot be deleted
3131 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
3132 }
3133 }
3134
3135 // Send response
3136 sendMessage(&msg);
3137 }
3138
3139 /**
3140 * Lock/unlock user database
3141 */
3142 void ClientSession::lockUserDB(UINT32 dwRqId, BOOL bLock)
3143 {
3144 NXCPMessage msg;
3145 TCHAR szBuffer[256];
3146
3147 // Prepare response message
3148 msg.setCode(CMD_REQUEST_COMPLETED);
3149 msg.setId(dwRqId);
3150
3151 if (m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_USERS)
3152 {
3153 if (bLock)
3154 {
3155 if (!LockComponent(CID_USER_DB, m_id, m_sessionName, NULL, szBuffer))
3156 {
3157 msg.setField(VID_RCC, RCC_COMPONENT_LOCKED);
3158 msg.setField(VID_LOCKED_BY, szBuffer);
3159 }
3160 else
3161 {
3162 m_dwFlags |= CSF_USER_DB_LOCKED;
3163 msg.setField(VID_RCC, RCC_SUCCESS);
3164 }
3165 }
3166 else
3167 {
3168 if (m_dwFlags & CSF_USER_DB_LOCKED)
3169 {
3170 UnlockComponent(CID_USER_DB);
3171 m_dwFlags &= ~CSF_USER_DB_LOCKED;
3172 }
3173 msg.setField(VID_RCC, RCC_SUCCESS);
3174 }
3175 }
3176 else
3177 {
3178 // Current user has no rights for user account management
3179 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
3180 }
3181
3182 // Send response
3183 sendMessage(&msg);
3184 }
3185
3186 /**
3187 * Change management status for the object
3188 */
3189 void ClientSession::changeObjectMgmtStatus(NXCPMessage *pRequest)
3190 {
3191 NXCPMessage msg;
3192 UINT32 dwObjectId;
3193 NetObj *object;
3194
3195 // Prepare response message
3196 msg.setCode(CMD_REQUEST_COMPLETED);
3197 msg.setId(pRequest->getId());
3198
3199 // Get object id and check access rights
3200 dwObjectId = pRequest->getFieldAsUInt32(VID_OBJECT_ID);
3201 object = FindObjectById(dwObjectId);
3202 if (object != NULL)
3203 {
3204 if (object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_MODIFY))
3205 {
3206 if ((object->getObjectClass() != OBJECT_TEMPLATE) &&
3207 (object->getObjectClass() != OBJECT_TEMPLATEGROUP) &&
3208 (object->getObjectClass() != OBJECT_TEMPLATEROOT))
3209 {
3210 BOOL bIsManaged = (BOOL)pRequest->getFieldAsUInt16(VID_MGMT_STATUS);
3211 object->setMgmtStatus(bIsManaged);
3212 msg.setField(VID_RCC, RCC_SUCCESS);
3213 WriteAuditLog(AUDIT_OBJECTS, TRUE, m_dwUserId, m_workstation, m_id, object->getId(),
3214 _T("Object %s set to %s state"), object->getName(), bIsManaged ? _T("managed") : _T("unmanaged"));
3215 }
3216 else
3217 {
3218 msg.setField(VID_RCC, RCC_INCOMPATIBLE_OPERATION);
3219 }
3220 }
3221 else
3222 {
3223 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
3224 }
3225 }
3226 else
3227 {
3228 msg.setField(VID_RCC, RCC_INVALID_OBJECT_ID);
3229 }
3230
3231 // Send response
3232 sendMessage(&msg);
3233 }
3234
3235 /**
3236 * Enter maintenance mode for object
3237 */
3238 void ClientSession::enterMaintenanceMode(NXCPMessage *request)
3239 {
3240 NXCPMessage msg;
3241 msg.setCode(CMD_REQUEST_COMPLETED);
3242 msg.setId(request->getId());
3243
3244 // Get object id and check access rights
3245 NetObj *object = FindObjectById(request->getFieldAsUInt32(VID_OBJECT_ID));
3246 if (object != NULL)
3247 {
3248 if (object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_MODIFY))
3249 {
3250 if ((object->getObjectClass() == OBJECT_CONTAINER) ||
3251 (object->getObjectClass() == OBJECT_CLUSTER) ||
3252 (object->getObjectClass() == OBJECT_NODE) ||
3253 (object->getObjectClass() == OBJECT_MOBILEDEVICE) ||
3254 (object->getObjectClass() == OBJECT_ACCESSPOINT) ||
3255 (object->getObjectClass() == OBJECT_CHASSIS) ||
3256 (object->getObjectClass() == OBJECT_ZONE) ||
3257 (object->getObjectClass() == OBJECT_SUBNET) ||
3258 (object->getObjectClass() == OBJECT_NETWORK) ||
3259 (object->getObjectClass() == OBJECT_SERVICEROOT))
3260 {
3261 object->enterMaintenanceMode();
3262 msg.setField(VID_RCC, RCC_SUCCESS);
3263 WriteAuditLog(AUDIT_OBJECTS, TRUE, m_dwUserId, m_workstation, m_id, object->getId(),
3264 _T("Requested maintenance mode enter for object %s [%d]"), object->getName(), object->getId());
3265 }
3266 else
3267 {
3268 msg.setField(VID_RCC, RCC_INCOMPATIBLE_OPERATION);
3269 }
3270 }
3271 else
3272 {
3273 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
3274 WriteAuditLog(AUDIT_OBJECTS, FALSE, m_dwUserId, m_workstation, m_id, object->getId(),
3275 _T("Access denied on maintenance mode enter request for object %s [%d]"), object->getName(), object->getId());
3276 }
3277 }
3278 else
3279 {
3280 msg.setField(VID_RCC, RCC_INVALID_OBJECT_ID);
3281 }
3282
3283 sendMessage(&msg);
3284 }
3285
3286 /**
3287 * Leave maintenance mode for object
3288 */
3289 void ClientSession::leaveMaintenanceMode(NXCPMessage *request)
3290 {
3291 NXCPMessage msg;
3292 msg.setCode(CMD_REQUEST_COMPLETED);
3293 msg.setId(request->getId());
3294
3295 // Get object id and check access rights
3296 NetObj *object = FindObjectById(request->getFieldAsUInt32(VID_OBJECT_ID));
3297 if (object != NULL)
3298 {
3299 if (object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_MODIFY))
3300 {
3301 if ((object->getObjectClass() == OBJECT_CONTAINER) ||
3302 (object->getObjectClass() == OBJECT_CLUSTER) ||
3303 (object->getObjectClass() == OBJECT_NODE) ||
3304 (object->getObjectClass() == OBJECT_MOBILEDEVICE) ||
3305 (object->getObjectClass() == OBJECT_ACCESSPOINT) ||
3306 (object->getObjectClass() == OBJECT_CHASSIS) ||
3307 (object->getObjectClass() == OBJECT_ZONE) ||
3308 (object->getObjectClass() == OBJECT_SUBNET) ||
3309 (object->getObjectClass() == OBJECT_NETWORK) ||
3310 (object->getObjectClass() == OBJECT_SERVICEROOT))
3311 {
3312 object->leaveMaintenanceMode();
3313 msg.setField(VID_RCC, RCC_SUCCESS);
3314 WriteAuditLog(AUDIT_OBJECTS, TRUE, m_dwUserId, m_workstation, m_id, object->getId(),
3315 _T("Requested maintenance mode exit for object %s [%d]"), object->getName(), object->getId());
3316 }
3317 else
3318 {
3319 msg.setField(VID_RCC, RCC_INCOMPATIBLE_OPERATION);
3320 }
3321 }
3322 else
3323 {
3324 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
3325 WriteAuditLog(AUDIT_OBJECTS, FALSE, m_dwUserId, m_workstation, m_id, object->getId(),
3326 _T("Access denied on maintenance mode exit request for object %s [%d]"), object->getName(), object->getId());
3327 }
3328 }
3329 else
3330 {
3331 msg.setField(VID_RCC, RCC_INVALID_OBJECT_ID);
3332 }
3333
3334 sendMessage(&msg);
3335 }
3336
3337 /**
3338 * Validate password for currently logged in user
3339 */
3340 void ClientSession::validatePassword(NXCPMessage *request)
3341 {
3342 NXCPMessage msg;
3343 msg.setCode(CMD_REQUEST_COMPLETED);
3344 msg.setId(request->getId());
3345
3346 #ifdef UNICODE
3347 TCHAR password[256];
3348 request->getFieldAsString(VID_PASSWORD, password, 256);
3349 #else
3350 char password[256];
3351 request->getFieldAsUtf8String(VID_PASSWORD, password, 256);
3352 #endif
3353
3354 bool isValid = false;
3355 msg.setField(VID_RCC, ValidateUserPassword(m_dwUserId, m_loginName, password, &isValid));
3356 msg.setField(VID_PASSWORD_IS_VALID, (INT16)(isValid ? 1 : 0));
3357
3358 sendMessage(&msg);
3359 }
3360
3361 /**
3362 * Set user's password
3363 */
3364 void ClientSession::setPassword(NXCPMessage *request)
3365 {
3366 NXCPMessage msg;
3367 UINT32 dwUserId;
3368
3369 // Prepare response message
3370 msg.setCode(CMD_REQUEST_COMPLETED);
3371 msg.setId(request->getId());
3372
3373 dwUserId = request->getFieldAsUInt32(VID_USER_ID);
3374
3375 if (((m_dwSystemAccess & SYSTEM_ACCESS_MANAGE_USERS) &&
3376 !((dwUserId == 0) && (m_dwUserId != 0))) || // Only administrator can change password for UID 0
3377 (dwUserId == m_dwUserId)) // User can change password for itself
3378 {
3379 UINT32 dwResult;
3380 TCHAR newPassword[1024], oldPassword[1024];
3381
3382 #ifdef UNICODE
3383 request->getFieldAsString(VID_PASSWORD, newPassword, 256);
3384 if (request->isFieldExist(VID_OLD_PASSWORD))
3385 request->getFieldAsString(VID_OLD_PASSWORD, oldPassword, 256);
3386 #else
3387 request->getFieldAsUtf8String(VID_PASSWORD, newPassword, 1024);
3388 if (request->isFieldExist(VID_OLD_PASSWORD))
3389 request->getFieldAsUtf8String(VID_OLD_PASSWORD, oldPassword, 1024);
3390 #endif
3391 else
3392 oldPassword[0] = 0;
3393 dwResult = SetUserPassword(dwUserId, newPassword, oldPassword, dwUserId == m_dwUserId);
3394 msg.setField(VID_RCC, dwResult);
3395
3396 if (dwResult == RCC_SUCCESS)
3397 {
3398 TCHAR userName[MAX_DB_STRING];
3399 ResolveUserId(dwUserId, userName, MAX_DB_STRING);
3400 WriteAuditLog(AUDIT_SECURITY, TRUE, m_dwUserId, m_workstation, m_id, 0, _T("Changed password for user %s"), userName);
3401 }
3402 }
3403 else
3404 {
3405 // Current user has no rights to change password for specific user
3406 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
3407 }
3408
3409 // Send response
3410 sendMessage(&msg);
3411 }
3412
3413 /**
3414 * Send node's DCIs to client and lock data collection settings
3415 */
3416 void ClientSession::openNodeDCIList(NXCPMessage *request)
3417 {
3418 NXCPMessage msg;
3419 UINT32 dwObjectId;
3420 NetObj *object;
3421 BOOL bSuccess = FALSE;
3422 TCHAR szLockInfo[MAX_SESSION_NAME];
3423
3424 // Prepare response message
3425 msg.setCode(CMD_REQUEST_COMPLETED);
3426 msg.setId(request->getId());
3427
3428 // Get node id and check object class and access rights
3429 dwObjectId = request->getFieldAsUInt32(VID_OBJECT_ID);
3430 object = FindObjectById(dwObjectId);
3431 if (object != NULL)
3432 {
3433 if (object->isDataCollectionTarget() || (object->getObjectClass() == OBJECT_TEMPLATE))
3434 {
3435 if (object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_READ))
3436 {
3437 // Try to lock DCI list
3438 if (((Template *)object)->lockDCIList(m_id, m_sessionName, szLockInfo))
3439 {
3440 bSuccess = TRUE;
3441 msg.setField(VID_RCC, RCC_SUCCESS);
3442
3443 // modify list of open nodes DCI lists
3444 m_pOpenDCIList = (UINT32 *)realloc(m_pOpenDCIList, sizeof(UINT32) * (m_dwOpenDCIListSize + 1));
3445 m_pOpenDCIList[m_dwOpenDCIListSize] = dwObjectId;
3446 m_dwOpenDCIListSize++;
3447 }
3448 else
3449 {
3450 msg.setField(VID_RCC, RCC_COMPONENT_LOCKED);
3451 msg.setField(VID_LOCKED_BY, szLockInfo);
3452 }
3453 }
3454 else
3455 {
3456 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
3457 }
3458 }
3459 else
3460 {
3461 msg.setField(VID_RCC, RCC_INVALID_OBJECT_ID);
3462 }
3463 }
3464 else
3465 {
3466 msg.setField(VID_RCC, RCC_INVALID_OBJECT_ID);
3467 }
3468
3469 // Send response
3470 sendMessage(&msg);
3471
3472 // If DCI list was successfully locked, send it to client
3473 if (bSuccess)
3474 ((Template *)object)->sendItemsToClient(this, request->getId());
3475 }
3476
3477 /**
3478 * Unlock node's data collection settings
3479 */
3480 void ClientSession::closeNodeDCIList(NXCPMessage *request)
3481 {
3482 NXCPMessage msg;
3483 UINT32 dwObjectId;
3484 NetObj *object;
3485
3486 // Prepare response message
3487 msg.setCode(CMD_REQUEST_COMPLETED);
3488 msg.setId(request->getId());
3489
3490 // Get node id and check object class and access rights
3491 dwObjectId = request->getFieldAsUInt32(VID_OBJECT_ID);
3492 object = FindObjectById(dwObjectId);
3493 if (object != NULL)
3494 {
3495 if (object->isDataCollectionTarget() || (object->getObjectClass() == OBJECT_TEMPLATE))
3496 {
3497 if (object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_READ))
3498 {
3499 BOOL bSuccess;
3500
3501 // Try to unlock DCI list
3502 bSuccess = ((Template *)object)->unlockDCIList(m_id);
3503 msg.setField(VID_RCC, bSuccess ? RCC_SUCCESS : RCC_OUT_OF_STATE_REQUEST);
3504
3505 // modify list of open nodes DCI lists
3506 if (bSuccess)
3507 {
3508 UINT32 i;
3509
3510 for(i = 0; i < m_dwOpenDCIListSize; i++)
3511 if (m_pOpenDCIList[i] == dwObjectId)
3512 {
3513 m_dwOpenDCIListSize--;
3514 memmove(&m_pOpenDCIList[i], &m_pOpenDCIList[i + 1], sizeof(UINT32) * (m_dwOpenDCIListSize - i));
3515 break;
3516 }
3517 }
3518 }
3519 else
3520 {
3521 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
3522 }
3523 }
3524 else
3525 {
3526 msg.setField(VID_RCC, RCC_INVALID_OBJECT_ID);
3527 }
3528 }
3529 else
3530 {
3531 msg.setField(VID_RCC, RCC_INVALID_OBJECT_ID);
3532 }
3533
3534 // Send response
3535 sendMessage(&msg);
3536 }
3537
3538 /**
3539 * Create, modify, or delete data collection item for node
3540 */
3541 void ClientSession::modifyNodeDCI(NXCPMessage *request)
3542 {
3543 NXCPMessage msg;
3544 UINT32 dwObjectId;
3545 NetObj *object;
3546
3547 // Prepare response message
3548 msg.setCode(CMD_REQUEST_COMPLETED);
3549 msg.setId(request->getId());
3550
3551 // Get node id and check object class and access rights
3552 dwObjectId = request->getFieldAsUInt32(VID_OBJECT_ID);
3553 object = FindObjectById(dwObjectId);
3554 if (object != NULL)
3555 {
3556 if (object->isDataCollectionTarget() || (object->getObjectClass() == OBJECT_TEMPLATE))
3557 {
3558 if (((Template *)object)->isLockedBySession(m_id))
3559 {
3560 if (object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_MODIFY))
3561 {
3562 UINT32 i, dwItemId, dwNumMaps, *pdwMapId, *pdwMapIndex;
3563 DCObject *dcObject;
3564 BOOL bSuccess = FALSE;
3565
3566 int dcObjectType = (int)request->getFieldAsUInt16(VID_DCOBJECT_TYPE);
3567 switch(request->getCode())
3568 {
3569 case CMD_CREATE_NEW_DCI:
3570 // Create dummy DCI
3571 switch(dcObjectType)
3572 {
3573 case DCO_TYPE_ITEM:
3574 dcObject = new DCItem(CreateUniqueId(IDG_ITEM), _T("no name"), DS_INTERNAL, DCI_DT_INT,
3575 ConfigReadInt(_T("DefaultDCIPollingInterval"), 60),
3576 ConfigReadInt(_T("DefaultDCIRetentionTime"), 30), (Node *)object);
3577 break;
3578 case DCO_TYPE_TABLE:
3579 dcObject = new DCTable(CreateUniqueId(IDG_ITEM), _T("no name"), DS_INTERNAL,
3580 ConfigReadInt(_T("DefaultDCIPollingInterval"), 60),
3581 ConfigReadInt(_T("DefaultDCIRetentionTime"), 30), (Node *)object);
3582 break;
3583 default:
3584 dcObject = NULL;
3585 break;
3586 }
3587 if (dcObject != NULL)
3588 {
3589 dcObject->setStatus(ITEM_STATUS_DISABLED, false);
3590 if ((bSuccess = ((Template *)object)->addDCObject(dcObject)))
3591 {
3592 msg.setField(VID_RCC, RCC_SUCCESS);
3593 // Return new item id to client
3594 msg.setField(VID_DCI_ID, dcObject->getId());
3595 }
3596 else // Unable to add item to node
3597 {
3598 delete dcObject;
3599 msg.setField(VID_RCC, RCC_DUPLICATE_DCI);
3600 }
3601 }
3602 else
3603 {
3604 msg.setField(VID_RCC, RCC_INVALID_ARGUMENT);
3605 }
3606 break;
3607 case CMD_MODIFY_NODE_DCI:
3608 dwItemId = request->getFieldAsUInt32(VID_DCI_ID);
3609 bSuccess = ((Template *)object)->updateDCObject(dwItemId, request, &dwNumMaps, &pdwMapIndex, &pdwMapId);
3610 if (bSuccess)
3611 {
3612 msg.setField(VID_RCC, RCC_SUCCESS);
3613
3614 // Send index to id mapping for newly created thresholds to client
3615 if (dcObjectType == DCO_TYPE_ITEM)
3616 {
3617 msg.setField(VID_DCI_NUM_MAPS, dwNumMaps);
3618 for(i = 0; i < dwNumMaps; i++)
3619 {
3620 pdwMapId[i] = htonl(pdwMapId[i]);
3621 pdwMapIndex[i] = htonl(pdwMapIndex[i]);
3622 }
3623 msg.setField(VID_DCI_MAP_IDS, (BYTE *)pdwMapId, sizeof(UINT32) * dwNumMaps);
3624 msg.setField(VID_DCI_MAP_INDEXES, (BYTE *)pdwMapIndex, sizeof(UINT32) * dwNumMaps);
3625 safe_free(pdwMapId);
3626 safe_free(pdwMapIndex);
3627 }
3628 }
3629 else
3630 {
3631 msg.setField(VID_RCC, RCC_INVALID_DCI_ID);
3632 }
3633 break;
3634 case CMD_DELETE_NODE_DCI:
3635 dwItemId = request->getFieldAsUInt32(VID_DCI_ID);
3636 bSuccess = ((Template *)object)->deleteDCObject(dwItemId, true);
3637 msg.setField(VID_RCC, bSuccess ? RCC_SUCCESS : RCC_INVALID_DCI_ID);
3638 break;
3639 }
3640 if (bSuccess)
3641 ((Template *)object)->setDCIModificationFlag();
3642 }
3643 else // User doesn't have MODIFY rights on object
3644 {
3645 msg.setField(VID_RCC, RCC_ACCESS_DENIED);
3646 }
3647 }
3648 else // Nodes DCI list not locked by this session
3649 {
3650 msg.setField(VID_RCC, RCC_OUT_OF_STATE_REQUEST);
3651 }
3652 }
3653 else // Object is not a node
3654 {
3655 msg.setField(VID_RCC, RCC_INVALID_OBJECT_ID);
3656 }
3657 }
3658 else // No object with given ID
3659 {
3660 msg.setField(VID_RCC, RCC_INVALID_OBJECT_ID);
3661 }
3662
3663 // Send response
3664 sendMessage(&msg);
3665 }
3666
3667 /**
3668 * Change status for one or more DCIs
3669 */
3670 void ClientSession::changeDCIStatus(NXCPMessage *request)
3671 {
3672 NXCPMessage msg;
3673 NetObj *object;
3674
3675 // Prepare response message
3676 msg.setCode(CMD_REQUEST_COMPLETED);
3677 msg.setId(request->getId());
3678
3679 // Get node id and check object class and access rights
3680 object = FindObjectById(request->getFieldAsUInt32(VID_OBJECT_ID));
3681 if (object != NULL)
3682 {
3683 if (object->isDataCollectionTarget() || (object->getObjectClass() == OBJECT_TEMPLATE))
3684 {
3685 if (((Template *)object)->isLockedBySession(m_id))
3686 {
3687 if (object->checkAccessRights(m_dwUserId, OBJECT_ACCESS_MODIFY))
3688 {
3689 UINT32 dwNumItems, *pdwItemList;
3690 int iStatus;
3691
3692 iStatus = request->getFieldAsUInt16(VID_DCI_STATUS);
3693 dwNumItems = request->getFieldAsUInt32(VID_NUM_ITEMS);
3694 pdwItemList = (UINT32 *)malloc(sizeof(UINT32) * dwNumItems);
3695 request->getFieldAsInt32Array(VID_ITEM_LIST, dwNumItems, pdwItemList);
3696 if (((Template *)object)->setItemStatus(dwNumItems, pdwItemList, iStatus))
3697 msg.setField(VID_RCC, RCC_SUCCESS);
3698 else
3699 msg.setField(