/**
  * Parses a textual representation of an object ID as dotted string (e.g. "1.3.6.1.2.1.1") and
  * returns its raw value.
  *
  * @param text a textual representation of an OID.
  * @return the raw OID value.
  * @throws ParseException if the OID cannot be parsed successfully.
  */
 public int[] parse(String text) throws ParseException {
   StringTokenizer st = new StringTokenizer(text, ".", true);
   int size = st.countTokens();
   int[] value = new int[size];
   size = 0;
   StringBuffer buf = null;
   while (st.hasMoreTokens()) {
     String t = st.nextToken();
     if ((buf == null) && t.startsWith("'")) {
       buf = new StringBuffer();
       t = t.substring(1);
     }
     if ((buf != null) && (t.endsWith("'"))) {
       buf.append(t.substring(0, t.length() - 1));
       OID o = new OctetString(buf.toString()).toSubIndex(true);
       int[] h = value;
       value = new int[st.countTokens() + h.length + o.size()];
       System.arraycopy(h, 0, value, 0, size);
       System.arraycopy(o.getValue(), 0, value, size, o.size());
       size += o.size();
       buf = null;
     } else if (buf != null) {
       buf.append(t);
     } else if (!".".equals(t)) {
       value[size++] = (int) Long.parseLong(t.trim());
     }
   }
   if (size < value.length) {
     int[] h = value;
     value = new int[size];
     System.arraycopy(h, 0, value, 0, size);
   }
   return value;
 }
Exemple #2
0
 public void _setIndex(OID oid) {
   byte[] _oidBytes = oid.toByteArray();
   int[] _oidInts = oid.toIntArray();
   int arrayOffset = 11;
   int _len;
   _index = new OID(_oidInts, 11, (oid.size() - 11)).toString();
   setEventIndex(_oidInts[arrayOffset]);
   arrayOffset += 1;
 }
Exemple #3
0
 /**
  * Creates a static managed object group for the sub-tree with the specified root OID.
  *
  * @param root the root OID of the sub-tree to be registered by this managed object.
  * @param vbs the variable bindings to be returned in this sub-tree.
  */
 public StaticMOGroup(OID root, VariableBinding[] vbs) {
   this.root = root;
   this.scope = new DefaultMOScope(root, true, root.nextPeer(), false);
   for (VariableBinding vb : vbs) {
     if ((vb.getOid() != null) && (vb.getVariable() != null)) {
       if ((vb.getOid().size() >= root.size())
           && (vb.getOid().leftMostCompare(root.size(), root) == 0)) {
         this.vbs.put(vb.getOid(), vb.getVariable());
       }
     }
   }
 }
Exemple #4
0
  /**
   * Encodes a <code>Variable</code> to an <code>OutputStream</code>.
   *
   * @param outputStream an <code>OutputStream</code>.
   * @throws IOException if an error occurs while writing to the stream.
   */
  @Override
  public void encodeBER(OutputStream outputStream) throws IOException {
    BER.encodeHeader(outputStream, type, getBERPayloadLength());

    if (type == PDU.V1TRAP) {
      enterprise.encodeBER(outputStream);
      agentAddress.encodeBER(outputStream);
      genericTrap.encodeBER(outputStream);
      specificTrap.encodeBER(outputStream);
      timestamp.encodeBER(outputStream);
    } else {
      requestID.encodeBER(outputStream);
      errorStatus.encodeBER(outputStream);
      errorIndex.encodeBER(outputStream);
    }
    int vbLength = 0;
    for (VariableBinding variableBinding : variableBindings) {
      vbLength += variableBinding.getBERLength();
    }
    BER.encodeHeader(outputStream, BER.SEQUENCE, vbLength);
    for (VariableBinding vb : variableBindings) {
      if (!isVariableV1(vb.getVariable())) {
        throw new IOException("Cannot encode Counter64 into a SNMPv1 PDU");
      }
      vb.encodeBER(outputStream);
    }
  }
  public Map collect() {

    java.util.Map res = null;

    try {

      java.util.Map a =
          snmpAdapter.get(ipAdEntIfIndexAttr, new OID(ipAdEntIfIndexOID.toString() + "." + nodeIP));
      if (a != null && a.get(ipAdEntIfIndexAttr) != null) {
        String ifIndex = (String) a.get(ipAdEntIfIndexAttr);

        res =
            snmpAdapter.get(
                ifPhysAddressAttr,
                new OID(ifPhysAddressOID.toString() + "." + new Integer(ifIndex)));
      }

      return res;
    } catch (Exception e) {
      // TODO Auto-generated catch block
      // e.printStackTrace();
      if (e instanceof SNMPTimeoutException || e instanceof SNMPCredentialFailException) {
        log.error("Get MAC error for " + nodeIP + ":" + e.getMessage());
      } else {
        log.error("Get MAC error for " + nodeIP, e);
      }
    }
    return null;
  }
