void CIMListenerIndicationDispatcher::handleEnqueue(Message* message)
{
    PEG_METHOD_ENTER(TRC_SERVER,
        "CIMListenerIndicationDispatcher::handleEnqueue");

    if(message!=NULL)
    {
        switch (message->getType())
        {
            case CIM_EXPORT_INDICATION_REQUEST_MESSAGE:
                {
                    CIMExportIndicationRequestMessage* request =
                        (CIMExportIndicationRequestMessage*)message;

                    CIMExportIndicationResponseMessage* response =
                        static_cast<CIMListenerIndicationDispatcherRep*>(_rep)->
                            handleIndicationRequest(request);

                    MessageQueue* queue = MessageQueue::lookup(response->dest);
                    PEGASUS_ASSERT(queue != 0);
                    queue->enqueue(response);
                }
                break;
            default:
                break;
        }
    delete message;
    }

    PEG_METHOD_EXIT();
}
void MessageQueueService::handle_AsyncLegacyOperationStart(AsyncLegacyOperationStart *req)
{
   // remove the legacy message from the request and enqueue it to its destination
   Uint32 result = async_results::CIM_NAK;

   Message *legacy = req->_act;
   if (legacy != 0)
   {
      MessageQueue* queue = MessageQueue::lookup(req->_legacy_destination);
      if (queue != 0)
      {
         if (queue->isAsync() == true)
         {
            (static_cast<MessageQueueService *>(queue))->handleEnqueue(legacy);
         }
         else
         {
            // Enqueue the response:
            queue->enqueue(req->get_action());
         }

         result = async_results::OK;
      }
   }
   _make_response(req, result);
}
void CIMExportRequestDispatcher::handleEnqueue(Message* message)
{
    PEG_METHOD_ENTER(TRC_EXP_REQUEST_DISP,
        "CIMExportRequestDispatcher::handleEnqueue");

    PEGASUS_ASSERT(message != 0);

    switch (message->getType())
    {
        case CIM_EXPORT_INDICATION_REQUEST_MESSAGE:
        {
            CIMExportIndicationResponseMessage* response =
                _handleExportIndicationRequest(
                    (CIMExportIndicationRequestMessage*) message);

            PEG_TRACE((
                TRC_HTTP,
                Tracer::LEVEL4,
                "_CIMExportRequestDispatcher::handleEnqueue(message) - "
                    "message->getCloseConnect() returned %d",
                message->getCloseConnect()));

            response->setCloseConnect(message->getCloseConnect());

            MessageQueue* queue = MessageQueue::lookup(response->dest);
            PEGASUS_ASSERT(queue != 0);

            queue->enqueue(response);
            break;
        }

        default:
            PEGASUS_UNREACHABLE(PEGASUS_ASSERT(0);)
            break;
    }
Beispiel #4
0
PEGASUS_THREAD_RETURN PEGASUS_THREAD_CDECL fibonacci(void * parm)
{
    Thread* my_thread = (Thread *)parm;
    parmdef * Parm = (parmdef *)my_thread->get_parm();
    int first = Parm->first;
    int second = Parm->second;
    int count = Parm->count;
    Condition * condstart = Parm->cond_start;
    MessageQueue * mq = Parm->mq;
    
    condstart->signal(my_thread->self());

    int add_to_type = 0;
    if (count < 20)
        add_to_type = 100;

    for (int i=0; i < count; i++)
    {
        int sum = first + second;
        first = second;
        second = sum;
        Message * message = new Message(i+add_to_type, 0, sum);
        mq->enqueue(message);
    }

    if (!add_to_type)
        Parm->th->thread_switch();

    my_thread->exit_self(0);
    return NULL;
}
void CIMExportRequestDecoder::sendResponse(
    Uint32 queueId,
    Buffer& message,
    Boolean closeConnect)
{
    MessageQueue* queue = MessageQueue::lookup(queueId);

    if (queue)
    {
        HTTPMessage* httpMessage = new HTTPMessage(message);
        httpMessage->setCloseConnect(closeConnect);
        queue->enqueue(httpMessage);
    }
}
Beispiel #6
0
void CIMOperationRequestAuthorizer::sendResponse(
    Uint32 queueId,
    Buffer& message)
{
    PEG_METHOD_ENTER(TRC_SERVER, "CIMOperationRequestAuthorizer::sendResponse");

    MessageQueue* queue = MessageQueue::lookup(queueId);

    if (queue)
    {
        queue->enqueue(new HTTPMessage(message));
    }

    PEG_METHOD_EXIT();
}
void CIMOperationRequestAuthorizer::sendResponse(
   Uint32 queueId,
   Array<char>& message)
{
   PEG_METHOD_ENTER(TRC_SERVER, "CIMOperationRequestAuthorizer::sendResponse");

   MessageQueue* queue = MessageQueue::lookup(queueId);

   if (queue)
   {
      AutoPtr<HTTPMessage> httpMessage(new HTTPMessage(message));

      queue->enqueue(httpMessage.release());
   }
   PEG_METHOD_EXIT();
}
Beispiel #8
0
void TestMessageQueue3()
{
    MessageQueue q;

    Uint32 sum = 0;

    for (Uint32 i = 1; i <= 5; i++)
    {
	q.enqueue(new Alarm(i));
	sum += i;
    }
    assert(sum == 15);

    while (!q.isEmpty())
	q.remove(q.back());

    assert(q.getCount() == 0);
}
Beispiel #9
0
void WsmResponseEncoder::sendResponse(const SoapResponse* response)
{
    PEG_METHOD_ENTER(TRC_WSMSERVER, "WsmResponseEncoder::sendResponse");
    PEG_TRACE((TRC_WSMSERVER, Tracer::LEVEL3,
        "WsmResponseEncoder::sendResponse()"));

    if (!response)
    {
        PEG_METHOD_EXIT();
        return;
    }

    Uint32 queueId = response->getQueueId();
    Boolean httpCloseConnect = response->getHttpCloseConnect();

    PEG_TRACE((TRC_WSMSERVER, Tracer::LEVEL4,
        "WsmResponseEncoder::sendResponse()- "
            "response->getHttpCloseConnect() returned %d",
        httpCloseConnect));

    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;
    }
    PEGASUS_ASSERT(dynamic_cast<HTTPConnection*>(queue) != 0);

    Buffer message = response->getResponseContent();

    // Note: WS-Management responses are never sent in chunks, so there is no
    // need to check dynamic_cast<HTTPConnection*>(queue)->isChunkRequested().
    // HTTPMessage::isComplete() defaults to true, and we leave it that way.

    AutoPtr<HTTPMessage> httpMessage(new HTTPMessage(message));

    httpMessage->setCloseConnect(httpCloseConnect);
    queue->enqueue(httpMessage.release());

    PEG_METHOD_EXIT();
}
Beispiel #10
0
void TestMessageQueue1()
{
    MessageQueue q;

    Uint32 sum = 0;

    for (Uint32 i = 1; i <= 5; i++)
    {
	q.enqueue(new Alarm(i));
	sum += i;
    }

    assert(Sum(q) == sum);

    // Test removing from the middle:
    Message* m = q.findByKey(3);
    assert(m != 0);
    q.remove(m);
    assert(Sum(q) == sum - 3);
    assert(q.getCount() == 4);

    // Test removing from the front:
    q.remove(q.front());
    assert(Sum(q) == sum - 3 - 1);
    assert(q.getCount() == 3);

    // Test removing from the front:
    q.remove(q.back());
    assert(Sum(q) == sum - 3 - 1 - 5);
    assert(q.getCount() == 2);

    // Test dequeue:
    m = q.dequeue();
    assert(m->getKey() == 2);
    assert(Sum(q) == sum - 3 - 1 - 5 - 2);
    assert(q.getCount() == 1);

    // Test dequeue:
    m = q.dequeue();
    assert(m->getKey() == 4);
    assert(Sum(q) == sum - 3 - 1 - 5 - 2 - 4);
    assert(q.getCount() == 0);
}
Beispiel #11
0
void HTTPAuthenticatorDelegator::_sendResponse(
    Uint32 queueId,
    Buffer& message,
    Boolean closeConnect)
{
    PEG_METHOD_ENTER(TRC_HTTP,
        "HTTPAuthenticatorDelegator::_sendResponse");

    MessageQueue* queue = MessageQueue::lookup(queueId);

    if (queue)
    {
        AutoPtr<HTTPMessage> httpMessage(new HTTPMessage(message));
        httpMessage->dest = queue->getQueueId();
        
        queue->enqueue(httpMessage.release());
    }

    PEG_METHOD_EXIT();
}
/*
    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();
}
Beispiel #13
0
void HTTPAuthenticatorDelegator::handleHTTPMessage(
    HTTPMessage* httpMessage,
    Boolean & deleteMessage)
{  
    PEG_METHOD_ENTER(TRC_HTTP,
        "HTTPAuthenticatorDelegator::handleHTTPMessage");

    Boolean authenticated = false;
    deleteMessage = true;

    // ATTN-RK-P3-20020408: This check probably shouldn't be necessary, but
    // we're getting an empty message when the client closes the connection
    if (httpMessage->message.size() == 0)
    {
        // The message is empty; just drop it
        PEG_METHOD_EXIT();
        return;
    }

    //
    // get the configured authentication flag
    //
    // WMI MAPPER SPECIFIC: AUTHENTICATION ALWAYS ENABLED:
    Boolean enableAuthentication = true;
    /* NORMAL METHOD OF LOOKING UP AUTHENTICATION CONFIGURATION:
    Boolean enableAuthentication = ConfigManager::parseBooleanValue(
        ConfigManager::getInstance()->getCurrentValue("enableAuthentication"));
    */

    //
    // Save queueId:
    //
    Uint32 queueId = httpMessage->queueId;

    //
    // Parse the HTTP message:
    //
    String startLine;
    Array<HTTPHeader> headers;
    Uint32 contentLength;

    httpMessage->parse(startLine, headers, contentLength);
    
    //
    // Parse the request line:
    //
    String methodName;
    String requestUri;
    String httpVersion;
    HttpMethod httpMethod = HTTP_METHOD__POST;

    HTTPMessage::parseRequestLine(
        startLine, methodName, requestUri, httpVersion);

    //
    //  Set HTTP method for the request
    //
    if (methodName == "M-POST")
    {
        httpMethod = HTTP_METHOD_M_POST;
    }

    if (methodName != "M-POST" && methodName != "POST")
    {
        // Only POST and M-POST are implemented by this server
        _sendHttpError(queueId,
                       HTTP_STATUS_NOTIMPLEMENTED);
    }
    else if ((httpMethod == HTTP_METHOD_M_POST) &&
             (httpVersion == "HTTP/1.0"))
    {
        //
        //  M-POST method is not valid with version 1.0
        //
        _sendHttpError(queueId,
                       HTTP_STATUS_BADREQUEST);
    }
    else
    {
        //
        // Process M-POST and POST messages:
        //
        PEG_TRACE_CSTRING(
            TRC_HTTP,
            Tracer::LEVEL3,
            "HTTPAuthenticatorDelegator - M-POST/POST processing start");

        //
        // Search for Authorization header:
        //
        String authorization;

        //
        // Do not require authentication for indication delivery 
        //
        String cimExport;
        if (enableAuthentication &&
            HTTPMessage::lookupHeader(
                headers, "CIMExport", cimExport, true)) 
        {
            enableAuthentication = false;
        }

        if ( HTTPMessage::lookupHeader(
             headers, "PegasusAuthorization", authorization, false) &&
             enableAuthentication
           )
        {
            try 
            {
                //
                // Do pegasus/local authentication
                //
                authenticated = 
                    _authenticationManager->performPegasusAuthentication(
                        authorization,
                        httpMessage->authInfo);

                if (!authenticated)
                {
                    String authChallenge;
                    String authResp;

                    authResp =
                        _authenticationManager->getPegasusAuthResponseHeader(
                            authorization,
                            httpMessage->authInfo);

                    if (!String::equal(authResp, String::EMPTY))
                    {
                        _sendChallenge(queueId, authResp, false);
                    }
                    else
                    {
                        _sendHttpError(queueId,
                                       HTTP_STATUS_BADREQUEST,
                                       String::EMPTY,
                                       "Authorization header error");
                    }

                    PEG_METHOD_EXIT();
                    return;
                }
            }
            catch (CannotOpenFile &cof)
            {
                _sendHttpError(queueId,
                               HTTP_STATUS_INTERNALSERVERERROR);
                PEG_METHOD_EXIT();
                return;
                
            }
        }

        if ( HTTPMessage::lookupHeader(
             headers, "Authorization", authorization, false) &&
             enableAuthentication
           )
        {
#ifdef PEGASUS_KERBEROS_AUTHENTICATION
            // The presence of a Security Association indicates that Kerberos
            // is being used.
            CIMKerberosSecurityAssociation *sa =
                httpMessage->authInfo->getSecurityAssociation();
            if (sa)
            {
                sa->setClientSentAuthorization(true);
            }
#endif        
            //
            // Do http authentication if not authenticated already
            //
            if (!authenticated)
            {
                authenticated =
                    _authenticationManager->performHttpAuthentication(
                        authorization,
                        httpMessage->authInfo);

                if (!authenticated)
                {
                    //ATTN: the number of challenges get sent for a 
                    //      request on a connection can be pre-set.
#ifdef PEGASUS_KERBEROS_AUTHENTICATION
                    // Kerberos authentication needs access to the
                    // AuthenticationInfo object for this session in order
                    // to set up the reference to the
                    // CIMKerberosSecurityAssociation object for this session.

                    String authResp =   
                        _authenticationManager->getHttpAuthResponseHeader(
                            httpMessage->authInfo);
#else
                    String authResp =
                        _authenticationManager->getHttpAuthResponseHeader();
#endif
                    if (!String::equal(authResp, String::EMPTY))
                    {
                        _sendChallenge(queueId, authResp, false);
                    }
                    else
                    {
                        _sendHttpError(queueId,
                                       HTTP_STATUS_BADREQUEST,
                                       String::EMPTY,
                                       "Authorization header error");
                    }

                    PEG_METHOD_EXIT();
                    return;
                }
            }  // first not authenticated check
        }  // "Authorization" header check

#ifdef PEGASUS_KERBEROS_AUTHENTICATION
        // The presence of a Security Association indicates that Kerberos is
        // being used.
        CIMKerberosSecurityAssociation *sa =
            httpMessage->authInfo->getSecurityAssociation();

        // This will process a request with no content.
        if (sa && authenticated)
        {
            if (sa->getServerToken().size())
            {
                // This will handle the scenario where client did not send
                // data (content) but is authenticated.  After the client
                // receives the success it should will send the request.
                // For mutual authentication the client may choose not to
                // send request data until the context is fully established.
                // Note:  if mutual authentication wass not requested by the
                // client then no server token will be available.
                if (contentLength == 0)
                {
                    String authResp =   
                        _authenticationManager->getHttpAuthResponseHeader(
                            httpMessage->authInfo);
                    if (!String::equal(authResp, String::EMPTY))
                    {
                        _sendSuccess(queueId, authResp);
                    }
                    else
                    {
                        _sendHttpError(queueId,
                                       HTTP_STATUS_BADREQUEST,
                                       String::EMPTY,
                                       "Authorization header error");
                    }

                    PEG_METHOD_EXIT();
                    return;
                }
            }
        }

        // This will process a request without an authorization record.
        if (sa && !authenticated)
        {
            // Not authenticated can result from the client not sending an
            // authorization record due to a previous authentication.  In
            // this scenario the client was previous authenticated but
            // chose not to send an authorization record.  The Security
            // Association maintains state so a request will not be
            // processed unless the Security association thinks the client
            // is authenticated.

            // This will handle the scenario where the client was
            // authenticated in the previous request but choose not to
            // send an authorization record.
            if (sa->getClientAuthenticated())
            {        
                authenticated = true;
            }
        }

        // The following is processing to unwrap (unencrypt) the message
        // received from the client when using kerberos authentication.
        // For Kerberos there should always be an "Authorization" record
        // sent with the request so the authenticated flag in the method
        // should always be checked to verify that the client is actually
        // authenticated.  If no "Authoriztion" was sent then the client
        // can't be authenticated.  The "Authorization" record was
        // processed above and if the "Authorization" record was
        // successfully processed then the client is authenticated.
        if (sa  &&  authenticated)
        {
            Uint32 rc;  // return code for the wrap
            Array<Sint8> final_buffer;
            final_buffer.clear();
            Array<Sint8> header_buffer;
            header_buffer.clear();
            Array<Sint8> inWrappedMessage;
            inWrappedMessage.clear();
            Array<Sint8> outUnwrappedMessage;
            outUnwrappedMessage.clear();

            // The message needs to be parsed in order to distinguish
            // between the headers and content. The message was parsed
            // earlier in this method so we can use the contentLength set
            // during that parse. When parsing the code breaks out of the
            // loop as soon as it finds the double separator that
            // terminates the headers so the headers and content can be
            // easily separated.

            // Extract the unwrapped headers
            for (Uint32 i = 0; i < httpMessage->message.size() - contentLength;
                 i++)
            {
                header_buffer.append(httpMessage->message[i]);
            }

            // Extract the wrapped content
            for (Uint32 i = httpMessage->message.size() - contentLength;
                 i < httpMessage->message.size(); i++)
            {
                inWrappedMessage.append(httpMessage->message[i]);
            }

            rc = sa->unwrap_message(inWrappedMessage,          
                                    outUnwrappedMessage);  // ASCII

            if (rc) 
            {
                // clear out the outUnwrappedMessage; if unwrapping is required
                // and it fails we need to send back a bad request.  A message
                // left in an wrapped state will be a severe failue later.  
                // Reason for unwrap failing may be due to a problem with the 
                // credentials or context or some other failure may have 
                // occurred.
                outUnwrappedMessage.clear();
                // build a bad request.  We do not want to risk sending back
                // data that can't be authenticated.
                final_buffer = 
                  XmlWriter::formatHttpErrorRspMessage(HTTP_STATUS_BADREQUEST);
                //remove the last separater; the authentication record still
                // needs to be added.
                final_buffer.remove(final_buffer.size());  // "\n"
                final_buffer.remove(final_buffer.size());  // "\r"

                // Build the WWW_Authenticate record with token.
                String authResp =   
                  _authenticationManager->getHttpAuthResponseHeader(
                                httpMessage->authInfo);
                // error occurred on wrap so the final_buffer needs to be built
                // differently
                final_buffer << authResp;
                // add double separaters to end
                final_buffer << "\r\n";
                final_buffer << "\r\n";

                _sendResponse(queueId, final_buffer);
                PEG_METHOD_EXIT();
                return;
            }

            // If outUnwrappedMessage does not have any content data this
            // is a result of no data available.  This could be a result
            // of the client not sending any content data.  This is not
            // unique to Kerberos so this will not be handled here but it
            // will be handled when the content is processed. Or, the
            // client did not wrap message...this is okay.  If the unwrap
            // resulted in no data when there should have been data then
            // this should have been caught above when the unwrap returned
            // a bad return code
            if (final_buffer.size() == 0)
            {
                // if outUnwrappedMessage is empty that indicates client did 
                // not wrap the message.  The original message will be used.
                if (outUnwrappedMessage.size())
                {
                    final_buffer.appendArray(header_buffer);
                    final_buffer.appendArray(outUnwrappedMessage);
                    // add back char that was appended earlier
                    final_buffer.append('\0'); 
                    // Note: if additional characters added 
                    // in future add back here
                }
            }
            else
            {
                // The final buffer should not have any data at this point.
                // If it does end the server because something bad happened.
                PEG_TRACE_CSTRING(
                    TRC_HTTP,
                    Tracer::LEVEL2,
                    "HTTPAuthenticatorDelegator - the final buffer should "
                        "not have data");
                PEGASUS_ASSERT(0);
            }

            // replace the existing httpMessage with the headers and
            // unwrapped message
            // If the final buffer has not been set then the original
            // httpMessage will be used.
            if (final_buffer.size())
            {
                    httpMessage->message.clear();
                    httpMessage->message = final_buffer;
            }
        } // if not kerberos and client not authenticated
#endif

        if ( authenticated || !enableAuthentication )
        {
            //
            // Search for "CIMOperation" header:
            //
            String cimOperation;

            if (HTTPMessage::lookupHeader(
                headers, "CIMOperation", cimOperation, true))
            {
                PEG_TRACE((
                    TRC_HTTP,
                    Tracer::LEVEL3,
                    "HTTPAuthenticatorDelegator - CIMOperation: %s ",
                    (const char*) cimOperation.getCString()));

                MessageQueue* queue =
                    MessageQueue::lookup(_cimOperationMessageQueueId);

                if (queue)
                {
                   httpMessage->dest = queue->getQueueId();
                   
                   try
                     {
                       queue->enqueue(httpMessage);
                     }
                   catch(exception & e)
                     {
                       delete httpMessage;
                       _sendHttpError(queueId,
                                      HTTP_STATUS_REQUEST_TOO_LARGE);
                       PEG_METHOD_EXIT();
                       deleteMessage = false;
                       return;
                     }
                 deleteMessage = false;
                }
            }
            else if (HTTPMessage::lookupHeader(
                headers, "CIMExport", cimOperation, true))
            {
                PEG_TRACE((
                    TRC_HTTP,
                    Tracer::LEVEL3,
                    "HTTPAuthenticatorDelegator - CIMExport: $0 ",
                    (const char*) cimOperation.getCString()));

                MessageQueue* queue =
                    MessageQueue::lookup(_cimExportMessageQueueId);

                if (queue)
                {
                    httpMessage->dest = queue->getQueueId();

                    queue->enqueue(httpMessage);
                    deleteMessage = false;
                }
            }
            else
            {
                // We don't recognize this request message type

                // The Specification for CIM Operations over HTTP reads:
                //
                //     3.3.4. CIMOperation
                //
                //     If a CIM Server receives a CIM Operation request without
                //     this [CIMOperation] header, it MUST NOT process it as if
                //     it were a CIM Operation Request.  The status code
                //     returned by the CIM Server in response to such a request
                //     is outside of the scope of this specification.
                //
                //     3.3.5. CIMExport
                //
                //     If a CIM Listener receives a CIM Export request without
                //     this [CIMExport] header, it MUST NOT process it.  The
                //     status code returned by the CIM Listener in response to
                //     such a request is outside of the scope of this
                //     specification.
                //
                // The author has chosen to send a 400 Bad Request error, but
                // without the CIMError header since this request must not be
                // processed as a CIM request.

                _sendHttpError(queueId,
                               HTTP_STATUS_BADREQUEST);
                PEG_METHOD_EXIT();
                return;
            } // bad request
        } // authenticated and enableAuthentication check
        else
        {  // client not authenticated; send challenge
#ifdef PEGASUS_KERBEROS_AUTHENTICATION
            String authResp =    
                _authenticationManager->getHttpAuthResponseHeader(
                    httpMessage->authInfo);
#else
            String authResp =
                _authenticationManager->getHttpAuthResponseHeader();
#endif

            if (!String::equal(authResp, String::EMPTY))
            {
                _sendChallenge(queueId, authResp, false);
            }
            else
            {
                _sendHttpError(queueId,
                               HTTP_STATUS_BADREQUEST,
                               String::EMPTY,
                               "Authorization header error");
            }
        }
    } // M-POST and POST processing

    PEG_METHOD_EXIT();
}
Beispiel #14
0
// Test Thread, MessageQueue, and Condition
int test01()
{
    MessageQueue * mq = new MessageQueue("testQueue", true);
    parmdef * parm[4];

    for (int i = 0; i < 4;i++)
    {
        parm[i] = new parmdef();
        parm[i]->mq = mq;
    }

    parm[0]->first = 0;
    parm[0]->second = 1;
    parm[0]->count = 20;

    parm[3]->first = 4;
    parm[3]->second = 6;
    parm[3]->count = 10;

    parm[0]->th = new Thread(fibonacci,parm[0],false);
    parm[1]->th = new Thread(deq,parm[1],false);
    parm[2]->th = new Thread(deq,parm[2],false);
    parm[3]->th = new Thread(fibonacci,parm[3],false);

    for (int i = 0; i < 4;i++)
    {
       parm[i]->cond_start->lock_object(pegasus_thread_self());
       parm[i]->th->run();
    }

    // Let the thread start and wait for Start Condition to be signaled
    for (int i = 0; i < 4;i++)
    {
        parm[i]->cond_start->unlocked_wait( pegasus_thread_self() );
        parm[i]->cond_start->unlock_object( );
    }

    // all fired up successfully

    // Finish the enqueueing tasks
    parm[0]->th->join();
    parm[3]->th->join();

    // Tell one of the dequeueing tasks to finish
    Message * message;
    message = new Message(MY_CANCEL_TYPE,0); 
    mq->enqueue(message);
    
    // Tell the other dequeueing task to finish
    message = new Message(MY_CANCEL_TYPE,0); 
    mq->enqueue(message);

    // Finish the dequeueing tasks
    parm[1]->th->join();
    parm[2]->th->join();

    // Clean up
    for (int i = 0; i < 4; i++)
    {
        delete parm[i]->th;
        delete parm[i];
    }

    delete mq;

    return 0;
}
int IPACM_EvtDispatcher::PostEvt
(
	 ipacm_cmd_q_data *data
)
{
	Message *item = NULL;
	MessageQueue *MsgQueue = NULL;

	if(data->event < IPA_EXTERNAL_EVENT_MAX)
	{
		IPACMDBG("Insert event into external queue.\n");
		MsgQueue = MessageQueue::getInstanceExternal();
	}
	else
	{
		IPACMDBG("Insert event into internal queue.\n");
		MsgQueue = MessageQueue::getInstanceInternal();
	}
	if(MsgQueue == NULL)
	{
		IPACMERR("unable to retrieve MsgQueue instance\n");
		return IPACM_FAILURE;
	}

	item = new Message();
	if(item == NULL)
	{
		IPACMERR("unable to create new message item\n");
		return IPACM_FAILURE;
	}

	item->evt.callback_ptr = IPACM_EvtDispatcher::ProcessEvt;
	memcpy(&item->evt.data, data, sizeof(ipacm_cmd_q_data));

	if(pthread_mutex_lock(&mutex) != 0)
	{
		IPACMERR("unable to lock the mutex\n");
		return IPACM_FAILURE;
	}

	IPACMDBG("Enqueing item\n");
	MsgQueue->enqueue(item);
	IPACMDBG("Enqueued item %p\n", item);

	if(pthread_cond_signal(&cond_var) != 0)
	{
		IPACMDBG("unable to lock the mutex\n");
		/* Release the mutex before you return failure */
		if(pthread_mutex_unlock(&mutex) != 0)
		{
			IPACMERR("unable to unlock the mutex\n");
			return IPACM_FAILURE;
		}
		return IPACM_FAILURE;
	}

	if(pthread_mutex_unlock(&mutex) != 0)
	{
		IPACMERR("unable to unlock the mutex\n");
		return IPACM_FAILURE;
	}

	return IPACM_SUCCESS;
}