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