Exemple #6
0
  /**
   * Decodes a <code>Variable</code> from an <code>InputStream</code>.
   *
   * @param inputStream an <code>InputStream</code> containing a BER encoded byte stream.
   * @throws IOException
   */
  @Override
  public void decodeBER(BERInputStream inputStream) throws IOException {
    MutableByte pduType = new MutableByte();
    int length = BER.decodeHeader(inputStream, pduType);
    int pduStartPos = (int) inputStream.getPosition();

    switch (pduType.getValue()) {
      case PDU.SET:
      case PDU.GET:
      case PDU.GETNEXT:
      case PDU.V1TRAP:
      case PDU.RESPONSE:
        break;
        // The following PDU types are not supported by the SNMPv1 standard!
      case PDU.NOTIFICATION:
      case PDU.INFORM:
        if (SNMP4JSettings.isAllowSNMPv2InV1()) {
          break;
        }
        // fall through
      default:
        throw new IOException("Unsupported PDU type: " + pduType.getValue());
    }
    this.setType(pduType.getValue());
    if (getType() == PDU.V1TRAP) {
      enterprise.decodeBER(inputStream);
      agentAddress.decodeBER(inputStream);
      genericTrap.decodeBER(inputStream);
      specificTrap.decodeBER(inputStream);
      timestamp.decodeBER(inputStream);
    } else {
      requestID.decodeBER(inputStream);
      errorStatus.decodeBER(inputStream);
      errorIndex.decodeBER(inputStream);
    }
    // reusing pduType here to save memory ;-)
    pduType = new BER.MutableByte();
    int vbLength = BER.decodeHeader(inputStream, pduType);
    if (pduType.getValue() != BER.SEQUENCE) {
      throw new IOException("Encountered invalid tag, SEQUENCE expected: " + pduType.getValue());
    }
    // rest read count
    int startPos = (int) inputStream.getPosition();
    variableBindings = new Vector<>();
    while (inputStream.getPosition() - startPos < vbLength) {
      VariableBinding vb = new VariableBinding();
      vb.decodeBER(inputStream);
      if (!isVariableV1(vb.getVariable())) {
        throw new MessageException("Counter64 encountered in SNMPv1 PDU " + "(RFC 2576 §4.1.2.1)");
      }
      variableBindings.add(vb);
    }
    if (BER.isCheckSequenceLength()) {
      BER.checkSequenceLength(vbLength, (int) inputStream.getPosition() - startPos, this);
      BER.checkSequenceLength(length, (int) inputStream.getPosition() - pduStartPos, this);
    }
  }
