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

📄 proxyforwarderimpl.java

📁 你个snmp的源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*_############################################################################
  _##
  _##  SNMP4J-Agent - ProxyForwarderImpl.java
  _##
  _##  Copyright 2005-2006  Frank Fock (SNMP4J.org)
  _##
  _##  Licensed under the Apache License, Version 2.0 (the "License");
  _##  you may not use this file except in compliance with the License.
  _##  You may obtain a copy of the License at
  _##
  _##      http://www.apache.org/licenses/LICENSE-2.0
  _##
  _##  Unless required by applicable law or agreed to in writing, software
  _##  distributed under the License is distributed on an "AS IS" BASIS,
  _##  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  _##  See the License for the specific language governing permissions and
  _##  limitations under the License.
  _##
  _##########################################################################*/

package org.snmp4j.agent.mo.snmp;

import java.io.*;
import java.util.*;

import org.snmp4j.*;
import org.snmp4j.agent.*;
import org.snmp4j.agent.mo.*;
import org.snmp4j.agent.mo.snmp.SnmpProxyMIB.*;
import org.snmp4j.agent.mo.snmp.SnmpTargetMIB.*;
import org.snmp4j.agent.request.*;
import org.snmp4j.agent.security.*;
import org.snmp4j.event.*;
import org.snmp4j.log.*;
import org.snmp4j.mp.*;
import org.snmp4j.smi.*;
import org.snmp4j.util.*;

/**
 * The <code>ProxyForwarderImpl</code> class implements a proxy forwarder
 * instance as defined by RFC 3413. It is configured through the SNMP-PROXY-MIB
 * and SNMP-TARGET-MIB implementations provided on construction. It sends
 * notifications through the provided SNMP session.
 *
 * @author Frank Fock
 * @version 1.0
 */
public class ProxyForwarderImpl implements ProxyForwarder {

  private static final LogAdapter logger =
      LogFactory.getLogger(ProxyForwarderImpl.class);

  private Snmp session;
  private SnmpProxyMIB proxyMIB;
  private SnmpTargetMIB targetMIB;
  private transient Vector counterListeners;

  /**
   * Creates a <code>ProxyForwarder</code> implementation based on a SNMP
   * session used to send the notifications and a SNMP-PROXY-MIB
   * and a SNMP-TARGET-MIB implementation used for its configuration.
   * @param session
   *    a SNMP session.
   * @param proxyMIB
   *    a <code>SnmpProxyMIB</code> implementation with the proxy configuration.
   * @param targetMIB
   *    a <code>SnmpTargetMIB</code> implementation with the target
   *    configuration.
   */
  public ProxyForwarderImpl(Snmp session,
                            SnmpProxyMIB proxyMIB, SnmpTargetMIB targetMIB) {
    this.session = session;
    this.proxyMIB = proxyMIB;
    this.targetMIB = targetMIB;
  }

  /**
   * Forwards a <code>Request</code> if it matches the criteria defined by the
   * SNMP-PROXY-MIB associated with this proxy forwarder.
   *
   * @param request
   *    a <code>ProxyForwardRequest</code> encapsuling the forwarding request.
   * @return
   *   <code>true</code> if the request has been forwarded,
   *   <code>false</code> otherwise.
   */
  public boolean forward(ProxyForwardRequest request) {
    int pduType = request.getCommandEvent().getPDU().getType();
    if (SnmpRequest.getViewType(pduType) == VACM.VIEW_NOTIFY) {
      return multipleForward(request);
    }
    else {
      ResponseEvent resp = singleForward(request);
      if ((resp != null) && (resp.getResponse() != null)) {
        PDU respPDU = resp.getResponse();
        PDU translatedResponse = DefaultPDUFactory.createPDU(
            request.getCommandEvent().getSecurityModel());
        if (!translatedResponse.getClass().equals(respPDU)) {
          // not required PDU instance -> copy data
          translatedResponse.setType(respPDU.getType());
          translatedResponse.addAll(respPDU.toArray());
          translatedResponse.setErrorIndex(respPDU.getErrorIndex());
          translatedResponse.setErrorStatus(respPDU.getErrorStatus());
        }
        else {
          translatedResponse = respPDU;
        }
        if (translatedResponse.getType() == PDU.RESPONSE) {
          translatedResponse.setRequestID(
              request.getCommandEvent().getPDU().getRequestID());
          if ((translatedResponse instanceof ScopedPDU) &&
              (request.getCommandEvent().getPDU() instanceof ScopedPDU)) {
            ScopedPDU scopedPDUReq =
                (ScopedPDU) request.getCommandEvent().getPDU();
            ScopedPDU scopedPDUResp = (ScopedPDU) translatedResponse;
            scopedPDUResp.setContextEngineID(scopedPDUReq.getContextEngineID());
            scopedPDUResp.setContextName(scopedPDUReq.getContextName());
          }
        }
        request.setResponsePDU(translatedResponse);
        return true;
      }
    }
    return false;
  }

