static void checkBlocked(CIMInstance &pm) { PEG_METHOD_ENTER(TRC_PROVIDERMANAGER, "checkBlocked"); Array<Uint16> operationalStatus; Uint32 pos = pm.findProperty(CIMName ("OperationalStatus")); if(pos == PEG_NOT_FOUND) { PEG_TRACE_STRING(TRC_PROVIDERMANAGER, Tracer::LEVEL4, "OperationalStatus not found."); PEG_METHOD_EXIT(); //l10n //throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, "provider lookup failed."); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( "ProviderManager.ProviderManagerService.PROVIDER_LOOKUP_FAILED", "provider lookup failed.")); } pm.getProperty(pos).getValue().get(operationalStatus); for(Uint32 i = 0; i < operationalStatus.size(); i++) { if(operationalStatus[i] == _MODULE_STOPPED || operationalStatus[i] == _MODULE_STOPPING) { PEG_TRACE_STRING(TRC_PROVIDERMANAGER, Tracer::LEVEL4, "Provider blocked."); PEG_METHOD_EXIT(); //l10n //throw PEGASUS_CIM_EXCEPTION(CIM_ERR_ACCESS_DENIED, "provider blocked."); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, MessageLoaderParms( "ProviderManager.ProviderManagerService.PROVIDER_BLOCKED", "provider blocked.")); } } }
void FileListenerDestination::_recordIndicationToFile( const char* path, const String& formattedText) { PEG_METHOD_ENTER(TRC_IND_HANDLER, "FileListenerDestination::_recordIndicationToFile"); FILE *fd = fopen(path, "a"); if(fd) { if( fprintf(fd, "%s\n", (const char*)formattedText.getCString()) > 0) { fclose(fd); } else { fclose(fd); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( "Handler.FileListenerDestination.FileListenerDestination." "FAILED_TO_WRITE_INDICATION_TO_FILE", "Failed to write indication to local file $0.", path)); } } else // file opening failed { PEG_METHOD_EXIT(); ThrowCannotOpenFileException(path); } PEG_METHOD_EXIT(); }
void EmailListenerDestination::_buildMailHeader( const Array<String> & mailTo, const Array<String> & mailCc, const String & mailSubject, FILE * filePtr) { PEG_METHOD_ENTER (TRC_IND_HANDLER, "EmailListenerDestination::_buildMailHeader"); String exceptionStr; String mailToStr = _buildMailAddrStr(mailTo); if (mailToStr == String::EMPTY) { PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L (CIM_ERR_FAILED, MessageLoaderParms("Handler.EmailListenerDestination." "EmailListenerDestination.DO_NOT_HAVE_EMAIL_ADDRESS", "Do not have an e-mail address.")); } String mailHdrStr = String::EMPTY; // Write the mailToStr to file mailHdrStr.append("To: "); mailHdrStr.append(mailToStr); _writeStrToFile(mailHdrStr, filePtr); String mailCcStr = _buildMailAddrStr(mailCc); // Write the mailCcStr to file mailHdrStr = String::EMPTY; mailHdrStr.append("Cc: "); mailHdrStr.append(mailCcStr); _writeStrToFile(mailHdrStr, filePtr); // build from string String fromStr = String::EMPTY; fromStr.append("From: "); fromStr.append(System::getEffectiveUserName()); fromStr.append("@"); fromStr.append(System::getFullyQualifiedHostName ()); // Write the fromStr to file _writeStrToFile(fromStr, filePtr); // Write the mailSubject string to file String mailSubjectStr = String::EMPTY; mailSubjectStr.append("Subject: "); mailSubjectStr.append(mailSubject); _writeStrToFile(mailSubjectStr, filePtr); PEG_METHOD_EXIT(); }
Boolean IndicationHandlerService::_loadHandler( CIMHandleIndicationRequestMessage* request, CIMException& cimException) { PEG_METHOD_ENTER(TRC_IND_HANDLER, "IndicationHandlerService::__loadHandler()"); CIMName className = request->handlerInstance.getClassName(); try { CIMHandler* handlerLib = _lookupHandlerForClass(className); if (handlerLib) { ContentLanguageList langs = ((ContentLanguageListContainer)request->operationContext. get(ContentLanguageListContainer::NAME)).getLanguages(); handlerLib->handleIndication( request->operationContext, request->nameSpace.getString(), request->indicationInstance, request->handlerInstance, request->subscriptionInstance, langs); } else { cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms("HandlerService." "IndicationHandlerService.FAILED_TO_LOAD", "Failed to load Handler")); PEG_METHOD_EXIT(); return false; } } catch (Exception& e) { cimException = PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, e.getMessage()); PEG_METHOD_EXIT(); return false; } catch (...) { cimException = PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, "Exception: Unknown"); PEG_METHOD_EXIT(); return false; } PEG_METHOD_EXIT(); return true; }
ProviderManagerContainer( const String& physicalName, const String& logicalName, const String& interfaceName, PEGASUS_INDICATION_CALLBACK_T indicationCallback, PEGASUS_RESPONSE_CHUNK_CALLBACK_T responseChunkCallback, Boolean subscriptionInitComplete) : _manager(0) { #if defined (PEGASUS_OS_VMS) String provDir = ConfigManager::getInstance()-> getCurrentValue("providerDir"); _physicalName = ConfigManager::getHomedPath(provDir) + "/" + FileSystem::buildLibraryFileName(physicalName); #else _physicalName = physicalName; // providerMgrPath comes with full path //_physicalName = ConfigManager::getHomedPath(PEGASUS_DEST_LIB_DIR) + // String("/") + FileSystem::buildLibraryFileName(physicalName); #endif _logicalName = logicalName; _interfaceName = interfaceName; _module.reset(new ProviderManagerModule(_physicalName)); Boolean moduleLoaded = _module->load(); if (moduleLoaded) { _manager = _module->getProviderManager(_logicalName); } else { PEG_TRACE_CSTRING(TRC_PROVIDERMANAGER, Tracer::LEVEL2, "ProviderManagerModule load failed."); } if (_manager == 0) { MessageLoaderParms parms( "ProviderManager.BasicProviderManagerRouter." "PROVIDERMANAGER_LOAD_FAILED", "Failed to load the Provider Manager for interface " "type \"$0\" from library \"$1\".", _interfaceName, _physicalName); Logger::put_l( Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE, parms); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, parms); } _manager->setIndicationCallback(indicationCallback); _manager->setResponseChunkCallback(responseChunkCallback); _manager->setSubscriptionInitComplete (subscriptionInitComplete); }
inline T * getInterface(CIMIndicationConsumerProvider* consumer) { T * p = dynamic_cast<T *>(consumer); if(p == 0) { //l10n //throw PEGASUS_CIM_EXCEPTION(CIM_ERR_NOT_SUPPORTED, "Invalid provider interface."); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_NOT_SUPPORTED, MessageLoaderParms( "ProviderManager.ProviderFacade.INVALID_PROVIDER_INTERFACE", "Provider interface is not valid.")); } return(p); }
void snmpDeliverTrap_emanate::initialize() { #ifndef SR_UDS_IPC InitIPCArrayTCP(&IPCfp); #else /* SR_UDS_IPC */ InitIPCArrayUDS(&IPCfp); #endif /* SR_UDS_IPC */ if (InitSubagent() == -1) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INITSUBAGENT_FAILED_KEY, _MSG_INITSUBAGENT_FAILED)); } }
// // Verify user authorization // void UserAuthProvider::_verifyAuthorization(const String& user) { PEG_METHOD_ENTER(TRC_CONFIG, "UserAuthProvider::_verifyAuthorization()"); if ( user.size() && !System::isPrivilegedUser(user) ) { MessageLoaderParms parms( "ControlProviders.UserAuthProvider." "MUST_BE_PRIVILEGED_USER", "Superuser authority is required to run this CIM operation."); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED,parms); } PEG_METHOD_EXIT(); }
// // Verify user authorization // void UserAuthProvider::_verifyAuthorization(const String& user) { PEG_METHOD_ENTER(TRC_CONFIG, "UserAuthProvider::_verifyAuthorization()"); if ( System::isPrivilegedUser(user) == false ) { PEG_METHOD_EXIT(); MessageLoaderParms parms( "ControlProviders.UserAuthProvider." "MUST_BE_PRIVILEGED_USER", "Must be a privileged user to execute this CIM operation."); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED,parms); } PEG_METHOD_EXIT(); }
PEGASUS_NAMESPACE_BEGIN JMPIProviderModule::JMPIProviderModule(const String & fileName, const String & interfaceName) : _fileName(fileName), _interfaceName(interfaceName), _ref_count(0), _library(0) { Uint32 i=fileName.find(".jar:"); if (i==PEG_NOT_FOUND) { String msg="Invalid Location format for Java providers: "+fileName; throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED,msg); } String jar=fileName.subString(0,i+4); _className=fileName.subString(i+5); if (jar[0]!='/') _fileName=JMPIProviderManager::resolveFileName(jar); else _fileName=jar; }
// l10n - note: ignoring indication language void snmpIndicationHandler::handleIndication( const OperationContext& context, const String nameSpace, CIMInstance& indication, CIMInstance& handler, CIMInstance& subscription, ContentLanguageList & contentLanguages) { Array<String> propOIDs; Array<String> propTYPEs; Array<String> propVALUEs; Array<String> mapStr; PEG_METHOD_ENTER(TRC_IND_HANDLER, "snmpIndicationHandler::handleIndication"); try { PEG_TRACE ((TRC_INDICATION_GENERATION, Tracer::LEVEL4, "snmpIndicationHandler %s:%s.%s processing %s Indication", (const char*)(nameSpace.getCString()), (const char*)(handler.getClassName().getString().getCString()), (const char*)(handler.getProperty( handler.findProperty(PEGASUS_PROPERTYNAME_NAME)). getValue().toString().getCString()), (const char*)(indication.getClassName().getString(). getCString()))); CIMClass indicationClass = _repository->getClass( nameSpace, indication.getClassName(), false, true, false, CIMPropertyList()); Uint32 propertyCount = indication.getPropertyCount(); for (Uint32 i=0; i < propertyCount; i++) { CIMProperty prop = indication.getProperty(i); Uint32 propDeclPos = indicationClass.findProperty(prop.getName()); if (propDeclPos != PEG_NOT_FOUND) { CIMProperty propDecl = indicationClass.getProperty(propDeclPos); Uint32 qualifierPos = propDecl.findQualifier(CIMName("MappingStrings")); if (qualifierPos != PEG_NOT_FOUND) { // // We are looking for following fields: // MappingStrings {"OID.IETF | SNMP." oidStr, // "DataType.IETF |" dataType} // oidStr is the object identifier (e.g. "1.3.6.1.2.1.5..." // dataType is either Integer, or OctetString, // or OID // Following is one example: // MappingStrings {"OID.IETF | SNMP.1.3.6.6.3.1.1.5.2", // "DataType.IETF | Integer"} // propDecl.getQualifier(qualifierPos).getValue().get( mapStr); String oidStr, dataType; String mapStr1, mapStr2; Boolean isValidAuthority = false; Boolean isValidDataType = false; for (Uint32 j=0; j < mapStr.size(); j++) { Uint32 barPos = mapStr[j].find("|"); if (barPos != PEG_NOT_FOUND) { mapStr1 = mapStr[j].subString(0, barPos); mapStr2 = mapStr[j].subString(barPos + 1); _trimWhitespace(mapStr1); _trimWhitespace(mapStr2); if ((mapStr1 == "OID.IETF") && (String::compare(mapStr2, String("SNMP."), 5) == 0)) { isValidAuthority = true; oidStr = mapStr2.subString(5); } else if (mapStr1 == "DataType.IETF") { isValidDataType = true; dataType = mapStr2; } if (isValidAuthority && isValidDataType) { propOIDs.append(oidStr); propTYPEs.append(dataType); propVALUEs.append(prop.getValue().toString()); break; } } } } } } // Collected complete data in arrays and ready to send the trap. // trap destination and SNMP type are defined in handlerInstance // and passing this instance as it is to deliverTrap() call Uint32 targetHostPos = handler.findProperty(CIMName("TargetHost")); Uint32 targetHostFormatPos = handler.findProperty(CIMName("TargetHostFormat")); Uint32 otherTargetHostFormatPos = handler.findProperty(CIMName("OtherTargetHostFormat")); Uint32 portNumberPos = handler.findProperty(CIMName("PortNumber")); Uint32 snmpVersionPos = handler.findProperty(CIMName("SNMPVersion")); Uint32 securityNamePos = handler.findProperty(CIMName("SNMPSecurityName")); Uint32 engineIDPos = handler.findProperty(CIMName("SNMPEngineID")); Uint32 snmpSecLevelPos = handler.findProperty(CIMName("SNMPSecurityLevel")); Uint32 snmpSecAuthProtoPos = handler.findProperty(CIMName("SNMPSecurityAuthProtocol")); Uint32 snmpSecAuthKeyPos = handler.findProperty(CIMName("SNMPSecurityAuthKey")); Uint32 snmpSecPrivProtoPos = handler.findProperty(CIMName("SNMPSecurityPrivProtocol")); Uint32 snmpSecPrivKeyPos = handler.findProperty(CIMName("SNMPSecurityPrivKey")); if (targetHostPos == PEG_NOT_FOUND) { PEG_TRACE((TRC_DISCARDED_DATA, Tracer::LEVEL1, "Target host is not set for IndicationHandlerSNMPMapper %s" " Indication.", (const char*)(indication.getClassName().getString(). getCString()))); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( "Handler.snmpIndicationHandler.snmpIndicationHandler." "INVALID_SNMP_INSTANCE", "Invalid IndicationHandlerSNMPMapper instance")); } if (targetHostFormatPos == PEG_NOT_FOUND) { PEG_TRACE((TRC_DISCARDED_DATA, Tracer::LEVEL1, "Target host format is not set for IndicationHandlerSNMPMapper" " %s Indication.", (const char*)(indication.getClassName().getString(). getCString()))); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( "Handler.snmpIndicationHandler.snmpIndicationHandler." "INVALID_SNMP_INSTANCE", "Invalid IndicationHandlerSNMPMapper instance")); } if (snmpVersionPos == PEG_NOT_FOUND) { PEG_TRACE((TRC_DISCARDED_DATA, Tracer::LEVEL1, "SNMP Version is not set for IndicationHandlerSNMPMapper %s" " Indication.", (const char*)(indication.getClassName().getString(). getCString()))); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( "Handler.snmpIndicationHandler.snmpIndicationHandler." "INVALID_SNMP_INSTANCE", "Invalid IndicationHandlerSNMPMapper instance")); } else { // properties from the handler instance String targetHost; String otherTargetHostFormat = String(); String securityName = String(); String engineID = String(); Uint16 targetHostFormat = 0; Uint16 snmpVersion = 0; Uint32 portNumber; Uint8 snmpSecLevel = 1; // noAuthnoPriv Uint8 snmpSecAuthProto = 0; Array<Uint8> snmpSecAuthKey;// no key Uint8 snmpSecPrivProto = 0; Array<Uint8> snmpSecPrivKey ;// no key String trapOid; Boolean trapOidAvailable = false; // // Get snmpTrapOid from context // if (context.contains(SnmpTrapOidContainer::NAME)) { SnmpTrapOidContainer trapContainer = context.get(SnmpTrapOidContainer::NAME); trapOid = trapContainer.getSnmpTrapOid(); trapOidAvailable = true; } else { // get trapOid from indication Class Uint32 pos = indicationClass.findQualifier(CIMName("MappingStrings")); if (pos != PEG_NOT_FOUND) { Array<String> classMapStr; indicationClass.getQualifier(pos).getValue(). get(classMapStr); for (Uint32 i=0; i < classMapStr.size(); i++) { Uint32 barPos = classMapStr[i].find("|"); if (barPos != PEG_NOT_FOUND) { String authorityName = classMapStr[i].subString(0, barPos); String oidStr = classMapStr[i].subString( barPos+1, PEG_NOT_FOUND); _trimWhitespace(authorityName); _trimWhitespace(oidStr); if ((authorityName == "OID.IETF") && (String::compare(oidStr, String("SNMP."), 5) == 0)) { trapOid = oidStr.subString(5); trapOidAvailable = true; break; } } } if (!trapOidAvailable) { PEG_TRACE(( TRC_IND_HANDLER, Tracer::LEVEL1, "No MappingStrings for snmp trap is specified " "for class: %s", (const char*) indication.getClassName().getString().getCString() )); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L( CIM_ERR_FAILED, MessageLoaderParms( "Handler.snmpIndicationHandler." "snmpIndicationHandler.NO_MS_FOR_SNMP_TRAP", "No MappingStrings for snmp trap is specified " "for class: $0", indication.getClassName().getString())); } } else { PEG_TRACE_CSTRING(TRC_IND_HANDLER, Tracer::LEVEL1, "Qualifier MappingStrings can not be found."); PEG_METHOD_EXIT(); MessageLoaderParms parms( "Handler.snmpIndicationHandler.snmpIndicationHandler." "QUALIFIER_MAPPINGS_NOT_FOUND", "Qualifier MappingStrings can not be found"); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, parms); } } handler.getProperty(targetHostPos).getValue().get(targetHost); handler.getProperty(targetHostFormatPos).getValue().get( targetHostFormat); if (otherTargetHostFormatPos != PEG_NOT_FOUND) { handler.getProperty(otherTargetHostFormatPos).getValue().get( otherTargetHostFormat); } if (portNumberPos != PEG_NOT_FOUND) { handler.getProperty(portNumberPos).getValue().get(portNumber); } else { // default port portNumber = SNMP_TRAP_DEFAULT_PORT; } handler.getProperty(snmpVersionPos).getValue().get(snmpVersion); if (securityNamePos != PEG_NOT_FOUND) { handler.getProperty(securityNamePos).getValue().get( securityName); } if (engineIDPos != PEG_NOT_FOUND) { handler.getProperty(engineIDPos).getValue().get(engineID); } if(snmpVersion == 5) // SNMPv3 Trap { //fetch the security data if(snmpSecLevelPos != PEG_NOT_FOUND) { handler.getProperty(snmpSecLevelPos).getValue(). \ get(snmpSecLevel); } if(snmpSecAuthProtoPos != PEG_NOT_FOUND) { handler.getProperty(snmpSecAuthProtoPos).getValue(). \ get(snmpSecAuthProto); } if(snmpSecAuthKeyPos != PEG_NOT_FOUND) { handler.getProperty(snmpSecAuthKeyPos).getValue(). \ get(snmpSecAuthKey); } if(snmpSecPrivProtoPos != PEG_NOT_FOUND) { handler.getProperty(snmpSecPrivProtoPos).getValue(). \ get(snmpSecPrivProto); } if(snmpSecPrivKeyPos!= PEG_NOT_FOUND) { handler.getProperty(snmpSecPrivKeyPos).getValue(). \ get(snmpSecPrivKey); } } PEG_TRACE ((TRC_INDICATION_GENERATION, Tracer::LEVEL4, "snmpIndicationHandler sending %s Indication trap %s to target" " host %s target port %d", (const char*)(indication.getClassName().getString(). getCString()), (const char*)(trapOid.getCString()), (const char*)(targetHost.getCString()),portNumber)); _snmpTrapSender->deliverTrap( trapOid, securityName, targetHost, targetHostFormat, otherTargetHostFormat, portNumber, snmpVersion, engineID, snmpSecLevel, snmpSecAuthProto, snmpSecAuthKey, snmpSecPrivProto, snmpSecPrivKey, propOIDs, propTYPEs, propVALUEs); PEG_TRACE ((TRC_INDICATION_GENERATION, Tracer::LEVEL4, "%s Indication trap %s sent to target host %s target port %d " "successfully", (const char*)(indication.getClassName().getString().getCString()), (const char*)(trapOid.getCString()), (const char*)(targetHost.getCString()),portNumber)); } } catch (CIMException& c) { PEG_TRACE((TRC_IND_HANDLER, Tracer::LEVEL1, "CIMException %s", (const char*)c.getMessage().getCString())); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, c.getMessage()); } catch (Exception& e) { PEG_TRACE((TRC_IND_HANDLER, Tracer::LEVEL1, "Exception %s", (const char*)e.getMessage().getCString())); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, e.getMessage()); } catch (...) { PEG_TRACE_CSTRING(TRC_IND_HANDLER, Tracer::LEVEL1, "Failed to deliver trap."); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( "Handler.snmpIndicationHandler.snmpIndicationHandler." "FAILED_TO_DELIVER_TRAP", "Failed to deliver trap.")); } PEG_METHOD_EXIT(); }
CIMHandleIndicationResponseMessage* IndicationHandlerService::_handleIndication( CIMHandleIndicationRequestMessage* request) { PEG_METHOD_ENTER(TRC_IND_HANDLER, "IndicationHandlerService::_handleIndication()"); Boolean handleIndicationSuccess = true; CIMException cimException = PEGASUS_CIM_EXCEPTION(CIM_ERR_SUCCESS, String::EMPTY); CIMName className = request->handlerInstance.getClassName(); CIMNamespaceName nameSpace = request->nameSpace; CIMInstance indication = request->indicationInstance; CIMInstance handler = request->handlerInstance; PEG_TRACE ((TRC_INDICATION_GENERATION, Tracer::LEVEL4, "Handler service received %s Indication %s for %s:%s.%s Handler", (const char*)(indication.getClassName().getString().getCString()), (const char*)(request->messageId.getCString()), (const char*)(request->nameSpace.getString().getCString()), (const char*)(handler.getClassName().getString().getCString()), (const char*)(handler.getProperty(handler.findProperty( PEGASUS_PROPERTYNAME_NAME)).getValue().toString().getCString()))); Uint32 pos = PEG_NOT_FOUND; if (className.equal (PEGASUS_CLASSNAME_INDHANDLER_CIMXML) || className.equal (PEGASUS_CLASSNAME_LSTNRDST_CIMXML)) { pos = handler.findProperty(PEGASUS_PROPERTYNAME_LSTNRDST_DESTINATION); if (pos == PEG_NOT_FOUND) { cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( "HandlerService.IndicationHandlerService." "CIMXML_HANDLER_WITHOUT_DESTINATION", "CIMXml Handler missing Destination property")); handleIndicationSuccess = false; } else { CIMProperty prop = handler.getProperty(pos); String destination = prop.getValue().toString(); if (destination.size() == 0) { cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( "HandlerService.IndicationHandlerService." "INVALID_DESTINATION", "invalid destination")); handleIndicationSuccess = false; } //compared index 10 is not : else if (destination.subString(0, 10) == String("localhost/")) { Uint32 exportServer = find_service_qid(PEGASUS_QUEUENAME_EXPORTREQDISPATCHER); // Listener is build with Cimom, so send message to ExportServer AutoPtr<CIMExportIndicationRequestMessage> exportmessage( new CIMExportIndicationRequestMessage( XmlWriter::getNextMessageId(), //taking localhost/CIMListener portion out from reg destination.subString(21), indication, QueueIdStack(exportServer, getQueueId()), String::EMPTY, String::EMPTY)); exportmessage->operationContext.insert( IdentityContainer(String::EMPTY)); exportmessage->operationContext.set( request->operationContext.get( ContentLanguageListContainer::NAME)); AutoPtr<AsyncOpNode> op( this->get_op()); AutoPtr<AsyncLegacyOperationStart> asyncRequest( new AsyncLegacyOperationStart( op.get(), exportServer, exportmessage.get())); exportmessage.release(); PEG_TRACE((TRC_IND_HANDLER, Tracer::LEVEL4, "Indication handler forwarding message to %s", ((MessageQueue::lookup(exportServer)) ? ((MessageQueue::lookup(exportServer))-> getQueueName()): "BAD queue name"))); PEG_TRACE ((TRC_INDICATION_GENERATION, Tracer::LEVEL4, "Sending %s Indication %s to destination %s", (const char*) (indication.getClassName().getString(). getCString()), (const char*)(request->messageId.getCString()), (const char*) destination.getCString())); //SendAsync(op, // exportServer[0], // IndicationHandlerService::_handleIndicationCallBack, // this, // (void *)request->queueIds.top()); AutoPtr<AsyncReply> asyncReply(SendWait(asyncRequest.get())); asyncRequest.release(); // Return the ExportIndication results in HandleIndication //response AutoPtr<CIMExportIndicationResponseMessage> exportResponse( reinterpret_cast<CIMExportIndicationResponseMessage *>( (static_cast<AsyncLegacyOperationResult *>( asyncReply.get()))->get_result())); cimException = exportResponse->cimException; this->return_op(op.release()); } else { handleIndicationSuccess = _loadHandler(request, cimException); } } } else if (className.equal (PEGASUS_CLASSNAME_INDHANDLER_SNMP)) { pos = handler.findProperty(PEGASUS_PROPERTYNAME_LSTNRDST_TARGETHOST); if (pos == PEG_NOT_FOUND) { cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( "HandlerService.IndicationHandlerService." "SNMP_HANDLER_WITHOUT_TARGETHOST", "Snmp Handler missing Targethost property")); handleIndicationSuccess = false; } else { CIMProperty prop = handler.getProperty(pos); String destination = prop.getValue().toString(); if (destination.size() == 0) { cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( "HandlerService.IndicationHandlerService." "INVALID_TARGETHOST", "invalid targethost")); handleIndicationSuccess = false; } else { handleIndicationSuccess = _loadHandler(request, cimException); } } } else if ((className.equal (PEGASUS_CLASSNAME_LSTNRDST_SYSTEM_LOG)) || (className.equal (PEGASUS_CLASSNAME_LSTNRDST_EMAIL))) { handleIndicationSuccess = _loadHandler(request, cimException); } // no success to handle indication // somewhere an exception message was build // time to write the error message to the log if (!handleIndicationSuccess) { Logger::put_l(Logger::ERROR_LOG, System::CIMSERVER, Logger::WARNING, MessageLoaderParms( "HandlerService.IndicationHandlerService." "INDICATION_DELIVERY_FAILED", "Failed to deliver an indication: $0", cimException.getMessage())); } CIMHandleIndicationResponseMessage* response = dynamic_cast<CIMHandleIndicationResponseMessage*>( request->buildResponse()); response->cimException = cimException; delete request; PEG_METHOD_EXIT(); return response; }
CIMResponseMessage* DefaultProviderManager::_handleDisableModuleRequest( CIMRequestMessage* message) { PEG_METHOD_ENTER(TRC_PROVIDERMANAGER, "DefaultProviderManager::_handleDisableModuleRequest"); CIMDisableModuleRequestMessage* request = dynamic_cast<CIMDisableModuleRequestMessage*>(message); PEGASUS_ASSERT(request != 0); Array<Uint16> operationalStatus; CIMException cimException; try { // get provider module name String moduleName; CIMInstance mInstance = request->providerModule; Uint32 pos = mInstance.findProperty(PEGASUS_PROPERTYNAME_NAME); PEGASUS_ASSERT(pos != PEG_NOT_FOUND); mInstance.getProperty(pos).getValue().get(moduleName); // // Unload providers // Array<CIMInstance> providerInstances = request->providers; for (Uint32 i = 0, n = providerInstances.size(); i < n; i++) { String pName; providerInstances[i].getProperty( providerInstances[i].findProperty(PEGASUS_PROPERTYNAME_NAME)). getValue().get(pName); Sint16 ret_value = _disableProvider(moduleName, pName); if (ret_value == 0) { // disable failed since there are pending requests, // stop trying to disable other providers in this module. operationalStatus.append(CIM_MSE_OPSTATUS_VALUE_OK); break; } else if (ret_value != 1) // Not success { // disable failed for other reason, throw exception throw PEGASUS_CIM_EXCEPTION_L( CIM_ERR_FAILED, MessageLoaderParms( "ProviderManager.ProviderManagerService." "DISABLE_PROVIDER_FAILED", "Failed to disable the provider.")); } } } catch (CIMException& e) { PEG_TRACE((TRC_PROVIDERMANAGER, Tracer::LEVEL1,"CIMException: %s", (const char*)e.getMessage().getCString())); cimException = e; } catch (Exception& e) { PEG_TRACE((TRC_PROVIDERMANAGER, Tracer::LEVEL1,"Exception: %s", (const char*)e.getMessage().getCString())); cimException = CIMException(CIM_ERR_FAILED, e.getMessage()); } catch (...) { PEG_TRACE_CSTRING(TRC_PROVIDERMANAGER, Tracer::LEVEL1, "Exception: Unknown"); cimException = PEGASUS_CIM_EXCEPTION_L( CIM_ERR_FAILED, MessageLoaderParms( "ProviderManager.ProviderManagerService.UNKNOWN_ERROR", "Unknown Error")); } if (cimException.getCode() == CIM_ERR_SUCCESS) { // Status is set to OK if a provider was busy if (operationalStatus.size() == 0) { operationalStatus.append(CIM_MSE_OPSTATUS_VALUE_STOPPED); } } else { // If exception occurs, module is not stopped operationalStatus.append(CIM_MSE_OPSTATUS_VALUE_OK); } CIMDisableModuleResponseMessage* response = dynamic_cast<CIMDisableModuleResponseMessage*>( request->buildResponse()); PEGASUS_ASSERT(response != 0); response->operationalStatus = operationalStatus; PEG_METHOD_EXIT(); return response; }
Boolean ProviderAgent::_readAndProcessRequest() { PEG_METHOD_ENTER(TRC_PROVIDERAGENT, "ProviderAgent::_readAndProcessRequest"); CIMRequestMessage* request; // // Read the request from CIM Server // CIMMessage* cimMessage; AnonymousPipe::Status readStatus = _pipeFromServer->readMessage(cimMessage); request = dynamic_cast<CIMRequestMessage*>(cimMessage); // Read operation was interrupted if (readStatus == AnonymousPipe::STATUS_INTERRUPT) { PEG_TRACE_CSTRING(TRC_PROVIDERAGENT, Tracer::LEVEL1, "Read operation was interrupted."); PEG_METHOD_EXIT(); return false; } if (readStatus == AnonymousPipe::STATUS_CLOSED) { // The CIM Server connection is closed PEG_TRACE_CSTRING(TRC_PROVIDERAGENT, Tracer::LEVEL2, "CIMServer connection closed. Exiting."); _terminating = true; PEG_METHOD_EXIT(); return false; } if (readStatus == AnonymousPipe::STATUS_ERROR) { PEG_TRACE_CSTRING(TRC_PROVIDERAGENT, Tracer::LEVEL1, "Error reading from pipe. Exiting."); Logger::put_l(Logger::ERROR_LOG, System::CIMSERVER, Logger::WARNING, MessageLoaderParms( "ProviderManager.ProviderAgent.ProviderAgent." "CIMSERVER_COMMUNICATION_FAILED", "cimprovagt \"$0\" communication with CIM Server failed. " "Exiting.", _agentId)); _terminating = true; PEG_METHOD_EXIT(); return false; } // The message was not a request message. if (request == 0) { // The message was not empty. if (0 != cimMessage ) { // The message was not a "wake up" message. if (cimMessage->getType() == PROVAGT_GET_SCMOCLASS_RESPONSE_MESSAGE) { PEG_TRACE_CSTRING(TRC_PROVIDERAGENT, Tracer::LEVEL3, "Processing a SCMOClassResponseMessage."); AutoPtr<ProvAgtGetScmoClassResponseMessage> response( dynamic_cast<ProvAgtGetScmoClassResponseMessage*> (cimMessage)); PEGASUS_DEBUG_ASSERT(response.get()); _processGetSCMOClassResponse(response.get()); // The provider agent is still busy. PEG_METHOD_EXIT(); return true; } } // A "wake up" message means we should unload idle providers PEG_TRACE_CSTRING(TRC_PROVIDERAGENT, Tracer::LEVEL4, "Got a wake up message."); if (!_providerManagerRouter.hasActiveProviders()) { // No active providers, so do not start an idle unload thread return false; } try { _unloadIdleProviders(); } catch (...) { // Ignore exceptions from idle provider unloading PEG_TRACE_CSTRING(TRC_PROVIDERAGENT, Tracer::LEVEL2, "Ignoring exception from _unloadIdleProviders()"); } PEG_METHOD_EXIT(); return false; } PEG_TRACE((TRC_PROVIDERAGENT, Tracer::LEVEL3, "Received request from server with messageId %s", (const char*)request->messageId.getCString())); const AcceptLanguageListContainer acceptLang = request->operationContext.get(AcceptLanguageListContainer::NAME); Thread::setLanguages(acceptLang.getLanguages()); // Get the ProviderIdContainer to complete the provider module instance // optimization. If the provider module instance is blank (optimized // out), fill it in from our cache. If it is not blank, update our // cache. (See the _providerModuleCache member description.) if (request->operationContext.contains(ProviderIdContainer::NAME)) { ProviderIdContainer pidc = request->operationContext.get( ProviderIdContainer::NAME); if (pidc.getModule().isUninitialized()) { // Provider module is optimized out. Fill it in from the cache. request->operationContext.set(ProviderIdContainer( _providerModuleCache, pidc.getProvider(), pidc.isRemoteNameSpace(), pidc.getRemoteInfo())); } else { // Update the cache with the new provider module instance. _providerModuleCache = pidc.getModule(); } } // // It never should be possible to receive a request other than "initialise" // before the provider agent is in state isInitialised // // Bail out. // if (!_isInitialised && (request->getType() != CIM_INITIALIZE_PROVIDER_AGENT_REQUEST_MESSAGE)) { Logger::put_l(Logger::ERROR_LOG, System::CIMSERVER, Logger::WARNING, MessageLoaderParms( "ProviderManager.ProviderAgent.ProviderAgent." "PROVIDERAGENT_NOT_INITIALIZED", "cimprovagt \"$0\" was not yet initialized " "prior to receiving a request message. Exiting.", _agentId)); _terminating = true; PEG_METHOD_EXIT(); return false; } // // Check for messages to be handled by the Agent itself. // if (request->getType() == CIM_INITIALIZE_PROVIDER_AGENT_REQUEST_MESSAGE) { // Process the request in this thread AutoPtr<CIMInitializeProviderAgentRequestMessage> ipaRequest( dynamic_cast<CIMInitializeProviderAgentRequestMessage*>(request)); PEGASUS_ASSERT(ipaRequest.get() != 0); ConfigManager::setPegasusHome(ipaRequest->pegasusHome); ConfigManager* configManager = ConfigManager::getInstance(); // Initialize the configuration properties for (Uint32 i = 0; i < ipaRequest->configProperties.size(); i++) { configManager->initCurrentValue( ipaRequest->configProperties[i].first, ipaRequest->configProperties[i].second); } // Set the default resource bundle directory for the MessageLoader MessageLoader::setPegasusMsgHome(ConfigManager::getHomedPath( configManager->getCurrentValue("messageDir"))); // Set the log file directory #if !defined(PEGASUS_USE_SYSLOGS) Logger::setHomeDirectory(ConfigManager::getHomedPath( configManager->getCurrentValue("logdir"))); #endif System::bindVerbose = ipaRequest->bindVerbose; // // Set _subscriptionInitComplete from value in // InitializeProviderAgent request // _providerManagerRouter.setSubscriptionInitComplete (ipaRequest->subscriptionInitComplete); PEG_TRACE_CSTRING(TRC_PROVIDERAGENT, Tracer::LEVEL2, "Processed the agent initialization message."); // Notify the cimserver that the provider agent is initialized. Uint32 messageLength = 0; _pipeToServer->writeBuffer((const char*)&messageLength, sizeof(Uint32)); #if defined(PEGASUS_OS_ZOS) && defined(PEGASUS_ZOS_SECURITY) // prepare and setup the thread-level security environment on z/OS // if security initialization fails startupCheckBPXServer(false); startupCheckMSC(); if (!isZOSSecuritySetup()) { Logger::put_l(Logger::ERROR_LOG, ZOS_SECURITY_NAME, Logger::FATAL, MessageLoaderParms( "ProviderManager.ProviderAgent.ProviderAgent." "UNINITIALIZED_SECURITY_SETUP.PEGASUS_OS_ZOS", "Security environment could not be initialised. " "Assume security fraud. Stopping Provider Agent.")); exit(1); } #endif // provider agent is initialised and ready to go _isInitialised = true; } else if (request->getType() == CIM_NOTIFY_CONFIG_CHANGE_REQUEST_MESSAGE) { // Process the request in this thread AutoPtr<CIMNotifyConfigChangeRequestMessage> notifyRequest( dynamic_cast<CIMNotifyConfigChangeRequestMessage*>(request)); PEGASUS_ASSERT(notifyRequest.get() != 0); // // Update the ConfigManager with the new property value // ConfigManager* configManager = ConfigManager::getInstance(); CIMException responseException; try { if (notifyRequest->currentValueModified) { String userName = ((IdentityContainer) request->operationContext.get( IdentityContainer::NAME)).getUserName(); configManager->updateCurrentValue( notifyRequest->propertyName, notifyRequest->newPropertyValue, userName, 0, false); } else { configManager->updatePlannedValue( notifyRequest->propertyName, notifyRequest->newPropertyValue, true); } } catch (Exception& e) { responseException = PEGASUS_CIM_EXCEPTION( CIM_ERR_FAILED, e.getMessage()); } AutoPtr<CIMResponseMessage> response(notifyRequest->buildResponse()); response->cimException = responseException; // Return response to CIM Server _writeResponse(response.get()); } else if ((request->getType() == CIM_DISABLE_MODULE_REQUEST_MESSAGE) || (request->getType() == CIM_STOP_ALL_PROVIDERS_REQUEST_MESSAGE)) { // Process the request in this thread AutoPtr<Message> response(_processRequest(request)); _writeResponse(response.get()); CIMResponseMessage * respMsg = dynamic_cast<CIMResponseMessage*>(response.get()); // If StopAllProviders, terminate the agent process. // If DisableModule not successful, leave agent process running. if ((request->getType() == CIM_STOP_ALL_PROVIDERS_REQUEST_MESSAGE) || ((request->getType() == CIM_DISABLE_MODULE_REQUEST_MESSAGE) && (!dynamic_cast<CIMDisableModuleRequestMessage*>(request)-> disableProviderOnly) && (respMsg->cimException.getCode() == CIM_ERR_SUCCESS))) { // Operation is successful. End the agent process. _providersStopped = true; _terminating = true; } delete request; } else if (request->getType () == CIM_SUBSCRIPTION_INIT_COMPLETE_REQUEST_MESSAGE || request->getType () == CIM_INDICATION_SERVICE_DISABLED_REQUEST_MESSAGE) { // // Process the request in this thread // AutoPtr <Message> response (_processRequest (request)); _writeResponse (response.get ()); // // Note: the response does not contain interesting data // delete request; } else { // Start a new thread to process the request ProviderAgentRequest* agentRequest = new ProviderAgentRequest(this, request); ThreadStatus rtn = PEGASUS_THREAD_OK; while ((rtn = _threadPool.allocate_and_awaken(agentRequest, ProviderAgent::_processRequestAndWriteResponse)) != PEGASUS_THREAD_OK) { if (rtn == PEGASUS_THREAD_INSUFFICIENT_RESOURCES) { Threads::yield(); } else { PEG_TRACE_CSTRING(TRC_PROVIDERAGENT, Tracer::LEVEL1, "Could not allocate thread to process agent request."); AutoPtr<CIMResponseMessage> response(request->buildResponse()); response->cimException = PEGASUS_CIM_EXCEPTION_L( CIM_ERR_FAILED, MessageLoaderParms( "ProviderManager.ProviderAgent.ProviderAgent." "THREAD_ALLOCATION_FAILED", "Failed to allocate a thread in cimprovagt \"$0\".", _agentId)); // Return response to CIM Server _writeResponse(response.get()); delete agentRequest; delete request; break; } } } PEG_METHOD_EXIT(); return true; }
void CIMOperationRequestAuthorizer::handleEnqueue(Message* request) { PEG_METHOD_ENTER(TRC_SERVER, "CIMOperationRequestAuthorizer::handleEnqueue"); if (!request) { PEG_METHOD_EXIT(); return; } CIMOperationRequestMessage* tmp = dynamic_cast<CIMOperationRequestMessage*>(request); AutoPtr<CIMOperationRequestMessage> req(tmp); PEGASUS_ASSERT(req.get()); // // Get the HTTPConnection queue id // QueueIdStack qis = req->queueIds.copyAndPop(); Uint32 queueId = qis.top(); // Set the client's requested language into this service thread. // This will allow functions in this service to return messages // in the correct language. req->updateThreadLanguages(); // // If CIMOM is shutting down, return "Service Unavailable" response // if (_serverTerminating) { Buffer message; message = XmlWriter::formatHttpErrorRspMessage( HTTP_STATUS_SERVICEUNAVAILABLE, String::EMPTY, "CIM Server is shutting down."); sendResponse(queueId, message); PEG_METHOD_EXIT(); return; } String userName = ((IdentityContainer)(req->operationContext.get( IdentityContainer::NAME))).getUserName(); String authType = req->authType; CIMNamespaceName nameSpace = req->nameSpace; String cimMethodName; switch (req->getType()) { case CIM_GET_CLASS_REQUEST_MESSAGE: cimMethodName = "GetClass"; break; case CIM_GET_INSTANCE_REQUEST_MESSAGE: cimMethodName = "GetInstance"; break; case CIM_DELETE_CLASS_REQUEST_MESSAGE: cimMethodName = "DeleteClass"; break; case CIM_DELETE_INSTANCE_REQUEST_MESSAGE: cimMethodName = "DeleteInstance"; break; case CIM_CREATE_CLASS_REQUEST_MESSAGE: cimMethodName = "CreateClass"; break; case CIM_CREATE_INSTANCE_REQUEST_MESSAGE: cimMethodName = "CreateInstance"; break; case CIM_MODIFY_CLASS_REQUEST_MESSAGE: cimMethodName = "ModifyClass"; break; case CIM_MODIFY_INSTANCE_REQUEST_MESSAGE: cimMethodName = "ModifyInstance"; break; case CIM_ENUMERATE_CLASSES_REQUEST_MESSAGE: cimMethodName = "EnumerateClasses"; break; case CIM_ENUMERATE_CLASS_NAMES_REQUEST_MESSAGE: cimMethodName = "EnumerateClassNames"; break; case CIM_ENUMERATE_INSTANCES_REQUEST_MESSAGE: cimMethodName = "EnumerateInstances"; break; case CIM_ENUMERATE_INSTANCE_NAMES_REQUEST_MESSAGE: cimMethodName = "EnumerateInstanceNames"; break; case CIM_EXEC_QUERY_REQUEST_MESSAGE: cimMethodName = "ExecQuery"; break; case CIM_ASSOCIATORS_REQUEST_MESSAGE: cimMethodName = "Associators"; break; case CIM_ASSOCIATOR_NAMES_REQUEST_MESSAGE: cimMethodName = "AssociatorNames"; break; case CIM_REFERENCES_REQUEST_MESSAGE: cimMethodName = "References"; break; case CIM_REFERENCE_NAMES_REQUEST_MESSAGE: cimMethodName = "ReferenceNames"; break; case CIM_GET_PROPERTY_REQUEST_MESSAGE: cimMethodName = "GetProperty"; break; case CIM_SET_PROPERTY_REQUEST_MESSAGE: cimMethodName = "SetProperty"; break; case CIM_GET_QUALIFIER_REQUEST_MESSAGE: cimMethodName = "GetQualifier"; break; case CIM_SET_QUALIFIER_REQUEST_MESSAGE: cimMethodName = "SetQualifier"; break; case CIM_DELETE_QUALIFIER_REQUEST_MESSAGE: cimMethodName = "DeleteQualifier"; break; case CIM_ENUMERATE_QUALIFIERS_REQUEST_MESSAGE: cimMethodName = "EnumerateQualifiers"; break; case CIM_INVOKE_METHOD_REQUEST_MESSAGE: cimMethodName = "InvokeMethod"; break; default: PEGASUS_ASSERT(0); break; } #ifdef PEGASUS_ZOS_SECURITY if (checkRequestTypeAuthorizationZOS( req->getType(), userName, nameSpace) == false) { // // user is not authorized, send an // error message to the requesting client. // if (cimMethodName == "InvokeMethod") { sendMethodError( queueId, req->getHttpMethod(), req->messageId, ((CIMInvokeMethodRequestMessage*)req.get())->methodName, PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, MessageLoaderParms( "Server.CIMOperationRequestAuthorizer." "NAMESPACE_AUTHORIZATION_FAILED", "User '$0' is not authorized to run '$1' in the " "namespace '$2'", userName, cimMethodName, nameSpace.getString()))); } else { sendIMethodError( queueId, req->getHttpMethod(), req->messageId, cimMethodName, PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, MessageLoaderParms( "Server.CIMOperationRequestAuthorizer." "NAMESPACE_AUTHORIZATION_FAILED", "User '$0' is not authorized to run '$1' in the " "namespace '$2'", userName, cimMethodName, nameSpace.getString()))); } PEG_METHOD_EXIT(); return; } #endif #ifdef PEGASUS_ENABLE_USERGROUP_AUTHORIZATION // // If the user is not privileged and authorized user group is specified, // then perform the user group authorization check. // try { if ( ! System::isPrivilegedUser(userName) ) { Uint32 size = _authorizedUserGroups.size(); if (size > 0) { Boolean authorized = false; // // Check if the user name is in the authorized user groups. // for (Uint32 i = 0; i < size; i++) { // // Check if the user is a member of the group // if (System::isGroupMember(userName.getCString(), _authorizedUserGroups[i].getCString())) { authorized = true; break; } } // // If the user is not a member of any of the authorized // user groups then generate error response. // if (!authorized) { PEG_TRACE((TRC_SERVER, Tracer::LEVEL1, "Authorization Failed: User '%s' " "is not a member of the authorized groups", (const char*)userName.getCString())); MessageLoaderParms msgLoaderParms( "Server.CIMOperationRequestAuthorizer." "NOT_IN_AUTHORIZED_GRP", "User '$0' is not authorized to access CIM data.", userName); // // user is not in the authorized user groups, send an // error message to the requesting client. // if (cimMethodName == "InvokeMethod") { sendMethodError( queueId, req->getHttpMethod(), req->messageId, ((CIMInvokeMethodRequestMessage*)req.get())-> methodName, PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, msgLoaderParms)); PEG_METHOD_EXIT(); return; } else { sendIMethodError( queueId, req->getHttpMethod(), req->messageId, cimMethodName, PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, msgLoaderParms)); PEG_METHOD_EXIT(); return; } } } } } catch (InternalSystemError& ise) { sendIMethodError( queueId, req->getHttpMethod(), req->messageId, cimMethodName, PEGASUS_CIM_EXCEPTION(CIM_ERR_ACCESS_DENIED, ise.getMessage())); PEG_METHOD_EXIT(); return; } #endif // #ifdef PEGASUS_ENABLE_USERGROUP_AUTHORIZATION // // Get a config manager instance // ConfigManager* configManager = ConfigManager::getInstance(); // // Do namespace authorization verification // if (ConfigManager::parseBooleanValue( configManager->getCurrentValue("enableNamespaceAuthorization"))) { // // If the user is not privileged, perform the authorization check. // if (!System::isPrivilegedUser(userName)) { UserManager* userManager = UserManager::getInstance(); if (!userManager || !userManager->verifyAuthorization( userName, nameSpace, cimMethodName)) { if (cimMethodName == "InvokeMethod") { sendMethodError( queueId, req->getHttpMethod(), req->messageId, ((CIMInvokeMethodRequestMessage*)req.get())->methodName, PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, MessageLoaderParms( "Server.CIMOperationRequestAuthorizer." "NAMESPACE_AUTHORIZATION_FAILED", "User '$0' is not authorized to run '$1' in the " "namespace '$2'", userName, cimMethodName, nameSpace.getString()))); } else { sendIMethodError( queueId, req->getHttpMethod(), req->messageId, cimMethodName, PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, MessageLoaderParms( "Server.CIMOperationRequestAuthorizer." "NAMESPACE_AUTHORIZATION_FAILED", "User '$0' is not authorized to run '$1' in " "the namespace '$2'", userName, cimMethodName, nameSpace.getString()))); } PEG_METHOD_EXIT(); return; } } } // // Enqueue the request // _outputQueue->enqueue(req.release()); PEG_METHOD_EXIT(); }
void CIMOperationRequestAuthorizer::handleEnqueue(Message *request) { PEG_METHOD_ENTER(TRC_SERVER, "CIMOperationRequestAuthorizer::handleEnqueue"); if (!request) { PEG_METHOD_EXIT(); return; } AutoPtr<CIMOperationRequestMessage> req(dynamic_cast<CIMOperationRequestMessage *>(request)); PEGASUS_ASSERT(req.get()); // // Get the HTTPConnection queue id // QueueIdStack qis = req->queueIds.copyAndPop(); Uint32 queueId = qis.top(); // l10n // Set the client's requested language into this service thread. // This will allow functions in this service to return messages // in the correct language. if (req->thread_changed()) { AutoPtr<AcceptLanguages> langs(new AcceptLanguages(((AcceptLanguageListContainer)req->operationContext.get (AcceptLanguageListContainer:: NAME)).getLanguages())); Thread::setLanguages(langs.release()); } // // If CIMOM is shutting down, return "Service Unavailable" response // if (_serverTerminating) { Array<char> message; message = XmlWriter::formatHttpErrorRspMessage( HTTP_STATUS_SERVICEUNAVAILABLE, String::EMPTY, "CIM Server is shutting down."); sendResponse(queueId, message); PEG_METHOD_EXIT(); return; } String userName = String::EMPTY; String authType = String::EMPTY; CIMNamespaceName nameSpace; String cimMethodName = String::EMPTY; // Set the username and namespace. nameSpace = req->nameSpace; userName = ((IdentityContainer)(req->operationContext.get (IdentityContainer::NAME))).getUserName(); switch (req->getType()) { case CIM_GET_CLASS_REQUEST_MESSAGE: authType = ((CIMGetClassRequestMessage*)req.get())->authType; cimMethodName = "GetClass"; break; case CIM_GET_INSTANCE_REQUEST_MESSAGE: authType = ((CIMGetInstanceRequestMessage*)req.get())->authType; cimMethodName = "GetInstance"; break; case CIM_DELETE_CLASS_REQUEST_MESSAGE: authType = ((CIMDeleteClassRequestMessage*)req.get())->authType; cimMethodName = "DeleteClass"; break; case CIM_DELETE_INSTANCE_REQUEST_MESSAGE: authType = ((CIMDeleteInstanceRequestMessage*)req.get())->authType; cimMethodName = "DeleteInstance"; break; case CIM_CREATE_CLASS_REQUEST_MESSAGE: authType = ((CIMCreateClassRequestMessage*)req.get())->authType; cimMethodName = "CreateClass"; break; case CIM_CREATE_INSTANCE_REQUEST_MESSAGE: authType = ((CIMCreateInstanceRequestMessage*)req.get())->authType; cimMethodName = "CreateInstance"; break; case CIM_MODIFY_CLASS_REQUEST_MESSAGE: authType = ((CIMModifyClassRequestMessage*)req.get())->authType; cimMethodName = "ModifyClass"; break; case CIM_MODIFY_INSTANCE_REQUEST_MESSAGE: authType = ((CIMModifyInstanceRequestMessage*)req.get())->authType; cimMethodName = "ModifyInstance"; break; case CIM_ENUMERATE_CLASSES_REQUEST_MESSAGE: authType = ((CIMEnumerateClassesRequestMessage*)req.get())->authType; cimMethodName = "EnumerateClasses"; break; case CIM_ENUMERATE_CLASS_NAMES_REQUEST_MESSAGE: authType = ((CIMEnumerateClassNamesRequestMessage*)req.get())->authType; cimMethodName = "EnumerateClassNames"; break; case CIM_ENUMERATE_INSTANCES_REQUEST_MESSAGE: authType = ((CIMEnumerateInstancesRequestMessage*)req.get())->authType; cimMethodName = "EnumerateInstances"; break; case CIM_ENUMERATE_INSTANCE_NAMES_REQUEST_MESSAGE: authType = ((CIMEnumerateInstanceNamesRequestMessage*)req.get())->authType; cimMethodName = "EnumerateInstanceNames"; break; case CIM_EXEC_QUERY_REQUEST_MESSAGE: authType = ((CIMExecQueryRequestMessage*)req.get())->authType; cimMethodName = "ExecQuery"; break; case CIM_ASSOCIATORS_REQUEST_MESSAGE: authType = ((CIMAssociatorsRequestMessage*)req.get())->authType; cimMethodName = "Associators"; break; case CIM_ASSOCIATOR_NAMES_REQUEST_MESSAGE: authType = ((CIMAssociatorNamesRequestMessage*)req.get())->authType; cimMethodName = "AssociatorNames"; break; case CIM_REFERENCES_REQUEST_MESSAGE: authType = ((CIMReferencesRequestMessage*)req.get())->authType; cimMethodName = "References"; break; case CIM_REFERENCE_NAMES_REQUEST_MESSAGE: authType = ((CIMReferenceNamesRequestMessage*)req.get())->authType; cimMethodName = "ReferenceNames"; break; case CIM_GET_PROPERTY_REQUEST_MESSAGE: authType = ((CIMGetPropertyRequestMessage*)req.get())->authType; cimMethodName = "GetProperty"; break; case CIM_SET_PROPERTY_REQUEST_MESSAGE: authType = ((CIMSetPropertyRequestMessage*)req.get())->authType; cimMethodName = "SetProperty"; break; case CIM_GET_QUALIFIER_REQUEST_MESSAGE: authType = ((CIMGetQualifierRequestMessage*)req.get())->authType; cimMethodName = "GetQualifier"; break; case CIM_SET_QUALIFIER_REQUEST_MESSAGE: authType = ((CIMSetQualifierRequestMessage*)req.get())->authType; cimMethodName = "SetQualifier"; break; case CIM_DELETE_QUALIFIER_REQUEST_MESSAGE: authType = ((CIMDeleteQualifierRequestMessage*)req.get())->authType; cimMethodName = "DeleteQualifier"; break; case CIM_ENUMERATE_QUALIFIERS_REQUEST_MESSAGE: authType = ((CIMEnumerateQualifiersRequestMessage*)req.get())->authType; cimMethodName = "EnumerateQualifiers"; break; case CIM_INVOKE_METHOD_REQUEST_MESSAGE: authType = ((CIMInvokeMethodRequestMessage*)req.get())->authType; cimMethodName = "InvokeMethod"; break; default: PEGASUS_ASSERT(0); break; } #ifdef PEGASUS_ENABLE_USERGROUP_AUTHORIZATION // // If the user is not privileged and authorized user group is specified, // then perform the user group authorization check. // try { if ( ! System::isPrivilegedUser(userName) ) { Uint32 size = _authorizedUserGroups.size(); if (size > 0) { Boolean authorized = false; // // Check if the user name is in the authorized user groups. // for (Uint32 i = 0; i < size; i++) { // // Check if the user is a member of the group // if ( System::isGroupMember(userName.getCString(), _authorizedUserGroups[i].getCString()) ) { authorized = true; break; } } // // If the user is not a member of any of the authorized // user groups then generate error response. // if (!authorized) { PEG_TRACE_STRING(TRC_SERVER, Tracer::LEVEL2, "Authorization Failed: User '" + userName + "' is not a member of the authorized groups"); MessageLoaderParms msgLoaderParms( "Server.CIMOperationRequestAuthorizer.NOT_IN_AUTHORIZED_GRP", "User '$0' is not authorized to access CIM data.", userName); // // user is not in the authorized user groups, send an // error message to the requesting client. // if (cimMethodName == "InvokeMethod") { // l10n sendMethodError( queueId, req->getHttpMethod(), req->messageId, ((CIMInvokeMethodRequestMessage*)req.get())->methodName, PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, msgLoaderParms)); PEG_METHOD_EXIT(); return; } else { // l10n sendIMethodError( queueId, req->getHttpMethod(), req->messageId, cimMethodName, PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, msgLoaderParms)); PEG_METHOD_EXIT(); return; } } } } } catch (InternalSystemError &ise) { sendIMethodError( queueId, req->getHttpMethod(), req->messageId, cimMethodName, PEGASUS_CIM_EXCEPTION(CIM_ERR_ACCESS_DENIED, ise.getMessage())); PEG_METHOD_EXIT(); return; } #endif // #ifdef PEGASUS_ENABLE_USERGROUP_AUTHORIZATION // // Get a config manager instance // ConfigManager* configManager = ConfigManager::getInstance(); // // Do namespace authorization verification // if (String::equalNoCase( configManager->getCurrentValue("enableNamespaceAuthorization"), "true")) { // // If the user is not privileged, perform the authorization check. // #if !defined(PEGASUS_PLATFORM_OS400_ISERIES_IBM) if ( ! System::isPrivilegedUser(userName) ) #else // On OS/400, always check authorization if remote user. // Always allow local privileged users through. // Check authorization for local non-privileged users. // (User authorization to providers are checked downstream from here). if ( ! String::equalNoCase(authType,"Local") || ! System::isPrivilegedUser(userName) ) #endif { UserManager* userManager = UserManager::getInstance(); if ( !userManager || !userManager->verifyAuthorization( userName, nameSpace, cimMethodName) ) { // l10n // String description = "Not authorized to run "; // description.append(cimMethodName); // description.append(" in the namespace "); // description.append(nameSpace.getString()); if (cimMethodName == "InvokeMethod") { // l10n sendMethodError( queueId, req->getHttpMethod(), req->messageId, ((CIMInvokeMethodRequestMessage*)req.get())->methodName, PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, MessageLoaderParms( "Server.CIMOperationRequestAuthorizer.NOT_AUTHORIZED", "Not authorized to run $0 in the namespace $1", cimMethodName, nameSpace.getString()))); } else { // l10n sendIMethodError( queueId, req->getHttpMethod(), req->messageId, cimMethodName, PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, MessageLoaderParms( "Server.CIMOperationRequestAuthorizer.NOT_AUTHORIZED", "Not authorized to run $0 in the namespace $1", cimMethodName, nameSpace.getString()))); } PEG_METHOD_EXIT(); return; } } } // // If the user is privileged, and remote privileged user access is not // enabled and the auth type is not Local then reject access. // if ( System::isPrivilegedUser(userName) && !String::equalNoCase(authType, "Local") && !String::equalNoCase( configManager->getCurrentValue("enableRemotePrivilegedUserAccess"), "true") ) { if (cimMethodName == "InvokeMethod") { // l10n sendMethodError( queueId, req->getHttpMethod(), req->messageId, ((CIMInvokeMethodRequestMessage*)req.get())->methodName, PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, MessageLoaderParms( "Server.CIMOperationRequestAuthorizer.REMOTE_NOT_ENABLED", "Remote privileged user access is not enabled."))); } else { // l10n sendIMethodError( queueId, req->getHttpMethod(), req->messageId, cimMethodName, PEGASUS_CIM_EXCEPTION_L(CIM_ERR_ACCESS_DENIED, MessageLoaderParms( "Server.CIMOperationRequestAuthorizer.REMOTE_NOT_ENABLED", "Remote privileged user access is not enabled."))); } PEG_METHOD_EXIT(); return; } // // Enqueue the request // _outputQueue->enqueue(req.release()); PEG_METHOD_EXIT(); }
// Creates a SNMP TRAP PDU void snmpDeliverTrap_netsnmp::_createPdu( Uint16 snmpVersion, const String& trapOid, snmp_session*& sessionPtr, snmp_pdu*& snmpPdu) { PEG_METHOD_ENTER(TRC_IND_HANDLER, "snmpDeliverTrap_netsnmp::_createPdu"); oid _SYSTEM_UP_TIME_OID [] = {1,3,6,1,2,1,1,3,0}; oid _SNMPTRAP_OID [] = {1,3,6,1,6,3,1,1,4,1,0}; in_addr_t* pduInAddr; switch (snmpVersion) { case _SNMPv1_TRAP: { sessionPtr->version = SNMP_VERSION_1; // Create the PDU snmpPdu = snmp_pdu_create(SNMP_MSG_TRAP); // Failed to create pdu if (!snmpPdu) { PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_PDU_CREATE_FAILED_KEY, _MSG_PDU_CREATE_FAILED)); } // Make sure that the v1 trap PDU includes the local IP address pduInAddr = (in_addr_t*) snmpPdu->agent_addr; *pduInAddr = get_myaddr(); // get system up time snmpPdu->time = get_uptime(); // Pack trap information into the PDU try { _packTrapInfoIntoPdu(trapOid, snmpPdu); } catch (CIMException& e) { Logger::put_l( Logger::STANDARD_LOG, System::CIMSERVER, Logger::WARNING, MessageLoaderParms( _MSG_PACK_TRAP_INFO_INTO_PDU_FAILED_KEY, _MSG_PACK_TRAP_INFO_INTO_PDU_FAILED, e.getMessage())); } break; } case _SNMPv2C_TRAP: { sessionPtr->version = SNMP_VERSION_2c; // Create the PDU snmpPdu = snmp_pdu_create(SNMP_MSG_TRAP2); // Failed to create pdu if (!snmpPdu) { PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_PDU_CREATE_FAILED_KEY, _MSG_PDU_CREATE_FAILED)); } // Add sysUpTime to the PDU char sysUpTime[32]; sprintf(sysUpTime, "%ld", get_uptime()); Sint32 retCode; retCode = snmp_add_var( snmpPdu, _SYSTEM_UP_TIME_OID, OID_LENGTH(_SYSTEM_UP_TIME_OID), 't', sysUpTime); // Failed to add sysUpTime to the pdu if (retCode != 0) { String errMsg = snmp_api_errstring(retCode); Logger::put_l( Logger::STANDARD_LOG, System::CIMSERVER, Logger::WARNING, MessageLoaderParms( _MSG_ADD_SYSUPTIME_TO_PDU_FAILED_KEY, _MSG_ADD_SYSUPTIME_TO_PDU_FAILED, errMsg)); } // Add snmp trap to the PDU retCode = snmp_add_var( snmpPdu, _SNMPTRAP_OID, OID_LENGTH(_SNMPTRAP_OID), 'o', trapOid.getCString()); // Failed to add snmp trap to the pdu if (retCode != 0) { String errMsg = snmp_api_errstring(retCode); Logger::put_l( Logger::STANDARD_LOG, System::CIMSERVER, Logger::WARNING, MessageLoaderParms( _MSG_ADD_SNMP_TRAP_TO_PDU_FAILED_KEY, _MSG_ADD_SNMP_TRAP_TO_PDU_FAILED, errMsg)); } break; } default: { PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_NOT_SUPPORTED, MessageLoaderParms( _MSG_VERSION_NOT_SUPPORTED_KEY, _MSG_VERSION_NOT_SUPPORTED)); } } PEG_METHOD_EXIT(); }
// l10n - note: ignoring indication language void snmpIndicationHandler::handleIndication( const OperationContext& context, const String nameSpace, CIMInstance& indication, CIMInstance& handler, CIMInstance& subscription, ContentLanguages & contentLanguages) { Array<String> propOIDs; Array<String> propTYPEs; Array<String> propVALUEs; CIMProperty prop; CIMQualifier trapQualifier; Uint32 qualifierPos; String propValue; String mapstr1; String mapstr2; PEG_METHOD_ENTER (TRC_IND_HANDLER, "snmpIndicationHandler::handleIndication"); try { CIMClass indicationClass = _repository->getClass( nameSpace, indication.getClassName(), false, true, false, CIMPropertyList()); Uint32 propertyCount = indication.getPropertyCount(); for (Uint32 i=0; i < propertyCount; i++) { prop = indication.getProperty(i); if (!prop.isUninitialized()) { CIMName propName = prop.getName(); Uint32 propPos = indicationClass.findProperty(propName); if (propPos != PEG_NOT_FOUND) { CIMProperty trapProp = indicationClass.getProperty(propPos); qualifierPos = trapProp.findQualifier(CIMName ("MappingStrings")); if (qualifierPos != PEG_NOT_FOUND) { trapQualifier = trapProp.getQualifier(qualifierPos); mapstr1.clear(); mapstr1 = trapQualifier.getValue().toString(); if ((mapstr1.find("OID.IETF") != PEG_NOT_FOUND) && (mapstr1.find("DataType.IETF") != PEG_NOT_FOUND)) { if (mapstr1.subString(0, 8) == "OID.IETF") { mapstr1 = mapstr1.subString(mapstr1.find("SNMP.")+5); if (mapstr1.find("|") != PEG_NOT_FOUND) { mapstr2.clear(); mapstr2 = mapstr1.subString(0, mapstr1.find("DataType.IETF")-1); propOIDs.append(mapstr2); propValue.clear(); propValue = prop.getValue().toString(); propVALUEs.append(propValue); mapstr2 = mapstr1.subString(mapstr1.find("|")+2); mapstr2 = mapstr2.subString(0, mapstr2.size()-1); propTYPEs.append(mapstr2); } } } } } } } // Collected complete data in arrays and ready to send the trap. // trap destination and SNMP type are defined in handlerInstance // and passing this instance as it is to deliverTrap() call #ifdef HPUX_EMANATE static snmpDeliverTrap_emanate emanateTrap; #else static snmpDeliverTrap_stub emanateTrap; #endif Uint32 targetHostPos = handler.findProperty(CIMName ("TargetHost")); Uint32 targetHostFormatPos = handler.findProperty(CIMName ("TargetHostFormat")); Uint32 otherTargetHostFormatPos = handler.findProperty(CIMName ( "OtherTargetHostFormat")); Uint32 portNumberPos = handler.findProperty(CIMName ("PortNumber")); Uint32 snmpVersionPos = handler.findProperty(CIMName ("SNMPVersion")); Uint32 securityNamePos = handler.findProperty(CIMName ("SNMPSecurityName")); Uint32 engineIDPos = handler.findProperty(CIMName ("SNMPEngineID")); if ((targetHostPos != PEG_NOT_FOUND) && (targetHostFormatPos != PEG_NOT_FOUND) && (snmpVersionPos != PEG_NOT_FOUND) && (indicationClass.findQualifier(CIMName ("MappingStrings")) != PEG_NOT_FOUND)) { // properties from the handler instance String targetHost; String otherTargetHostFormat = String(); String securityName = String(); String engineID = String(); Uint16 targetHostFormat = 0; Uint16 snmpVersion = 0; Uint32 portNumber; String trapOid; // // Get snmpTrapOid from context // try { SnmpTrapOidContainer trapContainer = context.get (SnmpTrapOidContainer::NAME); trapOid = trapContainer.getSnmpTrapOid(); } catch (Exception& e) { // get trapOid from indication Class Uint32 pos = indicationClass.findQualifier(CIMName ("MappingStrings")); if (pos != PEG_NOT_FOUND) { trapOid = indicationClass.getQualifier(pos).getValue().toString(); trapOid = trapOid.subString(11, PEG_NOT_FOUND); if ((String::compare(trapOid, "SNMP.", 5)) == 0) { trapOid = trapOid.subString(5, (trapOid.size()-6)); } else { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, "Invalid MappingStrings Value " + trapOid); PEG_METHOD_EXIT(); // l10n // throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, "Invalid MappingStrings Value"); throw PEGASUS_CIM_EXCEPTION_L (CIM_ERR_FAILED, MessageLoaderParms("Handler.snmpIndicationHandler.snmpIndicationHandler.INVALID_MS_VALUE", "Invalid MappingStrings Value")); } } else { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, "Qualifier MappingStrings can not be found."); PEG_METHOD_EXIT(); //L10N_ TODO DONE //throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, "Qualifier MappingStrings can not be found"); MessageLoaderParms parms("Handler.snmpIndicationHandler.snmpIndicationHandler.QUALIFIER_MAPPINGS_NOT_FOUND", "Qualifier MappingStrings can not be found"); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, parms); } } handler.getProperty(targetHostPos).getValue().get(targetHost); handler.getProperty(targetHostFormatPos).getValue().get(targetHostFormat); if (otherTargetHostFormatPos != PEG_NOT_FOUND) { handler.getProperty(otherTargetHostFormatPos).getValue().get (otherTargetHostFormat); } if (portNumberPos != PEG_NOT_FOUND) { handler.getProperty(portNumberPos).getValue().get(portNumber); } else { // default port portNumber = SNMP_TRAP_DEFAULT_PORT; } handler.getProperty(snmpVersionPos).getValue().get(snmpVersion); if (securityNamePos != PEG_NOT_FOUND) { handler.getProperty(securityNamePos).getValue().get(securityName); } if (engineIDPos != PEG_NOT_FOUND) { handler.getProperty(engineIDPos).getValue().get(engineID); } emanateTrap.deliverTrap( trapOid, securityName, targetHost, targetHostFormat, otherTargetHostFormat, portNumber, snmpVersion, engineID, propOIDs, propTYPEs, propVALUEs); } else { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, "Invalid IndicationHandlerSNMPMapper instance."); PEG_METHOD_EXIT(); // l10n // throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, // "Invalid IndicationHandlerSNMPMapper instance"); throw PEGASUS_CIM_EXCEPTION_L (CIM_ERR_FAILED, MessageLoaderParms("Handler.snmpIndicationHandler.snmpIndicationHandler.INVALID_SNMP_INSTANCE", "Invalid IndicationHandlerSNMPMapper instance")); } } catch (CIMException & c) { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, c.getMessage()); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION (CIM_ERR_FAILED, c.getMessage()); } catch (Exception& e) { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, e.getMessage()); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION (CIM_ERR_FAILED, e.getMessage()); } catch (...) { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, "Failed to deliver trap."); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L (CIM_ERR_FAILED, MessageLoaderParms("Handler.snmpIndicationHandler.snmpIndicationHandler.FAILED_TO_DELIVER_TRAP", "Failed to deliver trap.")); } }
// Pack oids into the PDU void snmpDeliverTrap_netsnmp::_packOidsIntoPdu( const Array<String>& vbOids, const Array<String>& vbTypes, const Array<String>& vbValues, snmp_pdu* snmpPdu) { PEG_METHOD_ENTER(TRC_IND_HANDLER, "snmpDeliverTrap_netsnmp::_packOidsIntoPdu"); char dataType; oid vbOid[MAX_OID_LEN]; size_t vbOidLength = MAX_OID_LEN; for (Uint32 i=0; i < vbOids.size(); i++) { if (vbTypes[i] == "OctetString") { dataType = 's'; } else if (vbTypes[i] == "Integer") { dataType = 'i'; } else if (vbTypes[i] == "OID") { dataType = 'o'; } else { // Integer, OctetString, and OID are supported SNMP Data Types // for the CIM Property PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms(_MSG_UNSUPPORTED_SNMP_DATA_TYPE_KEY, _MSG_UNSUPPORTED_SNMP_DATA_TYPE, vbTypes[i])); } // Convert oid of a CIM property from numeric form to a list of // subidentifiers if (read_objid((const char*)vbOids[i].getCString(), vbOid, &vbOidLength) == 0) { // Failed to parse vbOids PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms(_MSG_PARSE_CIM_PROPERTY_OID_FAILED_KEY, _MSG_PARSE_CIM_PROPERTY_OID_FAILED, vbOids[i])); } Sint32 retCode; retCode = snmp_add_var(snmpPdu, vbOid, vbOidLength, dataType, vbValues[i].getCString()); // Failed to add vbOid to the pdu if (retCode != 0) { PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms(_MSG_ADD_VAR_TO_PDU_FAILED_KEY, _MSG_ADD_VAR_TO_PDU_FAILED, vbOids[i], String(snmp_api_errstring(retCode)))); } } PEG_METHOD_EXIT(); }
void EmailListenerDestination::_sendViaEmail( const Array<String> & mailTo, const Array<String> & mailCc, const String & mailSubject, const String & formattedText) { PEG_METHOD_ENTER (TRC_IND_HANDLER, "EmailListenerDestination::_sendViaEmail"); #if defined(PEGASUS_OS_HPUX) || defined(PEGASUS_OS_LINUX) String exceptionStr; FILE * mailFilePtr; FILE * filePtr; char mailFile[TEMP_NAME_LEN]; // Check for proper execute permissions for sendmail if (access(SENDMAIL_CMD, X_OK) < 0) { Tracer::trace(TRC_IND_HANDLER, Tracer::LEVEL4, "Cannot execute %s: %s." SENDMAIL_CMD, strerror(errno)); MessageLoaderParms parms( "Handler.EmailListenerDestination.EmailListenerDestination._MSG_EXECUTE_ACCESS_FAILED", "Cannot execute $0: $1", SENDMAIL_CMD, strerror(errno)); Logger::put_l (Logger::STANDARD_LOG, System::CIMSERVER, Logger::WARNING, "Handler.EmailListenerDestination.EmailListenerDestination._MSG_EXECUTE_ACCESS_FAILED", MessageLoader::getMessage(parms)); PEG_METHOD_EXIT(); return; } // open a temporary file to hold the indication mail message _openFile(&filePtr, mailFile); try { _buildMailHeader(mailTo, mailCc, mailSubject, filePtr); // write indication text to the file _writeStrToFile(formattedText, filePtr); fclose(filePtr); } catch (CIMException &c) { fclose(filePtr); unlink(mailFile); PEG_METHOD_EXIT(); return; } try { // send the message _sendMsg(mailFile); } catch (CIMException &c) { unlink(mailFile); PEG_METHOD_EXIT(); return; } unlink(mailFile); PEG_METHOD_EXIT(); #else PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, "sendmail is not supported."); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L (CIM_ERR_NOT_SUPPORTED, MessageLoaderParms("Handler.EmailListenerDestination." "EmailListenerDestination.UNSUPPORTED_OPERATION", "sendmail is not supported.")); #endif PEG_METHOD_EXIT(); }
CIMHandleIndicationResponseMessage* IndicationHandlerService::_handleIndication( CIMHandleIndicationRequestMessage* request) { PEG_METHOD_ENTER (TRC_IND_HANDLE, "IndicationHandlerService::_handleIndication"); CIMException cimException = PEGASUS_CIM_EXCEPTION(CIM_ERR_SUCCESS, String::EMPTY); CIMName className = request->handlerInstance.getClassName(); CIMNamespaceName nameSpace = request->nameSpace; CIMInstance indication = request->indicationInstance; CIMInstance handler = request->handlerInstance; Uint32 pos = PEG_NOT_FOUND; if (className.equal (PEGASUS_CLASSNAME_INDHANDLER_CIMXML) || className.equal (PEGASUS_CLASSNAME_LSTNRDST_CIMXML)) { pos = handler.findProperty(PEGASUS_PROPERTYNAME_LSTNRDST_DESTINATION); if (pos == PEG_NOT_FOUND) { cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms("HandlerService.IndicationHandlerService." "CIMXML_HANDLER_WITHOUT_DESTINATION", "CIMXml Handler missing Destination property")); } else { CIMProperty prop = handler.getProperty(pos); String destination = prop.getValue().toString(); if (destination.size() == 0) { cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms("HandlerService.IndicationHandlerService." "INVALID_DESTINATION", "invalid destination")); } //compared index 10 is not : else if (destination.subString(0, 10) == String("localhost/")) { Array<Uint32> exportServer; find_services(PEGASUS_QUEUENAME_EXPORTREQDISPATCHER, 0, 0, &exportServer); // Listener is build with Cimom, so send message to ExportServer AutoPtr<CIMExportIndicationRequestMessage> exportmessage( new CIMExportIndicationRequestMessage( XmlWriter::getNextMessageId(), destination.subString(21), //taking localhost/CIMListener portion out from reg indication, QueueIdStack(exportServer[0], getQueueId()), String::EMPTY, String::EMPTY)); exportmessage->operationContext.set( request->operationContext.get( ContentLanguageListContainer::NAME)); AutoPtr<AsyncOpNode> op( this->get_op()); AutoPtr<AsyncLegacyOperationStart> asyncRequest( new AsyncLegacyOperationStart( get_next_xid(), op.get(), exportServer[0], exportmessage.get(), _queueId)); exportmessage.release(); PEG_TRACE_STRING(TRC_IND_HANDLE, Tracer::LEVEL4, "Indication handler forwarding message to " + ((MessageQueue::lookup(exportServer[0])) ? String( ((MessageQueue::lookup(exportServer[0]))-> getQueueName()) ) : String("BAD queue name"))); //SendAsync(op, // exportServer[0], // IndicationHandlerService::_handleIndicationCallBack, // this, // (void *)request->queueIds.top()); AutoPtr<AsyncReply> asyncReply(SendWait(asyncRequest.get())); asyncRequest.release(); // Return the ExportIndication results in HandleIndication //response AutoPtr<CIMExportIndicationResponseMessage> exportResponse( reinterpret_cast<CIMExportIndicationResponseMessage *>( (static_cast<AsyncLegacyOperationResult *>( asyncReply.get()))->get_result())); cimException = exportResponse->cimException; op->release(); this->return_op(op.release()); } else { _loadHandler(request, cimException); } } } else if (className.equal (PEGASUS_CLASSNAME_INDHANDLER_SNMP)) { pos = handler.findProperty(PEGASUS_PROPERTYNAME_LSTNRDST_TARGETHOST); if (pos == PEG_NOT_FOUND) { cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms("HandlerService.IndicationHandlerService." "SNMP_HANDLER_WITHOUT_TARGETHOST", "Snmp Handler missing Targethost property")); } else { CIMProperty prop = handler.getProperty(pos); String destination = prop.getValue().toString(); if (destination.size() == 0) { cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms("HandlerService.IndicationHandlerService." "INVALID_TARGETHOST", "invalid targethost")); } else { _loadHandler(request, cimException); } } } else if ((className.equal (PEGASUS_CLASSNAME_LSTNRDST_SYSTEM_LOG)) || (className.equal (PEGASUS_CLASSNAME_LSTNRDST_EMAIL))) { _loadHandler(request, cimException); } CIMHandleIndicationResponseMessage* response = new CIMHandleIndicationResponseMessage( request->messageId, cimException, request->queueIds.copyAndPop()); delete request; return response; }
void CIMExportRequestDecoder::handleMethodRequest( Uint32 queueId, HttpMethod httpMethod, char* content, const String& requestUri, const char* cimProtocolVersionInHeader, const char* cimExportMethodInHeader, const String& userName, const String& ipAddress, const AcceptLanguageList& httpAcceptLanguages, const ContentLanguageList& httpContentLanguages, Boolean closeConnect) { // Set the Accept-Language into the thread for this service. // This will allow all code in this thread to get // the languages for the messages returned to the client. Thread::setLanguages(httpAcceptLanguages); // // If CIM Listener is shutting down, return error response // if (_serverTerminating) { sendHttpError( queueId, HTTP_STATUS_SERVICEUNAVAILABLE, String::EMPTY, "CIM Listener is shutting down.", closeConnect); return; } // Create a parser: XmlParser parser(content); XmlEntry entry; String messageId; const char* cimExportMethodName = ""; AutoPtr<CIMExportIndicationRequestMessage> request; try { // // Process <?xml ... > // // These values are currently unused const char* xmlVersion = 0; const char* xmlEncoding = 0; XmlReader::getXmlDeclaration(parser, xmlVersion, xmlEncoding); // Expect <CIM ...> const char* cimVersion = 0; const char* dtdVersion = 0; XmlReader::getCimStartTag(parser, cimVersion, dtdVersion); if (!XmlReader::isSupportedCIMVersion(cimVersion)) { sendHttpError( queueId, HTTP_STATUS_NOTIMPLEMENTED, "unsupported-cim-version", String::EMPTY, closeConnect); return; } if (!XmlReader::isSupportedDTDVersion(dtdVersion)) { sendHttpError( queueId, HTTP_STATUS_NOTIMPLEMENTED, "unsupported-dtd-version", String::EMPTY, closeConnect); return; } // Expect <MESSAGE ...> String protocolVersion; if (!XmlReader::getMessageStartTag( parser, messageId, protocolVersion)) { MessageLoaderParms mlParms( "ExportServer.CIMExportRequestDecoder.EXPECTED_MESSAGE_ELEMENT", "expected MESSAGE element"); throw XmlValidationError(parser.getLine(), mlParms); } // Validate that the protocol version in the header matches the XML if (!String::equalNoCase(protocolVersion, cimProtocolVersionInHeader)) { sendHttpError( queueId, HTTP_STATUS_BADREQUEST, "header-mismatch", String::EMPTY, closeConnect); return; } if (!XmlReader::isSupportedProtocolVersion(protocolVersion)) { // See Specification for CIM Operations over HTTP section 4.3 sendHttpError( queueId, HTTP_STATUS_NOTIMPLEMENTED, "unsupported-protocol-version", String::EMPTY, closeConnect); return; } if (XmlReader::testStartTag(parser, entry, "MULTIEXPREQ")) { // We wouldn't have gotten here if CIMExportBatch header was // specified, so this must be indicative of a header mismatch sendHttpError( queueId, HTTP_STATUS_BADREQUEST, "header-mismatch", String::EMPTY, closeConnect); return; // Future: When MULTIEXPREQ is supported, must ensure // CIMExportMethod header is absent, and CIMExportBatch header // is present. } // Expect <SIMPLEEXPREQ ...> XmlReader::expectStartTag(parser, entry, "SIMPLEEXPREQ"); // Expect <EXPMETHODCALL ...> if (!XmlReader::getEMethodCallStartTag(parser, cimExportMethodName)) { MessageLoaderParms mlParms( "ExportServer.CIMExportRequestDecoder." "EXPECTED_EXPMETHODCALL_ELEMENT", "expected EXPMETHODCALL element"); throw XmlValidationError(parser.getLine(), mlParms); } // The Specification for CIM Operations over HTTP reads: // 3.3.9. CIMExportMethod // // This header MUST be present in any CIM Export Request // message that contains a Simple Export Request. // // It MUST NOT be present in any CIM Export Response message, // nor in any CIM Export Request message that is not a // Simple Export Request. It MUST NOT be present in any CIM // Operation Request or Response message. // // The name of the CIM export method within a Simple Export // Request is defined to be the value of the NAME attribute // of the <EXPMETHODCALL> element. // // If a CIM Listener receives a CIM Export Request for which // either: // // - The CIMExportMethod header is present but has an invalid // value, or; // - The CIMExportMethod header is not present but the Export // Request Message is a Simple Export Request, or; // - The CIMExportMethod header is present but the Export // Request Message is not a Simple Export Request, or; // - The CIMExportMethod header is present, the Export Request // Message is a Simple Export Request, but the CIMIdentifier // value (when unencoded) does not match the unique method // name within the Simple Export Request, // // then it MUST fail the request and return a status of // "400 Bad Request" (and MUST include a CIMError header in the // response with a value of header-mismatch), subject to the // considerations specified in Errors. if (System::strcasecmp( cimExportMethodName, cimExportMethodInHeader) != 0) { // ATTN-RK-P3-20020404: How to decode cimExportMethodInHeader? sendHttpError( queueId, HTTP_STATUS_BADREQUEST, "header-mismatch", String::EMPTY, closeConnect); return; } // This try block only catches CIMExceptions, because they must be // responded to with a proper EMETHODRESPONSE. Other exceptions are // caught in the outer try block. try { // Delegate to appropriate method to handle: if (System::strcasecmp( cimExportMethodName, "ExportIndication") == 0) { request.reset(decodeExportIndicationRequest( queueId, parser, messageId, requestUri)); } else { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_NOT_SUPPORTED, MessageLoaderParms( "ExportServer.CIMExportRequestDecoder." "UNRECOGNIZED_EXPORT_METHOD", "Unrecognized export method: $0", cimExportMethodName)); } } catch (CIMException& e) { sendEMethodError( queueId, httpMethod, messageId, cimExportMethodName, e, closeConnect); return; } // Expect </EXPMETHODCALL> XmlReader::expectEndTag(parser, "EXPMETHODCALL"); // Expect </SIMPLEEXPREQ> XmlReader::expectEndTag(parser, "SIMPLEEXPREQ"); // Expect </MESSAGE> XmlReader::expectEndTag(parser, "MESSAGE"); // Expect </CIM> XmlReader::expectEndTag(parser, "CIM"); } catch (XmlValidationError& e) { PEG_TRACE((TRC_XML,Tracer::LEVEL1, "CIMExportRequestDecoder::handleMethodRequest - " "XmlValidationError exception has occurred. Message: %s", (const char*) e.getMessage().getCString())); sendHttpError( queueId, HTTP_STATUS_BADREQUEST, "request-not-valid", e.getMessage(), closeConnect); return; } catch (XmlSemanticError& e) { PEG_TRACE((TRC_XML,Tracer::LEVEL1, "CIMExportRequestDecoder::handleMethodRequest - " "XmlSemanticError exception has occurred. Message: %s", (const char*) e.getMessage().getCString())); // ATTN-RK-P2-20020404: Is this the correct response for these errors? sendHttpError( queueId, HTTP_STATUS_BADREQUEST, "request-not-valid", e.getMessage(), closeConnect); return; } catch (XmlException& e) { PEG_TRACE((TRC_XML,Tracer::LEVEL1, "CIMExportRequestDecoder::handleMethodRequest - " "XmlException has occurred. Message: %s", (const char*) e.getMessage().getCString())); sendHttpError( queueId, HTTP_STATUS_BADREQUEST, "request-not-well-formed", e.getMessage(), closeConnect); return; } catch (Exception& e) { // Don't know why I got this exception. Seems like a bad thing. // Any exceptions we're expecting should be caught separately and // dealt with appropriately. This is a last resort. sendHttpError( queueId, HTTP_STATUS_INTERNALSERVERERROR, String::EMPTY, e.getMessage(), closeConnect); return; } catch (...) { // Don't know why I got whatever this is. Seems like a bad thing. // Any exceptions we're expecting should be caught separately and // dealt with appropriately. This is a last resort. sendHttpError( queueId, HTTP_STATUS_INTERNALSERVERERROR, String::EMPTY, String::EMPTY, closeConnect); return; } // l10n TODO - might want to move A-L and C-L to Message // to make this more maintainable // Add the language headers to the request. // Note: Since the text of an export error response will be ignored // by the export client, ignore Accept-Language in the export request. // This will cause any export error response message to be sent in the // default language. request->operationContext.insert(IdentityContainer(userName)); request->operationContext.set( ContentLanguageListContainer(httpContentLanguages)); request->operationContext.set( AcceptLanguageListContainer(AcceptLanguageList())); request->ipAddress = ipAddress; request->setCloseConnect(closeConnect); _outputQueue->enqueue(request.release()); }
/* Pull operation version of SendResponse. This adds one additional parameter (bodyParamsIn) that contains the parameters. This is because the parameters are added only on the the final segment of a chunk */ void CIMOperationResponseEncoder::sendResponsePull( CIMResponseMessage* response, const String& name, Boolean isImplicit, Buffer* bodyParams, Buffer* bodygiven) { PEG_METHOD_ENTER(TRC_DISPATCHER, "CIMOperationResponseEncoder::sendResponse"); PEG_TRACE((TRC_HTTP, Tracer::LEVEL4, "name = %s", (const char*)name.getCString())); if (! response) { PEG_METHOD_EXIT(); return; } Uint32 queueId = response->queueIds.top(); Boolean closeConnect = response->getCloseConnect(); PEG_TRACE(( TRC_HTTP, Tracer::LEVEL4, "CIMOperationResponseEncoder::sendResponse()- " "response->getCloseConnect() returned %d", closeConnect)); MessageQueue* queue = MessageQueue::lookup(queueId); if (!queue) { PEG_TRACE((TRC_DISCARDED_DATA, Tracer::LEVEL1, "ERROR: non-existent queueId = %u, response not sent.", queueId)); PEG_METHOD_EXIT(); return; } HttpMethod httpMethod = response->getHttpMethod(); String& messageId = response->messageId; CIMException& cimException = response->cimException; Buffer message; // Note: the language is ALWAYS passed empty to the xml formatters because // it is HTTPConnection that needs to make the decision of whether to add // the languages to the HTTP message. ContentLanguageList contentLanguage; CIMName cimName(name); Uint32 messageIndex = response->getIndex(); Boolean isFirst = messageIndex == 0 ? true : false; Boolean isLast = response->isComplete(); Buffer bodylocal; Buffer& body = bodygiven ? *bodygiven : bodylocal; Buffer& bodyParamsBuf = bodyParams ? *bodyParams : bodylocal; // STAT_SERVEREND sets the getTotalServerTime() value in the message class STAT_SERVEREND #ifndef PEGASUS_DISABLE_PERFINST Uint64 serverTime = response->getTotalServerTime(); #else Uint64 serverTime = 0; #endif Buffer (*formatResponse)( const CIMName& iMethodName, const String& messageId, HttpMethod httpMethod, const ContentLanguageList& httpContentLanguages, const Buffer& bodyParams, const Buffer& body, Uint64 serverResponseTime, Boolean isFirst, Boolean isLast); Buffer (*formatError)( const CIMName& methodName, const String& messageId, HttpMethod httpMethod, const CIMException& cimException); if (isImplicit == false) { formatResponse = XmlWriter::formatSimpleMethodRspMessage; formatError = XmlWriter::formatSimpleMethodErrorRspMessage; } else { formatError = XmlWriter::formatSimpleIMethodErrorRspMessage; if (response->binaryResponse) { formatResponse = BinaryCodec::formatSimpleIMethodRspMessage; } else { formatResponse = XmlWriter::formatSimpleIMethodRspMessage; } } if (cimException.getCode() != CIM_ERR_SUCCESS) { HTTPConnection* httpQueue = dynamic_cast<HTTPConnection*>(queue); Boolean isChunkRequest = false; Boolean isFirstError = true; // Note: The WMI Mapper may use a non-HTTPConnection queue here. if (httpQueue) { isChunkRequest = httpQueue->isChunkRequested(); isFirstError = (httpQueue->cimException.getCode() == CIM_ERR_SUCCESS); } // only process the FIRST error if (isFirstError) { // NOTE: even if this error occurs in the middle, HTTPConnection // will flush the entire queued message and reformat. if (isChunkRequest == false) { message = formatError(name, messageId, httpMethod, cimException); } // uri encode the error (for the http header) only when it is // non-chunking or the first error with chunking if (isChunkRequest == false || (isChunkRequest == true && isFirst == true)) { String msg = TraceableCIMException(cimException).getDescription(); String uriEncodedMsg = XmlWriter::encodeURICharacters(msg); CIMException cimExceptionUri( cimException.getCode(), uriEncodedMsg); cimExceptionUri.setContentLanguages( cimException.getContentLanguages()); cimException = cimExceptionUri; } } // if first error in response stream // never put the error in chunked response (because it will end up in // the trailer), so just use the non-error response formatter to send // more data if (isChunkRequest == true) { message = formatResponse( cimName, messageId, httpMethod, contentLanguage, bodyParamsBuf, body, serverTime, isFirst, isLast); } } else { // else non-error condition try { message = formatResponse( cimName, messageId, httpMethod, contentLanguage, bodyParamsBuf, body, serverTime, isFirst, isLast); } catch (PEGASUS_STD(bad_alloc)&) { MessageLoaderParms parms( "Server.CIMOperationResponseEncoder.OUT_OF_MEMORY", "A System error has occurred. Please retry the CIM Operation " "at a later time."); Logger::put_l( Logger::ERROR_LOG, System::CIMSERVER, Logger::WARNING, parms); cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, parms); // try again with new error and no body body.clear(); sendResponse(response, name, isImplicit); PEG_METHOD_EXIT(); return; } STAT_BYTESSENT } AutoPtr<HTTPMessage> httpMessage( new HTTPMessage(message, 0, &cimException)); httpMessage->setComplete(isLast); httpMessage->setIndex(messageIndex); httpMessage->binaryResponse = response->binaryResponse; if (cimException.getCode() != CIM_ERR_SUCCESS) { httpMessage->contentLanguages = cimException.getContentLanguages(); } else { const OperationContext::Container& container = response->operationContext.get(ContentLanguageListContainer::NAME); const ContentLanguageListContainer& listContainer = *dynamic_cast<const ContentLanguageListContainer*>(&container); contentLanguage = listContainer.getLanguages(); httpMessage->contentLanguages = contentLanguage; } httpMessage->setCloseConnect(closeConnect); queue->enqueue(httpMessage.release()); PEG_METHOD_EXIT(); }
// // Deletes the specified instance. // void UserAuthProvider::deleteInstance( const OperationContext & context, const CIMObjectPath& myInstance, ResponseHandler & handler) { CIMValue userName ; String userNameStr; String namespaceStr; Array<CIMKeyBinding> kbArray; PEG_METHOD_ENTER(TRC_USER_MANAGER,"UserAuthProvider::deleteInstance"); // // get userName // String user; try { IdentityContainer container = context.get(IdentityContainer::NAME); user= container.getUserName(); } catch (...) { user= String::EMPTY; } // // verify user authorizations // if ( user != String::EMPTY || user != "" ) { _verifyAuthorization(user); } // begin processing the request handler.processing(); #ifndef PEGASUS_NO_PASSWORDFILE // // check if the class name requested is PG_User // if (myInstance.getClassName().equal (CLASS_NAME_PG_USER)) { // // Get the user name from the instance // try { kbArray = myInstance.getKeyBindings(); if ( ! kbArray.size() ) { //l10n //throw PEGASUS_CIM_EXCEPTION( CIM_ERR_INVALID_PARAMETER, //"Unable to find Key Property Username"); MessageLoaderParms parms("ControlProviders.UserAuthProvider.UNABLE_TO_FIND_KEY_PROPERTY_USERNAME", "Unable to find Key Property Username"); throw PEGASUS_CIM_EXCEPTION_L( CIM_ERR_INVALID_PARAMETER,parms); } if ( kbArray[0].getName() == PROPERTY_NAME_USERNAME ) { userNameStr = kbArray[0].getValue(); } else { //l10n //throw PEGASUS_CIM_EXCEPTION(CIM_ERR_INVALID_PARAMETER, //"Unexpected Key property"); MessageLoaderParms parms("ControlProviders.UserAuthProvider.UNEXPECTED_KEY_PROPERTY", "Unexpected Key property"); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_INVALID_PARAMETER,parms); } // // Remove the user from User Manager // _userManager->removeUser(userNameStr); } catch ( const CIMException & ) { handler.complete(); PEG_METHOD_EXIT(); throw; } catch ( const Exception &e ) { handler.complete(); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, e.getMessage()); } } // // check if the class name requested is PG_Authorization // else if (myInstance.getClassName().equal (CLASS_NAME_PG_AUTHORIZATION)) #else if (myInstance.getClassName().equal (CLASS_NAME_PG_AUTHORIZATION)) #endif { try { // // Get the user name and namespace from the instance // kbArray = myInstance.getKeyBindings(); for (Uint32 i = 0; i < kbArray.size(); i++) { if ( kbArray[i].getName() == PROPERTY_NAME_USERNAME ) { userNameStr = kbArray[i].getValue(); } else if ( kbArray[i].getName() == PROPERTY_NAME_NAMESPACE ) { namespaceStr = kbArray[i].getValue(); } } } catch ( CIMException &e ) { PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, e.getMessage()); } if ( !userNameStr.size() ) { PEG_METHOD_EXIT(); //l10n //throw PEGASUS_CIM_EXCEPTION ( //CIM_ERR_INVALID_PARAMETER, //"Username property can not be empty.") ; MessageLoaderParms parms("ControlProviders.UserAuthProvider.USERNAME_PROPERTY_CANNOT_BE_EMPTY", "Username property can not be empty."); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_INVALID_PARAMETER,parms); } else if ( !namespaceStr.size() ) { PEG_METHOD_EXIT(); //l10n //throw PEGASUS_CIM_EXCEPTION ( //CIM_ERR_INVALID_PARAMETER, //"Namespace property can not be empty.") ; MessageLoaderParms parms("ControlProviders.UserAuthProvider.NAMESPACE_PROPERTY_CANNOT_BE_EMPTY", "Namespace property can not be empty."); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_INVALID_PARAMETER,parms); } try { // // ATTN: Note that the following is a hack, because // deleteInstance() in repository does not like // the hostname and namespace included in the CIMObjectPath // passed to it as a parameter. // CIMObjectPath ref("", CIMNamespaceName (), myInstance.getClassName(), myInstance.getKeyBindings()); _repository->deleteInstance( myInstance.getNameSpace(), ref); // // remove authorization in the UserManager // _userManager->removeAuthorization( userNameStr, namespaceStr ); } catch ( CIMException &e ) { PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, e.getMessage()); } } else { PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION( CIM_ERR_NOT_FOUND, myInstance.getClassName().getString()); } // complete processing the request handler.complete(); PEG_METHOD_EXIT(); return; }
// Creates a SNMP session void snmpDeliverTrap_netsnmp::_createSession( const String& targetHost, Uint16 targetHostFormat, Uint32 portNumber, const String& securityName, void*& sessionHandle, snmp_session*& sessionPtr) { PEG_METHOD_ENTER(TRC_IND_HANDLER, "snmpDeliverTrap_netsnmp::_createSession"); Sint32 libErr, sysErr; char* errStr; String exceptionStr; struct snmp_session snmpSession; { AutoMutex autoMut(_sessionInitMutex); snmp_sess_init(&snmpSession); CString targetHostCStr = targetHost.getCString(); // peername has format: targetHost:portNumber snmpSession.peername = (char*)malloc((size_t)(strlen(targetHostCStr) + 1 + 32)); if (targetHostFormat == _IPV6_ADDRESS) { sprintf(snmpSession.peername, "udp6:[%s]:%u", (const char*)targetHostCStr, portNumber); } else { sprintf(snmpSession.peername, "%s:%u", (const char*)targetHostCStr, portNumber); } sessionHandle = snmp_sess_open(&snmpSession); } if (sessionHandle == NULL) { exceptionStr = _MSG_SESSION_OPEN_FAILED; // Get library, system errno snmp_error(&snmpSession, &libErr, &sysErr, &errStr); exceptionStr.append(errStr); free(errStr); free(snmpSession.peername); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms(_MSG_SESSION_OPEN_FAILED_KEY, exceptionStr)); } try { // get the snmp_session pointer sessionPtr = snmp_sess_session(sessionHandle); if (sessionPtr == NULL) { exceptionStr = _MSG_GET_SESSION_POINT_FAILED; // Get library, system errno snmp_sess_error(&snmpSession, &libErr, &sysErr, &errStr); exceptionStr.append(errStr); free(errStr); free(snmpSession.peername); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_GET_SESSION_POINTER_FAILED_KEY, exceptionStr)); } // Community Name, default is public String communityName; if (securityName.size() == 0) { communityName.assign("public"); } else { communityName = securityName; } free(snmpSession.peername); free(sessionPtr->community); CString communityNameCStr = communityName.getCString(); size_t communityNameLen = strlen(communityNameCStr); sessionPtr->community = (u_char*)malloc(communityNameLen); memcpy(sessionPtr->community, (const char*)communityNameCStr, communityNameLen); sessionPtr->community_len = communityNameLen; } catch (...) { _destroySession(sessionHandle); PEG_METHOD_EXIT(); throw; } PEG_METHOD_EXIT(); }
// // Invoke Method, used to modify user's password // void UserAuthProvider::invokeMethod( const OperationContext & context, const CIMObjectPath & ref, const CIMName & methodName, const Array<CIMParamValue> & inParams, MethodResultResponseHandler & handler) { PEG_METHOD_ENTER(TRC_USER_MANAGER,"UserAuthProvider::invokeMethod"); // // get userName // String user; try { IdentityContainer container = context.get(IdentityContainer::NAME); user= container.getUserName(); } catch (...) { user= String::EMPTY; } // // verify user authorizations // if ( user != String::EMPTY || user != "" ) { _verifyAuthorization(user); } #ifndef PEGASUS_NO_PASSWORDFILE String userName; String password; String newPassword; Array<CIMKeyBinding> kbArray; // Begin processing the request handler.processing(); // Check if the class name is PG_USER if (!ref.getClassName().equal (CLASS_NAME_PG_USER)) { handler.complete(); throw PEGASUS_CIM_EXCEPTION (CIM_ERR_NOT_SUPPORTED, ref.getClassName().getString()); } // Check if the method name is correct if (!methodName.equal (METHOD_NAME_MODIFY_PASSWORD)) { handler.complete(); PEG_METHOD_EXIT(); //l10n //throw PEGASUS_CIM_EXCEPTION ( //CIM_ERR_FAILED, //"Unsupported method name, " + methodName.getString()); MessageLoaderParms parms("ControlProviders.UserAuthProvider.UNSUPPORTED_METHOD_NAME", "Unsupported method name, $0", methodName.getString()); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED,parms); } // Check if all the input parameters are passed. if ( inParams.size() < 2 ) { handler.complete(); PEG_METHOD_EXIT(); //l10n // throw PEGASUS_CIM_EXCEPTION( CIM_ERR_INVALID_PARAMETER, // "Input parameters are not valid."); MessageLoaderParms parms("ControlProviders.UserAuthProvider.INPUT_PARAMETERS_NOT_VALID", "Input parameters are not valid."); throw PEGASUS_CIM_EXCEPTION_L( CIM_ERR_INVALID_PARAMETER, parms); } try { kbArray = ref.getKeyBindings(); if ( !kbArray.size() ) { PEG_METHOD_EXIT(); //l10n //throw PEGASUS_CIM_EXCEPTION( CIM_ERR_INVALID_PARAMETER, // "Unable to find Key Property Username"); MessageLoaderParms parms("ControlProviders.UserAuthProvider.UNABLE_TO_FIND_KEY_PROPERTY_USERNAME", "Unable to find Key Property Username"); throw PEGASUS_CIM_EXCEPTION_L( CIM_ERR_INVALID_PARAMETER,parms); } // // Get the user name // if ( kbArray[0].getName() == PROPERTY_NAME_USERNAME ) { userName = kbArray[0].getValue(); } else { PEG_METHOD_EXIT(); MessageLoaderParms parms( "ControlProviders.UserAuthProvider.UNEXPECTED_KEY_PROPERTY", "Unexpected key property"); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_INVALID_PARAMETER, parms); } // // Get the old and the new password params // for ( Uint32 i=0; i < 2; i++) { // // check the param name // if ( inParams[i].getParameterName() == OLD_PASSWORD ) { inParams[i].getValue().get(password); } if ( inParams[i].getParameterName() == NEW_PASSWORD ) { inParams[i].getValue().get(newPassword); } } // Modify the user's password in User Manager _userManager->modifyUser( userName, password, newPassword); } catch ( const CIMException& ) { handler.complete(); PEG_METHOD_EXIT(); throw; } catch (const Exception& e) { handler.complete(); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, e.getMessage()); } // Return zero as there is no error Uint32 retCode = 0; handler.deliver(CIMValue(retCode)); // complete processing the request handler.complete(); PEG_METHOD_EXIT(); return; #else PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION (CIM_ERR_NOT_SUPPORTED, ref.getClassName().getString()); #endif }
// Pack trap information into the PDU void snmpDeliverTrap_netsnmp::_packTrapInfoIntoPdu( const String& trapOid, snmp_pdu* snmpPdu) { PEG_METHOD_ENTER(TRC_IND_HANDLER, "snmpDeliverTrap_netsnmp::_packTrapInfoIntoPdu"); oid enterpriseOid[MAX_OID_LEN]; size_t enterpriseOidLength; Array<String> standard_traps; standard_traps.append(String("1.3.6.1.6.3.1.1.5.1")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.2")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.3")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.4")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.5")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.6")); Array<const char*> oidSubIdentifiers; CString trapOidCStr = trapOid.getCString(); char* trapOidCopy = strdup(trapOidCStr); char* numericEntOid = (char*) malloc(strlen(trapOidCStr)); try { #if !defined(PEGASUS_OS_TYPE_WINDOWS) && !defined(PEGASUS_OS_ZOS) char* last; for (const char* p = strtok_r(trapOidCopy, ".", &last); p; p=strtok_r(NULL, ".", &last)) #else for (const char* p = strtok(trapOidCopy, "."); p; p=strtok(NULL, ".")) #endif { oidSubIdentifiers.append(p); } long genTrap = 0; long specTrap = 0; enterpriseOidLength = MAX_OID_LEN; if (Contains(standard_traps, trapOid)) { // // if the trapOid is one of the standard traps, // then the SNMPV1 enterprise parameter must be set // to the value of the trapOid, the generic-trap // parameter must be set to one of (0 - 5), and the // specific-trap parameter must be set to 0 // // Convert trapOid from numeric form to a list of subidentifiers if (read_objid((const char*)trapOidCStr, enterpriseOid, &enterpriseOidLength) == 0) { // Failed to parse trapOid PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms(_MSG_READ_OBJID_FAILED_KEY, _MSG_READ_OBJID_FAILED, trapOid)); } // the generic trap is last sub-identifier of the // trapOid minus 1 snmpPdu->trap_type = atoi(oidSubIdentifiers[oidSubIdentifiers.size() - 1]) - 1; snmpPdu->specific_type = 0; } else { // // if the trapOid is not one of the standard traps: // then 1) the generic-trap parameter must be set to 6, // 2) if the next-to-last sub-identifier of the // trapOid is zero, then the SNMPV1 enterprise // parameter is the trapOid with the last 2 // sub-identifiers removed, otherwise, the // SNMPV1 enterprise parameter is the trapOid // with the last sub-identifier removed; // 3) the SNMPv1 specific-trap parameter is the last // sub-identifier of the trapOid; // snmpPdu->trap_type = 6; snmpPdu->specific_type = atoi(oidSubIdentifiers[oidSubIdentifiers.size()-1]); strcpy(numericEntOid, oidSubIdentifiers[0]); for (Uint32 i = 1; i < oidSubIdentifiers.size()-2; i++) { strcat(numericEntOid, "."); strcat(numericEntOid, oidSubIdentifiers[i]); } if (strcmp(oidSubIdentifiers[oidSubIdentifiers.size()-2], "0") != 0) { strcat(numericEntOid, "."); strcat(numericEntOid, oidSubIdentifiers[oidSubIdentifiers.size()-2]); } // Convert ent from numeric form to a list of subidentifiers if (read_objid(numericEntOid, enterpriseOid, &enterpriseOidLength) == 0) { // Failed to parse numericEntOid PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms(_MSG_READ_ENTOID_FAILED_KEY, _MSG_READ_ENTOID_FAILED, String(numericEntOid))); } } snmpPdu->enterprise = (oid*) malloc(enterpriseOidLength * sizeof(oid)); memcpy(snmpPdu->enterprise, enterpriseOid, enterpriseOidLength * sizeof(oid)); snmpPdu->enterprise_length = enterpriseOidLength; } catch (...) { free(trapOidCopy); free(numericEntOid); PEG_METHOD_EXIT(); throw; } free(trapOidCopy); free(numericEntOid); PEG_METHOD_EXIT(); }
void snmpDeliverTrap_emanate::deliverTrap( const String& trapOid, const String& securityName, const String& targetHost, const Uint16& targetHostFormat, const String& otherTargetHostFormat, const Uint32& portNumber, const Uint16& snmpVersion, const String& engineID, const Array<String>& vbOids, const Array<String>& vbTypes, const Array<String>& vbValues) { VarBind* vbhead = NULL; VarBind* vb = NULL; VarBind* vblast = NULL; OID* object = NULL; // Translate a string into an OID OID* sendtrapOid = MakeOIDFromDot(trapOid.getCString()); if (sendtrapOid == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_KEY, _MSG_INVALID_TRAPOID)); } // Destination : convert targetHost into Transport CString trap_dest = targetHost.getCString(); TransportInfo global_ti; global_ti.type = SR_IP_TRANSPORT; switch (targetHostFormat) { case _HOST_NAME: { char* ipAddr = _getIPAddress(trap_dest); if (ipAddr == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_DESTINATION_NOT_FOUND_KEY, _MSG_DESTINATION_NOT_FOUND)); } global_ti.t_ipAddr = inet_addr(trap_dest); break; } case _IPV4_ADDRESS: { global_ti.t_ipAddr = inet_addr(trap_dest); break; } default: { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_NOT_SUPPORTED, MessageLoaderParms( _MSG_TARGETHOSTFORMAT_NOT_SUPPORTED_KEY, _MSG_TARGETHOSTFORMAT_NOT_SUPPORTED)); break; } } global_ti.t_ipPort = htons((unsigned short)portNumber); // Community Name, default is public CString _community; if (securityName.size() == 0) { String community; community.assign("public"); _community = community.getCString(); } else { _community = securityName.getCString(); } OctetString* community_name = MakeOctetStringFromText(_community); if (community_name == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_SECURITY_NAME_KEY, _MSG_INVALID_SECURITY_NAME)); } // getting IP address of the host CString hostname = System::getHostName().getCString(); char* IP_string = _getIPAddress(hostname); // formatting agent(host) address into OctetString format OctetString* agent_addr; SR_INT32 s1, s2, s3, s4; SR_UINT32 ipaddr; // pull out each of the 4 octet values from IP address sscanf(IP_string,"%d.%d.%d.%d", &s1, &s2, &s3, &s4); // validate the values for s1, s2, s3, and s4 to make sure values are // between 0 and 255 if (!_isValidOctet(s1) || !_isValidOctet(s2) || !_isValidOctet(s3) || !_isValidOctet(s4)) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_OCTET_VALUE_KEY, _MSG_INVALID_OCTET_VALUE)); } // create an empty 4 length OctetString agent_addr = MakeOctetString(NULL,4); if (agent_addr == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_CREATE_OCTET_FAILED_KEY, _MSG_CREATE_OCTET_FAILED)); } // fill in values for OctetString agent_addr->octet_ptr[0] = (unsigned char)s1; agent_addr->octet_ptr[1] = (unsigned char)s2; agent_addr->octet_ptr[2] = (unsigned char)s3; agent_addr->octet_ptr[3] = (unsigned char)s4; // specTrap from trapOid. SR_INT32 genTrap = 0; SR_INT32 specTrap = 0; OID* enterpriseOid ; Array<String> standard_traps; standard_traps.append(String("1.3.6.1.6.3.1.1.5.1")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.2")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.3")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.4")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.5")); standard_traps.append(String("1.3.6.1.6.3.1.1.5.6")); Array<String> oids; String tmpoid = trapOid; while(tmpoid.find(".") != PEG_NOT_FOUND) { oids.append(tmpoid.subString(0, tmpoid.find("."))); tmpoid = tmpoid.subString(tmpoid.find(".") + 1); } oids.append(tmpoid); String ent; if (Contains(standard_traps, trapOid)) { // // if the trapOid is one of the standard traps, // then the SNMPV1 enterprise parameter must be set // to the value of the trapOid, the generic-trap // parameter must be set to one of (0 - 5), and the // specific-trap parameter must be set to 0 // enterpriseOid = sendtrapOid; // the generic trap is last sub-identifier of the // trapOid minus 1 genTrap = atoi(oids[oids.size() - 1].getCString()) - 1; specTrap = 0; } else { // // if the trapOid is not one of the standard traps: // then 1) the generic-trap parameter must be set to 6, // 2) if the next-to-last sub-identifier of the // trapOid is zero, then the SNMPV1 enterprise // parameter is the trapOid with the last 2 // sub-identifiers removed, otherwise, the // SNMPV1 enterprise parameter is the trapOid // with the last sub-identifier removed; // 3) the SNMPv1 specific-trap parameter is the last // sub-identifier of the trapOid; // genTrap = 6; specTrap = atoi(oids[oids.size()-1].getCString()); ent = oids[0]; for (Uint8 i = 1; i < oids.size()-2; i++) { ent = ent + "." + oids[i]; } if (oids[oids.size()-2] != "0") { ent = ent + "." + oids[oids.size()-2]; } enterpriseOid = MakeOIDFromDot(ent.getCString()); if (enterpriseOid == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_ENTERPRISEOID_KEY, _MSG_INVALID_ENTERPRISEOID)); } } // creates VarBind for (Uint32 i = 0; i < vbOids.size(); i++) { CString _vbOid = vbOids[i].getCString(); CString _vbValue = vbValues[i].getCString(); if ((object = MakeOIDFromDot(_vbOid)) == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_PROPERTYOID_KEY, _MSG_INVALID_PROPERTYOID)); } if (String::equalNoCase(vbTypes[i], "OctetString")) { OctetString* value; value = CloneOctetString(MakeOctetStringFromText(_vbValue)); if (value == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_PROPERTYVALUE_KEY, _MSG_INVALID_PROPERTYVALUE)); } if ((vb = MakeVarBindWithValue( object, (OID*) NULL, OCTET_PRIM_TYPE, value)) == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_MAKE_VARBIND_FAILED_FOR_OCTET_PRIM_TYPE_KEY, _MSG_MAKE_VARBIND_FAILED_FOR_OCTET_PRIM_TYPE)); } } else if (String::equalNoCase(vbTypes[i], "OID")) { void* value = MakeOIDFromDot(_vbValue); if (value == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_PROPERTYVALUE_KEY, _MSG_INVALID_PROPERTYVALUE)); } if ((vb = MakeVarBindWithValue( object, (OID*) NULL, OBJECT_ID_TYPE, value)) == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_MAKE_VARBIND_FAILED_FOR_OBJECT_ID_TYPE_KEY, _MSG_MAKE_VARBIND_FAILED_FOR_OBJECT_ID_TYPE)); } } else { int vbvalue = atoi(_vbValue); void* value = &vbvalue; if (value == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_INVALID_PROPERTYVALUE_KEY, _MSG_INVALID_PROPERTYVALUE)); } if ((vb = MakeVarBindWithValue( object, (OID*) NULL, INTEGER_TYPE, value)) == NULL) { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms( _MSG_MAKE_VARBIND_FAILED_FOR_INTEGER_TYPE_KEY, _MSG_MAKE_VARBIND_FAILED_FOR_INTEGER_TYPE)); } } if (i == 0) { vbhead = vb; vblast = vb; } else { vblast->next_var = vb; vblast = vblast->next_var; } } vblast->next_var = NULL; // Now send the trap switch (snmpVersion) { case _SNMPv1_TRAP: { SendNotificationToDestSMIv1Params( 1, // notifyType - TRAP genTrap, // genTrap specTrap, // specTrap enterpriseOid, // enterprise agent_addr, // agent_addr vbhead, // vb NULL, // contextName 1, // retryCount 1, // timeout community_name, // securityName, SR_SECURITY_LEVEL_NOAUTH, // securityLevel SR_SECURITY_MODEL_V1, // securityModel &global_ti, // Transport Info 0); // cfg_chk break; } case _SNMPv2C_TRAP: { SendNotificationToDestSMIv2Params( (SR_INT32)SNMPv2_TRAP_TYPE, // notifyType - NOTIFICATION sendtrapOid, // snmpTrapOID agent_addr, // agent_addr vbhead, // vb NULL, // contextName 1, // retryCount 100, // timeout community_name, // securityName or community SR_SECURITY_LEVEL_NOAUTH, // securityLevel SR_SECURITY_MODEL_V2C, // securityModel &global_ti, // TransportInfo 0); // cfg_chk break; } default: { throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_NOT_SUPPORTED, MessageLoaderParms( _MSG_VERSION_NOT_SUPPORTED_KEY, _MSG_VERSION_NOT_SUPPORTED)); break; } } // Free OID built by calls MakeOIDFromDot() FreeOID(sendtrapOid); FreeOID(enterpriseOid); FreeOID(object); // Free the data structures allocated and built by calls // MakeOctetString() and MakeOctetStringFrom Text() FreeOctetString(community_name); FreeOctetString(agent_addr); // Free the VarBind data structures allocated and built // by calls MakeVarBindWithValue() FreeVarBindList(vbhead); FreeVarBindList(vb); FreeVarBindList(vblast); }
void snmpDeliverTrap_netsnmp::deliverTrap( const String& trapOid, const String& securityName, const String& targetHost, const Uint16& targetHostFormat, const String& otherTargetHostFormat, const Uint32& portNumber, const Uint16& snmpVersion, const String& engineID, const Array<String>& vbOids, const Array<String>& vbTypes, const Array<String>& vbValues) { PEG_METHOD_ENTER(TRC_IND_HANDLER, "snmpDeliverTrap_netsnmp::deliverTrap"); void* sessionHandle; struct snmp_session* sessionPtr; struct snmp_pdu* snmpPdu; // Creates a SNMP session _createSession(targetHost, targetHostFormat, portNumber, securityName, sessionHandle, sessionPtr); try { _createPdu(snmpVersion, trapOid, sessionPtr, snmpPdu); } catch (...) { _destroySession(sessionHandle); PEG_METHOD_EXIT(); throw; } // Pack OIDs into the PDU try { _packOidsIntoPdu(vbOids, vbTypes, vbValues, snmpPdu); } catch (Exception& e) { Logger::put_l(Logger::STANDARD_LOG, System::CIMSERVER, Logger::WARNING, MessageLoaderParms( _MSG_PACK_CIM_PROPERTY_TO_PDU_FAILED_KEY, _MSG_PACK_CIM_PROPERTY_TO_PDU_FAILED, e.getMessage())); } catch (...) { PEG_TRACE_CSTRING(TRC_DISCARDED_DATA, Tracer::LEVEL2, "Snmp Indication Handler failed to pack a CIM " "Property into the SNMP PDU: Unknown exception."); } // Send the trap to the destination if (snmp_sess_send(sessionHandle, snmpPdu) == 0) { Sint32 libErr, sysErr; char* errStr; // snmp_sess_send failed // get library, system errno snmp_sess_error(sessionHandle, &libErr, &sysErr, &errStr); String exceptionStr = _MSG_SESSION_SEND_FAILED; exceptionStr.append(errStr); free(errStr); snmp_free_pdu(snmpPdu); _destroySession(sessionHandle); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, MessageLoaderParms(_MSG_SESSION_SEND_FAILED_KEY, exceptionStr)); } _destroySession(sessionHandle); PEG_METHOD_EXIT(); }
void EmailListenerDestination::handleIndication( const OperationContext& context, const String nameSpace, CIMInstance& indication, CIMInstance& handler, CIMInstance& subscription, ContentLanguages & contentLanguages) { PEG_METHOD_ENTER (TRC_IND_HANDLER, "EmailListenerDestination::handleIndication"); String indicationText; try { // gets formatted indication message indicationText = IndicationFormatter::getFormattedIndText( subscription, indication, contentLanguages); // get MailTo from handler instance Array<String> mailTo; handler.getProperty(handler.findProperty( PEGASUS_PROPERTYNAME_LSTNRDST_MAILTO)).getValue().get(mailTo); // get MailSubject from handler instance String mailSubject = String::EMPTY; handler.getProperty(handler.findProperty( PEGASUS_PROPERTYNAME_LSTNRDST_MAILSUBJECT)).getValue().get( mailSubject); // get MailCc from handler instance CIMValue mailCcValue; Array<String> mailCc; Uint32 posMailCc = handler.findProperty( PEGASUS_PROPERTYNAME_LSTNRDST_MAILCC); if (posMailCc != PEG_NOT_FOUND) { mailCcValue = handler.getProperty(posMailCc).getValue(); } if (!mailCcValue.isNull()) { if ((mailCcValue.getType() == CIMTYPE_STRING) && (mailCcValue.isArray())) { mailCcValue.get(mailCc); } } // Sends the formatted indication to the specified recipients _sendViaEmail(mailTo, mailCc, mailSubject, indicationText); } catch (CIMException & c) { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, c.getMessage()); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION (CIM_ERR_FAILED, c.getMessage()); } catch (Exception& e) { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, e.getMessage()); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION (CIM_ERR_FAILED, e.getMessage()); } catch (...) { PEG_TRACE_STRING(TRC_IND_HANDLER, Tracer::LEVEL4, "Failed to deliver indication via e-mail."); PEG_METHOD_EXIT(); throw PEGASUS_CIM_EXCEPTION_L (CIM_ERR_FAILED, MessageLoaderParms("Handler.EmailListenerDestination." "EmailListenerDestination.FAILED_TO_DELIVER_INDICATION_VIA_EMAIL", "Failed to deliver indication via e-mail.")); } PEG_METHOD_EXIT(); }