Exemple #7
0
 private boolean processWalk(PDU response, PDU request, OID rootOID) throws SnmpException {
   if ((response == null)
       || (response.getErrorStatus() != 0)
       || (response.getType() == PDU.REPORT)) {
     return true;
   }
   boolean finished = false;
   OID lastOID = request.get(0).getOid();
   for (int i = 0; (!finished) && (i < response.size()); i++) {
     VariableBinding vb = response.get(i);
     if ((vb.getOid() == null)
         || (vb.getOid().size() < rootOID.size())
         || (rootOID.leftMostCompare(rootOID.size(), vb.getOid()) != 0)) {
       finished = true;
     } else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
       outputResponse(vb);
       finished = true;
     } else if (vb.getOid().compareTo(lastOID) <= 0) {
       throw new SnmpException(
           "Variable received is not lexicographic successor of requested one:"
               + vb.toString()
               + " <= "
               + lastOID);
     } else {
       outputResponse(vb);
       lastOID = vb.getOid();
     }
   }
   if (response.size() == 0) {
     finished = true;
   }
   if (!finished) {
     VariableBinding next = response.get(response.size() - 1);
     next.setVariable(new Null());
     request.set(0, next);
     request.setRequestID(new Integer32(0));
   }
   return finished;
 }
  @Override
  public void transform(SmiModule module, SmiObject object) {
    OID oid = object.getOID();

    if (standardFilterCriteria(module, object)) {
      if (oid != null) {
        System.out.println("+++++++++++++++++++");
        System.out.printf("name: %s%noid: %s%n", oid, oid.toDottedString());
        System.out.printf("SyntaxString: %s%nSyntax: %s%n", oid.getSyntaxString(), oid.getSyntax());
        System.out.printf("ObjectName: %s%nType: %s%n", object.getObjectName(), object.getType());
        System.out.printf(
            "ObjectName:SNMP.%s.%s%n",
            module.getModuleName(), PluginUtil.toUpperUnderscore(object.getObjectName(), '.'));
        String smiSyntax = getSmiSyntax(object.getSmiSyntax());
        System.out.printf(
            "SmiSyntax: %s%nReference: %s%n",
            smiSyntax == null ? object.getSmiSyntax() : smiSyntax, object.getReference());
        System.out.printf("Description: %s%n", object.getDescription());
        System.out.printf("Oid Syntax: %s%n", oid.getSyntaxString());
        System.out.println("-------------------");
      }
    }
  }
 public void _setIndex(OID oid) {
   byte[] _oidBytes = oid.toByteArray();
   int[] _oidInts = oid.toIntArray();
   int arrayOffset = 10;
   int _len;
   _index = new OID(_oidInts, 10, (oid.size() - 10)).toString();
   setUdpEndpointLocalAddressType(_oidInts[arrayOffset]);
   arrayOffset += 1;
   _len = _oidInts[arrayOffset++];
   setUdpEndpointLocalAddress(_getObjectIdentifier(_oidInts, arrayOffset, _len));
   arrayOffset += _len;
   setUdpEndpointLocalPort(_oidInts[arrayOffset]);
   arrayOffset += 1;
   setUdpEndpointRemoteAddressType(_oidInts[arrayOffset]);
   arrayOffset += 1;
   _len = _oidInts[arrayOffset++];
   setUdpEndpointRemoteAddress(_getObjectIdentifier(_oidInts, arrayOffset, _len));
   arrayOffset += _len;
   setUdpEndpointRemotePort(_oidInts[arrayOffset]);
   arrayOffset += 1;
   setUdpEndpointInstance(_oidInts[arrayOffset]);
   arrayOffset += 1;
 }
  private int enumerateIndexed(JrdsElement hostEleme, ProbeDescSummary summary, boolean withOid)
      throws IOException {
    OID indexOid = new OID(summary.specifics.get("indexOid"));
    int count = 0;
    log(Level.TRACE, "Will enumerate %s", indexOid);
    Set<OID> oidsSet = Collections.singleton(indexOid);
    Map<OID, Object> indexes = SnmpRequester.TREE.doSnmpGet(active, oidsSet);
    log(Level.TRACE, "Elements : %s", indexes);
    for (Map.Entry<OID, Object> e : indexes.entrySet()) {
      count++;
      Map<String, String> beans = new HashMap<String, String>(2);
      OID rowOid = e.getKey();
      String indexName = e.getValue().toString();
      beans.put("index", indexName);

      int[] index = Arrays.copyOfRange(rowOid.getValue(), indexOid.size(), rowOid.size());

      // If we wanted to generate a static oid
      if (withOid) {
        OID suffixOid = new OID(index);
        beans.put("oid", suffixOid.toString());
      }

      // We try to auto-generate the label
      String label = summary.specifics.get("labelOid");
      String labelValue = null;
      if (label != null && !label.isEmpty()) {
        OID suffixOid = new OID(index);
        for (String lookin : label.split(",")) {
          OID labelOID = new OID(lookin.trim() + "." + suffixOid.toString());
          labelValue = getLabel(active, labelOID);
          if (labelValue != null) break;
        }
      }

      addProbe(hostEleme, summary.name, labelValue, null, null, beans);
    }
    return count;
  }