  protected List getMatches(ProxyForwardRequest request) {
    List matches =
        proxyMIB.getProxyRows(request.getProxyType(),
                              request.getContextEngineID(),
                              request.getContext());
    for (Iterator it = matches.iterator(); it.hasNext(); ) {
      SnmpProxyRow possibleMatch =
          (SnmpProxyRow) (MOTableRow) it.next();
      OctetString paramIn = possibleMatch.getSnmpProxyTargetParamsIn();
      if (logger.isDebugEnabled()) {
        logger.debug("Checking possible match for in parameter: "+paramIn);
      }
      if (!matchParameters(request.getCommandEvent(), paramIn)) {
        it.remove();
      }
    }
    return matches;
  }

  protected boolean matchParameters(CommandResponderEvent request,
                                    OctetString paramIn) {
    MOTableRow param2Match = targetMIB.getTargetParamsRow(paramIn, true);
    if (param2Match != null) {
      int mpModel = param2Match.getValue(
          SnmpTargetMIB.idxSnmpTargetParamsMPModel).toInt();
      int secModel = param2Match.getValue(
          SnmpTargetMIB.idxSnmpTargetParamsSecurityModel).toInt();
      int secLevel = param2Match.getValue(
          SnmpTargetMIB.idxSnmpTargetParamsSecurityLevel).toInt();
      OctetString secName = (OctetString) param2Match.getValue(
          SnmpTargetMIB.idxSnmpTargetParamsSecurityName);
      if (logger.isDebugEnabled()) {
        logger.debug("Matching request "+request+"  with mpModel="+mpModel+
                     ", secModel="+secModel+", secLevel="+secLevel+
                     ", secName="+secName);
      }
      if ((mpModel == request.getMessageProcessingModel()) &&
          (secName.equals(request.getSecurityName())) &&
          ((secModel == 0) || (secModel == request.getSecurityModel())) &&
          (secLevel == request.getSecurityLevel())) {
        return true;
      }
    }
    return false;
  }

  protected ResponseEvent singleForward(ProxyForwardRequest request) {
    List matches = getMatches(request);
    if ((matches == null) || (matches.isEmpty())) {
      if (logger.isInfoEnabled()) {
        logger.info("No matching proxy entry found for contextEngineID="+
                    request.getContextEngineID()+
                    ", context="+request.getContext()+" and request="+
                    request);
      }
      return null;
    }
    OctetString outParam = (OctetString)
        ((MOTableRow)
         matches.get(0)).getValue(SnmpProxyMIB.idxSnmpProxySingleTargetOut);
    Target target = targetMIB.getTarget(outParam,
                                        request.getContextEngineID(),
                                        request.getContext());
    if (target == null) {
      if (logger.isInfoEnabled()) {
        logger.info("No matching target with name '" + outParam + "'");
      }
      return null;
    }
    // forwarding request
    if (logger.isInfoEnabled()) {
      logger.info("Forwarding proxy request "+request+" to "+target);
    }
    PDU reqPDU = request.getCommandEvent().getPDU();
    PDU pdu = DefaultPDUFactory.createPDU(target, reqPDU.getType());
    try {
      proxyForwardTranslation(request, reqPDU, pdu);
      ResponseEvent response = null;
      do {
        response = session.send(pdu, target);
        if (logger.isInfoEnabled()) {
          logger.info("Received proxy response from " +
                      response.getPeerAddress() +
                      " is " + response.getResponse());
        }
      }
      while (proxyBackwardTranslation(reqPDU, pdu, response));
      return response;
    }
    catch (Exception ex) {
      if (logger.isDebugEnabled()) {
        ex.printStackTrace();
      }
      logger.error("Failed to send proxy request to "+target+" because: "+
                   ex.getMessage());
      fireIncrementCounter(new CounterEvent(this, SnmpConstants.snmpProxyDrops));
      return null;
    }
  }

  protected boolean proxyBackwardTranslation(PDU reqPDU, PDU pdu,
                                             ResponseEvent response) {
    if (response.getResponse() == null) {
      return false;

⌨️ 快捷键说明

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