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

📄 notificationoriginatorimpl.java

📁 你个snmp的源码
💻 JAVA
字号:
/*_############################################################################
  _##
  _##  SNMP4J-Agent - NotificationOriginatorImpl.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.util.*;

import org.snmp4j.*;
import org.snmp4j.agent.*;
import org.snmp4j.agent.mo.*;
import org.snmp4j.agent.security.*;
import org.snmp4j.event.*;
import org.snmp4j.smi.*;
import org.snmp4j.log.LogFactory;
import org.snmp4j.log.LogAdapter;
import org.snmp4j.mp.MessageProcessingModel;
import org.snmp4j.agent.mo.snmp.SnmpTargetMIB.SnmpTargetAddrEntryRow;
import java.io.IOException;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.agent.mo.snmp.SysUpTime;

/**
 * The <code>NotificationOriginatorImpl</code> class implements a notification
 * originator application for SNMP4J.
 * <p>
 * See also RFC 3411 for a description of notification originators.
 * </p>
 * @author Frank Fock
 * @version 1.0
 */
public class NotificationOriginatorImpl implements NotificationOriginator {

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

  private Snmp session;
  private VACM vacm;
  private SnmpTargetMIB targetMIB;
  private SnmpNotificationMIB notificationMIB;
  private SnmpCommunityMIB communityMIB;
  private SysUpTime sysUpTime;

  /**
   * Creates a notification originator.
   * @param session
   *    the Snmp instance to be used to send the notifications/informs.
   * @param vacm
   *    the VACM to be used to check access for notifications.
   * @param sysUpTime
   *    the sysUpTime instance to be used to determine sysUpTime.0 when
   *    sending notifications without specifically specified sysUpTime.
   * @param targetMIB
   *    the SnmpTargetMIB containing notification target information.
   * @param notificationMIB SnmpNotificationMIB
   */
  public NotificationOriginatorImpl(Snmp session,
                                    VACM vacm,
                                    SysUpTime sysUpTime,
                                    SnmpTargetMIB targetMIB,
                                    SnmpNotificationMIB notificationMIB) {
    this.session = session;
    this.sysUpTime = sysUpTime;
    this.vacm = vacm;
    this.targetMIB = targetMIB;
    this.notificationMIB = notificationMIB;
  }

  /**
   * Creates a notification originator.
   * @param session
   *    the Snmp instance to be used to send the notifications/informs.
   * @param vacm
   *    the VACM to be used to check access for notifications.
   * @param sysUpTime
   *    the sysUpTime instance to be used to determine sysUpTime.0 when
   *    sending notifications without specifically specified sysUpTime.
   * @param targetMIB
   *    the SnmpTargetMIB containing notification target information.
   * @param notificationMIB
   *    the SnmpNotificationMIB containing notification filtering information.
   * @param communityMIB
   *    the community MIB for coexistence information.
   */
  public NotificationOriginatorImpl(Snmp session,
                                    VACM vacm,
                                    SysUpTime sysUpTime,
                                    SnmpTargetMIB targetMIB,
                                    SnmpNotificationMIB notificationMIB,
                                    SnmpCommunityMIB communityMIB) {
    this(session, vacm, sysUpTime, targetMIB, notificationMIB);
    this.communityMIB = communityMIB;
  }

  /**
   * Sends notifications (traps) to all appropriate notification targets.
   *
   * @param context the context name of the context on whose behalf this
   *   notification has been generated.
   * @param notificationID the object ID that uniquely identifies this
   *   notification. For SNMPv1 traps, the notification ID has to be build
   *   using the rules provided by RFC 2576.
   * @param vbs an array of <code>VariableBinding</code> instances
   *   representing the payload of the notification.
   * @return an array of ResponseEvent instances. Since the
   *   <code>NotificationOriginator</code> determines on behalf of the
   *   SNMP-NOTIFICTON-MIB contents whether a notification is sent as
   *   trap/notification or as inform request, the returned array contains an
   *   element for each addressed target, but only a response PDU for inform
   *   targets.
   */
  public Object notify(OctetString context, OID notificationID,
                       VariableBinding[] vbs) {
    return notify(context, notificationID, null, vbs);
  }

