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