⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mgmtapi.c

📁 windows的snmp api源码
💻 C
📖 第 1 页 / 共 5 页
字号:
                SnmpGetLastError((HSNMP_SESSION)NULL)
                ));

            // failure
            fOk = FALSE;
        }

        // re-initialize
        pSMS->hAgentEntity = (HSNMP_ENTITY)NULL;
    }

    // check if manager entity allocated
    if (pSMS->hManagerEntity != (HSNMP_ENTITY)NULL) {

        // close the entity handle
        status = SnmpFreeEntity(pSMS->hManagerEntity);

        // validate status
        if (WSNMP_FAILED(status)) {

            SNMPDBG((
                SNMP_LOG_ERROR,
                "MGMTAPI: SnmpFreeEntity returned %d.\n",
                SnmpGetLastError((HSNMP_SESSION)NULL)
                ));

            // failure
            fOk = FALSE;
        }

        // re-initialize
        pSMS->hManagerEntity = (HSNMP_ENTITY)NULL;
    }

    // check if session allocated
    if (pSMS->hSnmpSession != (HSNMP_SESSION)NULL) {

        // close the winsnmp session
        status = SnmpClose(pSMS->hSnmpSession);

        // validate status
        if (WSNMP_FAILED(status)) {

            SNMPDBG((
                SNMP_LOG_ERROR,
                "MGMTAPI: SnmpClose returned %d.\n",
                SnmpGetLastError((HSNMP_SESSION)NULL)
                ));

            // failure
            fOk = FALSE;
        }

        // re-initialize
        pSMS->hSnmpSession = (HSNMP_SESSION)NULL;
    }

    return fOk;
}

SNMPAPI_STATUS SNMPAPI_CALL
   SnmpConveyAgentAddress (SNMPAPI_STATUS mode);


BOOL
OpenSession(
    PSNMP_MGR_SESSION pSMS,
    LPSTR             pAgentAddress,
    LPSTR             pAgentCommunity,
    INT               nTimeOut,
    INT               nRetries
    )

/*++

Routine Description:

    Open WinSNMP session and associate with MGMTAPI session.

Arguments:

    pSMS - pointer to MGMTAPI session structure.

    pAgentAddress - points to a null-terminated string specifying either a
        dotted-decimal IP address or a host name that can be resolved to an
        IP address, an IPX address (in 8.12 notation), or an ethernet address.

    pAgentCommunity - points to a null-terminated string specifying the
        SNMP community name used when communicating with the agent specified
        in the lpAgentAddress parameter

    nTimeOut - specifies the communications time-out in milliseconds.

    nRetries - specifies the communications retry count.

Return Values:

    Returns true if successful.

--*/