Exemple #11
0
 @Override
 protected int getBERPayloadLengthPDU() {
   if (getType() != PDU.V1TRAP) {
     return super.getBERPayloadLengthPDU();
   } else {
     int length = 0;
     // length for all vbs
     for (VariableBinding variableBinding : variableBindings) {
       length += variableBinding.getBERLength();
     }
     length += BER.getBERLengthOfLength(length) + 1;
     length += agentAddress.getBERLength();
     length += enterprise.getBERLength();
     length += genericTrap.getBERLength();
     length += specificTrap.getBERLength();
     length += timestamp.getBERLength();
     return length;
   }
 }
Exemple #12
0
    public void rowChanged(MOTableRowEvent event) {
      if ((event.getType() == MOTableRowEvent.CREATE)
          || (event.getType() == MOTableRowEvent.UPDATED)) {
        // ignore
        return;
      }
      // update counter
      Counter32 counter = (Counter32) event.getRow().getValue(Snmp4jDemoMib.idxSnmp4jDemoEntryCol3);
      if (counter == null) {
        counter = new Counter32(0);
        ((MOMutableTableRow) event.getRow())
            .setValue(Snmp4jDemoMib.idxSnmp4jDemoEntryCol3, counter);
      }
      counter.increment();
      // update timestamp
      TimeStamp timestamp =
          (TimeStamp) event.getTable().getColumn(Snmp4jDemoMib.idxSnmp4jDemoEntryCol4);
      timestamp.update((MOMutableTableRow) event.getRow(), Snmp4jDemoMib.idxSnmp4jDemoEntryCol4);
      // fire notification
      Integer32 type = new Integer32(Snmp4jDemoMib.Snmp4jDemoTableRowModificationEnum.updated);
      switch (event.getType()) {
        case MOTableRowEvent.ADD:
          type.setValue(Snmp4jDemoMib.Snmp4jDemoTableRowModificationEnum.created);
          break;
        case MOTableRowEvent.DELETE:
          type.setValue(Snmp4jDemoMib.Snmp4jDemoTableRowModificationEnum.deleted);
          break;
      }
      VariableBinding[] payload = new VariableBinding[2];
      OID table = event.getTable().getOID();
      OID updateCount = new OID(table);
      updateCount.append(Snmp4jDemoMib.colSnmp4jDemoEntryCol3);
      updateCount.append(event.getRow().getIndex());

      OID modifyType = new OID(table);
      modifyType.append(Snmp4jDemoMib.colSnmp4jDemoTableRowModification);
      modifyType.append(event.getRow().getIndex());

      payload[0] = new VariableBinding(updateCount, counter);
      payload[1] = new VariableBinding(modifyType, type);
      // modules.getSnmp4jDemoMib().snmp4jDemoEvent(
      // agent.getNotificationOriginator(), new OctetString(), payload);
    }
