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