{
    BOOL fOk;
    struct sockaddr AgentSockAddr;
    CHAR AgentStrAddr[MAXENTITYSTRLEN+1];
    smiOCTETS smiCommunity;

    // validate session ptr
    WSNMP_ASSERT(pSMS != NULL);

    // initialize notification window
    if (!CreateNotificationWindow(pSMS)) {
        return FALSE; // bail...
    }

    // open a winsnmp session which corresponds to mgmtapi session
    pSMS->hSnmpSession = SnmpOpen(pSMS->hWnd, WM_WSNMP_INCOMING);

    // --ft
    // we need to turn this on in order to have WINSNMP to pass back not
    // only the entity standing for the source Ip address but also the
    // agent address as it was sent into the V1 Trap Pdu. Without it,
    // SnmpMgrGetTrapEx() will return a NULL address for the pSourceAddress
    // paramter. However, SnmpMgrGetTrapEx() is not documented!!!
    SnmpConveyAgentAddress(SNMPAPI_ON);

    // validate session handle returned
    if (WSNMP_FAILED(pSMS->hSnmpSession)) {

        SNMPDBG((
            SNMP_LOG_ERROR,
            "MGMTAPI: SnmpOpen returned %d.\n",
            SnmpGetLastError((HSNMP_SESSION)NULL)
            ));

        // re-initialize
        pSMS->hSnmpSession = (HSNMP_SESSION)NULL;

        goto cleanup; // bail...
    }

    // validate pointer
    if (pAgentAddress != NULL) {

        // use snmpapi.dll to do convert to sockets structure
        if (!SnmpSvcAddrToSocket(pAgentAddress, &AgentSockAddr)) {
            goto cleanup; // bail...
        }

        // check address family of agent
        if (AgentSockAddr.sa_family == AF_INET) {

            LPSTR pAgentStrAddr;
            struct sockaddr_in * pAgentSockAddr;

            // cast generic socket address structure to inet
            pAgentSockAddr = (struct sockaddr_in *)&AgentSockAddr;

            // obtain exclusive access to api
            EnterCriticalSection(&g_GlobalLock);

            // attempt to convert address into string
            pAgentStrAddr = inet_ntoa(pAgentSockAddr->sin_addr);

            // copy to stack variable
            strcpy(AgentStrAddr, pAgentStrAddr);

            // release exclusive access to api
            LeaveCriticalSection(&g_GlobalLock);

        } else if (AgentSockAddr.sa_family == AF_IPX) {

            // simply copy original string
            strcpy(AgentStrAddr, pAgentAddress);

        } else {

            SNMPDBG((
                SNMP_LOG_ERROR,
                "MGMTAPI: Incorrect address family.\n"
                ));

            goto cleanup; // bail...
        }

        // create remote agent entity
        pSMS->hAgentEntity = SnmpStrToEntity(
                                    pSMS->hSnmpSession,
                                    AgentStrAddr
                                    );

        // validate agent entity returned
        if (WSNMP_FAILED(pSMS->hAgentEntity)) {

            SNMPDBG((
                SNMP_LOG_ERROR,
                "MGMTAPI: SnmpStrToEntity returned %d.\n",
                SnmpGetLastError(pSMS->hSnmpSession)
                ));

            // re-initialize
            pSMS->hAgentEntity = (HSNMP_ENTITY)NULL;

            goto cleanup; // bail...
        }

        // attach timeout specified with agent
        SnmpSetTimeout(pSMS->hAgentEntity, nTimeOut / 10);

        // attach retries specified with agent
        SnmpSetRetry(pSMS->hAgentEntity, nRetries);

        // create local manager entity
        pSMS->hManagerEntity = SnmpStrToEntity(
                                        pSMS->hSnmpSession,
                                        (AgentSockAddr.sa_family == AF_INET)
                                            ? DEFAULT_ADDRESS_IP
                                            : DEFAULT_ADDRESS_IPX
                                        );

        // validate manager entity returned
        if (WSNMP_FAILED(pSMS->hManagerEntity)) {

            SNMPDBG((
                SNMP_LOG_ERROR,
                "MGMTAPI: SnmpStrToEntity returned %d.\n",
                SnmpGetLastError(pSMS->hSnmpSession)
                ));

            // re-initialize
            pSMS->hManagerEntity = (HSNMP_ENTITY)NULL;

            goto cleanup; // bail...
        }

        // attach timeout specified with manager
        SnmpSetTimeout(pSMS->hManagerEntity, nTimeOut / 10);

        // attach retries specified with manager
        SnmpSetRetry(pSMS->hManagerEntity, nRetries);
    }

    // validate pointer
    if (pAgentCommunity != NULL) {

        // transfer community string
        smiCommunity.ptr = (smiLPBYTE)pAgentCommunity;
        smiCommunity.len = pAgentCommunity ? lstrlen(pAgentCommunity) : 0;

        // obtain context from community string
        pSMS->hViewContext = SnmpStrToContext(
                                pSMS->hSnmpSession,
                                &smiCommunity
                                );

        // validate context handle
        if (WSNMP_FAILED(pSMS->hViewContext)) {

            SNMPDBG((
                SNMP_LOG_ERROR,
                "MGMTAPI: SnmpStrToContext returned %d.\n",
                SnmpGetLastError(pSMS->hSnmpSession)
                ));

            // re-initialize
            pSMS->hViewContext = (HSNMP_CONTEXT)NULL;

            goto cleanup; // bail...
        }
    }

    // success
    return TRUE;

cleanup:

    // cleanup resources
    CloseSession(pSMS);

    // failure
    return FALSE;
}


BOOL
AllocateSession(
    PSNMP_MGR_SESSION * ppSMS
    )

/*++

Routine Description:

    Allocate mgmtapi session structure.

Arguments:

    ppSMS - pointer to session pointer to return.

Return Values:

    Returns true if successful.

--*/