Exemple #13
0
  public void processPdu(CommandResponderEvent pRequest) {

    final PDU requestPdu = pRequest.getPDU();

    if (requestPdu == null) {
      return;
    }

    try {

      final PDU responsePdu = new PDU(requestPdu);
      responsePdu.setType(PDU.RESPONSE);

      if (requestPdu.getType() == PDU.GET) {

        for (VariableBinding binding : responsePdu.toArray()) {
          final OID oid = binding.getOid();
          final String path = jmxMib.getPathFromOid(oid.toString());

          if (path == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final JmxAttribute attribute = jmxIndex.getAttributeAtPath(path);

          if (attribute == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final Variable variable = getVariableFromJmxAttribute(attribute);

          if (variable != null) {
            binding.setVariable(variable);
          }
        }

      } else if (requestPdu.getType() == PDU.GETNEXT) {

        for (VariableBinding binding : responsePdu.toArray()) {
          final OID oid = binding.getOid();
          final String next = jmxMib.getNextOidFromOid(oid.toString());

          if (next == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final OID nextOid = new OID(next);

          binding.setOid(nextOid);

          final String path = jmxMib.getPathFromOid(nextOid.toString());

          if (path == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final JmxAttribute attribute = jmxIndex.getAttributeAtPath(path);

          if (attribute == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final Variable variable = getVariableFromJmxAttribute(attribute);

          if (variable != null) {
            binding.setVariable(variable);
          }
        }

      } else {

      }

      pRequest.getStateReference().setTransportMapping(pRequest.getTransportMapping());
      pRequest
          .getMessageDispatcher()
          .returnResponsePdu(
              pRequest.getMessageProcessingModel(),
              pRequest.getSecurityModel(),
              pRequest.getSecurityName(),
              pRequest.getSecurityLevel(),
              responsePdu,
              pRequest.getMaxSizeResponsePDU(),
              pRequest.getStateReference(),
              new StatusInformation());

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #14
0
 /**
  * Sets the "enterprise" OID of the SNMPv1 trap. The enterprise OID could be any OID although the
  * name could lead to the assumption that the enterprise OID has to be an OID under the
  * iso(1).org(3).dod(6).internet(1).private(4).enterprises(1) node, but that's not true.
  *
  * @param enterprise an OID instance.
  * @throws UnsupportedOperationException if the type of this PDU is not {@link PDU#V1TRAP}.
  */
 public void setEnterprise(OID enterprise) {
   checkV1TRAP();
   checkNull(enterprise);
   this.enterprise = (OID) enterprise.clone();
 }
  /** {@inheritDoc} */
  public PDU processPdu(PDU pdu) throws SnmpToolkitException {
    Log log = LogFactory.getLog(this.getClass());

    // 応答用のPDUを生成する
    PDU retPdu = new PDU();
    retPdu.setType(PDU.RESPONSE);

    // 要求のリクエストIDを取得し、応答PDUにセットする
    Integer32 requestID = pdu.getRequestID();
    retPdu.setRequestID(requestID);

    // SNMP4J用の型変換オブジェクト
    SnmpVariableHelper varHelper = new Snmp4jVariableHelper();

    // AgentServiceからAgentを取得する
    Agent agent = this.agentService_.getAgent();

    // 要求PDUのVarbindを走査する
    int varCount = 0;
    List<?> reqVarbinds = pdu.getVariableBindings();
    for (Object reqVarbindObj : reqVarbinds) {
      varCount++;

      // 要求されているOIDを取得する
      VariableBinding reqVarbind = (VariableBinding) reqVarbindObj;
      OID oid = reqVarbind.getOid();

      // GETNEXTでない場合は、指定されたOIDそのものを取得しようとする
      // GETNEXTの場合は、指定されたOID配下で最も近いオブジェクトを探す
      boolean exact = (pdu.getType() != PDU.GETNEXT);
      SnmpVarbind foundVarbind = agent.findObject(oid.toString(), exact);
      if (foundVarbind == null) {
        // Varbindが見つからなかった場合はnoSuchNameを返す
        log.warn("varbind is not found. oid=" + oid.toString());

        retPdu.setErrorStatus(SnmpConstants.SNMP_ERROR_NO_SUCH_NAME);
        retPdu.setErrorIndex(varCount);

        Variable retObject = new Null();
        VariableBinding retVarbind = new VariableBinding(oid, retObject);
        retPdu.add(retVarbind);
        break;
      }

      // READ-WRITEでなければエラー応答を返す
      String accessibility = foundVarbind.getAccessibility();
      if (accessibility.equals(SnmpVarbind.ACCESSIBILITY_NOT_ACCESSIBLE) == true) {
        log.warn("varbind is not accessible. accessibility=" + accessibility);

        retPdu.setErrorStatus(SnmpConstants.SNMP_ERROR_NO_ACCESS);
        retPdu.setErrorIndex(varCount);

        Variable retObject = new Null();
        VariableBinding retVarbind = new VariableBinding(oid, retObject);
        retPdu.add(retVarbind);
        break;
      }

      try {
        // 正常の応答を返す
        retPdu.setErrorStatus(SnmpConstants.SNMP_ERROR_SUCCESS);
        retPdu.setErrorIndex(0);

        log.debug("varbind is found: " + foundVarbind.toString());
        String typeStr = foundVarbind.getType();
        Object retValueObj = foundVarbind.getValue();
        Variable retObject = (Variable) varHelper.createAsnObject(retValueObj, typeStr);

        OID retOID = new OID(foundVarbind.getOid());
        VariableBinding retVarbind = new VariableBinding(retOID, retObject);
        retPdu.add(retVarbind);
      } catch (Exception exception) {
        log.warn("exception occured", exception);

        // 未知のエラーを示す応答PDUを作成する
        retPdu.setErrorStatus(SnmpConstants.SNMP_ERROR_GENERAL_ERROR);
        retPdu.setErrorIndex(varCount);

        if (foundVarbind != null) {
          OID retOID = new OID(foundVarbind.getOid());
          Variable retObject = new Null();
          VariableBinding retVarbind = new VariableBinding(retOID, retObject);
          retPdu.add(retVarbind);
        }
      }
    }
    return retPdu;
  }
Exemple #16
0
 public OID getID() {
   return (OID) ID.clone();
 }
Exemple #17
0
 private Request createSnmpRequest(URI url) throws UnknownHostException {
   String host = url.getHost();
   int port = url.getPort();
   if (port == -1) {
     port = SnmpConstants.DEFAULT_COMMAND_RESPONDER_PORT;
   }
   String userInfo = url.getUserInfo();
   if (userInfo == null) {
     userInfo = defaultUserInfo;
   }
   String path = url.getPath();
   String[] segments = path.split("/");
   String contextInfo;
   String contextName = "";
   OctetString contextEngineID = null;
   String oidPart = null;
   if (segments.length > 1) {
     contextInfo = segments[0];
     oidPart = segments[1];
     String[] contextInfos = contextInfo.split(";");
     if (contextInfos.length > 1) {
       contextEngineID = OctetString.fromHexStringPairs(contextInfos[1]);
     }
     contextName = contextInfos[0];
   } else if (segments.length == 1) {
     oidPart = segments[0];
   }
   Target t = createTarget(new OctetString(userInfo));
   if (host != null) {
     if (t instanceof CertifiedTarget) {
       t.setAddress(new TlsAddress(InetAddress.getByName(host), port));
     } else {
       t.setAddress(new UdpAddress(InetAddress.getByName(host), port));
     }
   } else {
     t = defaultTarget;
   }
   PDU pdu = pduFactory.createPDU(t);
   if (pdu instanceof ScopedPDU) {
     if (contextEngineID != null) {
       ((ScopedPDU) pdu).setContextEngineID(contextEngineID);
     }
     if (contextName != null) {
       ((ScopedPDU) pdu).setContextName(new OctetString(contextName));
     }
   }
   SnmpUriType type = SnmpUriType.GET;
   if (oidPart != null && oidPart.endsWith(".*")) {
     type = SnmpUriType.SUBTREE;
     oidPart = oidPart.substring(0, oidPart.length() - 2);
   } else if (oidPart != null && oidPart.endsWith("+")) {
     type = SnmpUriType.NEXT;
     oidPart = oidPart.substring(0, oidPart.length() - 1);
   }
   List<OID> oids;
   if (oidPart != null && oidPart.contains("(")) {
     String[] oidStrings = oidPart.split("[\\(,\\),\\,]");
     oids = new ArrayList<>(oidStrings.length);
     for (String oidString : oidStrings) {
       if (!oidString.isEmpty()) {
         OID o = new OID(oidString);
         if (o.isValid()) {
           oids.add(o);
         }
       }
     }
   } else if (oidPart != null) {
     oids = Collections.singletonList(new OID(oidPart));
   } else {
     oids = Collections.emptyList();
   }
   return new Request(t, pdu, oids.toArray(new OID[oids.size()]), type);
 }