  private ResponseEvent sendNotification(MOTableRow addr, MOTableRow paramsRow,
                                         OctetString context,
                                         OID notificationID,
                                         TimeTicks sysUpTime,
                                         VariableBinding[] vbs,
                                         int type) {
    Integer32 mpModel = (Integer32)
        paramsRow.getValue(SnmpTargetMIB.idxSnmpTargetParamsMPModel);
    OctetString secName = (OctetString)
        paramsRow.getValue(SnmpTargetMIB.idxSnmpTargetParamsSecurityName);
    Integer32 secLevel = (Integer32)
        paramsRow.getValue(SnmpTargetMIB.idxSnmpTargetParamsSecurityLevel);
    Integer32 secModel = (Integer32)
        paramsRow.getValue(SnmpTargetMIB.idxSnmpTargetParamsSecurityModel);
    OctetString community = secName;
    if (communityMIB != null) {
       community = communityMIB.getCommunity(secName, null, context);
    }
    Address address = ((SnmpTargetAddrEntryRow)addr).getAddress();
    Target t;
    PDU pdu;
    switch (mpModel.getValue()) {
      case MessageProcessingModel.MPv1: {
         t = new CommunityTarget(address, community);
        PDUv1 trap = new PDUv1();
        pdu = trap;
        if (sysUpTime != null) {
          trap.setTimestamp(sysUpTime.getValue());
        }
        else {
          trap.setTimestamp(this.sysUpTime.get().getValue());
        }
        int genericID = SnmpConstants.getGenericTrapID(notificationID);
        if (genericID < 0) {
          if ((notificationID.size() > 2) &&
              (notificationID.get(notificationID.size() - 2) == 0)) {
            OID enterprise =
                new OID(notificationID.getValue(), 0,
                        notificationID.size() - 2);
            trap.setEnterprise(enterprise);
          }
          else {
            OID enterprise =
                new OID(notificationID.getValue(), 0,
                        notificationID.size() - 1);
            trap.setEnterprise(enterprise);
          }
          trap.setSpecificTrap(notificationID.last());
        }
        else {
          trap.setGenericTrap(genericID);
          trap.setEnterprise(new OID(new int[] { 0,0 }));
        }
        break;
      }
      case MessageProcessingModel.MPv2c: {
        t = new CommunityTarget(address, community);
        pdu = new PDU();
        break;
      }
      default: {
        byte[] authEngineID =
            (type == SnmpNotificationMIB.SnmpNotifyTypeEnum.inform) ?
            new byte[0] : session.getLocalEngineID();
        UserTarget ut =
            new UserTarget(address, secName, authEngineID, secLevel.getValue());
        t = ut;
        ScopedPDU scopedPdu = new ScopedPDU();
        scopedPdu.setContextName(context);
        pdu = scopedPdu;
      }
    }
    t.setVersion(mpModel.getValue());
    Integer32 timeout = (Integer32)
        addr.getValue(SnmpTargetMIB.idxSnmpTargetAddrTimeout);
    Integer32 retries = (Integer32)
        addr.getValue(SnmpTargetMIB.idxSnmpTargetAddrRetryCount);
    t.setTimeout(timeout.getValue() * 10);
    t.setRetries(retries.getValue());
    if (mpModel.getValue() != MessageProcessingModel.MPv1) {
      if (sysUpTime != null) {
        pdu.add(new VariableBinding(SnmpConstants.sysUpTime, sysUpTime));
      }
      else {
        pdu.add(new VariableBinding(SnmpConstants.sysUpTime,
                                    this.sysUpTime.get()));
      }
      pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, notificationID));
    }
    pdu.addAll(vbs);
    pdu.setType((type == SnmpNotificationMIB.SnmpNotifyTypeEnum.inform) ?
                PDU.INFORM : (mpModel.getValue() == MessageProcessingModel.MPv1)
                ? PDU.V1TRAP : PDU.TRAP);
    try {
      ResponseEvent response = session.send(pdu, t);
      logger.info("Sent notification "+pdu+" to "+t);
      return response;
    }
    catch (IOException iox) {
      logger.error("Failed to send notification: "+iox.getMessage());

    }
    return null;
  }

  private boolean isAccessGranted(MOTableRow addr, MOTableRow paramsRow,
                                  OctetString context,
                                  OID notificationID,
                                  VariableBinding[] vbs) {
    if (!notificationMIB.passesFilter(paramsRow.getIndex(), notificationID, vbs)) {
      if (logger.isInfoEnabled()) {
        logger.info("Notification " + notificationID + " did not pass filter " +
                    paramsRow.getIndex());
      }
      return false;
    }
//    Integer32 mpModel = (Integer32)
//        paramsRow.getValue(SnmpTargetMIB.idxSnmpTargetParamsMPModel);
    OctetString secName = (OctetString)
        paramsRow.getValue(SnmpTargetMIB.idxSnmpTargetParamsSecurityName);
    Integer32 secLevel = (Integer32)
        paramsRow.getValue(SnmpTargetMIB.idxSnmpTargetParamsSecurityLevel);
    Integer32 secModel = (Integer32)
        paramsRow.getValue(SnmpTargetMIB.idxSnmpTargetParamsSecurityModel);
    int status = vacm.isAccessAllowed(context, secName,
                                      secModel.getValue(), secLevel.getValue(),
                                      VACM.VIEW_NOTIFY, notificationID);
    for (int i=0; (status == VACM.VACM_OK) && (i<vbs.length); i++) {
      status = vacm.isAccessAllowed(context, secName,
                                    secModel.getValue(), secLevel.getValue(),
                                    VACM.VIEW_NOTIFY, vbs[i].getOid());
    }
    return (status == VACM.VACM_OK);
  }

  public Object notify(OctetString context, OID notificationID,
                       TimeTicks sysUpTime, VariableBinding[] vbs) {
    if (logger.isInfoEnabled()) {
      logger.info("Notification " + notificationID + " issued with " +
                  Arrays.asList(vbs));
    }
    List responses = new LinkedList();
    for (Iterator it = notificationMIB.getNotifyTable().getModel().iterator();
         it.hasNext(); ) {
      MOTableRow notifyRow = (MOTableRow) it.next();
      OctetString tag = (OctetString)
          notifyRow.getValue(SnmpNotificationMIB.idxSnmpNotifyTag);
      Integer32 type =
          (Integer32) notifyRow.getValue(SnmpNotificationMIB.idxSnmpNotifyType);
      Collection addresses = targetMIB.getTargetAddrRowsForTag(tag);
      MOTableRowFilter aFilter =
          new RowStatus.ActiveRowsFilter(SnmpTargetMIB.idxSnmpTargetAddrRowStatus);
      for (Iterator ait = addresses.iterator(); ait.hasNext(); ) {
        MOTableRow addr = (MOTableRow) ait.next();
        if (aFilter.passesFilter(addr)) {
          OctetString params =
              (OctetString)addr.getValue(SnmpTargetMIB.idxSnmpTargetAddrParams);
          MOTableRow paramsRow = targetMIB.getTargetParamsRow(params);
          if (RowStatus.isRowActive(paramsRow,
                                    SnmpTargetMIB.idxSnmpTargetParamsRowStatus)) {
            if (isAccessGranted(addr, paramsRow, context, notificationID, vbs)) {
              ResponseEvent response =
                  sendNotification(addr, paramsRow, context,
                                   notificationID,
                                   sysUpTime,
                                   vbs, type.getValue());
              responses.add(response);
            }
            else {
              if (logger.isWarnEnabled()) {
                logger.warn("Access denied by VACM for "+notificationID);
              }
            }
          }
          else {
            logger.warn("Found active target address but corrsponding params"+
                        " are not active");
          }
        }
      }
    }
    return (ResponseEvent[]) responses.toArray(new ResponseEvent[0]);
  }
}

⌨️ 快捷键说明

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