linkmon-1.1/0000775000175000017500000000000010433632414012362 5ustar julienjulienlinkmon-1.1/snmp/0000755000175000017500000000000010433632545013342 5ustar julienjulienlinkmon-1.1/snmp/SNMPBERCodec.java0000664000175000017500000001623407152274534016265 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.util.*; import java.io.*; /** * SNMPBERCodec defines methods for converting from ASN.1 BER encoding to SNMPObject subclasses. The extraction * process usually produces a tree structure of objects with an SNMPSequence object at the root; this * is the usual behavior when a received encoded message is received from an SNMP device. */ public class SNMPBERCodec { public static final byte SNMPINTEGER = 0x02; public static final byte SNMPBITSTRING = 0x03; public static final byte SNMPOCTETSTRING = 0x04; public static final byte SNMPNULL = 0x05; public static final byte SNMPOBJECTIDENTIFIER = 0x06; public static final byte SNMPSEQUENCE = 0x30; public static final byte SNMPIPADDRESS = (byte)0x40; public static final byte SNMPCOUNTER32 = (byte)0x41; public static final byte SNMPGAUGE32 = (byte)0x42; public static final byte SNMPTIMETICKS = (byte)0x43; public static final byte SNMPOPAQUE = (byte)0x44; public static final byte SNMPNSAPADDRESS = (byte)0x45; public static final byte SNMPCOUNTER64 = (byte)0x46; public static final byte SNMPUINTEGER32 = (byte)0x47; public static final byte SNMPGETREQUEST = (byte)0xA0; public static final byte SNMPGETNEXTREQUEST = (byte)0xA1; public static final byte SNMPGETRESPONSE = (byte)0xA2; public static final byte SNMPSETREQUEST = (byte)0xA3; // SNMPv2p constants; unused!! public static final byte SNMPv2pCOMMUNICATION = (byte)0xA2; public static final byte SNMPv2pAUTHORIZEDMESSAGE = (byte)0xA1; public static final byte SNMPv2pENCRYPTEDMESSAGE = (byte)0xA1; public static final byte SNMPv2pENCRYPTEDDATA = (byte)0xA1; public static final byte SNMPUNKNOWNOBJECT = 0x00; /** * Extracts an SNMP object given its type, length, value triple as an SNMPTLV object. * Called by SNMPObject subclass constructors. * @throws SNMPBadValueException Indicates byte array in value field is uninterprettable for * specified SNMP object type. */ public static SNMPObject extractEncoding(SNMPTLV theTLV) throws SNMPBadValueException { switch (theTLV.tag) { case SNMPINTEGER: { return new SNMPInteger(theTLV.value); } case SNMPSEQUENCE: { return new SNMPSequence(theTLV.value); } case SNMPOBJECTIDENTIFIER: { return new SNMPObjectIdentifier(theTLV.value); } case SNMPOCTETSTRING: { return new SNMPOctetString(theTLV.value); } case SNMPIPADDRESS: { return new SNMPIPAddress(theTLV.value); } case SNMPCOUNTER32: { return new SNMPCounter32(theTLV.value); } case SNMPGAUGE32: { return new SNMPGauge32(theTLV.value); } case SNMPTIMETICKS: { return new SNMPTimeTicks(theTLV.value); } case SNMPNSAPADDRESS: { return new SNMPNSAPAddress(theTLV.value); } case SNMPCOUNTER64: { return new SNMPCounter64(theTLV.value); } case SNMPUINTEGER32: { return new SNMPUInteger32(theTLV.value); } case SNMPGETREQUEST: case SNMPGETNEXTREQUEST: case SNMPGETRESPONSE: case SNMPSETREQUEST: { return new SNMPPDU(theTLV.value, theTLV.tag); } case SNMPNULL: case SNMPOPAQUE: { return new SNMPNull(); } default: { System.out.println("Unrecognized tag"); //return new SNMPOctetString(theTLV.value); return new SNMPUnknownObject(theTLV.value); } } } /** * Extracts the type, length and value of the SNMP object whose BER encoding begins at the * specified position in the given byte array. (??what about errors??) */ public static SNMPTLV extractNextTLV(byte[] enc, int position) { SNMPTLV nextTLV = new SNMPTLV(); int currentPos = position; // get tag if ((enc[currentPos] % 32) < 31) { // single byte tag; extract value nextTLV.tag = (int)(enc[currentPos]); } else { // multiple byte tag; for now, just return value in subsequent bytes ... // but need to think about universal / application fields, etc... nextTLV.tag = 0; do { currentPos++; nextTLV.tag = nextTLV.tag * 128 + (int)(enc[currentPos] % 128); } while ((enc[currentPos]/128) >= 1); } currentPos++; // now at start of length info // get length of data int dataLength; int unsignedValue = enc[currentPos]; if (unsignedValue < 0) unsignedValue += 256; if ((unsignedValue / 128) < 1) { // single byte length; extract value dataLength = unsignedValue; } else { // multiple byte length; first byte's value (minus first bit) is # of length bytes int numBytes = (unsignedValue % 128); dataLength = 0; for (int i = 0; i < numBytes; i++) { currentPos++; unsignedValue = enc[currentPos]; if (unsignedValue < 0) unsignedValue += 256; dataLength = dataLength * 256 + unsignedValue; } } currentPos++; // now at start of data // set total length nextTLV.totalLength = currentPos - position + dataLength; // extract data portion ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); outBytes.write(enc, currentPos, dataLength); nextTLV.value = outBytes.toByteArray(); return nextTLV; } /** * Utility function for encoding a length as a BER byte sequence */ public static byte[] encodeLength(int length) { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); // see if can be represented in single byte // don't forget the first bit is the "long field test" bit!! if (length < 128) { byte[] len = {(byte)length}; outBytes.write(len, 0, 1); } else { // too big for one byte // see how many are needed: int numBytes = 0; int temp = length; while (temp > 0) { ++numBytes; temp = (int)Math.floor(temp / 256); } byte num = (byte)numBytes; num += 128; // set the "long format" bit outBytes.write(num); byte[] len = new byte[numBytes]; for (int i = numBytes-1; i >= 0; --i) { len[i] = (byte)(length % 256); length = (int)Math.floor(length / 256); } outBytes.write(len, 0, numBytes); } return outBytes.toByteArray(); } }linkmon-1.1/snmp/SNMPBadValueException.java0000664000175000017500000000235707152274532020260 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; /** * Exception thrown whenever attempt made to create SNMPObject subclass with inappropriate * data, or to set its value with inappropriate data, */ public class SNMPBadValueException extends Exception { public SNMPBadValueException() { super(); } /** * Create exception with message string. */ public SNMPBadValueException(String s) { super(s); } }linkmon-1.1/snmp/SNMPCounter32.java0000664000175000017500000000613107203332716016470 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.math.*; /** * Defines a 32-bit counter, whose value wraps if initialized with a larger * value. For an indicator which "pegs" at its maximum value if initialized with * a larger value, use SNMPGauge32; for a counter with a wider range, use SNMPCounter64. * @see snmp.SNMPGauge32 * @see snmp.SNMPCounter64 */ public class SNMPCounter32 extends SNMPInteger { // maximum value is 2^32 - 1 private static BigInteger maxValue = new BigInteger("4294967295"); protected byte tag = SNMPBERCodec.SNMPCOUNTER32; /** Initialize value to 0. */ public SNMPCounter32() { this(0); // initialize value to 0 } public SNMPCounter32(long newValue) { value = new BigInteger(new Long(newValue).toString()); // wrap if value > maxValue value = value.mod(maxValue); } /** Used to initialize from the BER encoding, usually received in a response from * an SNMP device responding to an SNMPGetRequest. * @throws SNMPBadValueException Indicates an invalid BER encoding supplied. Shouldn't * occur in normal operation, i.e., when valid responses are received from devices. */ public SNMPCounter32(byte[] enc) throws SNMPBadValueException { extractValueFromBEREncoding(enc); // wrap if value > maxValue value = value.mod(maxValue); } /** Used to set the value with an instance of java.lang.Integer or * java.lang.BigInteger. The value of the constructed SNMPCounter32 object is the * supplied value mod 2^32. * @throws SNMPBadValueException Indicates an incorrect object type supplied. */ public void setValue(Object newValue) throws SNMPBadValueException { if (newValue instanceof BigInteger) { value = (BigInteger)newValue; value = value.mod(maxValue); // wrap when value exceeds 2^32 } else if (newValue instanceof Integer) { value = new BigInteger(newValue.toString()); value = value.mod(maxValue); // wrap when value exceeds 2^32 } else if (newValue instanceof String) { value = value = new BigInteger((String)newValue); value = value.mod(maxValue); // wrap when value exceeds 2^32 } else throw new SNMPBadValueException(" Counter32: bad object supplied to set value "); } }linkmon-1.1/snmp/SNMPCounter64.java0000664000175000017500000000616507203332674016507 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.math.*; /** Defines a 64-bit counter, whose value wraps if initialized with a larger * value. For an indicator which "pegs" at its maximum value if initialized with * a larger value, use SNMPGauge32; for a counter with a smaller range, use SNMPCounter32. * @see snmp.SNMPGauge32 * @see snmp.SNMPCounter32 */ public class SNMPCounter64 extends SNMPInteger { // maximum value is 2^64 - 1; using approximation!! private static BigInteger maxValue = new BigInteger("18446744070000000000"); protected byte tag = SNMPBERCodec.SNMPCOUNTER64; /** Initialize value to 0. */ public SNMPCounter64() { this(0); // initialize value to 0 } public SNMPCounter64(long newValue) { value = new BigInteger(new Long(newValue).toString()); // wrap if value > maxValue value = value.mod(maxValue); } /** Used to initialize from the BER encoding, usually received in a response from * an SNMP device responding to an SNMPGetRequest. * @throws SNMPBadValueException Indicates an invalid BER encoding supplied. Shouldn't * occur in normal operation, i.e., when valid responses are received from devices. */ public SNMPCounter64(byte[] enc) throws SNMPBadValueException { extractValueFromBEREncoding(enc); // wrap if value > maxValue value = value.mod(maxValue); } /** Used to set the value with an instance of java.lang.Integer or * java.lang.BigInteger. The value of the constructed SNMPCounter64 object is the * supplied value mod 2^64. * @throws SNMPBadValueException Indicates an incorrect object type supplied. */ public void setValue(Object newValue) throws SNMPBadValueException { if (newValue instanceof BigInteger) { value = (BigInteger)newValue; value = value.mod(maxValue); // wrap when value exceeds 2^64 } else if (newValue instanceof Integer) { value = value = new BigInteger(newValue.toString()); value = value.mod(maxValue); // wrap when value exceeds 2^64 } else if (newValue instanceof String) { value = value = new BigInteger((String)newValue); value = value.mod(maxValue); // wrap when value exceeds 2^64 } else throw new SNMPBadValueException(" Counter64: bad object supplied to set value "); } }linkmon-1.1/snmp/SNMPGauge32.java0000664000175000017500000000605007203332710016073 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.math.*; /** Defines a 32-bit gauge, whose value "pegs" at the maximum if initialized with a larger * value. For an indicator which wraps when it reaches its maximum value, use SNMPCounter32; * for a counter with a wider range, use SNMPCounter64. * @see snmp.SNMPCounter32 * @see snmp.SNMPCounter64 */ public class SNMPGauge32 extends SNMPInteger { // maximum value is 2^32 - 1 (hack w/ 4*107...) private static BigInteger maxValue = new BigInteger("4294967295"); protected byte tag = SNMPBERCodec.SNMPGAUGE32; /** Initialize value to 0. */ public SNMPGauge32() { this(0); // initialize value to 0 } public SNMPGauge32(long newValue) { value = new BigInteger(new Long(newValue).toString()); // peg if value > maxValue value = value.min(maxValue); } /** Used to initialize from the BER encoding, usually received in a response from * an SNMP device responding to an SNMPGetRequest. * @throws SNMPBadValueException Indicates an invalid BER encoding supplied. Shouldn't * occur in normal operation, i.e., when valid responses are received from devices. */ public SNMPGauge32(byte[] enc) throws SNMPBadValueException { extractValueFromBEREncoding(enc); // peg if value > maxValue value = value.min(maxValue); } /** Used to set the value with an instance of java.lang.Integer or * java.lang.BigInteger. The value of the constructed SNMPGauge32 object is the * supplied value or 2^32, whichever is less. * @throws SNMPBadValueException Indicates an incorrect object type supplied. */ public void setValue(Object newValue) throws SNMPBadValueException { // plateau when value hits maxValue if (newValue instanceof BigInteger) { value = (BigInteger)newValue; value = value.min(maxValue); } else if (newValue instanceof Integer) { value = value = new BigInteger(newValue.toString()); value = value.min(maxValue); } else if (newValue instanceof String) { value = value = new BigInteger((String)newValue); value = value.min(maxValue); } else throw new SNMPBadValueException(" Gauge32: bad object supplied to set value "); } }linkmon-1.1/snmp/SNMPGetException.java0000664000175000017500000000244107152274534017310 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; /** * Exception thrown when attempt to get value of SNMP OID from device fails. Reason could be that * specified variable not supported by device, or that supplied community name has insufficient * privileges. */ public class SNMPGetException extends Exception { public SNMPGetException() { super(); } /** * Create exception with message string. */ public SNMPGetException(String s) { super(s); } }linkmon-1.1/snmp/SNMPIPAddress.java0000664000175000017500000001030407203333016016511 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.util.*; import java.io.*; /** * Class to hold IP addresses; special case of SNMP Octet String. */ public class SNMPIPAddress extends SNMPOctetString { // length limited to 4 octets protected byte tag = SNMPBERCodec.SNMPIPADDRESS; /** * Initialize to 0.0.0.0 */ public SNMPIPAddress() { // initialize to 0.0.0.0 data = new byte[4]; for (int i = 0; i < 4; i++) data[i] = 0; } /* public SNMPIPAddress(String string) throws SNMPBadValueException { if (string.length() == 4) this.data = string.getBytes[]; else throw new SNMPBadValueException(" IPAddress: bad length string supplied to set value "); } */ /** * Used to initialize from the BER encoding, as received in a response from * an SNMP device responding to an SNMPGetRequest, or from a supplied byte array * containing the address components. * @throws SNMPBadValueException Indicates an invalid array supplied: must have length 4. */ public SNMPIPAddress(byte[] enc) throws SNMPBadValueException { if (enc.length == 4) { data = enc; } else // wrong size { throw new SNMPBadValueException(" IPAddress: bad BER encoding supplied to set value "); } } /** * Used to set the value from a byte array containing the address. * @throws SNMPBadValueException Indicates an incorrect object type supplied, or array of * incorrect size. */ public void setValue(Object newAddress) throws SNMPBadValueException { if ((newAddress instanceof byte[]) && (((byte[])newAddress).length == 4)) data = (byte[])newAddress; else if (newAddress instanceof String) { data = parseIPAddress((String)newAddress); } else throw new SNMPBadValueException(" IPAddress: bad data supplied to set value "); } /** * Return pretty-printed IP address. */ public String toString() { String returnString = new String(); if (data.length > 0) { int convert = data[0]; if (convert < 0) convert += 256; returnString += convert; for (int i = 1; i < data.length; i++) { convert = data[i]; if (convert < 0) convert += 256; returnString += "." + convert; } } return returnString; } private byte[] parseIPAddress(String addressString) throws SNMPBadValueException { try { StringTokenizer st = new StringTokenizer(addressString, " ."); int size = 0; while (st.hasMoreTokens()) { // figure out how many values are in string size++; st.nextToken(); } if (size != 4) { throw new SNMPBadValueException(" IPAddress: wrong number of components supplied to set value "); } byte[] returnBytes = new byte[size]; st = new StringTokenizer(addressString, " ."); for (int i = 0; i < size; i++) { int addressComponent = (Integer.parseInt(st.nextToken())); if ((addressComponent < 0) || (addressComponent > 255)) throw new SNMPBadValueException(" IPAddress: invalid component supplied to set value "); returnBytes[i] = (byte)addressComponent; } return returnBytes; } catch (NumberFormatException e) { throw new SNMPBadValueException(" IPAddress: invalid component supplied to set value "); } } }linkmon-1.1/snmp/SNMPInteger.java0000664000175000017500000001016607203332562016303 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.math.*; import java.io.*; /** Defines an arbitrarily-sized integer value; there is no limit on size due to the use * of Java.lang.BigInteger to store the value internally. For an indicator which "pegs" at its * maximum value if initialized with a larger value, use SNMPGauge32; for a counter which wraps, * use SNMPCounter32 or SNMPCounter64. * @see snmp.SNMPCounter32 * @see snmp.SNMPGauge32 * @see snmp.SNMPCounter64 */ public class SNMPInteger extends SNMPObject { protected BigInteger value; protected byte tag = SNMPBERCodec.SNMPINTEGER; /** Initialize value to 0. */ public SNMPInteger() { this(0); // initialize value to 0 } public SNMPInteger(long value) { this.value = new BigInteger(new Long(value).toString()); } /** Used to initialize from the BER encoding, usually received in a response from * an SNMP device responding to an SNMPGetRequest. * @throws SNMPBadValueException Indicates an invalid BER encoding supplied. Shouldn't * occur in normal operation, i.e., when valid responses are received from devices. */ public SNMPInteger(byte[] enc) throws SNMPBadValueException { extractValueFromBEREncoding(enc); } /** Returns a java.lang.BigInteger object with the current value. */ public Object getValue() { return value; } /** Used to set the value with an instance of java.lang.Integer or * java.lang.BigInteger. * @throws SNMPBadValueException Indicates an incorrect object type supplied. */ public void setValue(Object newValue) throws SNMPBadValueException { if (newValue instanceof BigInteger) value = (BigInteger)newValue; else if (newValue instanceof Integer) value = new BigInteger(((Integer)newValue).toString()); else if (newValue instanceof String) value = new BigInteger((String)newValue); else throw new SNMPBadValueException(" Integer: bad object supplied to set value "); } /** Returns the full BER encoding (type, length, value) of the SNMPInteger subclass. */ public byte[] getBEREncoding() { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); // write contents // boy, was THIS easy! Love that Java! BigInteger big = new BigInteger(value.toString()); byte[] data = big.toByteArray(); // calculate encoding for length of data byte[] len = SNMPBERCodec.encodeLength(data.length); // encode T,L,V info outBytes.write(tag); outBytes.write(len, 0, len.length); outBytes.write(data, 0, data.length); return outBytes.toByteArray(); } /** Used to extract a value from the BER encoding of the value. Called in constructors for * SNMPInteger subclasses. * @throws SNMPBadValueException Indicates an invalid BER encoding supplied. Shouldn't * occur in normal operation, i.e., when valid responses are received from devices. */ public void extractValueFromBEREncoding(byte[] enc) throws SNMPBadValueException { try { value = new BigInteger(enc); } catch (NumberFormatException e) { throw new SNMPBadValueException(" Integer: bad BER encoding supplied to set value "); } } public String toString() { return new String(value.toString()); } }linkmon-1.1/snmp/SNMPMessage.java0000664000175000017500000000663607152274534016310 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.util.*; /** * Defines the SNMPMessage class as a special case of SNMPSequence. Defines a * top-level SNMP message, as per the following definitions from RFC 1157 and * RFC 1901. RFC1157-SNMP DEFINITIONS IMPORTS FROM RFC1155-SMI; -- top-level message Message ::= SEQUENCE { version -- version-1 for this RFC INTEGER { version-1(0) }, community -- community name OCTET STRING, data -- e.g., PDUs if trivial ANY -- authentication is being used } -- From RFC 1901: COMMUNITY-BASED-SNMPv2 DEFINITIONS ::= BEGIN -- top-level message Message ::= SEQUENCE { version INTEGER { version(1) -- modified from RFC 1157 }, community -- community name OCTET STRING, data -- PDUs as defined in [4] ANY } } END */ public class SNMPMessage extends SNMPSequence { /** * Create an SNMP message with specified version, community, and pdu. * Use version = 0 for SNMP version 1, or version = 1 for enhanced capapbilities * provided through RFC 1157. */ public SNMPMessage(int version, String community, SNMPPDU pdu) throws SNMPBadValueException { super(); Vector contents = new Vector(); contents.insertElementAt(new SNMPInteger(version), 0); contents.insertElementAt(new SNMPOctetString(community), 1); contents.insertElementAt(pdu, 2); this.setValue(contents); } /** * Construct an SNMPMessage from a received ASN.1 byte representation. * @throws SNMPBadValueException Indicates invalid SNMP message encoding supplied. */ public SNMPMessage(byte[] enc) throws SNMPBadValueException { super(enc); } /** * Utility method which returns the PDU contained in the SNMP message. The pdu is the third component * of the sequence, after the version and community name. */ public SNMPPDU getPDU() { Vector contents = (Vector)(this.getValue()); return (SNMPPDU)(contents.elementAt(2)); } }linkmon-1.1/snmp/SNMPNSAPAddress.java0000664000175000017500000001047607203335024016755 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.util.*; import java.io.*; /** * Defines class for holding physical 6-byte addresses. */ public class SNMPNSAPAddress extends SNMPOctetString { // length limited to 6 octets protected byte tag = SNMPBERCodec.SNMPNSAPADDRESS; /** * Initialize address to 0.0.0.0.0.0. */ public SNMPNSAPAddress() { // initialize to 0.0.0.0.0.0 data = new byte[6]; for (int i = 0; i < 6; i++) data[i] = 0; } /* public SNMPNSAPAddress(String string) throws SNMPBadValueException { if (string.length() == 6) this.string = (String)string; else throw new SNMPBadValueException(" NSAPAddress: bad length string supplied to set value "); } */ /** * Used to initialize from the BER encoding, as received in a response from * an SNMP device responding to an SNMPGetRequest, or from a supplied byte array * containing the address components. * @throws SNMPBadValueException Indicates an invalid array supplied: must have length 6. */ public SNMPNSAPAddress(byte[] enc) throws SNMPBadValueException { if (enc.length == 6) { data = enc; } else // wrong size { throw new SNMPBadValueException(" NSAPAddress: bad BER encoding supplied to set value "); } } /** * Used to set the value from a byte array containing the address. * @throws SNMPBadValueException Indicates an incorrect object type supplied, or array of * incorrect size. */ public void setValue(Object newAddress) throws SNMPBadValueException { if ((newAddress instanceof byte[]) && (((byte[])newAddress).length == 6)) data = (byte[])newAddress; else if (newAddress instanceof String) { data = parseNSAPAddress((String)newAddress); } else throw new SNMPBadValueException(" NSAPAddress: bad length byte string supplied to set value "); } /** * Return pretty-printed (dash-separated) address. */ public String toString() { String returnString = new String(); if (data.length > 0) { int convert = data[0]; if (convert < 0) convert += 256; returnString += Integer.toHexString(convert); for (int i = 1; i < data.length; i++) { convert = data[i]; if (convert < 0) convert += 256; returnString += "-" + Integer.toHexString(convert); } } return returnString; } private byte[] parseNSAPAddress(String addressString) throws SNMPBadValueException { try { StringTokenizer st = new StringTokenizer(addressString, " .-"); // break on spaces, dots or dashes int size = 0; while (st.hasMoreTokens()) { // figure out how many values are in string size++; st.nextToken(); } if (size != 6) { throw new SNMPBadValueException(" NSAPAddress: wrong number of components supplied to set value "); } byte[] returnBytes = new byte[size]; st = new StringTokenizer(addressString, " .-"); for (int i = 0; i < size; i++) { int addressComponent = (Integer.parseInt(st.nextToken(), 16)); if ((addressComponent < 0) || (addressComponent > 255)) throw new SNMPBadValueException(" NSAPAddress: invalid component supplied to set value "); returnBytes[i] = (byte)addressComponent; } return returnBytes; } catch (NumberFormatException e) { throw new SNMPBadValueException(" NSAPAddress: invalid component supplied to set value "); } } }linkmon-1.1/snmp/SNMPNull.java0000664000175000017500000000334607152274534015631 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; /** * Object representing the SNMP Null data type. */ public class SNMPNull extends SNMPObject { /** * Returns Java null reference. */ public Object getValue() { return null; } /** * Always throws SNMPBadValueException (which null value did you want, anyway?) */ public void setValue(Object o) throws SNMPBadValueException { throw new SNMPBadValueException(" Null: attempt to set value "); } /** * Return BER encoding for a null object: two bytes, tag and length of 0. */ public byte[] getBEREncoding() { byte[] encoding = new byte[2]; // set tag byte encoding[0] = SNMPBERCodec.SNMPNULL; // len = 0 since no payload! encoding[1] = 0; // no V! return encoding; } /** * Returns String "Null".. */ public String toString() { return new String("Null"); } }linkmon-1.1/snmp/SNMPObject.java0000664000175000017500000000317207152274534016122 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; /** * Abstract base class of all SNMP data type classes. */ public abstract class SNMPObject { /** * Must return a Java object appropriate to represent the value/data contained * in the SNMP object */ public abstract Object getValue(); /** * Must set the value of the SNMP object when supplied with an appropriate * Java object containing an appropriate value. */ public abstract void setValue(Object o) throws SNMPBadValueException; /** * Must return the BER byte encoding (type, length, value) of the SNMP object. */ public abstract byte[] getBEREncoding(); /** * Should return an appropriate human-readable representation of the stored value. */ public abstract String toString(); }linkmon-1.1/snmp/SNMPObjectIdentifier.java0000664000175000017500000002120307205466112020112 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.util.*; import java.io.*; /** * Class representing ASN.1 object identifiers. These are unbounded sequences (arrays) of * natural numbers, written as dot-separated strings. */ public class SNMPObjectIdentifier extends SNMPObject { private int[] digits; // array of integers /** * Create a new empty object identifier (0-length array). */ public SNMPObjectIdentifier() { digits = new int[0]; } /** * Create a new object identifier from the supplied string of dot-separated nonegative * decimal integer values. * @throws SNMPBadValueException Indicates incorrectly-formatted string supplied. */ public SNMPObjectIdentifier(String digitString) throws SNMPBadValueException { convertDigitString(digitString); } /** * Create a new object identifier from the supplied array of nonegative * integer values. * @throws SNMPBadValueException Negative value(s) supplied. */ public SNMPObjectIdentifier(int[] digits) throws SNMPBadValueException { for (int i = 0; i < digits.length; i++) { if (digits[i] < 0) throw new SNMPBadValueException("Negative value supplied for SNMPObjectIdentifier."); } this.digits = digits; } /** * Used to initialize from the BER encoding, as received in a response from * an SNMP device responding to an SNMPGetRequest. * @throws SNMPBadValueException Indicates an invalid BER encoding supplied. Shouldn't * occur in normal operation, i.e., when valid responses are received from devices. */ public SNMPObjectIdentifier(byte[] enc) throws SNMPBadValueException { extractFromBEREncoding(enc); } /** * Return array of integers corresponding to components of identifier. */ public Object getValue() { return digits; } /** * Used to set the value from an integer array containing the identifier components, or from * a String containing a dot-separated sequence of nonegative values. * @throws SNMPBadValueException Indicates an incorrect object type supplied, or negative array * elements, or an incorrectly formatted String. */ public void setValue(Object digits) throws SNMPBadValueException { if (digits instanceof int[]) { for (int i = 0; i < ((int[])digits).length; i++) { if (((int[])digits)[i] < 0) throw new SNMPBadValueException("Negative value supplied for SNMPObjectIdentifier."); } this.digits = (int[])digits; } else if (digits instanceof String) { convertDigitString((String)digits); } else throw new SNMPBadValueException(" Object Identifier: bad object supplied to set value "); } /** * Return BER encoding for this object identifier. */ public byte[] getBEREncoding() { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); byte type = SNMPBERCodec.SNMPOBJECTIDENTIFIER; // write contents of array of values byte[] data = encodeArray(); // calculate encoding for length of data byte[] len = SNMPBERCodec.encodeLength(data.length); // encode T,L,V info outBytes.write(type); outBytes.write(len, 0, len.length); outBytes.write(data, 0, data.length); return outBytes.toByteArray(); } private byte[] encodeArray() { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); int numElements = digits.length; // encode first two identifier digits as one byte, using the 40*x + y rule; // of course, if only one element, just use 40*x; if none, do nothing if (numElements >= 2) { outBytes.write((byte)(40*digits[0] + digits[1])); } else if (numElements ==1) { outBytes.write((byte)(40*digits[0])); } for (int i = 2; i < numElements; ++i) { byte[] nextBytes = encodeValue(digits[i]); outBytes.write(nextBytes, 0, nextBytes.length); } return outBytes.toByteArray(); } private byte[] encodeValue(int v) { // see how many bytes are needed: each value uses just // 7 bits of each byte, with high-order bit functioning as // a continuation marker int numBytes = 0; int temp = v; do { ++numBytes; temp = (int)Math.floor(temp / 128); } while (temp > 0); byte[] enc = new byte[numBytes]; // encode lowest-order byte, without setting high bit enc[numBytes-1] = (byte)(v % 128); v = (int)Math.floor(v / 128); //.encode other bytes with high bit set for (int i = numBytes-2; i >= 0; --i) { enc[i] = (byte)((v % 128) + 128); v = (int)Math.floor(v / 128); } return enc; } private void convertDigitString(String digitString) throws SNMPBadValueException { try { StringTokenizer st = new StringTokenizer(digitString, " ."); int size = 0; while (st.hasMoreTokens()) { // figure out how many values are in string size++; st.nextToken(); } int[] returnDigits = new int[size]; st = new StringTokenizer(digitString, " ."); for (int i = 0; i < size; i++) { returnDigits[i] = Integer.parseInt(st.nextToken()); if (returnDigits[i] < 0) throw new SNMPBadValueException(" Object Identifier: bad string supplied to set value "); } digits = returnDigits; } catch (NumberFormatException e) { throw new SNMPBadValueException(" Object Identifier: bad string supplied for object identifier value "); } } private void extractFromBEREncoding(byte[] enc) throws SNMPBadValueException { // note: masks must be ints; byte internal representation issue(?) int bitTest = 0x80; // test for leading 1 int highBitMask = 0x7F; // mask out high bit for value // first, compute number of "digits"; // will just be number of bytes with leading 0's int numInts = 0; for (int i = 0; i < enc.length; i++) { if ((enc[i] & bitTest) == 0) //high-order bit not set; count numInts++; } if (numInts > 0) { // create new int array to hold digits; since first value is 40*x + y, // need one extra entry in array to hold this. digits = new int[numInts + 1]; int currentByte = -1; // will be incremented to 0 int value = 0; // read in values 'til get leading 0 in byte do { currentByte++; value = value*128 + (enc[currentByte] & highBitMask); } while ((enc[currentByte] & bitTest) > 0); // implies high bit set! // now handle 40a + b digits[0] = (int)Math.floor(value / 40); digits[1] = value % 40; // now read in rest! for (int i = 2; i < numInts + 1; i++) { // read in values 'til get leading 0 in byte value = 0; do { currentByte++; value = value*128 + (enc[currentByte] & highBitMask); } while ((enc[currentByte] & bitTest) > 0); digits[i] = value; } } else { // no digits; create empty digit array digits = new int[0]; } } /** * Test two obeject identifiers for equality. */ public boolean equals(SNMPObjectIdentifier other) { int[] otherDigits = (int[])(other.getValue()); boolean areEqual = true; if (digits.length != otherDigits.length) { areEqual = false; } else { for (int i = 0; i < digits.length; i++) { if (digits[i] != otherDigits[i]) { areEqual = false; break; } } } return areEqual; } /** * Return dot-separated sequence of decimal values. */ public String toString() { String valueString = new String(); if (digits.length > 0) { valueString += digits[0]; for (int i = 1; i < digits.length; ++i) { valueString += "." + digits[i]; } } return valueString; } }linkmon-1.1/snmp/SNMPOctetString.java0000664000175000017500000001104007205470336017147 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.util.*; import java.io.*; /** * Class representing a general string of octets. */ public class SNMPOctetString extends SNMPObject { protected byte[] data; protected byte tag = SNMPBERCodec.SNMPOCTETSTRING; /** * Create a zero-length octet string. */ public SNMPOctetString() { data = new byte[0]; } /** * Create an octet string from the bytes of the supplied String. */ public SNMPOctetString(String stringData) { this.data = stringData.getBytes(); } /** * Create an octet string from the supplied byte array. The array may be either * user-supplied, or part of a retrieved BER encoding. Note that the BER encoding * of the data of an octet string is just the raw bytes. */ public SNMPOctetString(byte[] enc) { extractFromBEREncoding(enc); } /** * Return the array of raw bytes. */ public Object getValue() { return data; } /** * Used to set the value from a byte array. * @throws SNMPBadValueException Indicates an incorrect object type supplied. */ public void setValue(Object data) throws SNMPBadValueException { if (data instanceof byte[]) this.data = (byte[])data; else if (data instanceof String) this.data = ((String)data).getBytes(); else throw new SNMPBadValueException(" Octet String: bad object supplied to set value "); } /** * Returns the BER encoding for the octet string. Note the the "value" part of the * BER type,length,value triple is just the sequence of raw bytes. */ public byte[] getBEREncoding() { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); // calculate encoding for length of data byte[] len = SNMPBERCodec.encodeLength(data.length); // encode T,L,V info outBytes.write(tag); outBytes.write(len, 0, len.length); outBytes.write(data, 0, data.length); return outBytes.toByteArray(); } protected void extractFromBEREncoding(byte[] enc) { data = new byte[enc.length]; // copy data for (int i = 0; i < enc.length; i++) { data[i] = enc[i]; } } /** * Returns a String constructed from the raw bytes. If the bytes contain non-printable * ASCII characters, tant pis! (Though it's fun when the bell rings!) */ public String toString() { String returnString; /* if ((data.length == 4) || (data.length == 6)) { returnString = new String(); int convert = data[0]; if (convert < 0) convert += 256; returnString += convert; for (int i = 1; i < data.length; i++) { convert = data[i]; if (convert < 0) convert += 256; returnString += "." + convert; } } else returnString = new String(data); */ /* byte[] converted = new byte[data.length]; for (int i = 0; i < data.length; i++) { if (data[i] == 0) converted[i] = 0x20; // space character else converted[i] = data[i]; } returnString = new String(converted); */ returnString = new String(data); return returnString; } private String hexByte(byte b) { int pos = b; if (pos < 0) pos += 256; String returnString = new String(); returnString += Integer.toHexString(pos/16); returnString += Integer.toHexString(pos%16); return returnString; } /** * Returns a space-separated hex string corresponding to the raw bytes. */ public String toHexString() { String returnString = new String(); for (int i = 0; i < data.length; i++) { returnString += hexByte(data[i]) + " "; } return returnString; } }linkmon-1.1/snmp/SNMPPDU.java0000664000175000017500000001265407152274534015351 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.util.*; import java.io.*; import java.math.*; /** * The SNMPPDU class represents an SNMP PDU from RFC 1157, as indicated below. This * forms the payload of an SNMP message. -- protocol data units PDUs ::= CHOICE { get-request GetRequest-PDU, get-next-request GetNextRequest-PDU, get-response GetResponse-PDU, set-request SetRequest-PDU, trap Trap-PDU } -- PDUs GetRequest-PDU ::= [0] IMPLICIT PDU GetNextRequest-PDU ::= [1] IMPLICIT PDU GetResponse-PDU ::= [2] IMPLICIT PDU SetRequest-PDU ::= [3] IMPLICIT PDU PDU ::= SEQUENCE { request-id INTEGER, error-status -- sometimes ignored INTEGER { noError(0), tooBig(1), noSuchName(2), badValue(3), readOnly(4), genErr(5) }, error-index -- sometimes ignored INTEGER, variable-bindings -- values are sometimes ignored VarBindList } -- variable bindings VarBind ::= SEQUENCE { name ObjectName, value ObjectSyntax } VarBindList ::= SEQUENCE OF VarBind END */ public class SNMPPDU extends SNMPSequence { //protected int type; /** * Create a new PDU of the specified type, with given request ID, error status, and error index, * and containing the supplied SNMP sequence as data. */ public SNMPPDU(int pduType, int requestID, int errorStatus, int errorIndex, SNMPSequence varList) throws SNMPBadValueException { super(); Vector contents = new Vector(); type = pduType; contents.insertElementAt(new SNMPInteger(requestID), 0); contents.insertElementAt(new SNMPInteger(errorStatus), 1); contents.insertElementAt(new SNMPInteger(errorIndex), 2); contents.insertElementAt(varList, 3); this.setValue(contents); } /** * Create a new PDU of the specified type from the supplied BER encoding. * @throws SNMPBadValueException Indicates invalid SNMP PDU encoding supplied in enc. */ public SNMPPDU(byte[] enc, int pduType) throws SNMPBadValueException { type = pduType; extractFromBEREncoding(enc); } /** * A utility method that extracts the variable binding list from the pdu. Useful for retrieving * the set of (object identifier, value) pairs returned in response to a request to an SNMP * device. The variable binding list is just an SNMP sequence containing the identifier, value pairs. * @see snmp.SNMPVarBindList */ public SNMPSequence getVarBindList() { Vector contents = (Vector)(this.getValue()); return (SNMPSequence)(contents.elementAt(3)); } /** * A utility method that extracts the request ID number from this PDU. */ public int getRequestID() { Vector contents = (Vector)(this.getValue()); return ((BigInteger)((SNMPInteger)(contents.elementAt(0))).getValue()).intValue(); } /** * A utility method that extracts the error status for this PDU; if nonzero, can get index of * problematic variable using getErrorIndex(). */ public int getErrorStatus() { Vector contents = (Vector)(this.getValue()); return ((BigInteger)((SNMPInteger)(contents.elementAt(1))).getValue()).intValue(); } /** * A utility method that returns the error index for this PDU, identifying the problematic variable. */ public int getErrorIndex() { Vector contents = (Vector)(this.getValue()); return ((BigInteger)((SNMPInteger)(contents.elementAt(2))).getValue()).intValue(); } }linkmon-1.1/snmp/SNMPSequence.java0000664000175000017500000001314307152274534016463 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.util.*; import java.io.*; /** * One of the most important SNMP classes. Represents a sequence of other SNMP data types. * Virtually all compound structures are subclasses of SNMPSequence - for example, the * top-level SNMPMessage, and the SNMPPDU it contains, are both just specializations of * SNMPSequence. Sequences are frequently nested within other sequences. */ public class SNMPSequence extends SNMPObject { protected Vector sequence; // Vector of whatever is in sequence protected int type = SNMPBERCodec.SNMPSEQUENCE; /** * Create a new empty sequence. */ public SNMPSequence() { sequence = new Vector(); } /** * Create a new SNMP sequence from the supplied Vector of SNMPObjects. * @throws SNMPBadValueException Thrown if non-SNMP object supplied in Vector v. */ public SNMPSequence(Vector v) throws SNMPBadValueException { Enumeration e = v.elements(); while (e.hasMoreElements()) { if (!(e.nextElement() instanceof SNMPObject)) throw new SNMPBadValueException("Non-SNMPObject supplied to SNMPSequence."); } sequence = v; } /** * Construct an SNMPMessage from a received ASN.1 byte representation. * @throws SNMPBadValueException Indicates invalid SNMP sequence encoding supplied. */ public SNMPSequence(byte[] enc) throws SNMPBadValueException { extractFromBEREncoding(enc); } /** * Returns a Vector containing the SNMPObjects in the sequence. */ public Object getValue() { return sequence; } /** * Used to set the contained SNMP objects from a supplied Vector. * @throws SNMPBadValueException Indicates an incorrect object type supplied, or that the supplied * Vector contains non-SNMPObjects. */ public void setValue(Object newSequence) throws SNMPBadValueException { if (newSequence instanceof Vector) { // check that all objects in vector are SNMPObjects Enumeration e = ((Vector)newSequence).elements(); while (e.hasMoreElements()) { if (!(e.nextElement() instanceof SNMPObject)) throw new SNMPBadValueException("Non-SNMPObject supplied to SNMPSequence."); } this.sequence = (Vector)newSequence; } else throw new SNMPBadValueException(" Sequence: bad object supplied to set value "); } /** * Return the number of SNMPObjects contained in the sequence. */ public int size() { return sequence.size(); } /** * Add the SNMP object to the end of the sequence. * @throws SNMPBadValueException Relevant only in subclasses */ public void addSNMPObject(SNMPObject newObject) throws SNMPBadValueException { sequence.insertElementAt(newObject, sequence.size()); } /** * Return the SNMP object at the specified index. Indices are 0-based. */ public SNMPObject getSNMPObjectAt(int index) { return (SNMPObject)(sequence.elementAt(index)); } /** * Return the BER encoding for the sequence. */ public byte[] getBEREncoding() { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); // recursively write contents of Vector byte[] data = encodeVector(); // calculate encoding for length of data byte[] len = SNMPBERCodec.encodeLength(data.length); // encode T,L,V info outBytes.write(type); outBytes.write(len, 0, len.length); outBytes.write(data, 0, data.length); return outBytes.toByteArray(); } private byte[] encodeVector() { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); int numElements = sequence.size(); for (int i = 0; i < numElements; ++i) { byte[] nextBytes = ((SNMPObject)(sequence.elementAt(i))).getBEREncoding(); outBytes.write(nextBytes, 0, nextBytes.length); } return outBytes.toByteArray(); } protected void extractFromBEREncoding(byte[] enc) throws SNMPBadValueException { Vector newVector = new Vector(); int totalLength = enc.length; int position = 0; while (position < totalLength) { SNMPTLV nextTLV = SNMPBERCodec.extractNextTLV(enc, position); newVector.insertElementAt(SNMPBERCodec.extractEncoding(nextTLV), newVector.size()); position += nextTLV.totalLength; } sequence = newVector; } /** * Return a sequence of representations of the contained objects, separated by spaces * and enclosed in parentheses. */ public String toString() { String valueString = new String("("); for (int i = 0; i < sequence.size(); ++i) { valueString += " " + ((SNMPObject)sequence.elementAt(i)).toString() + " "; } valueString += ")"; return valueString; } }linkmon-1.1/snmp/SNMPSetException.java0000664000175000017500000000244707152274534017332 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; /** * Exception thrown when attempt to set the value of an SNMP OID on a device fails. Reason could be * that specified variable not supported by device, or that supplied community name has insufficient * privileges. */ public class SNMPSetException extends Exception { public SNMPSetException() { super(); } /** * Create exception with message string. */ public SNMPSetException(String s) { super(s); } }linkmon-1.1/snmp/SNMPTLV.java0000664000175000017500000000176707152274534015371 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; /** * Utility class holding components of an ASN.1 (type, length, value) triple. */ class SNMPTLV { int tag, totalLength; byte[] value; }linkmon-1.1/snmp/SNMPTimeTicks.java0000664000175000017500000000242207152274534016605 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; /** * SNMP datatype used to represent time value. Just extension of SNMPInteger. */ public class SNMPTimeTicks extends SNMPInteger { protected byte tag = SNMPBERCodec.SNMPTIMETICKS; public SNMPTimeTicks() { this(0); // initialize value to 0 } public SNMPTimeTicks(long value) { super(value); } public SNMPTimeTicks(byte[] enc) throws SNMPBadValueException { super(enc); } }linkmon-1.1/snmp/SNMPUInteger32.java0000664000175000017500000000602507203332572016575 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.math.*; /** * Defines a 32-bit unsigned integer value; wraps if initialized with a larger value. * @see snmp.SNMPInteger */ public class SNMPUInteger32 extends SNMPInteger { // maximum value is 2^32 - 1 private static BigInteger maxValue = new BigInteger("4294967295"); protected byte tag = SNMPBERCodec.SNMPUINTEGER32; /** * Initialize value to 0. */ public SNMPUInteger32() { this(0); // initialize value to 0 } /** * Initialize value to newValue; wrap if newValue too big for 32 bits. */ public SNMPUInteger32(long newValue) { value = new BigInteger(new Long(newValue).toString()); // wrap if value > maxValue value = value.mod(maxValue); } /** * Used to initialize from the BER encoding, usually received in a response from * an SNMP device responding to an SNMPGetRequest. * @throws SNMPBadValueException Indicates an invalid BER encoding supplied. Shouldn't * occur in normal operation, i.e., when valid responses are received from devices. */ public SNMPUInteger32(byte[] enc) throws SNMPBadValueException { extractValueFromBEREncoding(enc); // wrap if value > maxValue value = value.mod(maxValue); } /** * Used to set the value with an instance of java.lang.Integer or * java.lang.BigInteger. The value of the constructed SNMPUInteger32 object is the * supplied value mod 2^32. * @throws SNMPBadValueException Indicates an incorrect object type supplied. */ public void setValue(Object newValue) throws SNMPBadValueException { if (newValue instanceof BigInteger) { value = (BigInteger)newValue; value = value.mod(maxValue); // wrap when value exceeds 2^32 } else if (newValue instanceof Integer) { value = value = new BigInteger(newValue.toString()); value = value.mod(maxValue); // wrap when value exceeds 2^32 } else if (newValue instanceof String) { value = value = new BigInteger((String)newValue); value = value.mod(maxValue); // wrap when value exceeds 2^32 } else throw new SNMPBadValueException(" Unsigned Integer: bad object supplied to set value "); } }linkmon-1.1/snmp/SNMPUnknownObject.java0000664000175000017500000000453407152274534017505 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.util.*; import java.io.*; /** * Used when an unknown SNMP object type is encountered. Just takes a byte array * for its constructor, and uses this as raw bytes. */ public class SNMPUnknownObject extends SNMPObject { private byte[] data; /** * Just takes a byte array, and uses this as raw bytes. */ public SNMPUnknownObject(byte[] enc) { data = enc; } /** * Return a byte array containing the raw bytes supplied. */ public Object getValue() { return data; } /** * Takes a byte array containing the raw bytes stored as the value. */ public void setValue(Object data) throws SNMPBadValueException { if (data instanceof byte[]) this.data = (byte[])data; else throw new SNMPBadValueException(" Unknown Object: bad object supplied to set value "); } /** * Return the BER encoding of this object. */ public byte[] getBEREncoding() { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); byte type = SNMPBERCodec.SNMPUNKNOWNOBJECT; // calculate encoding for length of data byte[] len = SNMPBERCodec.encodeLength(data.length); // encode T,L,V info outBytes.write(type); outBytes.write(len, 0, len.length); outBytes.write(data, 0, data.length); return outBytes.toByteArray(); } /** * Return String created from raw bytes of this object. */ public String toString() { return new String(data); } }linkmon-1.1/snmp/SNMPVarBindList.java0000664000175000017500000000365507152274534017103 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.util.*; /** * The SNMPVarBindList class is a specialization of SNMPSequence that contains a list of * SNMPVariablePair objects. * @see snmp.SNMPVariablePair -- variable bindings VarBind ::= SEQUENCE { name ObjectName, value ObjectSyntax } VarBindList ::= SEQUENCE OF VarBind END */ public class SNMPVarBindList extends SNMPSequence { /** * Create a new empty variable binding list. */ public SNMPVarBindList() { super(); } /** * Return the variable pairs in the list, separated by newlines. */ public String toString() { Vector sequence = (Vector)(this.getValue()); String valueString = new String(); for (int i = 0; i < sequence.size(); ++i) { valueString += ((SNMPObject)sequence.elementAt(i)).toString() + "\n"; } return valueString; } }linkmon-1.1/snmp/SNMPVariablePair.java0000664000175000017500000000351407152274532017253 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.util.*; /** * The SNMPVariablePair class implements the VarBind specification detailed below from RFC 1157. * It is a specialization of SNMPSequence, defining a 2-element sequence containing a single * (object identifier, value) pair. Note that the values are themselves SNMPObjects. -- variable bindings VarBind ::= SEQUENCE { name ObjectName, value ObjectSyntax } */ public class SNMPVariablePair extends SNMPSequence { /** * Create a new variable pair having the supplied object identifier and vale. */ public SNMPVariablePair(SNMPObjectIdentifier objectID, SNMPObject value) throws SNMPBadValueException { super(); Vector contents = new Vector(); contents.insertElementAt(objectID, 0); contents.insertElementAt(value, 1); this.setValue(contents); } }linkmon-1.1/snmp/SNMPv1CommunicationInterface.java0000664000175000017500000004703407224722220021604 0ustar julienjulien/* * AirportBaseStationConfigurator * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package snmp; import java.io.*; import java.math.*; import java.net.*; import java.util.*; /** * The class SNMPv1CommunicationInterface defines methods for communicating with SNMP entities. * The approach is that from version 1 of SNMP, using no encryption of data. Communication occurs * via UDP, using port 161, the standard SNMP port. */ public class SNMPv1CommunicationInterface { public static final int SNMPPORT = 161; public static final int MAXSIZE = 512; private int version; private InetAddress hostAddress; private String community; DatagramSocket dSocket; public int requestID = 1; /** * Construct a new communication object to communicate with the specified host using the * given community name. The version setting should be either 0 (version 1) or 1 (version 2, * a la RFC 1157). */ public SNMPv1CommunicationInterface(int version, InetAddress hostAddress, String community) throws SocketException { this.version = version; this.hostAddress = hostAddress; this.community = community; dSocket = new DatagramSocket(); dSocket.setSoTimeout(15000); //15 seconds } /** * Permits setting timeout value for underlying datagram socket (in milliseconds). */ public void setSocketTimeout(int socketTimeout) throws SocketException { dSocket.setSoTimeout(socketTimeout); } /** * Close the "connection" with the devive. */ public void closeConnection() throws SocketException { dSocket.close(); } /** * Retrieve all MIB variable values subsequent to the starting object identifier * given in startID (in dotted-integer notation). Return as SNMPVarBindList object. * Uses SNMPGetNextRequests to retrieve variable values in sequence. * @throws IOException Thrown when timeout experienced while waiting for response to request. * @throws SNMPBadValueException */ public SNMPVarBindList retrieveAllMIBInfo(String startID) throws IOException, SNMPBadValueException { // send GetNextRequests until receive // an error message or a repeat of the object identifier we sent out SNMPVarBindList retrievedVars = new SNMPVarBindList(); int errorStatus = 0; int errorIndex = 0; SNMPObjectIdentifier requestedObjectIdentifier = new SNMPObjectIdentifier(startID); SNMPVariablePair nextPair = new SNMPVariablePair(requestedObjectIdentifier, new SNMPInteger(0)); SNMPSequence varList = new SNMPSequence(); varList.addSNMPObject(nextPair); SNMPPDU pdu = new SNMPPDU(SNMPBERCodec.SNMPGETNEXTREQUEST, requestID, errorStatus, errorIndex, varList); SNMPMessage message = new SNMPMessage(version, community, pdu); byte[] messageEncoding = message.getBEREncoding(); DatagramPacket outPacket = new DatagramPacket(messageEncoding, messageEncoding.length, hostAddress, SNMPPORT); dSocket.send(outPacket); while (errorStatus == 0) { DatagramPacket inPacket = new DatagramPacket(new byte[MAXSIZE], MAXSIZE); dSocket.receive(inPacket); byte[] encodedMessage = inPacket.getData(); SNMPMessage receivedMessage = new SNMPMessage(SNMPBERCodec.extractNextTLV(encodedMessage,0).value); //errorStatus = ((BigInteger)((SNMPInteger)((receivedMessage.getPDU()).getSNMPObjectAt(1))).getValue()).intValue(); varList = (receivedMessage.getPDU()).getVarBindList(); SNMPSequence newPair = (SNMPSequence)(varList.getSNMPObjectAt(0)); SNMPObjectIdentifier newObjectIdentifier = (SNMPObjectIdentifier)(newPair.getSNMPObjectAt(0)); SNMPObject newValue = newPair.getSNMPObjectAt(1); retrievedVars.addSNMPObject(newPair); if (requestedObjectIdentifier.equals(newObjectIdentifier)) break; requestedObjectIdentifier = newObjectIdentifier; requestID++; pdu = new SNMPPDU(SNMPBERCodec.SNMPGETNEXTREQUEST, requestID, errorStatus, errorIndex, varList); message = new SNMPMessage(version, community, pdu); messageEncoding = message.getBEREncoding(); outPacket = new DatagramPacket(messageEncoding, messageEncoding.length, hostAddress, SNMPPORT); dSocket.send(outPacket); } return retrievedVars; } private String hexByte(byte b) { int pos = b; if (pos < 0) pos += 256; String returnString = new String(); returnString += Integer.toHexString(pos/16); returnString += Integer.toHexString(pos%16); return returnString; } /** * Retrieve the MIB variable values corresponding to the object identifier * given in itemID (in dotted-integer notation). Return as SNMPVarBindList object; if no * such variable (either due to device not supporting it, or community name having incorrect * access privilege), variable value will be SNMPNull object * @throws IOException Thrown when timeout experienced while waiting for response to request. * @throws SNMPBadValueException */ public SNMPVarBindList getMIBEntry(String itemID) throws IOException, SNMPBadValueException, SNMPGetException { // send GetRequest to specified host to retrieve specified object identifier SNMPVarBindList retrievedVars = new SNMPVarBindList(); int errorStatus = 0; int errorIndex = 0; SNMPObjectIdentifier requestedObjectIdentifier = new SNMPObjectIdentifier(itemID); SNMPVariablePair nextPair = new SNMPVariablePair(requestedObjectIdentifier, new SNMPInteger(0)); SNMPSequence varList = new SNMPSequence(); varList.addSNMPObject(nextPair); SNMPPDU pdu = new SNMPPDU(SNMPBERCodec.SNMPGETREQUEST, requestID, errorStatus, errorIndex, varList); SNMPMessage message = new SNMPMessage(version, community, pdu); byte[] messageEncoding = message.getBEREncoding(); /* System.out.println("Request Message bytes:"); for (int i = 0; i < messageEncoding.length; ++i) System.out.print(hexByte(messageEncoding[i]) + " "); */ DatagramPacket outPacket = new DatagramPacket(messageEncoding, messageEncoding.length, hostAddress, SNMPPORT); dSocket.send(outPacket); DatagramPacket inPacket = new DatagramPacket(new byte[MAXSIZE], MAXSIZE); while (true) // wait until receive reply for requestID & OID (or error) { dSocket.receive(inPacket); byte[] encodedMessage = inPacket.getData(); /* System.out.println("Message bytes:"); for (int i = 0; i < encodedMessage.length; ++i) { System.out.print(hexByte(encodedMessage[i]) + " "); } */ SNMPMessage receivedMessage = new SNMPMessage(SNMPBERCodec.extractNextTLV(encodedMessage,0).value); SNMPPDU receivedPDU = receivedMessage.getPDU(); // check request identifier; if incorrect, just ignore packet and continue waiting if (receivedPDU.getRequestID() == requestID) { // check error status; if retrieval problem, throw SNMPGetException if (receivedPDU.getErrorStatus() != 0) throw new SNMPGetException("OID " + itemID + " not available for retrieval"); varList = receivedPDU.getVarBindList(); SNMPSequence newPair = (SNMPSequence)(varList.getSNMPObjectAt(0)); SNMPObjectIdentifier newObjectIdentifier = (SNMPObjectIdentifier)(newPair.getSNMPObjectAt(0)); SNMPObject newValue = newPair.getSNMPObjectAt(1); // check the object identifier to make sure the correct variable has been received; // if not, just continue waiting for receive if (newObjectIdentifier.toString().equals(itemID)) { // got the right one; add it to retrieved var list and break! retrievedVars.addSNMPObject(newPair); break; } } } requestID++; return retrievedVars; } /** * Retrieve the MIB variable value corresponding to the object identifier following that * given in itemID (in dotted-integer notation). Return as SNMPVarBindList object; if no * such variable (either due to device not supporting it, or community name having incorrect * access privilege), variable value will be SNMPNull object * @throws IOException Thrown when timeout experienced while waiting for response to request. * @throws SNMPBadValueException */ public SNMPVarBindList getNextMIBEntry(String itemID) throws IOException, SNMPBadValueException, SNMPGetException { // send GetRequest to specified host to retrieve specified object identifier SNMPVarBindList retrievedVars = new SNMPVarBindList(); int errorStatus = 0; int errorIndex = 0; SNMPObjectIdentifier requestedObjectIdentifier = new SNMPObjectIdentifier(itemID); SNMPVariablePair nextPair = new SNMPVariablePair(requestedObjectIdentifier, new SNMPInteger(0)); SNMPSequence varList = new SNMPSequence(); varList.addSNMPObject(nextPair); SNMPPDU pdu = new SNMPPDU(SNMPBERCodec.SNMPGETNEXTREQUEST, requestID, errorStatus, errorIndex, varList); SNMPMessage message = new SNMPMessage(version, community, pdu); byte[] messageEncoding = message.getBEREncoding(); /* System.out.println("Request Message bytes:"); for (int i = 0; i < messageEncoding.length; ++i) System.out.print(hexByte(messageEncoding[i]) + " "); */ DatagramPacket outPacket = new DatagramPacket(messageEncoding, messageEncoding.length, hostAddress, SNMPPORT); dSocket.send(outPacket); DatagramPacket inPacket = new DatagramPacket(new byte[MAXSIZE], MAXSIZE); while (true) // wait until receive reply for requestID & OID (or error) { dSocket.receive(inPacket); byte[] encodedMessage = inPacket.getData(); /* System.out.println("Message bytes:"); for (int i = 0; i < encodedMessage.length; ++i) { System.out.print(hexByte(encodedMessage[i]) + " "); } */ SNMPMessage receivedMessage = new SNMPMessage(SNMPBERCodec.extractNextTLV(encodedMessage,0).value); SNMPPDU receivedPDU = receivedMessage.getPDU(); // check request identifier; if incorrect, just ignore packet and continue waiting if (receivedPDU.getRequestID() == requestID) { // check error status; if retrieval problem, throw SNMPGetException if (receivedPDU.getErrorStatus() != 0) throw new SNMPGetException("OID " + itemID + " not available for retrieval"); varList = receivedPDU.getVarBindList(); SNMPSequence newPair = (SNMPSequence)(varList.getSNMPObjectAt(0)); SNMPObjectIdentifier newObjectIdentifier = (SNMPObjectIdentifier)(newPair.getSNMPObjectAt(0)); SNMPObject newValue = newPair.getSNMPObjectAt(1); retrievedVars.addSNMPObject(newPair); break; } } requestID++; return retrievedVars; } /** * Set the MIB variable value of the object identifier * given in startID (in dotted-integer notation). Return SNMPVarBindList object returned * by device in its response; can be used to check that setting was successful. * Uses SNMPGetNextRequests to retrieve variable values in sequence. * @throws IOException Thrown when timeout experienced while waiting for response to request. * @throws SNMPBadValueException */ public SNMPVarBindList setMIBEntry(String itemID, SNMPObject newValue) throws IOException, SNMPBadValueException, SNMPSetException { // send SetRequest to specified host to set value of specified object identifier SNMPVarBindList retrievedVars = new SNMPVarBindList(); int errorStatus = 0; int errorIndex = 0; SNMPObjectIdentifier requestedObjectIdentifier = new SNMPObjectIdentifier(itemID); SNMPVariablePair nextPair = new SNMPVariablePair(requestedObjectIdentifier, newValue); SNMPSequence varList = new SNMPSequence(); varList.addSNMPObject(nextPair); SNMPPDU pdu = new SNMPPDU(SNMPBERCodec.SNMPSETREQUEST, requestID, errorStatus, errorIndex, varList); SNMPMessage message = new SNMPMessage(version, community, pdu); byte[] messageEncoding = message.getBEREncoding(); /* System.out.println("Message bytes:"); for (int i = 0; i < messageEncoding.length; ++i) { System.out.print(getHex(messageEncoding[i]) + " "); } */ DatagramPacket outPacket = new DatagramPacket(messageEncoding, messageEncoding.length, hostAddress, SNMPPORT); dSocket.send(outPacket); DatagramPacket inPacket = new DatagramPacket(new byte[MAXSIZE], MAXSIZE); while (true) // wait until receive reply for correct OID (or error) { dSocket.receive(inPacket); byte[] encodedMessage = inPacket.getData(); /* System.out.println("Message bytes:"); for (int i = 0; i < encodedMessage.length; ++i) { System.out.print((encodedMessage[i]) + " "); } */ SNMPMessage receivedMessage = new SNMPMessage(SNMPBERCodec.extractNextTLV(encodedMessage,0).value); SNMPPDU receivedPDU = receivedMessage.getPDU(); // check request identifier; if incorrect, just ignore packet and continue waiting if (receivedPDU.getRequestID() == requestID) { // check error status; if retrieval problem, throw SNMPGetException if (receivedPDU.getErrorStatus() != 0) { switch (receivedPDU.getErrorStatus()) { case 1: throw new SNMPSetException("Value supplied for OID " + itemID + " too big."); case 2: throw new SNMPSetException("OID " + itemID + " not available for setting."); case 3: throw new SNMPSetException("Bad value supplied for OID " + itemID + "."); case 4: throw new SNMPSetException("OID " + itemID + " read-only."); default: throw new SNMPSetException("Error setting OID " + itemID + "."); } } varList = receivedPDU.getVarBindList(); SNMPSequence newPair = (SNMPSequence)(varList.getSNMPObjectAt(0)); // check the object identifier to make sure the correct variable has been received; // if not, just continue waiting for receive if (((SNMPObjectIdentifier)newPair.getSNMPObjectAt(0)).toString().equals(itemID)) { // got the right one; add it to retrieved var list and break! retrievedVars.addSNMPObject(newPair); break; } } } requestID++; return retrievedVars; } /* public void broadcastDiscovery(String itemID) throws IOException, SNMPBadValueException { // send GetRequest to all hosts to retrieve specified object identifier int errorStatus = 0; int errorIndex = 0; int requestID = 0; SNMPObjectIdentifier requestedObjectIdentifier = new SNMPObjectIdentifier(itemID); SNMPVariablePair nextPair = new SNMPVariablePair(requestedObjectIdentifier, new SNMPInteger(0)); SNMPSequence varList = new SNMPSequence(); varList.addSNMPObject(nextPair); SNMPPDU pdu = new SNMPPDU(SNMPBERCodec.SNMPGETREQUEST, requestID, errorStatus, errorIndex, varList); SNMPMessage message = new SNMPMessage(0, community, pdu); byte[] messageEncoding = message.getBEREncoding(); DatagramPacket outPacket = new DatagramPacket(messageEncoding, messageEncoding.length, hostAddress, SNMPPORT); dSocket.send(outPacket); } public String receiveDiscovery() throws IOException, SNMPBadValueException { // receive responses from hosts responding to discovery message int MAXSIZE = 512; String returnString = new String(); int errorStatus = 0; int errorIndex = 0; int requestID = 0; DatagramPacket inPacket = new DatagramPacket(new byte[MAXSIZE], MAXSIZE); dSocket.receive(inPacket); String hostString = inPacket.getAddress().toString(); returnString += "Packet received from: " + hostString + "\n"; byte[] encodedMessage = inPacket.getData(); returnString += "Message bytes:" + "\n"; for (int i = 0; i < encodedMessage.length; ++i) { returnString += (encodedMessage[i]) + " "; } SNMPMessage receivedMessage = new SNMPMessage(SNMPBERCodec.extractNextTLV(encodedMessage,0).value); SNMPSequence varList = (receivedMessage.getPDU()).getVarBindList(); SNMPSequence newPair = (SNMPSequence)(varList.getSNMPObjectAt(0)); SNMPObject newValue = newPair.getSNMPObjectAt(1); // return just value string returnString += newValue.toString() + "\n\n"; returnString += "Received message contents:\n"; returnString += receivedMessage.toString() + "\n"; System.out.println(receivedMessage.toString()); return returnString; } public String discoverDevices(String itemID) throws IOException, SNMPBadValueException { // send GetRequest to all hosts to retrieve specified object identifier int MAXSIZE = 512; String returnString = new String(); try { int errorStatus = 0; int errorIndex = 0; DatagramSocket dSocket = new DatagramSocket(); int requestID = 0; SNMPObjectIdentifier requestedObjectIdentifier = new SNMPObjectIdentifier(itemID); SNMPVariablePair nextPair = new SNMPVariablePair(requestedObjectIdentifier, new SNMPInteger(0)); SNMPSequence varList = new SNMPSequence(); varList.addSNMPObject(nextPair); SNMPPDU pdu = new SNMPPDU(SNMPBERCodec.SNMPGETREQUEST, requestID, errorStatus, errorIndex, varList); SNMPMessage message = new SNMPMessage(0, community, pdu); byte[] messageEncoding = message.getBEREncoding(); DatagramPacket outPacket = new DatagramPacket(messageEncoding, messageEncoding.length, hostAddress, SNMPPORT); dSocket.send(outPacket); DatagramPacket inPacket = new DatagramPacket(new byte[MAXSIZE], MAXSIZE); while (true) { dSocket.receive(inPacket); String hostString = inPacket.getAddress().toString(); returnString += "Packet received from: " + hostString + "\n"; byte[] encodedMessage = inPacket.getData(); returnString += "Message bytes:" + "\n"; for (int i = 0; i < encodedMessage.length; ++i) { returnString += (encodedMessage[i]) + " "; } SNMPMessage receivedMessage = new SNMPMessage(SNMPBERCodec.extractNextTLV(encodedMessage,0).value); returnString += "Received message contents:\n"; returnString += receivedMessage.toString() + "\n"; } } catch (Exception e) { } return returnString; } private String getHex(byte theByte) { int b = theByte; if (b < 0) b += 256; String returnString = new String(Integer.toHexString(b)); // add leading 0 if needed if (returnString.length()%2 == 1) returnString = "0" + returnString; return returnString; } */ }linkmon-1.1/snmp/package.html0000664000175000017500000000362407152274532015634 0ustar julienjulien SNMP package The snmp package defines classes used to communicate with SNMP devices. Classes corresponding to each of the basic SNMP data types are defined, each extending the SNMPObject abstarct class. In addition, some utility classes provide additional functionality.

Each of the SNMPObject subclasses defines methods to create an object, either from a "reasonable" representation (e.g., Java.lang.Integer for an SNMPInteger object, or a suitable String such as "1.2.1.1.3.2.1.1.0" for an SNMPObjectIdentifier), or from a byte array presumed to contain a valid ASN.1 Basic Encoding Rules (BER) encoding of a value of the appropriate type. The objects also define methods that permit their values to be set, and generate their BER encodings.

SNMPSequence subclasses, in particular, contain Vectors of other SNMPObject subclasses. They can be created "manually", with objects added as desired, or can be created from a BER encoding of the sequence contents, recursively creating the contained objects. BER generation also recursively generates the BER for each contained component; thus calling  mySequence.getBerEncoding() automatically generates the encoding for the entire sequence, including the contained components. SNMPBERCodec contains a number of static utility methods for converting to and from BER encodings, as well as constants used by the various classes.

Finally, SNMPv1CommunicationsInterface defines methods for sending SNMP Get and Set requests to devices; this class handles all of the communication tasks needed for developing simple SNMP applications. linkmon-1.1/AboutDialog.java0000664000175000017500000001055007300033260015411 0ustar julienjulien/* * Wireless Link Quality Monitoring Utility * * Copyright (C) 2001, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ import java.awt.*; import javax.swing.*; import java.io.*; public class AboutDialog extends JDialog implements Runnable { private JLabel aboutLabel1 = new JLabel(" "); private JLabel aboutLabel2 = new JLabel(" "); private JLabel aboutLabel3 = new JLabel(" "); private JLabel aboutLabel4 = new JLabel(" "); private String aboutString1 = "Wireless Link Quality Monitoring Utility"; private String aboutString2 = "Version 1.1 "; private String aboutString3 = "J. Sevy "; private String aboutString4 = "May 2001 "; Thread displayThread; public AboutDialog(JFrame parent) { super(parent, "About...", true /*modal*/); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setUpDisplay(); this.setLocation(Math.round((parent.size().width - this.size().width)/2), Math.round((parent.size().height - this.size().height)/2)); // create and start display thread displayThread = new Thread(this); displayThread.start(); this.show(); } public void hide() { super.hide(); // interrupt thread so it can exit.. displayThread.interrupt(); } private void setUpDisplay() { // set params for layout manager GridBagLayout theLayout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = 1; c.gridheight = 1; c.fill = GridBagConstraints.NONE; c.ipadx = 0; c.ipady = 0; c.insets = new Insets(2,2,2,2); c.anchor = GridBagConstraints.CENTER; c.weightx = 0; c.weighty = 0; JPanel aboutPanel = new JPanel(); aboutPanel.setLayout(theLayout); c.gridx = 1; c.gridy = 1; theLayout.setConstraints(aboutLabel1, c); aboutPanel.add(aboutLabel1); c.gridx = 1; c.gridy = 2; theLayout.setConstraints(aboutLabel2, c); aboutPanel.add(aboutLabel2); c.gridx = 1; c.gridy = 3; theLayout.setConstraints(aboutLabel3, c); aboutPanel.add(aboutLabel3); c.gridx = 1; c.gridy = 4; theLayout.setConstraints(aboutLabel4, c); aboutPanel.add(aboutLabel4); this.getContentPane().add(aboutPanel); this.pack(); this.setSize(300, 150); } public void run() { try { Color textColor = new Color(255, 0, 255); aboutLabel1.setForeground(textColor); // write message out a character at a time... int numChars = aboutString1.length(); Font titleFont = new Font("SansSerif",Font.BOLD + Font.ITALIC, 12); Font labelFont = new Font("SansSerif",Font.PLAIN, 10); aboutLabel1.setFont(titleFont); aboutLabel1.setText(aboutString1); aboutLabel1.setSize(0, 30); for (int i = 0; i < this.getWidth() - 20; i++) { aboutLabel1.setSize(i, 30); Thread.currentThread().sleep(6); } aboutLabel2.setText(aboutString2); aboutLabel3.setText(aboutString3); aboutLabel4.setText(aboutString4); aboutLabel2.setFont(labelFont); aboutLabel3.setFont(labelFont); aboutLabel4.setFont(labelFont); // change color of other strings... int numSteps = 255; for (int i = 0; i < numSteps; i++) { textColor = new Color(255, 255-i, i); aboutLabel2.setForeground(textColor); aboutLabel3.setForeground(textColor); aboutLabel4.setForeground(textColor); Thread.currentThread().sleep(20); } } catch(Exception e) { // don't bother informing of exception; just exit... //System.out.println(e); } // later! } }linkmon-1.1/LinkMonitor.java0000664000175000017500000006255607300033350015501 0ustar julienjulien/* * Airport Monitor Utility * * Copyright (C) 2000, Jonathan Sevy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ import java.util.*; import java.net.*; import java.awt.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.*; import java.awt.event.*; import java.io.*; import java.math.*; import snmp.*; public class LinkMonitor extends JFrame implements ActionListener, Runnable { JButton newHostButton, newCommunityButton, newWirelessHostButton, scanButton; JTextArea messagesArea; JScrollPane messagesScroll; JTextField hostIDField, communityField, wirelessHostField, wirelessHostMACField; JLabel authorLabel, hostIDLabel, communityLabel, wirelessHostLabel, wirelessHostMACLabel; JProgressBar localSignalBar, localSNRBar, localNoiseBar; JProgressBar remoteSignalBar, remoteSNRBar, remoteNoiseBar; JLabel localSignalTextField, localSNRTextField, localNoiseTextField; JLabel remoteSignalTextField, remoteSNRTextField, remoteNoiseTextField; MenuBar theMenubar; Menu fileMenu; MenuItem quitItem, aboutItem; SNMPv1CommunicationInterface comInterface; String community; InetAddress hostAddress; int version; int wirelessHostNum = 1; Thread statusThread; // WindowCloseAdapter to catch window close-box closings private class WindowCloseAdapter extends WindowAdapter { public void windowClosing(WindowEvent evt) { // stop current statusThread, if alive, and wait for it to die: stopLinkTest(); // then git! System.exit(0); } }; public LinkMonitor() { setUpDisplay(); try { community = "public"; version = 0; // SNMPv1 hostAddress = InetAddress.getByName(hostIDField.getText()); comInterface = new SNMPv1CommunicationInterface(version, hostAddress, community); // set socket timeout to 5 seconds comInterface.setSocketTimeout(5000); statusThread = new Thread(this); } catch(Exception e) { messagesArea.setText("Exception during connection status polling startup: " + e + "\n"); } } private void setUpDisplay() { try { // set look-and-feel to native platform l&f, if possible UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { // or not... } this.getRootPane().setBorder(new BevelBorder(BevelBorder.RAISED)); // set fonts to smaller-than-normal size, for compaction! UIManager manager = new UIManager(); FontUIResource appFont = new FontUIResource("SansSerif", Font.PLAIN, 10); UIDefaults defaults = manager.getLookAndFeelDefaults(); Enumeration keys = defaults.keys(); while (keys.hasMoreElements()) { String nextKey = (String)(keys.nextElement()); if ((nextKey.indexOf("font") > -1) || (nextKey.indexOf("Font") > -1)) { manager.put(nextKey, appFont); } } // add WindowCloseAdapter to catch window close-box closings addWindowListener(new WindowCloseAdapter()); theMenubar = new MenuBar(); this.setMenuBar(theMenubar); fileMenu = new Menu("File"); aboutItem = new MenuItem("About..."); aboutItem.setActionCommand("about"); aboutItem.addActionListener(this); fileMenu.add(aboutItem); fileMenu.addSeparator(); quitItem = new MenuItem("Quit"); quitItem.setActionCommand("quit"); quitItem.addActionListener(this); fileMenu.add(quitItem); theMenubar.add(fileMenu); hostIDLabel = new JLabel("Base station address:"); hostIDField = new JTextField(20); hostIDField.setText("10.0.1.1"); hostIDField.setEditable(false); communityLabel = new JLabel("Community (password):"); communityField = new JTextField(20); communityField.setText(""); communityField.setEditable(false); wirelessHostLabel = new JLabel("Wireless host name:"); wirelessHostField = new JTextField(20); wirelessHostField.setText(""); wirelessHostField.setEditable(false); wirelessHostMACLabel = new JLabel("Wireless host MAC:"); wirelessHostMACField = new JTextField(20); wirelessHostMACField.setText(""); wirelessHostMACField.setEditable(false); authorLabel = new JLabel(" Version 1.1 J. Sevy, May 2001"); authorLabel.setFont(new Font("SansSerif", Font.ITALIC, 8)); newHostButton = new JButton(" Set address "); newHostButton.setActionCommand("new host"); newHostButton.addActionListener(this); newCommunityButton = new JButton(" Set community "); newCommunityButton.setActionCommand("new community"); newCommunityButton.addActionListener(this); newWirelessHostButton = new JButton("Select new host"); newWirelessHostButton.setActionCommand("new wireless host"); newWirelessHostButton.addActionListener(this); scanButton = new JButton("Test wireless link"); scanButton.setActionCommand("test link"); scanButton.addActionListener(this); localSignalBar = new JProgressBar(0, 100); localSignalBar.setValue(0); localSNRBar = new JProgressBar(0, 100); localSNRBar.setValue(0); localNoiseBar = new JProgressBar(0, 100); localNoiseBar.setValue(0); remoteSignalBar = new JProgressBar(0, 100); remoteSignalBar.setValue(0); remoteSNRBar = new JProgressBar(0, 100); remoteSNRBar.setValue(0); remoteNoiseBar = new JProgressBar(0, 100); remoteNoiseBar.setValue(0); Dimension labelDimension = new Dimension(20,20); localSignalTextField = new JLabel(); localSignalTextField.setPreferredSize(labelDimension); localSNRTextField = new JLabel(); localSNRTextField.setPreferredSize(labelDimension); localNoiseTextField = new JLabel(); localNoiseTextField.setPreferredSize(labelDimension); remoteSignalTextField = new JLabel(); remoteSignalTextField.setPreferredSize(labelDimension); remoteSNRTextField = new JLabel(); remoteSNRTextField.setPreferredSize(labelDimension); remoteNoiseTextField = new JLabel(); remoteNoiseTextField.setPreferredSize(labelDimension); messagesArea = new JTextArea(5,50); messagesScroll = new JScrollPane(messagesArea); /* URL url = AirportBaseStationHangup.class.getResource("iconImage.gif"); this.setIconImage(Toolkit.getDefaultToolkit().getImage(url)); */ // now set up display // set params for layout manager GridBagLayout theLayout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = 1; c.gridheight = 1; c.fill = GridBagConstraints.NONE; c.ipadx = 0; c.ipady = 0; c.insets = new Insets(2,2,2,2); c.anchor = GridBagConstraints.CENTER; c.weightx = .5; c.weighty = .5; this.setTitle("Access Point Wireless Link Quality Monitoring Utility"); Panel hostPanel = new Panel(); hostPanel.setLayout(theLayout); c.gridx = 1; c.gridy = 1; theLayout.setConstraints(hostIDLabel, c); hostPanel.add(hostIDLabel); c.gridx = 2; c.gridy = 1; theLayout.setConstraints(hostIDField, c); hostPanel.add(hostIDField); c.gridx = 3; c.gridy = 1; theLayout.setConstraints(newHostButton, c); hostPanel.add(newHostButton); c.gridx = 1; c.gridy = 2; theLayout.setConstraints(communityLabel, c); hostPanel.add(communityLabel); c.gridx = 2; c.gridy = 2; theLayout.setConstraints(communityField, c); hostPanel.add(communityField); c.gridx = 3; c.gridy = 2; theLayout.setConstraints(newCommunityButton, c); hostPanel.add(newCommunityButton); c.gridx = 1; c.gridy = 3; theLayout.setConstraints(wirelessHostLabel, c); hostPanel.add(wirelessHostLabel); c.gridx = 2; c.gridy = 3; theLayout.setConstraints(wirelessHostField, c); hostPanel.add(wirelessHostField); c.gridx = 1; c.gridy = 4; theLayout.setConstraints(wirelessHostMACLabel, c); hostPanel.add(wirelessHostMACLabel); c.gridx = 2; c.gridy = 4; theLayout.setConstraints(wirelessHostMACField, c); hostPanel.add(wirelessHostMACField); c.gridheight = 2; c.gridx = 3; c.gridy = 3; theLayout.setConstraints(newWirelessHostButton, c); hostPanel.add(newWirelessHostButton); c.gridheight = 1; c.gridwidth = 3; c.gridx = 1; c.gridy = 5; theLayout.setConstraints(scanButton, c); hostPanel.add(scanButton); c.gridwidth = 1; JLabel barLabel; Panel localPanel = new Panel(); localPanel.setLayout(theLayout); c.gridx = 1; c.gridy = 1; barLabel = new JLabel("Local signal level"); theLayout.setConstraints(barLabel, c); localPanel.add(barLabel); c.gridx = 2; c.gridy = 1; theLayout.setConstraints(localSignalBar, c); localPanel.add(localSignalBar); c.gridx = 3; c.gridy = 1; theLayout.setConstraints(localSignalTextField, c); localPanel.add(localSignalTextField); c.gridx = 1; c.gridy = 2; barLabel = new JLabel("Local SNR"); theLayout.setConstraints(barLabel, c); localPanel.add(barLabel); c.gridx = 2; c.gridy = 2; theLayout.setConstraints(localSNRBar, c); localPanel.add(localSNRBar); c.gridx = 3; c.gridy = 2; theLayout.setConstraints(localSNRTextField, c); localPanel.add(localSNRTextField); c.gridx = 1; c.gridy = 3; barLabel = new JLabel("Local noise level"); theLayout.setConstraints(barLabel, c); localPanel.add(barLabel); c.gridx = 2; c.gridy = 3; theLayout.setConstraints(localNoiseBar, c); localPanel.add(localNoiseBar); c.gridx = 3; c.gridy = 3; theLayout.setConstraints(localNoiseTextField, c); localPanel.add(localNoiseTextField); Panel remotePanel = new Panel(); remotePanel.setLayout(theLayout); c.gridx = 1; c.gridy = 1; barLabel = new JLabel("Remote signal level"); theLayout.setConstraints(barLabel, c); remotePanel.add(barLabel); c.gridx = 2; c.gridy = 1; theLayout.setConstraints(remoteSignalBar, c); remotePanel.add(remoteSignalBar); c.gridx = 3; c.gridy = 1; theLayout.setConstraints(remoteSignalTextField, c); remotePanel.add(remoteSignalTextField); c.gridx = 1; c.gridy = 2; barLabel = new JLabel("Remote SNR"); theLayout.setConstraints(barLabel, c); remotePanel.add(barLabel); c.gridx = 2; c.gridy = 2; theLayout.setConstraints(remoteSNRBar, c); remotePanel.add(remoteSNRBar); c.gridx = 3; c.gridy = 2; theLayout.setConstraints(remoteSNRTextField, c); remotePanel.add(remoteSNRTextField); c.gridx = 1; c.gridy = 3; barLabel = new JLabel("Remote noise level"); theLayout.setConstraints(barLabel, c); remotePanel.add(barLabel); c.gridx = 2; c.gridy = 3; theLayout.setConstraints(remoteNoiseBar, c); remotePanel.add(remoteNoiseBar); c.gridx = 3; c.gridy = 3; theLayout.setConstraints(remoteNoiseTextField, c); remotePanel.add(remoteNoiseTextField); Panel barPanel = new Panel(); barPanel.setLayout(theLayout); c.gridx = 1; c.gridy = 1; theLayout.setConstraints(localPanel, c); barPanel.add(localPanel); c.gridx = 2; c.gridy = 1; theLayout.setConstraints(remotePanel, c); barPanel.add(remotePanel); this.getContentPane().setLayout(theLayout); c.gridx = 1; c.gridy = 1; theLayout.setConstraints(hostPanel, c); this.getContentPane().add(hostPanel); c.gridx = 1; c.gridy = 2; theLayout.setConstraints(barPanel, c); this.getContentPane().add(barPanel); c.gridx = 1; c.gridy = 3; JLabel messagesLabel = new JLabel("Messages:"); theLayout.setConstraints(messagesLabel, c); this.getContentPane().add(messagesLabel); c.gridx = 1; c.gridy = 4; theLayout.setConstraints(messagesScroll, c); this.getContentPane().add(messagesScroll); c.gridx = 1; c.gridy = 5; theLayout.setConstraints(authorLabel, c); this.getContentPane().add(authorLabel); } public void actionPerformed(ActionEvent theEvent) // respond to button pushes, menu selections { String command = theEvent.getActionCommand(); if (command == "quit") { // stop current link test thread, and wait for it to die: stopLinkTest(); System.exit(0); } if (command == "about") { AboutDialog aboutDialog = new AboutDialog(this); } if (command == "new host") { String newHost = JOptionPane.showInputDialog("Input access point address:"); if (newHost != null) { try { version = 0; // SNMPv1 hostAddress = InetAddress.getByName(newHost); // stop current link test thread, and wait for it to die: stopLinkTest(); // set up polling parameters comInterface = new SNMPv1CommunicationInterface(version, hostAddress, community); // set socket timeout to 5 seconds comInterface.setSocketTimeout(5000); hostIDField.setText(newHost); } catch(UnknownHostException e) { JOptionPane.showMessageDialog(this, "Unknown host supplied."); } catch(Exception e) { JOptionPane.showMessageDialog(this, "Error setting new access point address: " + e); } } } if (command == "new community") { String newCommunity = JOptionPane.showInputDialog("Input new community:"); if (newCommunity != null) { try { version = 0; // SNMPv1 community = newCommunity; // stop current link test thread, and wait for it to die: stopLinkTest(); // set up polling parameters comInterface = new SNMPv1CommunicationInterface(version, hostAddress, community); // set socket timeout to 5 seconds comInterface.setSocketTimeout(5000); communityField.setText(newCommunity); } catch(Exception e) { JOptionPane.showMessageDialog(this, "Error setting new community: " + e); } } } if (command == "new wireless host") { try { // stop current link test thread, and wait for it to die: stopLinkTest(); // clear messages area messagesArea.setText(""); int k; // try 10 times for (k = 0; k < 10; k++) { // do wireless host discovery process String itemID; SNMPVarBindList newVars; SNMPSequence pair; SNMPInteger snmpIntegerValue; SNMPObject snmpValue; // first, need to write values to appropriate OID's - why, I don't know... for (int i = 1; i <= 3; i++) { itemID = "1.3.6.1.4.1.762.2.5.5." + i; comInterface.setMIBEntry(itemID, new SNMPInteger(50)); itemID = "1.3.6.1.4.1.762.2.5.4." + i; comInterface.setMIBEntry(itemID, new SNMPInteger(3)); } // now, read the number of wireless hosts to select from itemID = "1.3.6.1.4.1.762.2.5.1.0"; newVars = comInterface.getMIBEntry(itemID); pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); snmpIntegerValue = (SNMPInteger)pair.getSNMPObjectAt(1); int numHosts = Integer.parseInt(snmpIntegerValue.toString()); if (numHosts > 0) { // get info on these hosts: names should do... String[] hostNames = new String[numHosts]; for (int i = 0; i < numHosts; i++) { itemID = "1.3.6.1.4.1.762.2.5.2.1.3." + (i + 1); newVars = comInterface.getMIBEntry(itemID); pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); snmpValue = pair.getSNMPObjectAt(1); hostNames[i] = snmpValue.toString(); } // put up a dialog with the names as chioces String newHost = (String)JOptionPane.showInputDialog(null, "Select new wireless host:", "", JOptionPane.PLAIN_MESSAGE, null, hostNames, hostNames[0]); if (newHost != null) { // determine which host number was selected for (int i = 0; i < numHosts; i++) { if (newHost.equals(hostNames[i])) wirelessHostNum = i + 1; } wirelessHostField.setText(newHost); itemID = "1.3.6.1.4.1.762.2.5.2.1.11." + wirelessHostNum; newVars = comInterface.getMIBEntry(itemID); pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); snmpValue = pair.getSNMPObjectAt(1); wirelessHostMACField.setText(((SNMPOctetString)snmpValue).toHexString()); } // found our host; break out of for loop break; } } if (k >= 10) { // didn't find a wireless host in 10 tries; display error message messagesArea.setText("Try again... no wireless hosts currently available"); } } catch(Exception e) { messagesArea.setText("Error selecting new wireless host: " + e); } } if (command == "test link") { startLinkTest(); } if (command == "stop link test") { stopLinkTest(); } } private void stopLinkTest() { if (statusThread.isAlive()) { try { // stop current statusThread, and wait for it to die: statusThread.interrupt(); statusThread.join(); } catch(InterruptedException ex) { messagesArea.setText("Exception during link test thread exit: " + ex + "\n"); } scanButton.setText("Test wireless link"); scanButton.setActionCommand("test link"); } } private void startLinkTest() { if (!statusThread.isAlive()) { scanButton.setText("Stop link test"); scanButton.setActionCommand("stop link test"); // recreate and start status polling thread statusThread = new Thread(this); statusThread.start(); } } private String hexByte(byte b) { int pos = b; if (pos < 0) pos += 256; String returnString = new String(); returnString += Integer.toHexString(pos/16); returnString += Integer.toHexString(pos%16); return returnString; } public void run() { while(!Thread.interrupted()) { try { String itemID; SNMPVarBindList newVars; SNMPSequence pair; SNMPInteger snmpSetValue, snmpIntegerValue; SNMPObject snmpValue; messagesArea.setText(""); /* // first, need to write values to appropriate OID's - why, I don't know... for (int i = 1; i <= 3; i++) { itemID = "1.3.6.1.4.1.762.2.5.5." + i; newVars = comInterface.setMIBEntry(itemID, new SNMPInteger(50)); itemID = "1.3.6.1.4.1.762.2.5.4." + i; newVars = comInterface.setMIBEntry(itemID, new SNMPInteger(3)); } */ // now, should be able to read the desired values... // first, set up testing parameters // 1.3.6.1.4.1.762.2.5.2.1.27.1=1500: packet size? itemID = "1.3.6.1.4.1.762.2.5.2.1.27." + wirelessHostNum; newVars = comInterface.setMIBEntry(itemID, new SNMPInteger(1500)); // 1.3.6.1.4.1.762.2.5.2.1.26.1=25 itemID = "1.3.6.1.4.1.762.2.5.2.1.26." + wirelessHostNum; newVars = comInterface.setMIBEntry(itemID, new SNMPInteger(25)); // 1.3.6.1.4.1.762.2.5.2.1.25.1=88: total number of packets to send? (half out, half back?) itemID = "1.3.6.1.4.1.762.2.5.2.1.25." + wirelessHostNum; newVars = comInterface.setMIBEntry(itemID, new SNMPInteger(88)); itemID = "1.3.6.1.4.1.762.2.5.2.1.3." + wirelessHostNum; newVars = comInterface.getMIBEntry(itemID); pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); snmpValue = pair.getSNMPObjectAt(1); wirelessHostMACField.setText(snmpValue.toString()); itemID = "1.3.6.1.4.1.762.2.5.2.1.11." + wirelessHostNum; newVars = comInterface.getMIBEntry(itemID); pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); snmpValue = pair.getSNMPObjectAt(1); wirelessHostMACField.setText(((SNMPOctetString)snmpValue).toHexString()); // next, check the number of wireless hosts available itemID = "1.3.6.1.4.1.762.2.5.1.0"; newVars = comInterface.getMIBEntry(itemID); pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); snmpIntegerValue = (SNMPInteger)pair.getSNMPObjectAt(1); int numHosts = Integer.parseInt(snmpIntegerValue.toString()); if (numHosts >= wirelessHostNum) { // now, read parameters //messagesArea.append("Local signal:\n"); itemID = "1.3.6.1.4.1.762.2.5.2.1.32." + wirelessHostNum; newVars = comInterface.getMIBEntry(itemID); pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); snmpIntegerValue = (SNMPInteger)pair.getSNMPObjectAt(1); //messagesArea.append(" local signal: " + snmpIntegerValue +"\n"); localSignalBar.setValue(Integer.parseInt(snmpIntegerValue.toString())); localSignalTextField.setText(snmpIntegerValue.toString()); itemID = "1.3.6.1.4.1.762.2.5.2.1.33." + wirelessHostNum; newVars = comInterface.getMIBEntry(itemID); pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); snmpIntegerValue = (SNMPInteger)pair.getSNMPObjectAt(1); //messagesArea.append(" local noise: " + snmpIntegerValue +"\n"); localNoiseBar.setValue(Integer.parseInt(snmpIntegerValue.toString())); localNoiseTextField.setText(snmpIntegerValue.toString()); itemID = "1.3.6.1.4.1.762.2.5.2.1.35." + wirelessHostNum; newVars = comInterface.getMIBEntry(itemID); pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); snmpIntegerValue = (SNMPInteger)pair.getSNMPObjectAt(1); //messagesArea.append(" local SNR: " + snmpIntegerValue +"\n"); localSNRBar.setValue(Integer.parseInt(snmpIntegerValue.toString())); localSNRTextField.setText(snmpIntegerValue.toString()); itemID = "1.3.6.1.4.1.762.2.5.2.1.44." + wirelessHostNum; newVars = comInterface.getMIBEntry(itemID); pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); snmpIntegerValue = (SNMPInteger)pair.getSNMPObjectAt(1); //messagesArea.append(" remote signal: " + snmpIntegerValue +"\n"); remoteSignalBar.setValue(Integer.parseInt(snmpIntegerValue.toString())); remoteSignalTextField.setText(snmpIntegerValue.toString()); itemID = "1.3.6.1.4.1.762.2.5.2.1.45." + wirelessHostNum; newVars = comInterface.getMIBEntry(itemID); pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); snmpIntegerValue = (SNMPInteger)pair.getSNMPObjectAt(1); //messagesArea.append(" remote noise: " + snmpIntegerValue +"\n"); remoteNoiseBar.setValue(Integer.parseInt(snmpIntegerValue.toString())); remoteNoiseTextField.setText(snmpIntegerValue.toString()); itemID = "1.3.6.1.4.1.762.2.5.2.1.47." + wirelessHostNum; newVars = comInterface.getMIBEntry(itemID); pair = (SNMPSequence)(newVars.getSNMPObjectAt(0)); snmpIntegerValue = (SNMPInteger)pair.getSNMPObjectAt(1); //messagesArea.append(" local SNR: " + snmpIntegerValue +"\n"); remoteSNRBar.setValue(Integer.parseInt(snmpIntegerValue.toString())); remoteSNRTextField.setText(snmpIntegerValue.toString()); } try { // sleep for 10 seconds Thread.currentThread().sleep(10000); } catch(InterruptedException e) { // don't bother informing of interruption; will just exit... // but must reset this thread's interrupted status statusThread.interrupt(); //messagesArea.setText("Exception during modem status polling: " + e + "\n"); } } catch(InterruptedIOException e) { // don't bother informing of interruption //messagesArea.setText("Exception during modem status polling: " + e + "\n"); } catch(Exception e) { messagesArea.append("Exception during link status polling: " + e + "\n"); } } try { // set total number of packets to send to 0 String itemID = "1.3.6.1.4.1.762.2.5.2.1.25." + wirelessHostNum; comInterface.setMIBEntry(itemID, new SNMPInteger(0)); } catch(Exception e) { messagesArea.append("Exception during modem status polling exit: " + e + "\n"); } //messagesArea.setText("Status thread exiting!\n"); } public static void main(String args[]) { try { LinkMonitor theApp = new LinkMonitor(); theApp.pack(); // tweak app size to make it a little larger than necessary, to address the // "shrunken textfields" problem arising from the layout manager packing stuff // a little too tightly. Dimension dim = theApp.getSize(); dim.height += 20; dim.width += 20; theApp.setSize(dim); theApp.show(); } catch (Exception e) {} } }