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