{
    PSNMP_MGR_SESSION pSMS = NULL;

       __try
    {
        // allocate new session table entry
        pSMS = SnmpUtilMemAlloc(sizeof(SNMP_MGR_SESSION));

        // validate pointer
        if (pSMS != NULL) {

            // initialize session level lock
            InitializeCriticalSection(&pSMS->SessionLock);

        } else {

            SNMPDBG((
                SNMP_LOG_ERROR,
                "MGMTAPI: Could not allocate session.\n"
                ));

            // notify application of error
            SetLastError(SNMP_MEM_ALLOC_ERROR);
        }

        // transfer
        *ppSMS = pSMS;
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
        if (pSMS != NULL)
        {
            SnmpUtilMemFree(pSMS);
            pSMS = NULL;
        }
    }

    // return status
    return (pSMS != NULL);
}


VOID
FreeSession(
    PSNMP_MGR_SESSION pSMS
    )

/*++

Routine Description:

    Frees mgmtapi session structure.

Arguments:

    pSMS - pointer to mgmtapi session structure.

Return Values:

    None.

--*/

{
    // is session valid?
    if (pSMS != NULL) {

        // destroy the session level lock
        DeleteCriticalSection(&pSMS->SessionLock);

        // free session object
        SnmpUtilMemFree(pSMS);
    }
}


BOOL
ProcessAgentResponse(
    PSNMP_MGR_SESSION pSMS
    )

/*++

Routine Description:

    Message pump for notification window.

Arguments:

    pSMS - pointer to MGMTAPI session structure.

Return Values:

    Returns true if agent responded.

--*/

{
    MSG msg;
    BOOL fOk = FALSE;

    // validate session ptr
    WSNMP_ASSERT(pSMS != NULL);

    // get the next message for this session
    while (GetMessage(&msg, pSMS->hWnd, 0, 0)) {

        // check for private message
        if (msg.message != WM_WSNMP_DONE) {

            // translate message
            TranslateMessage(&msg);

            // dispatch message
            DispatchMessage(&msg);

        } else {

            // success
            fOk = TRUE;

            break;
        }
    }

    return fOk;
}


DWORD
WINAPI
TrapThreadProc(
    LPVOID lpParam
    )

/*++

Routine Description:

    Trap processing procedure.

Arguments:

    lpParam - unused thread parameter.

Return Values:

    Returns NOERROR if successful.

--*/

{
    SNMPAPI_STATUS status;
    PSNMP_MGR_SESSION pSMS;

    SNMPDBG((
        SNMP_LOG_TRACE,
        "MGMTAPI: Trap thread starting...\n"
        ));

    // obtain pointer
    pSMS = &g_TrapSMS;

    // re-initialize
    pSMS->nLastError = 0;

    g_fIsTrapRegistered = FALSE; // init to failure. Note that there will
                                 // be only 1 instance of this thread


    // initialize winsnmp trap session
    if (OpenSession(pSMS, NULL, NULL, 0, 0)) 
    {

        // register
        status = SnmpRegister(
                    pSMS->hSnmpSession,
                    (HSNMP_ENTITY)NULL,     // hAgentEntity
                    (HSNMP_ENTITY)NULL,     // hManagerEntity
                    (HSNMP_CONTEXT)NULL,    // hViewContext
                    (smiLPCOID)NULL,        // notification
                    SNMPAPI_ON
                    );

        // validate return code
        if (WSNMP_SUCCEEDED(status)) 
        {
            // signal main thread that Trap has been registered with WinSNMP
            g_fIsTrapRegistered = TRUE;
            SetEvent(g_hTrapRegisterdEvent);

            // loop processing responses
            while (ProcessAgentResponse(pSMS)) 
            {

                //
                // processing done in window procedure...
                //
            }

        } 
        else 
        {

            SNMPDBG((
                SNMP_LOG_ERROR,
                "MGMTAPI: SnmpRegister returned %d.\n",
                SnmpGetLastError(pSMS->hSnmpSession)
                ));

            // transfer last error to global structure
            pSMS->nLastError = SnmpGetLastError(pSMS->hSnmpSession);

            // signal main thread that there is an error 
            // in registering Trap with WinSNMP
            
            SetEvent(g_hTrapRegisterdEvent);
        }

    } 
    else 
    {

        // transfer last error to global structure
        pSMS->nLastError = SnmpGetLast

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -